@enbox/dwn-sdk-js 0.2.1 → 0.2.2

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
  || ${o} === "boolean" || ${s} === null`).assign(i,(0,It._)`[${s}]`)}}}function wY({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,It._)`${e} !== undefined`,()=>t.assign((0,It._)`${e}[${r}]`,n))}function Tk(t,e,r,n=wh.Correct){let s=n===wh.Correct?It.operators.EQ:It.operators.NEQ,a;switch(t){case"null":return(0,It._)`${e} ${s} null`;case"array":a=(0,It._)`Array.isArray(${e})`;break;case"object":a=(0,It._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":a=o((0,It._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":a=o();break;default:return(0,It._)`typeof ${e} ${s} ${t}`}return n===wh.Correct?a:(0,It.not)(a);function o(i=It.nil){return(0,It.and)((0,It._)`typeof ${e} == "number"`,i,r?(0,It._)`isFinite(${e})`:It.nil)}}Zs.checkDataType=Tk;function Ik(t,e,r,n){if(t.length===1)return Tk(t[0],e,r,n);let s,a=(0,OO.toHash)(t);if(a.array&&a.object){let o=(0,It._)`typeof ${e} != "object"`;s=a.null?o:(0,It._)`!${e} || ${o}`,delete a.null,delete a.array,delete a.object}else s=It.nil;a.number&&delete a.integer;for(let o in a)s=(0,It.and)(s,Tk(o,e,r,n));return s}Zs.checkDataTypes=Ik;var vY={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,It._)`{type: ${t}}`:(0,It._)`{type: ${e}}`};function Ak(t){let e=bY(t);(0,pY.reportError)(e,vY)}Zs.reportTypeError=Ak;function bY(t){let{gen:e,data:r,schema:n}=t,s=(0,OO.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var LO=Ee(Db=>{"use strict";w();Object.defineProperty(Db,"__esModule",{value:!0});Db.assignDefaults=void 0;var vh=kt(),PY=Ut();function xY(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)UO(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,a)=>UO(t,a,s.default))}Db.assignDefaults=xY;function UO(t,e,r){let{gen:n,compositeRule:s,data:a,opts:o}=t;if(r===void 0)return;let i=(0,vh._)`${a}${(0,vh.getProperty)(e)}`;if(s){(0,PY.checkStrictMode)(t,`default is ignored for: ${i}`);return}let c=(0,vh._)`${i} === undefined`;o.useDefaults==="empty"&&(c=(0,vh._)`${c} || ${i} === null || ${i} === ""`),n.if(c,(0,vh._)`${i} = ${(0,vh.stringify)(r)}`)}});var $o=Ee(Ir=>{"use strict";w();Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateUnion=Ir.validateArray=Ir.usePattern=Ir.callValidateCode=Ir.schemaProperties=Ir.allSchemaProperties=Ir.noPropertyInData=Ir.propertyInData=Ir.isOwnProperty=Ir.hasPropFunc=Ir.reportMissingProp=Ir.checkMissingProp=Ir.checkReportMissingProp=void 0;var Gr=kt(),Rk=Ut(),xu=jo(),SY=Ut();function EY(t,e){let{gen:r,data:n,it:s}=t;r.if(Ck(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Gr._)`${e}`},!0),t.error()})}Ir.checkReportMissingProp=EY;function _Y({gen:t,data:e,it:{opts:r}},n,s){return(0,Gr.or)(...n.map(a=>(0,Gr.and)(Ck(t,e,a,r.ownProperties),(0,Gr._)`${s} = ${a}`)))}Ir.checkMissingProp=_Y;function kY(t,e){t.setParams({missingProperty:e},!0),t.error()}Ir.reportMissingProp=kY;function KO(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Gr._)`Object.prototype.hasOwnProperty`})}Ir.hasPropFunc=KO;function Dk(t,e,r){return(0,Gr._)`${KO(t)}.call(${e}, ${r})`}Ir.isOwnProperty=Dk;function TY(t,e,r,n){let s=(0,Gr._)`${e}${(0,Gr.getProperty)(r)} !== undefined`;return n?(0,Gr._)`${s} && ${Dk(t,e,r)}`:s}Ir.propertyInData=TY;function Ck(t,e,r,n){let s=(0,Gr._)`${e}${(0,Gr.getProperty)(r)} === undefined`;return n?(0,Gr.or)(s,(0,Gr.not)(Dk(t,e,r))):s}Ir.noPropertyInData=Ck;function zO(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ir.allSchemaProperties=zO;function IY(t,e){return zO(e).filter(r=>!(0,Rk.alwaysValidSchema)(t,e[r]))}Ir.schemaProperties=IY;function AY({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:a},it:o},i,c,u){let d=u?(0,Gr._)`${t}, ${e}, ${n}${s}`:e,l=[[xu.default.instancePath,(0,Gr.strConcat)(xu.default.instancePath,a)],[xu.default.parentData,o.parentData],[xu.default.parentDataProperty,o.parentDataProperty],[xu.default.rootData,xu.default.rootData]];o.opts.dynamicRef&&l.push([xu.default.dynamicAnchors,xu.default.dynamicAnchors]);let f=(0,Gr._)`${d}, ${r.object(...l)}`;return c!==Gr.nil?(0,Gr._)`${i}.call(${c}, ${f})`:(0,Gr._)`${i}(${f})`}Ir.callValidateCode=AY;var RY=(0,Gr._)`new RegExp`;function DY({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,a=s(r,n);return t.scopeValue("pattern",{key:a.toString(),ref:a,code:(0,Gr._)`${s.code==="new RegExp"?RY:(0,SY.useFunc)(t,s)}(${r}, ${n})`})}Ir.usePattern=DY;function CY(t){let{gen:e,data:r,keyword:n,it:s}=t,a=e.name("valid");if(s.allErrors){let i=e.let("valid",!0);return o(()=>e.assign(i,!1)),i}return e.var(a,!0),o(()=>e.break()),a;function o(i){let c=e.const("len",(0,Gr._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Rk.Type.Num},a),e.if((0,Gr.not)(a),i)})}}Ir.validateArray=CY;function jY(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Rk.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let o=e.let("valid",!1),i=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},i);e.assign(o,(0,Gr._)`${o} || ${i}`),t.mergeValidEvaluated(d,i)||e.if((0,Gr.not)(o))})),t.result(o,()=>t.reset(),()=>t.error(!0))}Ir.validateUnion=jY});var GO=Ee(uc=>{"use strict";w();Object.defineProperty(uc,"__esModule",{value:!0});uc.validateKeywordUsage=uc.validSchemaType=uc.funcKeywordCode=uc.macroKeywordCode=void 0;var xi=kt(),af=jo(),$Y=$o(),MY=bg();function OY(t,e){let{gen:r,keyword:n,schema:s,parentSchema:a,it:o}=t,i=e.macro.call(o.self,s,a,o),c=FO(r,n,i);o.opts.validateSchema!==!1&&o.self.validateSchema(i,!0);let u=r.name("valid");t.subschema({schema:i,schemaPath:xi.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}uc.macroKeywordCode=OY;function BY(t,e){var r;let{gen:n,keyword:s,schema:a,parentSchema:o,$data:i,it:c}=t;UY(c,e);let u=!i&&e.compile?e.compile.call(c.self,a,o,c):e.validate,d=FO(n,s,u),l=n.let("valid");t.block$data(l,f),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function f(){if(e.errors===!1)m(),e.modifying&&qO(t),y(()=>t.error());else{let S=e.async?h():p();e.modifying&&qO(t),y(()=>NY(t,S))}}function h(){let S=n.let("ruleErrs",null);return n.try(()=>m((0,xi._)`await `),v=>n.assign(l,!1).if((0,xi._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(S,(0,xi._)`${v}.errors`),()=>n.throw(v))),S}function p(){let S=(0,xi._)`${d}.errors`;return n.assign(S,null),m(xi.nil),S}function m(S=e.async?(0,xi._)`await `:xi.nil){let v=c.opts.passContext?af.default.this:af.default.self,E=!("compile"in e&&!i||e.schema===!1);n.assign(l,(0,xi._)`${S}${(0,$Y.callValidateCode)(t,d,v,E)}`,e.modifying)}function y(S){var v;n.if((0,xi.not)((v=e.valid)!==null&&v!==void 0?v:l),S)}}uc.funcKeywordCode=BY;function qO(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,xi._)`${n.parentData}[${n.parentDataProperty}]`))}function NY(t,e){let{gen:r}=t;r.if((0,xi._)`Array.isArray(${e})`,()=>{r.assign(af.default.vErrors,(0,xi._)`${af.default.vErrors} === null ? ${e} : ${af.default.vErrors}.concat(${e})`).assign(af.default.errors,(0,xi._)`${af.default.vErrors}.length`),(0,MY.extendErrors)(t)},()=>t.error())}function UY({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function FO(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,xi.stringify)(r)})}function LY(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")}uc.validSchemaType=LY;function KY({schema:t,opts:e,self:r,errSchemaPath:n},s,a){if(Array.isArray(s.keyword)?!s.keyword.includes(a):s.keyword!==a)throw new Error("ajv implementation error");let o=s.dependencies;if(o?.some(i=>!Object.prototype.hasOwnProperty.call(t,i)))throw new Error(`parent schema must have dependencies of ${a}: ${o.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[a])){let c=`keyword "${a}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}uc.validateKeywordUsage=KY});var VO=Ee(Su=>{"use strict";w();Object.defineProperty(Su,"__esModule",{value:!0});Su.extendSubschemaMode=Su.extendSubschemaData=Su.getSubschema=void 0;var lc=kt(),WO=Ut();function zY(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:a,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let i=t.schema[e];return r===void 0?{schema:i,schemaPath:(0,lc._)`${t.schemaPath}${(0,lc.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:i[r],schemaPath:(0,lc._)`${t.schemaPath}${(0,lc.getProperty)(e)}${(0,lc.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,WO.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||a===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:o,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}Su.getSubschema=zY;function qY(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:a,propertyName:o}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:i}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,f=i.let("data",(0,lc._)`${e.data}${(0,lc.getProperty)(r)}`,!0);c(f),t.errorPath=(0,lc.str)`${u}${(0,WO.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,lc._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof lc.Name?s:i.let("data",s,!0);c(u),o!==void 0&&(t.propertyName=o)}a&&(t.dataTypes=a);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Su.extendSubschemaData=qY;function FY(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:a}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),a!==void 0&&(t.allErrors=a),t.jtdDiscriminator=e,t.jtdMetadata=r}Su.extendSubschemaMode=FY});var jk=Ee((wRe,HO)=>{"use strict";w();HO.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,s,a;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))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(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,a[s]))return!1;for(s=n;s--!==0;){var o=a[s];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r}});var ZO=Ee((bRe,JO)=>{"use strict";w();var Eu=JO.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};Cb(e,n,s,t,"",t)};Eu.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Eu.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Eu.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Eu.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 Cb(t,e,r,n,s,a,o,i,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,a,o,i,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in Eu.arrayKeywords)for(var f=0;f<l.length;f++)Cb(t,e,r,l[f],s+"/"+d+"/"+f,a,s,d,n,f)}else if(d in Eu.propsKeywords){if(l&&typeof l=="object")for(var h in l)Cb(t,e,r,l[h],s+"/"+d+"/"+GY(h),a,s,d,n,h)}else(d in Eu.keywords||t.allKeys&&!(d in Eu.skipKeywords))&&Cb(t,e,r,l,s+"/"+d,a,s,d,n)}r(n,s,a,o,i,c,u)}}function GY(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var xg=Ee(Mi=>{"use strict";w();Object.defineProperty(Mi,"__esModule",{value:!0});Mi.getSchemaRefs=Mi.resolveUrl=Mi.normalizeId=Mi._getFullPath=Mi.getFullPath=Mi.inlineRef=void 0;var WY=Ut(),VY=jk(),HY=ZO(),JY=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function ZY(t,e=!0){return typeof t=="boolean"?!0:e===!0?!$k(t):e?YO(t)<=e:!1}Mi.inlineRef=ZY;var YY=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function $k(t){for(let e in t){if(YY.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some($k)||typeof r=="object"&&$k(r))return!0}return!1}function YO(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!JY.has(r)&&(typeof t[r]=="object"&&(0,WY.eachItem)(t[r],n=>e+=YO(n)),e===1/0))return 1/0}return e}function QO(t,e="",r){r!==!1&&(e=bh(e));let n=t.parse(e);return XO(t,n)}Mi.getFullPath=QO;function XO(t,e){return t.serialize(e).split("#")[0]+"#"}Mi._getFullPath=XO;var QY=/#\/?$/;function bh(t){return t?t.replace(QY,""):""}Mi.normalizeId=bh;function XY(t,e,r){return r=bh(r),t.resolve(e,r)}Mi.resolveUrl=XY;var eQ=/^[a-z_][-a-z0-9._]*$/i;function tQ(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=bh(t[r]||e),a={"":s},o=QO(n,s,!1),i={},c=new Set;return HY(t,{allKeys:!0},(l,f,h,p)=>{if(p===void 0)return;let m=o+f,y=a[p];typeof l[r]=="string"&&(y=S.call(this,l[r])),v.call(this,l.$anchor),v.call(this,l.$dynamicAnchor),a[f]=y;function S(E){let k=this.opts.uriResolver.resolve;if(E=bh(y?k(y,E):E),c.has(E))throw d(E);c.add(E);let A=this.refs[E];return typeof A=="string"&&(A=this.refs[A]),typeof A=="object"?u(l,A.schema,E):E!==bh(m)&&(E[0]==="#"?(u(l,i[E],E),i[E]=l):this.refs[E]=m),E}function v(E){if(typeof E=="string"){if(!eQ.test(E))throw new Error(`invalid anchor "${E}"`);S.call(this,`#${E}`)}}}),i;function u(l,f,h){if(f!==void 0&&!VY(l,f))throw d(h)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Mi.getSchemaRefs=tQ});var _g=Ee(_u=>{"use strict";w();Object.defineProperty(_u,"__esModule",{value:!0});_u.getData=_u.KeywordCxt=_u.validateFunctionCode=void 0;var s4=jO(),e4=Pg(),Ok=kk(),jb=Pg(),rQ=LO(),Eg=GO(),Mk=VO(),Ve=kt(),gt=jo(),nQ=xg(),dd=Ut(),Sg=bg();function sQ(t){if(a4(t)&&(c4(t),o4(t))){aQ(t);return}i4(t,()=>(0,s4.topBoolOrEmptySchema)(t))}_u.validateFunctionCode=sQ;function i4({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},a){s.code.es5?t.func(e,(0,Ve._)`${gt.default.data}, ${gt.default.valCxt}`,n.$async,()=>{t.code((0,Ve._)`"use strict"; ${t4(r,s)}`),oQ(t,s),t.code(a)}):t.func(e,(0,Ve._)`${gt.default.data}, ${iQ(s)}`,n.$async,()=>t.code(t4(r,s)).code(a))}function iQ(t){return(0,Ve._)`{${gt.default.instancePath}="", ${gt.default.parentData}, ${gt.default.parentDataProperty}, ${gt.default.rootData}=${gt.default.data}${t.dynamicRef?(0,Ve._)`, ${gt.default.dynamicAnchors}={}`:Ve.nil}}={}`}function oQ(t,e){t.if(gt.default.valCxt,()=>{t.var(gt.default.instancePath,(0,Ve._)`${gt.default.valCxt}.${gt.default.instancePath}`),t.var(gt.default.parentData,(0,Ve._)`${gt.default.valCxt}.${gt.default.parentData}`),t.var(gt.default.parentDataProperty,(0,Ve._)`${gt.default.valCxt}.${gt.default.parentDataProperty}`),t.var(gt.default.rootData,(0,Ve._)`${gt.default.valCxt}.${gt.default.rootData}`),e.dynamicRef&&t.var(gt.default.dynamicAnchors,(0,Ve._)`${gt.default.valCxt}.${gt.default.dynamicAnchors}`)},()=>{t.var(gt.default.instancePath,(0,Ve._)`""`),t.var(gt.default.parentData,(0,Ve._)`undefined`),t.var(gt.default.parentDataProperty,(0,Ve._)`undefined`),t.var(gt.default.rootData,gt.default.data),e.dynamicRef&&t.var(gt.default.dynamicAnchors,(0,Ve._)`{}`)})}function aQ(t){let{schema:e,opts:r,gen:n}=t;i4(t,()=>{r.$comment&&e.$comment&&u4(t),fQ(t),n.let(gt.default.vErrors,null),n.let(gt.default.errors,0),r.unevaluated&&cQ(t),d4(t),mQ(t)})}function cQ(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Ve._)`${r}.evaluated`),e.if((0,Ve._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Ve._)`${t.evaluated}.props`,(0,Ve._)`undefined`)),e.if((0,Ve._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Ve._)`${t.evaluated}.items`,(0,Ve._)`undefined`))}function t4(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Ve._)`/*# sourceURL=${r} */`:Ve.nil}function dQ(t,e){if(a4(t)&&(c4(t),o4(t))){uQ(t,e);return}(0,s4.boolOrEmptySchema)(t,e)}function o4({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 a4(t){return typeof t.schema!="boolean"}function uQ(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&u4(t),pQ(t),hQ(t);let a=n.const("_errs",gt.default.errors);d4(t,a),n.var(e,(0,Ve._)`${a} === ${gt.default.errors}`)}function c4(t){(0,dd.checkUnknownRules)(t),lQ(t)}function d4(t,e){if(t.opts.jtd)return r4(t,[],!1,e);let r=(0,e4.getSchemaTypes)(t.schema),n=(0,e4.coerceAndCheckDataType)(t,r);r4(t,r,!n,e)}function lQ(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,dd.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function fQ(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,dd.checkStrictMode)(t,"default is ignored in the schema root")}function pQ(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,nQ.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function hQ(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function u4({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let a=r.$comment;if(s.$comment===!0)t.code((0,Ve._)`${gt.default.self}.logger.log(${a})`);else if(typeof s.$comment=="function"){let o=(0,Ve.str)`${n}/$comment`,i=t.scopeValue("root",{ref:e.root});t.code((0,Ve._)`${gt.default.self}.opts.$comment(${a}, ${o}, ${i}.schema)`)}}function mQ(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:a}=t;r.$async?e.if((0,Ve._)`${gt.default.errors} === 0`,()=>e.return(gt.default.data),()=>e.throw((0,Ve._)`new ${s}(${gt.default.vErrors})`)):(e.assign((0,Ve._)`${n}.errors`,gt.default.vErrors),a.unevaluated&&yQ(t),e.return((0,Ve._)`${gt.default.errors} === 0`))}function yQ({gen:t,evaluated:e,props:r,items:n}){r instanceof Ve.Name&&t.assign((0,Ve._)`${e}.props`,r),n instanceof Ve.Name&&t.assign((0,Ve._)`${e}.items`,n)}function r4(t,e,r,n){let{gen:s,schema:a,data:o,allErrors:i,opts:c,self:u}=t,{RULES:d}=u;if(a.$ref&&(c.ignoreKeywordsWithRef||!(0,dd.schemaHasRulesButRef)(a,d))){s.block(()=>f4(t,"$ref",d.all.$ref.definition));return}c.jtd||gQ(t,e),s.block(()=>{for(let f of d.rules)l(f);l(d.post)});function l(f){(0,Ok.shouldUseGroup)(a,f)&&(f.type?(s.if((0,jb.checkDataType)(f.type,o,c.strictNumbers)),n4(t,f),e.length===1&&e[0]===f.type&&r&&(s.else(),(0,jb.reportTypeError)(t)),s.endIf()):n4(t,f),i||s.if((0,Ve._)`${gt.default.errors} === ${n||0}`))}}function n4(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,rQ.assignDefaults)(t,e.type),r.block(()=>{for(let a of e.rules)(0,Ok.shouldUseRule)(n,a)&&f4(t,a.keyword,a.definition,e.type)})}function gQ(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(wQ(t,e),t.opts.allowUnionTypes||vQ(t,e),bQ(t,t.dataTypes))}function wQ(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{l4(t.dataTypes,r)||Bk(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),xQ(t,e)}}function vQ(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Bk(t,"use allowUnionTypes to allow union type keyword")}function bQ(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,Ok.shouldUseRule)(t.schema,s)){let{type:a}=s.definition;a.length&&!a.some(o=>PQ(e,o))&&Bk(t,`missing type "${a.join(",")}" for keyword "${n}"`)}}}function PQ(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function l4(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function xQ(t,e){let r=[];for(let n of t.dataTypes)l4(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Bk(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,dd.checkStrictMode)(t,e,t.opts.strictTypes)}var $b=class{constructor(e,r,n){if((0,Eg.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,dd.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",p4(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Eg.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",gt.default.errors))}result(e,r,n){this.failResult((0,Ve.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,Ve.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,Ve._)`${r} !== undefined && (${(0,Ve.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?Sg.reportExtraError:Sg.reportError)(this,this.def.error,r)}$dataError(){(0,Sg.reportError)(this,this.def.$dataError||Sg.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Sg.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=Ve.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Ve.nil,r=Ve.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:a,def:o}=this;n.if((0,Ve.or)((0,Ve._)`${s} === undefined`,r)),e!==Ve.nil&&n.assign(e,!0),(a.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Ve.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:a}=this;return(0,Ve.or)(o(),i());function o(){if(n.length){if(!(r instanceof Ve.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Ve._)`${(0,jb.checkDataTypes)(c,r,a.opts.strictNumbers,jb.DataType.Wrong)}`}return Ve.nil}function i(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,Ve._)`!${c}(${r})`}return Ve.nil}}subschema(e,r){let n=(0,Mk.getSubschema)(this.it,e);(0,Mk.extendSubschemaData)(n,this.it,e),(0,Mk.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return dQ(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=dd.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=dd.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,Ve.Name)),!0}};_u.KeywordCxt=$b;function f4(t,e,r,n){let s=new $b(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Eg.funcKeywordCode)(s,r):"macro"in r?(0,Eg.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Eg.funcKeywordCode)(s,r)}var SQ=/^\/(?:[^~]|~0|~1)*$/,EQ=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function p4(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,a;if(t==="")return gt.default.rootData;if(t[0]==="/"){if(!SQ.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,a=gt.default.rootData}else{let u=EQ.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(s=u[2],s==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(a=r[e-d],!s)return a}let o=a,i=s.split("/");for(let u of i)u&&(a=(0,Ve._)`${a}${(0,Ve.getProperty)((0,dd.unescapeJsonPointer)(u))}`,o=(0,Ve._)`${o} && ${a}`);return o;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}_u.getData=p4});var Mb=Ee(Uk=>{"use strict";w();Object.defineProperty(Uk,"__esModule",{value:!0});var Nk=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Uk.default=Nk});var kg=Ee(zk=>{"use strict";w();Object.defineProperty(zk,"__esModule",{value:!0});var Lk=xg(),Kk=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Lk.resolveUrl)(e,r,n),this.missingSchema=(0,Lk.normalizeId)((0,Lk.getFullPath)(e,this.missingRef))}};zk.default=Kk});var Tg=Ee(Mo=>{"use strict";w();Object.defineProperty(Mo,"__esModule",{value:!0});Mo.resolveSchema=Mo.getCompilingSchema=Mo.resolveRef=Mo.compileSchema=Mo.SchemaEnv=void 0;var xa=kt(),_Q=Mb(),cf=jo(),Sa=xg(),h4=Ut(),kQ=_g(),Ph=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,Sa.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Mo.SchemaEnv=Ph;function Fk(t){let e=m4.call(this,t);if(e)return e;let r=(0,Sa.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:a}=this.opts,o=new xa.CodeGen(this.scope,{es5:n,lines:s,ownProperties:a}),i;t.$async&&(i=o.scopeValue("Error",{ref:_Q.default,code:(0,xa._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");t.validateName=c;let u={gen:o,allErrors:this.opts.allErrors,data:cf.default.data,parentData:cf.default.parentData,parentDataProperty:cf.default.parentDataProperty,dataNames:[cf.default.data],dataPathArr:[xa.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,xa.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:i,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:xa.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,xa._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,kQ.validateFunctionCode)(u),o.optimize(this.opts.code.optimize);let l=o.toString();d=`${o.scopeRefs(cf.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let h=new Function(`${cf.default.self}`,`${cf.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{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:c,validateCode:l,scopeValues:o._values}),this.opts.unevaluated){let{props:p,items:m}=u;h.evaluated={props:p instanceof xa.Name?void 0:p,items:m instanceof xa.Name?void 0:m,dynamicProps:p instanceof xa.Name,dynamicItems:m instanceof xa.Name},h.source&&(h.source.evaluated=(0,xa.stringify)(h.evaluated))}return t.validate=h,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}Mo.compileSchema=Fk;function TQ(t,e,r){var n;r=(0,Sa.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let a=RQ.call(this,t,r);if(a===void 0){let o=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:i}=this.opts;o&&(a=new Ph({schema:o,schemaId:i,root:t,baseId:e}))}if(a!==void 0)return t.refs[r]=IQ.call(this,a)}Mo.resolveRef=TQ;function IQ(t){return(0,Sa.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Fk.call(this,t)}function m4(t){for(let e of this._compilations)if(AQ(e,t))return e}Mo.getCompilingSchema=m4;function AQ(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function RQ(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ob.call(this,t,e)}function Ob(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Sa._getFullPath)(this.opts.uriResolver,r),s=(0,Sa.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return qk.call(this,r,t);let a=(0,Sa.normalizeId)(n),o=this.refs[a]||this.schemas[a];if(typeof o=="string"){let i=Ob.call(this,t,o);return typeof i?.schema!="object"?void 0:qk.call(this,r,i)}if(typeof o?.schema=="object"){if(o.validate||Fk.call(this,o),a===(0,Sa.normalizeId)(e)){let{schema:i}=o,{schemaId:c}=this.opts,u=i[c];return u&&(s=(0,Sa.resolveUrl)(this.opts.uriResolver,s,u)),new Ph({schema:i,schemaId:c,root:t,baseId:s})}return qk.call(this,r,o)}}Mo.resolveSchema=Ob;var DQ=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function qk(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let i of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,h4.unescapeFragment)(i)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!DQ.has(i)&&u&&(e=(0,Sa.resolveUrl)(this.opts.uriResolver,e,u))}let a;if(typeof r!="boolean"&&r.$ref&&!(0,h4.schemaHasRulesButRef)(r,this.RULES)){let i=(0,Sa.resolveUrl)(this.opts.uriResolver,e,r.$ref);a=Ob.call(this,n,i)}let{schemaId:o}=this.opts;if(a=a||new Ph({schema:r,schemaId:o,root:n,baseId:e}),a.schema!==a.root.schema)return a}});var y4=Ee((CRe,CQ)=>{CQ.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 Wk=Ee((jRe,b4)=>{"use strict";w();var jQ=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),w4=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 Gk(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 $Q=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function g4(t){return t.length=0,!0}function MQ(t,e,r){if(t.length){let n=Gk(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function OQ(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],a=!1,o=!1,i=MQ;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(a===!0&&(o=!0),!i(s,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(a=!0),n.push(":");continue}else if(u==="%"){if(!i(s,n,r))break;i=g4}else{s.push(u);continue}}return s.length&&(i===g4?r.zone=s.join(""):o?n.push(s.join("")):n.push(Gk(s))),r.address=n.join(""),r}function v4(t){if(BQ(t,":")<2)return{host:t,isIPV6:!1};let e=OQ(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 BQ(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function NQ(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===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(s===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 UQ(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 LQ(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!w4(r)){let n=v4(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}b4.exports={nonSimpleDomain:$Q,recomposeAuthority:LQ,normalizeComponentEncoding:UQ,removeDotSegments:NQ,isIPv4:w4,isUUID:jQ,normalizeIPv6:v4,stringArrayToHexStripped:Gk}});var _4=Ee((MRe,E4)=>{"use strict";w();var{isUUID:KQ}=Wk(),zQ=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,qQ=["http","https","ws","wss","urn","urn:uuid"];function FQ(t){return qQ.indexOf(t)!==-1}function Vk(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 P4(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function x4(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 GQ(t){return t.secure=Vk(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function WQ(t){if((t.port===(Vk(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 VQ(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(zQ);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,a=Hk(s);t.path=void 0,a&&(t=a.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function HQ(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(),s=`${r}:${e.nid||n}`,a=Hk(s);a&&(t=a.serialize(t,e));let o=t,i=t.nss;return o.path=`${n||e.nid}:${i}`,e.skipEscape=!0,o}function JQ(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!KQ(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function ZQ(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var S4={scheme:"http",domainHost:!0,parse:P4,serialize:x4},YQ={scheme:"https",domainHost:S4.domainHost,parse:P4,serialize:x4},Bb={scheme:"ws",domainHost:!0,parse:GQ,serialize:WQ},QQ={scheme:"wss",domainHost:Bb.domainHost,parse:Bb.parse,serialize:Bb.serialize},XQ={scheme:"urn",parse:VQ,serialize:HQ,skipNormalize:!0},eX={scheme:"urn:uuid",parse:JQ,serialize:ZQ,skipNormalize:!0},Nb={http:S4,https:YQ,ws:Bb,wss:QQ,urn:XQ,"urn:uuid":eX};Object.setPrototypeOf(Nb,null);function Hk(t){return t&&(Nb[t]||Nb[t.toLowerCase()])||void 0}E4.exports={wsIsSecure:Vk,SCHEMES:Nb,isValidSchemeName:FQ,getSchemeHandler:Hk}});var I4=Ee((BRe,Lb)=>{"use strict";w();var{normalizeIPv6:tX,removeDotSegments:Ig,recomposeAuthority:rX,normalizeComponentEncoding:Ub,isIPv4:nX,nonSimpleDomain:sX}=Wk(),{SCHEMES:iX,getSchemeHandler:k4}=_4();function oX(t,e){return typeof t=="string"?t=fc(ud(t,e),e):typeof t=="object"&&(t=ud(fc(t,e),e)),t}function aX(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=T4(ud(t,n),ud(e,n),n,!0);return n.skipEscape=!0,fc(s,n)}function T4(t,e,r,n){let s={};return n||(t=ud(fc(t,r),r),e=ud(fc(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ig(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ig(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Ig(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=Ig(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function cX(t,e,r){return typeof t=="string"?(t=unescape(t),t=fc(Ub(ud(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=fc(Ub(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=fc(Ub(ud(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=fc(Ub(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function fc(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),s=[],a=k4(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&&s.push(r.scheme,":");let o=rX(r);if(o!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(o),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let i=r.path;!n.absolutePath&&(!a||!a.absolutePath)&&(i=Ig(i)),o===void 0&&i[0]==="/"&&i[1]==="/"&&(i="/%2F"+i.slice(2)),s.push(i)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var dX=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ud(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},s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let a=t.match(dX);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(nX(n.host)===!1){let c=tX(n.host);n.host=c.host.toLowerCase(),s=c.isIPV6}else s=!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 o=k4(r.scheme||n.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)&&n.host&&(r.domainHost||o&&o.domainHost)&&s===!1&&sX(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(i){n.error=n.error||"Host's domain name can not be converted to ASCII: "+i}(!o||o&&!o.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)))),o&&o.parse&&o.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Jk={SCHEMES:iX,normalize:oX,resolve:aX,resolveComponent:T4,equal:cX,serialize:fc,parse:ud};Lb.exports=Jk;Lb.exports.default=Jk;Lb.exports.fastUri=Jk});var R4=Ee(Zk=>{"use strict";w();Object.defineProperty(Zk,"__esModule",{value:!0});var A4=I4();A4.code='require("ajv/dist/runtime/uri").default';Zk.default=A4});var N4=Ee(Ts=>{"use strict";w();Object.defineProperty(Ts,"__esModule",{value:!0});Ts.CodeGen=Ts.Name=Ts.nil=Ts.stringify=Ts.str=Ts._=Ts.KeywordCxt=void 0;var uX=_g();Object.defineProperty(Ts,"KeywordCxt",{enumerable:!0,get:function(){return uX.KeywordCxt}});var xh=kt();Object.defineProperty(Ts,"_",{enumerable:!0,get:function(){return xh._}});Object.defineProperty(Ts,"str",{enumerable:!0,get:function(){return xh.str}});Object.defineProperty(Ts,"stringify",{enumerable:!0,get:function(){return xh.stringify}});Object.defineProperty(Ts,"nil",{enumerable:!0,get:function(){return xh.nil}});Object.defineProperty(Ts,"Name",{enumerable:!0,get:function(){return xh.Name}});Object.defineProperty(Ts,"CodeGen",{enumerable:!0,get:function(){return xh.CodeGen}});var lX=Mb(),M4=kg(),fX=_k(),Ag=Tg(),pX=kt(),Rg=xg(),Kb=Pg(),Qk=Ut(),D4=y4(),hX=R4(),O4=(t,e)=>new RegExp(t,e);O4.code="new RegExp";var mX=["removeAdditional","useDefaults","coerceTypes"],yX=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),gX={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."},wX={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},C4=200;function vX(t){var e,r,n,s,a,o,i,c,u,d,l,f,h,p,m,y,S,v,E,k,A,D,B,j,F;let q=t.strict,N=(e=t.code)===null||e===void 0?void 0:e.optimize,W=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:O4,R=(s=t.uriResolver)!==null&&s!==void 0?s:hX.default;return{strictSchema:(o=(a=t.strictSchema)!==null&&a!==void 0?a:q)!==null&&o!==void 0?o:!0,strictNumbers:(c=(i=t.strictNumbers)!==null&&i!==void 0?i:q)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:q)!==null&&d!==void 0?d:"log",strictTuples:(f=(l=t.strictTuples)!==null&&l!==void 0?l:q)!==null&&f!==void 0?f:"log",strictRequired:(p=(h=t.strictRequired)!==null&&h!==void 0?h:q)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:W,regExp:ee}:{optimize:W,regExp:ee},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:C4,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:C4,meta:(S=t.meta)!==null&&S!==void 0?S:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(E=t.inlineRefs)!==null&&E!==void 0?E:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(A=t.addUsedSchema)!==null&&A!==void 0?A:!0,validateSchema:(D=t.validateSchema)!==null&&D!==void 0?D:!0,validateFormats:(B=t.validateFormats)!==null&&B!==void 0?B:!0,unicodeRegExp:(j=t.unicodeRegExp)!==null&&j!==void 0?j:!0,int32range:(F=t.int32range)!==null&&F!==void 0?F:!0,uriResolver:R}}var Dg=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...vX(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new pX.ValueScope({scope:{},prefixes:yX,es5:r,lines:n}),this.logger=_X(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,fX.getRules)(),j4.call(this,gX,e,"NOT SUPPORTED"),j4.call(this,wX,e,"DEPRECATED","warn"),this._metaOpts=SX.call(this),e.formats&&PX.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&xX.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),bX.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=D4;n==="id"&&(s={...D4},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[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 s=n(r);return"$async"in n||(this.errors=n.errors),s}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 s.call(this,e,r);async function s(d,l){await a.call(this,d.$schema);let f=this._addSchema(d,l);return f.validate||o.call(this,f)}async function a(d){d&&!this.getSchema(d)&&await s.call(this,{$ref:d},!0)}async function o(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof M4.default))throw l;return i.call(this,l),await c.call(this,l.missingSchema),o.call(this,d)}}function i({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await a.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,n,s);return this}let a;if(typeof e=="object"){let{schemaId:o}=this.opts;if(a=e[o],a!==void 0&&typeof a!="string")throw new Error(`schema ${o} must be string`)}return r=(0,Rg.normalizeId)(r||a),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!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 s=this.validate(n,e);if(!s&&r){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return s}getSchema(e){let r;for(;typeof(r=$4.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Ag.SchemaEnv({schema:{},schemaId:n});if(r=Ag.resolveSchema.call(this,s,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=$4.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,Rg.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(TX.call(this,n,r),!r)return(0,Qk.eachItem)(n,a=>Yk.call(this,a)),this;AX.call(this,r);let s={...r,type:(0,Kb.getJSONTypes)(r.type),schemaType:(0,Kb.getJSONTypes)(r.schemaType)};return(0,Qk.eachItem)(n,s.type.length===0?a=>Yk.call(this,a,s):a=>s.type.forEach(o=>Yk.call(this,a,s,o))),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 s=n.rules.findIndex(a=>a.keyword===e);s>=0&&n.rules.splice(s,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(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,a)=>s+r+a)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let a=s.split("/").slice(1),o=e;for(let i of a)o=o[i];for(let i in n){let c=n[i];if(typeof c!="object")continue;let{$data:u}=c.definition,d=o[i];u&&d&&(o[i]=B4(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,a=this.opts.addUsedSchema){let o,{schemaId:i}=this.opts;if(typeof e=="object")o=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Rg.normalizeId)(o||n);let u=Rg.getSchemaRefs.call(this,e,n);return c=new Ag.SchemaEnv({schema:e,schemaId:i,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),a&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Ag.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{Ag.compileSchema.call(this,e)}finally{this.opts=r}}};Dg.ValidationError=lX.default;Dg.MissingRefError=M4.default;Ts.default=Dg;function j4(t,e,r,n="error"){for(let s in t){let a=s;a in e&&this.logger[n](`${r}: option ${s}. ${t[a]}`)}}function $4(t){return t=(0,Rg.normalizeId)(t),this.schemas[t]||this.refs[t]}function bX(){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 PX(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function xX(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 SX(){let t={...this.opts};for(let e of mX)delete t[e];return t}var EX={log(){},warn(){},error(){}};function _X(t){if(t===!1)return EX;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 kX=/^[a-z_$][a-z0-9_$:-]*$/i;function TX(t,e){let{RULES:r}=this;if((0,Qk.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!kX.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 Yk(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,o=s?a.post:a.rules.find(({type:c})=>c===r);if(o||(o={type:r,rules:[]},a.rules.push(o)),a.keywords[t]=!0,!e)return;let i={keyword:t,definition:{...e,type:(0,Kb.getJSONTypes)(e.type),schemaType:(0,Kb.getJSONTypes)(e.schemaType)}};e.before?IX.call(this,o,i,e.before):o.rules.push(i),a.all[t]=i,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function IX(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function AX(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=B4(e)),t.validateSchema=this.compile(e,!0))}var RX={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function B4(t){return{anyOf:[t,RX]}}});var U4=Ee(Xk=>{"use strict";w();Object.defineProperty(Xk,"__esModule",{value:!0});var DX={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xk.default=DX});var Fb=Ee(df=>{"use strict";w();Object.defineProperty(df,"__esModule",{value:!0});df.callRef=df.getValidate=void 0;var CX=kg(),L4=$o(),Oi=kt(),Sh=jo(),K4=Tg(),zb=Ut(),jX={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:a,validateName:o,opts:i,self:c}=n,{root:u}=a;if((r==="#"||r==="#/")&&s===u.baseId)return l();let d=K4.resolveRef.call(c,u,s,r);if(d===void 0)throw new CX.default(n.opts.uriResolver,s,r);if(d instanceof K4.SchemaEnv)return f(d);return h(d);function l(){if(a===u)return qb(t,o,a,a.$async);let p=e.scopeValue("root",{ref:u});return qb(t,(0,Oi._)`${p}.validate`,u,u.$async)}function f(p){let m=z4(t,p);qb(t,m,p,p.$async)}function h(p){let m=e.scopeValue("schema",i.code.source===!0?{ref:p,code:(0,Oi.stringify)(p)}:{ref:p}),y=e.name("valid"),S=t.subschema({schema:p,dataTypes:[],schemaPath:Oi.nil,topSchemaRef:m,errSchemaPath:r},y);t.mergeEvaluated(S),t.ok(y)}}};function z4(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Oi._)`${r.scopeValue("wrapper",{ref:e})}.validate`}df.getValidate=z4;function qb(t,e,r,n){let{gen:s,it:a}=t,{allErrors:o,schemaEnv:i,opts:c}=a,u=c.passContext?Sh.default.this:Oi.nil;n?d():l();function d(){if(!i.$async)throw new Error("async schema referenced by sync schema");let p=s.let("valid");s.try(()=>{s.code((0,Oi._)`await ${(0,L4.callValidateCode)(t,e,u)}`),h(e),o||s.assign(p,!0)},m=>{s.if((0,Oi._)`!(${m} instanceof ${a.ValidationError})`,()=>s.throw(m)),f(m),o||s.assign(p,!1)}),t.ok(p)}function l(){t.result((0,L4.callValidateCode)(t,e,u),()=>h(e),()=>f(e))}function f(p){let m=(0,Oi._)`${p}.errors`;s.assign(Sh.default.vErrors,(0,Oi._)`${Sh.default.vErrors} === null ? ${m} : ${Sh.default.vErrors}.concat(${m})`),s.assign(Sh.default.errors,(0,Oi._)`${Sh.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=zb.mergeEvaluated.props(s,y.props,a.props));else{let S=s.var("props",(0,Oi._)`${p}.evaluated.props`);a.props=zb.mergeEvaluated.props(s,S,a.props,Oi.Name)}if(a.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(a.items=zb.mergeEvaluated.items(s,y.items,a.items));else{let S=s.var("items",(0,Oi._)`${p}.evaluated.items`);a.items=zb.mergeEvaluated.items(s,S,a.items,Oi.Name)}}}df.callRef=qb;df.default=jX});var q4=Ee(eT=>{"use strict";w();Object.defineProperty(eT,"__esModule",{value:!0});var $X=U4(),MX=Fb(),OX=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",$X.default,MX.default];eT.default=OX});var F4=Ee(tT=>{"use strict";w();Object.defineProperty(tT,"__esModule",{value:!0});var Gb=kt(),ku=Gb.operators,Wb={maximum:{okStr:"<=",ok:ku.LTE,fail:ku.GT},minimum:{okStr:">=",ok:ku.GTE,fail:ku.LT},exclusiveMaximum:{okStr:"<",ok:ku.LT,fail:ku.GTE},exclusiveMinimum:{okStr:">",ok:ku.GT,fail:ku.LTE}},BX={message:({keyword:t,schemaCode:e})=>(0,Gb.str)`must be ${Wb[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Gb._)`{comparison: ${Wb[t].okStr}, limit: ${e}}`},NX={keyword:Object.keys(Wb),type:"number",schemaType:"number",$data:!0,error:BX,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Gb._)`${r} ${Wb[e].fail} ${n} || isNaN(${r})`)}};tT.default=NX});var G4=Ee(rT=>{"use strict";w();Object.defineProperty(rT,"__esModule",{value:!0});var Cg=kt(),UX={message:({schemaCode:t})=>(0,Cg.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Cg._)`{multipleOf: ${t}}`},LX={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:UX,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,a=s.opts.multipleOfPrecision,o=e.let("res"),i=a?(0,Cg._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${a}`:(0,Cg._)`${o} !== parseInt(${o})`;t.fail$data((0,Cg._)`(${n} === 0 || (${o} = ${r}/${n}, ${i}))`)}};rT.default=LX});var W4=Ee(nT=>{"use strict";w();Object.defineProperty(nT,"__esModule",{value:!0});var uf=kt(),KX=Ut(),zX=i2(),qX={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,uf.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,uf._)`{limit: ${t}}`},FX={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:qX,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,a=e==="maxLength"?uf.operators.GT:uf.operators.LT,o=s.opts.unicode===!1?(0,uf._)`${r}.length`:(0,uf._)`${(0,KX.useFunc)(t.gen,zX.default)}(${r})`;t.fail$data((0,uf._)`${o} ${a} ${n}`)}};nT.default=FX});var V4=Ee(sT=>{"use strict";w();Object.defineProperty(sT,"__esModule",{value:!0});var GX=$o(),WX=Ut(),Eh=kt(),VX={message:({schemaCode:t})=>(0,Eh.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Eh._)`{pattern: ${t}}`},HX={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:VX,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:a,it:o}=t,i=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,u=c.code==="new RegExp"?(0,Eh._)`new RegExp`:(0,WX.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Eh._)`${u}(${a}, ${i}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Eh._)`!${d}`)}else{let c=(0,GX.usePattern)(t,s);t.fail$data((0,Eh._)`!${c}.test(${r})`)}}};sT.default=HX});var H4=Ee(iT=>{"use strict";w();Object.defineProperty(iT,"__esModule",{value:!0});var jg=kt(),JX={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,jg.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,jg._)`{limit: ${t}}`},ZX={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:JX,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?jg.operators.GT:jg.operators.LT;t.fail$data((0,jg._)`Object.keys(${r}).length ${s} ${n}`)}};iT.default=ZX});var J4=Ee(oT=>{"use strict";w();Object.defineProperty(oT,"__esModule",{value:!0});var $g=$o(),Mg=kt(),YX=Ut(),QX={message:({params:{missingProperty:t}})=>(0,Mg.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Mg._)`{missingProperty: ${t}}`},XX={keyword:"required",type:"object",schemaType:"array",$data:!0,error:QX,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:a,it:o}=t,{opts:i}=o;if(!a&&r.length===0)return;let c=r.length>=i.loopRequired;if(o.allErrors?u():d(),i.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=o.schemaEnv.baseId+o.errSchemaPath,S=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,YX.checkStrictMode)(o,S,o.opts.strictRequired)}}function u(){if(c||a)t.block$data(Mg.nil,l);else for(let h of r)(0,$g.checkReportMissingProp)(t,h)}function d(){let h=e.let("missing");if(c||a){let p=e.let("valid",!0);t.block$data(p,()=>f(h,p)),t.ok(p)}else e.if((0,$g.checkMissingProp)(t,r,h)),(0,$g.reportMissingProp)(t,h),e.else()}function l(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,$g.noPropertyInData)(e,s,h,i.ownProperties),()=>t.error())})}function f(h,p){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(p,(0,$g.propertyInData)(e,s,h,i.ownProperties)),e.if((0,Mg.not)(p),()=>{t.error(),e.break()})},Mg.nil)}}};oT.default=XX});var Z4=Ee(aT=>{"use strict";w();Object.defineProperty(aT,"__esModule",{value:!0});var Og=kt(),eee={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Og.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Og._)`{limit: ${t}}`},tee={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:eee,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Og.operators.GT:Og.operators.LT;t.fail$data((0,Og._)`${r}.length ${s} ${n}`)}};aT.default=tee});var Vb=Ee(cT=>{"use strict";w();Object.defineProperty(cT,"__esModule",{value:!0});var Y4=jk();Y4.code='require("ajv/dist/runtime/equal").default';cT.default=Y4});var Q4=Ee(uT=>{"use strict";w();Object.defineProperty(uT,"__esModule",{value:!0});var dT=Pg(),Is=kt(),ree=Ut(),nee=Vb(),see={message:({params:{i:t,j:e}})=>(0,Is.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Is._)`{i: ${t}, j: ${e}}`},iee={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:see,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:a,schemaCode:o,it:i}=t;if(!n&&!s)return;let c=e.let("valid"),u=a.items?(0,dT.getSchemaTypes)(a.items):[];t.block$data(c,d,(0,Is._)`${o} === false`),t.ok(c);function d(){let p=e.let("i",(0,Is._)`${r}.length`),m=e.let("j");t.setParams({i:p,j:m}),e.assign(c,!0),e.if((0,Is._)`${p} > 1`,()=>(l()?f:h)(p,m))}function l(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,m){let y=e.name("item"),S=(0,dT.checkDataTypes)(u,y,i.opts.strictNumbers,dT.DataType.Wrong),v=e.const("indices",(0,Is._)`{}`);e.for((0,Is._)`;${p}--;`,()=>{e.let(y,(0,Is._)`${r}[${p}]`),e.if(S,(0,Is._)`continue`),u.length>1&&e.if((0,Is._)`typeof ${y} == "string"`,(0,Is._)`${y} += "_"`),e.if((0,Is._)`typeof ${v}[${y}] == "number"`,()=>{e.assign(m,(0,Is._)`${v}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Is._)`${v}[${y}] = ${p}`)})}function h(p,m){let y=(0,ree.useFunc)(e,nee.default),S=e.name("outer");e.label(S).for((0,Is._)`;${p}--;`,()=>e.for((0,Is._)`${m} = ${p}; ${m}--;`,()=>e.if((0,Is._)`${y}(${r}[${p}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(S)})))}}};uT.default=iee});var X4=Ee(fT=>{"use strict";w();Object.defineProperty(fT,"__esModule",{value:!0});var lT=kt(),oee=Ut(),aee=Vb(),cee={message:"must be equal to constant",params:({schemaCode:t})=>(0,lT._)`{allowedValue: ${t}}`},dee={keyword:"const",$data:!0,error:cee,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:a}=t;n||a&&typeof a=="object"?t.fail$data((0,lT._)`!${(0,oee.useFunc)(e,aee.default)}(${r}, ${s})`):t.fail((0,lT._)`${a} !== ${r}`)}};fT.default=dee});var eB=Ee(pT=>{"use strict";w();Object.defineProperty(pT,"__esModule",{value:!0});var Bg=kt(),uee=Ut(),lee=Vb(),fee={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Bg._)`{allowedValues: ${t}}`},pee={keyword:"enum",schemaType:"array",$data:!0,error:fee,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:a,it:o}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let i=s.length>=o.opts.loopEnum,c,u=()=>c??(c=(0,uee.useFunc)(e,lee.default)),d;if(i||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let h=e.const("vSchema",a);d=(0,Bg.or)(...s.map((p,m)=>f(h,m)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",a,h=>e.if((0,Bg._)`${u()}(${r}, ${h})`,()=>e.assign(d,!0).break()))}function f(h,p){let m=s[p];return typeof m=="object"&&m!==null?(0,Bg._)`${u()}(${r}, ${h}[${p}])`:(0,Bg._)`${r} === ${m}`}}};pT.default=pee});var tB=Ee(hT=>{"use strict";w();Object.defineProperty(hT,"__esModule",{value:!0});var hee=F4(),mee=G4(),yee=W4(),gee=V4(),wee=H4(),vee=J4(),bee=Z4(),Pee=Q4(),xee=X4(),See=eB(),Eee=[hee.default,mee.default,yee.default,gee.default,wee.default,vee.default,bee.default,Pee.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},xee.default,See.default];hT.default=Eee});var yT=Ee(Ng=>{"use strict";w();Object.defineProperty(Ng,"__esModule",{value:!0});Ng.validateAdditionalItems=void 0;var lf=kt(),mT=Ut(),_ee={message:({params:{len:t}})=>(0,lf.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,lf._)`{limit: ${t}}`},kee={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:_ee,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,mT.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}rB(t,n)}};function rB(t,e){let{gen:r,schema:n,data:s,keyword:a,it:o}=t;o.items=!0;let i=r.const("len",(0,lf._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,lf._)`${i} <= ${e.length}`);else if(typeof n=="object"&&!(0,mT.alwaysValidSchema)(o,n)){let u=r.var("valid",(0,lf._)`${i} <= ${e.length}`);r.if((0,lf.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,i,d=>{t.subschema({keyword:a,dataProp:d,dataPropType:mT.Type.Num},u),o.allErrors||r.if((0,lf.not)(u),()=>r.break())})}}Ng.validateAdditionalItems=rB;Ng.default=kee});var gT=Ee(Ug=>{"use strict";w();Object.defineProperty(Ug,"__esModule",{value:!0});Ug.validateTuple=void 0;var nB=kt(),Hb=Ut(),Tee=$o(),Iee={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return sB(t,"additionalItems",e);r.items=!0,!(0,Hb.alwaysValidSchema)(r,e)&&t.ok((0,Tee.validateArray)(t))}};function sB(t,e,r=t.schema){let{gen:n,parentSchema:s,data:a,keyword:o,it:i}=t;d(s),i.opts.unevaluated&&r.length&&i.items!==!0&&(i.items=Hb.mergeEvaluated.items(n,r.length,i.items));let c=n.name("valid"),u=n.const("len",(0,nB._)`${a}.length`);r.forEach((l,f)=>{(0,Hb.alwaysValidSchema)(i,l)||(n.if((0,nB._)`${u} > ${f}`,()=>t.subschema({keyword:o,schemaProp:f,dataProp:f},c)),t.ok(c))});function d(l){let{opts:f,errSchemaPath:h}=i,p=r.length,m=p===l.minItems&&(p===l.maxItems||l[e]===!1);if(f.strictTuples&&!m){let y=`"${o}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,Hb.checkStrictMode)(i,y,f.strictTuples)}}}Ug.validateTuple=sB;Ug.default=Iee});var iB=Ee(wT=>{"use strict";w();Object.defineProperty(wT,"__esModule",{value:!0});var Aee=gT(),Ree={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Aee.validateTuple)(t,"items")};wT.default=Ree});var aB=Ee(vT=>{"use strict";w();Object.defineProperty(vT,"__esModule",{value:!0});var oB=kt(),Dee=Ut(),Cee=$o(),jee=yT(),$ee={message:({params:{len:t}})=>(0,oB.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,oB._)`{limit: ${t}}`},Mee={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:$ee,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,Dee.alwaysValidSchema)(n,e)&&(s?(0,jee.validateAdditionalItems)(t,s):t.ok((0,Cee.validateArray)(t)))}};vT.default=Mee});var cB=Ee(bT=>{"use strict";w();Object.defineProperty(bT,"__esModule",{value:!0});var Oo=kt(),Jb=Ut(),Oee={message:({params:{min:t,max:e}})=>e===void 0?(0,Oo.str)`must contain at least ${t} valid item(s)`:(0,Oo.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Oo._)`{minContains: ${t}}`:(0,Oo._)`{minContains: ${t}, maxContains: ${e}}`},Bee={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Oee,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:a}=t,o,i,{minContains:c,maxContains:u}=n;a.opts.next?(o=c===void 0?1:c,i=u):o=1;let d=e.const("len",(0,Oo._)`${s}.length`);if(t.setParams({min:o,max:i}),i===void 0&&o===0){(0,Jb.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(i!==void 0&&o>i){(0,Jb.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Jb.alwaysValidSchema)(a,r)){let m=(0,Oo._)`${d} >= ${o}`;i!==void 0&&(m=(0,Oo._)`${m} && ${d} <= ${i}`),t.pass(m);return}a.items=!0;let l=e.name("valid");i===void 0&&o===1?h(l,()=>e.if(l,()=>e.break())):o===0?(e.let(l,!0),i!==void 0&&e.if((0,Oo._)`${s}.length > 0`,f)):(e.let(l,!1),f()),t.result(l,()=>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,d,S=>{t.subschema({keyword:"contains",dataProp:S,dataPropType:Jb.Type.Num,compositeRule:!0},m),y()})}function p(m){e.code((0,Oo._)`${m}++`),i===void 0?e.if((0,Oo._)`${m} >= ${o}`,()=>e.assign(l,!0).break()):(e.if((0,Oo._)`${m} > ${i}`,()=>e.assign(l,!1).break()),o===1?e.assign(l,!0):e.if((0,Oo._)`${m} >= ${o}`,()=>e.assign(l,!0)))}}};bT.default=Bee});var Zb=Ee(pc=>{"use strict";w();Object.defineProperty(pc,"__esModule",{value:!0});pc.validateSchemaDeps=pc.validatePropertyDeps=pc.error=void 0;var PT=kt(),Nee=Ut(),Lg=$o();pc.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,PT.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,PT._)`{property: ${t},
8
8
  missingProperty: ${n},
9
9
  depsCount: ${e},
10
- deps: ${r}}`};var Uee={keyword:"dependencies",type:"object",schemaType:"object",error:pc.error,code(t){let[e,r]=Lee(t);dB(t,e),uB(t,r)}};function Lee({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function dB(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let a=r.let("missing");for(let o in e){let i=e[o];if(i.length===0)continue;let c=(0,Lg.propertyInData)(r,n,o,s.opts.ownProperties);t.setParams({property:o,depsCount:i.length,deps:i.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of i)(0,Lg.checkReportMissingProp)(t,u)}):(r.if((0,PT._)`${c} && (${(0,Lg.checkMissingProp)(t,i,a)})`),(0,Lg.reportMissingProp)(t,a),r.else())}}pc.validatePropertyDeps=dB;function uB(t,e=t.schema){let{gen:r,data:n,keyword:s,it:a}=t,o=r.name("valid");for(let i in e)(0,Nee.alwaysValidSchema)(a,e[i])||(r.if((0,Lg.propertyInData)(r,n,i,a.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:i},o);t.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),t.ok(o))}pc.validateSchemaDeps=uB;pc.default=Uee});var fB=Ee(xT=>{"use strict";w();Object.defineProperty(xT,"__esModule",{value:!0});var lB=kt(),Kee=Ut(),zee={message:"property name must be valid",params:({params:t})=>(0,lB._)`{propertyName: ${t.propertyName}}`},qee={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:zee,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,Kee.alwaysValidSchema)(s,r))return;let a=e.name("valid");e.forIn("key",n,o=>{t.setParams({propertyName:o}),t.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},a),e.if((0,lB.not)(a),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(a)}};xT.default=qee});var ET=Ee(ST=>{"use strict";w();Object.defineProperty(ST,"__esModule",{value:!0});var Yb=$o(),Ea=kt(),Fee=jo(),Qb=Ut(),Gee={message:"must NOT have additional properties",params:({params:t})=>(0,Ea._)`{additionalProperty: ${t.additionalProperty}}`},Wee={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Gee,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:a,it:o}=t;if(!a)throw new Error("ajv implementation error");let{allErrors:i,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Qb.alwaysValidSchema)(o,r))return;let u=(0,Yb.allSchemaProperties)(n.properties),d=(0,Yb.allSchemaProperties)(n.patternProperties);l(),t.ok((0,Ea._)`${a} === ${Fee.default.errors}`);function l(){e.forIn("key",s,y=>{!u.length&&!d.length?p(y):e.if(f(y),()=>p(y))})}function f(y){let S;if(u.length>8){let v=(0,Qb.schemaRefOrVal)(o,n.properties,"properties");S=(0,Yb.isOwnProperty)(e,v,y)}else u.length?S=(0,Ea.or)(...u.map(v=>(0,Ea._)`${y} === ${v}`)):S=Ea.nil;return d.length&&(S=(0,Ea.or)(S,...d.map(v=>(0,Ea._)`${(0,Yb.usePattern)(t,v)}.test(${y})`))),(0,Ea.not)(S)}function h(y){e.code((0,Ea._)`delete ${s}[${y}]`)}function p(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),i||e.break();return}if(typeof r=="object"&&!(0,Qb.alwaysValidSchema)(o,r)){let S=e.name("valid");c.removeAdditional==="failing"?(m(y,S,!1),e.if((0,Ea.not)(S),()=>{t.reset(),h(y)})):(m(y,S),i||e.if((0,Ea.not)(S),()=>e.break()))}}function m(y,S,v){let E={keyword:"additionalProperties",dataProp:y,dataPropType:Qb.Type.Str};v===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(E,S)}}};ST.default=Wee});var mB=Ee(kT=>{"use strict";w();Object.defineProperty(kT,"__esModule",{value:!0});var Vee=_g(),pB=$o(),_T=Ut(),hB=ET(),Hee={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:a}=t;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&hB.default.code(new Vee.KeywordCxt(a,hB.default,"additionalProperties"));let o=(0,pB.allSchemaProperties)(r);for(let l of o)a.definedProperties.add(l);a.opts.unevaluated&&o.length&&a.props!==!0&&(a.props=_T.mergeEvaluated.props(e,(0,_T.toHash)(o),a.props));let i=o.filter(l=>!(0,_T.alwaysValidSchema)(a,r[l]));if(i.length===0)return;let c=e.name("valid");for(let l of i)u(l)?d(l):(e.if((0,pB.propertyInData)(e,s,l,a.opts.ownProperties)),d(l),a.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return a.opts.useDefaults&&!a.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};kT.default=Hee});var vB=Ee(TT=>{"use strict";w();Object.defineProperty(TT,"__esModule",{value:!0});var yB=$o(),Xb=kt(),gB=Ut(),wB=Ut(),Jee={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:a}=t,{opts:o}=a,i=(0,yB.allSchemaProperties)(r),c=i.filter(m=>(0,gB.alwaysValidSchema)(a,r[m]));if(i.length===0||c.length===i.length&&(!a.opts.unevaluated||a.props===!0))return;let u=o.strictSchema&&!o.allowMatchingProperties&&s.properties,d=e.name("valid");a.props!==!0&&!(a.props instanceof Xb.Name)&&(a.props=(0,wB.evaluatedPropsToName)(e,a.props));let{props:l}=a;f();function f(){for(let m of i)u&&h(m),a.allErrors?p(m):(e.var(d,!0),p(m),e.if(d))}function h(m){for(let y in u)new RegExp(m).test(y)&&(0,gB.checkStrictMode)(a,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,y=>{e.if((0,Xb._)`${(0,yB.usePattern)(t,m)}.test(${y})`,()=>{let S=c.includes(m);S||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:wB.Type.Str},d),a.opts.unevaluated&&l!==!0?e.assign((0,Xb._)`${l}[${y}]`,!0):!S&&!a.allErrors&&e.if((0,Xb.not)(d),()=>e.break())})})}}};TT.default=Jee});var bB=Ee(IT=>{"use strict";w();Object.defineProperty(IT,"__esModule",{value:!0});var Zee=Ut(),Yee={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Zee.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};IT.default=Yee});var PB=Ee(AT=>{"use strict";w();Object.defineProperty(AT,"__esModule",{value:!0});var Qee=$o(),Xee={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Qee.validateUnion,error:{message:"must match a schema in anyOf"}};AT.default=Xee});var xB=Ee(RT=>{"use strict";w();Object.defineProperty(RT,"__esModule",{value:!0});var e1=kt(),ete=Ut(),tte={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,e1._)`{passingSchemas: ${t.passing}}`},rte={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:tte,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let a=r,o=e.let("valid",!1),i=e.let("passing",null),c=e.name("_valid");t.setParams({passing:i}),e.block(u),t.result(o,()=>t.reset(),()=>t.error(!0));function u(){a.forEach((d,l)=>{let f;(0,ete.alwaysValidSchema)(s,d)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,e1._)`${c} && ${o}`).assign(o,!1).assign(i,(0,e1._)`[${i}, ${l}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(i,l),f&&t.mergeEvaluated(f,e1.Name)})})}}};RT.default=rte});var SB=Ee(DT=>{"use strict";w();Object.defineProperty(DT,"__esModule",{value:!0});var nte=Ut(),ste={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 s=e.name("valid");r.forEach((a,o)=>{if((0,nte.alwaysValidSchema)(n,a))return;let i=t.subschema({keyword:"allOf",schemaProp:o},s);t.ok(s),t.mergeEvaluated(i)})}};DT.default=ste});var kB=Ee(CT=>{"use strict";w();Object.defineProperty(CT,"__esModule",{value:!0});var t1=kt(),_B=Ut(),ite={message:({params:t})=>(0,t1.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,t1._)`{failingKeyword: ${t.ifClause}}`},ote={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ite,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,_B.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=EB(n,"then"),a=EB(n,"else");if(!s&&!a)return;let o=e.let("valid",!0),i=e.name("_valid");if(c(),t.reset(),s&&a){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(i,u("then",d),u("else",d))}else s?e.if(i,u("then")):e.if((0,t1.not)(i),u("else"));t.pass(o,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);t.mergeEvaluated(d)}function u(d,l){return()=>{let f=t.subschema({keyword:d},i);e.assign(o,i),t.mergeValidEvaluated(f,o),l?e.assign(l,(0,t1._)`${d}`):t.setParams({ifClause:d})}}}};function EB(t,e){let r=t.schema[e];return r!==void 0&&!(0,_B.alwaysValidSchema)(t,r)}CT.default=ote});var TB=Ee(jT=>{"use strict";w();Object.defineProperty(jT,"__esModule",{value:!0});var ate=Ut(),cte={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,ate.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};jT.default=cte});var IB=Ee($T=>{"use strict";w();Object.defineProperty($T,"__esModule",{value:!0});var dte=yT(),ute=iB(),lte=gT(),fte=aB(),pte=cB(),hte=Zb(),mte=fB(),yte=ET(),gte=mB(),wte=vB(),vte=bB(),bte=PB(),Pte=xB(),xte=SB(),Ste=kB(),Ete=TB();function _te(t=!1){let e=[vte.default,bte.default,Pte.default,xte.default,Ste.default,Ete.default,mte.default,yte.default,hte.default,gte.default,wte.default];return t?e.push(ute.default,fte.default):e.push(dte.default,lte.default),e.push(pte.default),e}$T.default=_te});var OT=Ee(Kg=>{"use strict";w();Object.defineProperty(Kg,"__esModule",{value:!0});Kg.dynamicAnchor=void 0;var MT=kt(),kte=jo(),AB=Tg(),Tte=Fb(),Ite={keyword:"$dynamicAnchor",schemaType:"string",code:t=>RB(t,t.schema)};function RB(t,e){let{gen:r,it:n}=t;n.schemaEnv.root.dynamicAnchors[e]=!0;let s=(0,MT._)`${kte.default.dynamicAnchors}${(0,MT.getProperty)(e)}`,a=n.errSchemaPath==="#"?n.validateName:Ate(t);r.if((0,MT._)`!${s}`,()=>r.assign(s,a))}Kg.dynamicAnchor=RB;function Ate(t){let{schemaEnv:e,schema:r,self:n}=t.it,{root:s,baseId:a,localRefs:o,meta:i}=e.root,{schemaId:c}=n.opts,u=new AB.SchemaEnv({schema:r,schemaId:c,root:s,baseId:a,localRefs:o,meta:i});return AB.compileSchema.call(n,u),(0,Tte.getValidate)(t,u)}Kg.default=Ite});var BT=Ee(zg=>{"use strict";w();Object.defineProperty(zg,"__esModule",{value:!0});zg.dynamicRef=void 0;var DB=kt(),Rte=jo(),CB=Fb(),Dte={keyword:"$dynamicRef",schemaType:"string",code:t=>jB(t,t.schema)};function jB(t,e){let{gen:r,keyword:n,it:s}=t;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let a=e.slice(1);if(s.allErrors)o();else{let c=r.let("valid",!1);o(c),t.ok(c)}function o(c){if(s.schemaEnv.root.dynamicAnchors[a]){let u=r.let("_v",(0,DB._)`${Rte.default.dynamicAnchors}${(0,DB.getProperty)(a)}`);r.if(u,i(u,c),i(s.validateName,c))}else i(s.validateName,c)()}function i(c,u){return u?()=>r.block(()=>{(0,CB.callRef)(t,c),r.let(u,!0)}):()=>(0,CB.callRef)(t,c)}}zg.dynamicRef=jB;zg.default=Dte});var $B=Ee(NT=>{"use strict";w();Object.defineProperty(NT,"__esModule",{value:!0});var Cte=OT(),jte=Ut(),$te={keyword:"$recursiveAnchor",schemaType:"boolean",code(t){t.schema?(0,Cte.dynamicAnchor)(t,""):(0,jte.checkStrictMode)(t.it,"$recursiveAnchor: false is ignored")}};NT.default=$te});var MB=Ee(UT=>{"use strict";w();Object.defineProperty(UT,"__esModule",{value:!0});var Mte=BT(),Ote={keyword:"$recursiveRef",schemaType:"string",code:t=>(0,Mte.dynamicRef)(t,t.schema)};UT.default=Ote});var OB=Ee(LT=>{"use strict";w();Object.defineProperty(LT,"__esModule",{value:!0});var Bte=OT(),Nte=BT(),Ute=$B(),Lte=MB(),Kte=[Bte.default,Nte.default,Ute.default,Lte.default];LT.default=Kte});var NB=Ee(KT=>{"use strict";w();Object.defineProperty(KT,"__esModule",{value:!0});var BB=Zb(),zte={keyword:"dependentRequired",type:"object",schemaType:"object",error:BB.error,code:t=>(0,BB.validatePropertyDeps)(t)};KT.default=zte});var UB=Ee(zT=>{"use strict";w();Object.defineProperty(zT,"__esModule",{value:!0});var qte=Zb(),Fte={keyword:"dependentSchemas",type:"object",schemaType:"object",code:t=>(0,qte.validateSchemaDeps)(t)};zT.default=Fte});var LB=Ee(qT=>{"use strict";w();Object.defineProperty(qT,"__esModule",{value:!0});var Gte=Ut(),Wte={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:e,it:r}){e.contains===void 0&&(0,Gte.checkStrictMode)(r,`"${t}" without "contains" is ignored`)}};qT.default=Wte});var KB=Ee(FT=>{"use strict";w();Object.defineProperty(FT,"__esModule",{value:!0});var Vte=NB(),Hte=UB(),Jte=LB(),Zte=[Vte.default,Hte.default,Jte.default];FT.default=Zte});var qB=Ee(GT=>{"use strict";w();Object.defineProperty(GT,"__esModule",{value:!0});var Tu=kt(),zB=Ut(),Yte=jo(),Qte={message:"must NOT have unevaluated properties",params:({params:t})=>(0,Tu._)`{unevaluatedProperty: ${t.unevaluatedProperty}}`},Xte={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Qte,code(t){let{gen:e,schema:r,data:n,errsCount:s,it:a}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:o,props:i}=a;i instanceof Tu.Name?e.if((0,Tu._)`${i} !== true`,()=>e.forIn("key",n,l=>e.if(u(i,l),()=>c(l)))):i!==!0&&e.forIn("key",n,l=>i===void 0?c(l):e.if(d(i,l),()=>c(l))),a.props=!0,t.ok((0,Tu._)`${s} === ${Yte.default.errors}`);function c(l){if(r===!1){t.setParams({unevaluatedProperty:l}),t.error(),o||e.break();return}if(!(0,zB.alwaysValidSchema)(a,r)){let f=e.name("valid");t.subschema({keyword:"unevaluatedProperties",dataProp:l,dataPropType:zB.Type.Str},f),o||e.if((0,Tu.not)(f),()=>e.break())}}function u(l,f){return(0,Tu._)`!${l} || !${l}[${f}]`}function d(l,f){let h=[];for(let p in l)l[p]===!0&&h.push((0,Tu._)`${f} !== ${p}`);return(0,Tu.and)(...h)}}};GT.default=Xte});var GB=Ee(WT=>{"use strict";w();Object.defineProperty(WT,"__esModule",{value:!0});var ff=kt(),FB=Ut(),ere={message:({params:{len:t}})=>(0,ff.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ff._)`{limit: ${t}}`},tre={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:ere,code(t){let{gen:e,schema:r,data:n,it:s}=t,a=s.items||0;if(a===!0)return;let o=e.const("len",(0,ff._)`${n}.length`);if(r===!1)t.setParams({len:a}),t.fail((0,ff._)`${o} > ${a}`);else if(typeof r=="object"&&!(0,FB.alwaysValidSchema)(s,r)){let c=e.var("valid",(0,ff._)`${o} <= ${a}`);e.if((0,ff.not)(c),()=>i(c,a)),t.ok(c)}s.items=!0;function i(c,u){e.forRange("i",u,o,d=>{t.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:FB.Type.Num},c),s.allErrors||e.if((0,ff.not)(c),()=>e.break())})}}};WT.default=tre});var WB=Ee(VT=>{"use strict";w();Object.defineProperty(VT,"__esModule",{value:!0});var rre=qB(),nre=GB(),sre=[rre.default,nre.default];VT.default=sre});var VB=Ee(HT=>{"use strict";w();Object.defineProperty(HT,"__esModule",{value:!0});var Tn=kt(),ire={message:({schemaCode:t})=>(0,Tn.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Tn._)`{format: ${t}}`},ore={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:ire,code(t,e){let{gen:r,data:n,$data:s,schema:a,schemaCode:o,it:i}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=i;if(!c.validateFormats)return;s?f():h();function f(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,Tn._)`${p}[${o}]`),y=r.let("fType"),S=r.let("format");r.if((0,Tn._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,Tn._)`${m}.type || "string"`).assign(S,(0,Tn._)`${m}.validate`),()=>r.assign(y,(0,Tn._)`"string"`).assign(S,m)),t.fail$data((0,Tn.or)(v(),E()));function v(){return c.strictSchema===!1?Tn.nil:(0,Tn._)`${o} && !${S}`}function E(){let k=d.$async?(0,Tn._)`(${m}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,Tn._)`${S}(${n})`,A=(0,Tn._)`(typeof ${S} == "function" ? ${k} : ${S}.test(${n}))`;return(0,Tn._)`${S} && ${S} !== true && ${y} === ${e} && !${A}`}}function h(){let p=l.formats[a];if(!p){v();return}if(p===!0)return;let[m,y,S]=E(p);m===e&&t.pass(k());function v(){if(c.strictSchema===!1){l.logger.warn(A());return}throw new Error(A());function A(){return`unknown format "${a}" ignored in schema at path "${u}"`}}function E(A){let D=A instanceof RegExp?(0,Tn.regexpCode)(A):c.code.formats?(0,Tn._)`${c.code.formats}${(0,Tn.getProperty)(a)}`:void 0,B=r.scopeValue("formats",{key:a,ref:A,code:D});return typeof A=="object"&&!(A instanceof RegExp)?[A.type||"string",A.validate,(0,Tn._)`${B}.validate`]:["string",A,B]}function k(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Tn._)`await ${S}(${n})`}return typeof y=="function"?(0,Tn._)`${S}(${n})`:(0,Tn._)`${S}.test(${n})`}}}};HT.default=ore});var HB=Ee(JT=>{"use strict";w();Object.defineProperty(JT,"__esModule",{value:!0});var are=VB(),cre=[are.default];JT.default=cre});var JB=Ee(_h=>{"use strict";w();Object.defineProperty(_h,"__esModule",{value:!0});_h.contentVocabulary=_h.metadataVocabulary=void 0;_h.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];_h.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var YB=Ee(ZT=>{"use strict";w();Object.defineProperty(ZT,"__esModule",{value:!0});var dre=q4(),ure=tB(),lre=IB(),fre=OB(),pre=KB(),hre=WB(),mre=HB(),ZB=JB(),yre=[fre.default,dre.default,ure.default,(0,lre.default)(!0),mre.default,ZB.metadataVocabulary,ZB.contentVocabulary,pre.default,hre.default];ZT.default=yre});var XB=Ee(r1=>{"use strict";w();Object.defineProperty(r1,"__esModule",{value:!0});r1.DiscrError=void 0;var QB;(function(t){t.Tag="tag",t.Mapping="mapping"})(QB||(r1.DiscrError=QB={}))});var tN=Ee(QT=>{"use strict";w();Object.defineProperty(QT,"__esModule",{value:!0});var kh=kt(),YT=XB(),eN=Tg(),gre=kg(),wre=Ut(),vre={message:({params:{discrError:t,tagName:e}})=>t===YT.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,kh._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},bre={keyword:"discriminator",type:"object",schemaType:"object",error:vre,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:a}=t,{oneOf:o}=s;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let i=n.propertyName;if(typeof i!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,kh._)`${r}${(0,kh.getProperty)(i)}`);e.if((0,kh._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:YT.DiscrError.Tag,tag:u,tagName:i})),t.ok(c);function d(){let h=f();e.if(!1);for(let p in h)e.elseIf((0,kh._)`${u} === ${p}`),e.assign(c,l(h[p]));e.else(),t.error(!1,{discrError:YT.DiscrError.Mapping,tag:u,tagName:i}),e.endIf()}function l(h){let p=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:h},p);return t.mergeEvaluated(m,kh.Name),p}function f(){var h;let p={},m=S(s),y=!0;for(let k=0;k<o.length;k++){let A=o[k];if(A?.$ref&&!(0,wre.schemaHasRulesButRef)(A,a.self.RULES)){let B=A.$ref;if(A=eN.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,B),A instanceof eN.SchemaEnv&&(A=A.schema),A===void 0)throw new gre.default(a.opts.uriResolver,a.baseId,B)}let D=(h=A?.properties)===null||h===void 0?void 0:h[i];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);y=y&&(m||S(A)),v(D,k)}if(!y)throw new Error(`discriminator: "${i}" must be required`);return p;function S({required:k}){return Array.isArray(k)&&k.includes(i)}function v(k,A){if(k.const)E(k.const,A);else if(k.enum)for(let D of k.enum)E(D,A);else throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`)}function E(k,A){if(typeof k!="string"||k in p)throw new Error(`discriminator: "${i}" values must be unique strings`);p[k]=A}}}};QT.default=bre});var rN=Ee((MDe,Pre)=>{Pre.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 nN=Ee((ODe,xre)=>{xre.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 sN=Ee((BDe,Sre)=>{Sre.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 iN=Ee((NDe,Ere)=>{Ere.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 oN=Ee((UDe,_re)=>{_re.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 aN=Ee((LDe,kre)=>{kre.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 cN=Ee((KDe,Tre)=>{Tre.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 dN=Ee((zDe,Ire)=>{Ire.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 uN=Ee(XT=>{"use strict";w();Object.defineProperty(XT,"__esModule",{value:!0});var Are=rN(),Rre=nN(),Dre=sN(),Cre=iN(),jre=oN(),$re=aN(),Mre=cN(),Ore=dN(),Bre=["/properties"];function Nre(t){return[Are,Rre,Dre,Cre,jre,e(this,$re),Mre,e(this,Ore)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function e(r,n){return t?r.$dataMetaSchema(n,Bre):n}}XT.default=Nre});var rI=Ee((Wr,tI)=>{"use strict";w();Object.defineProperty(Wr,"__esModule",{value:!0});Wr.MissingRefError=Wr.ValidationError=Wr.CodeGen=Wr.Name=Wr.nil=Wr.stringify=Wr.str=Wr._=Wr.KeywordCxt=Wr.Ajv2020=void 0;var Ure=N4(),Lre=YB(),Kre=tN(),zre=uN(),eI="https://json-schema.org/draft/2020-12/schema",Th=class extends Ure.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Lre.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Kre.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:r}=this.opts;r&&(zre.default.call(this,e),this.refs["http://json-schema.org/schema"]=eI)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(eI)?eI:void 0)}};Wr.Ajv2020=Th;tI.exports=Wr=Th;tI.exports.Ajv2020=Th;Object.defineProperty(Wr,"__esModule",{value:!0});Wr.default=Th;var qre=_g();Object.defineProperty(Wr,"KeywordCxt",{enumerable:!0,get:function(){return qre.KeywordCxt}});var Ih=kt();Object.defineProperty(Wr,"_",{enumerable:!0,get:function(){return Ih._}});Object.defineProperty(Wr,"str",{enumerable:!0,get:function(){return Ih.str}});Object.defineProperty(Wr,"stringify",{enumerable:!0,get:function(){return Ih.stringify}});Object.defineProperty(Wr,"nil",{enumerable:!0,get:function(){return Ih.nil}});Object.defineProperty(Wr,"Name",{enumerable:!0,get:function(){return Ih.Name}});Object.defineProperty(Wr,"CodeGen",{enumerable:!0,get:function(){return Ih.CodeGen}});var Fre=Mb();Object.defineProperty(Wr,"ValidationError",{enumerable:!0,get:function(){return Fre.default}});var Gre=kg();Object.defineProperty(Wr,"MissingRefError",{enumerable:!0,get:function(){return Gre.default}})});var v9=Ee((HOe,_A)=>{"use strict";w();var Yde=Object.prototype.hasOwnProperty,_i="~";function Ow(){}Object.create&&(Ow.prototype=Object.create(null),new Ow().__proto__||(_i=!1));function Qde(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function w9(t,e,r,n,s){if(typeof r!="function")throw new TypeError("The listener must be a function");var a=new Qde(r,n||t,s),o=_i?_i+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],a]:t._events[o].push(a):(t._events[o]=a,t._eventsCount++),t}function gP(t,e){--t._eventsCount===0?t._events=new Ow:delete t._events[e]}function ti(){this._events=new Ow,this._eventsCount=0}ti.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)Yde.call(r,n)&&e.push(_i?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};ti.prototype.listeners=function(e){var r=_i?_i+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,a=n.length,o=new Array(a);s<a;s++)o[s]=n[s].fn;return o};ti.prototype.listenerCount=function(e){var r=_i?_i+e:e,n=this._events[r];return n?n.fn?1:n.length:0};ti.prototype.emit=function(e,r,n,s,a,o){var i=_i?_i+e:e;if(!this._events[i])return!1;var c=this._events[i],u=arguments.length,d,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,s),!0;case 5:return c.fn.call(c.context,r,n,s,a),!0;case 6:return c.fn.call(c.context,r,n,s,a,o),!0}for(l=1,d=new Array(u-1);l<u;l++)d[l-1]=arguments[l];c.fn.apply(c.context,d)}else{var f=c.length,h;for(l=0;l<f;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,r);break;case 3:c[l].fn.call(c[l].context,r,n);break;case 4:c[l].fn.call(c[l].context,r,n,s);break;default:if(!d)for(h=1,d=new Array(u-1);h<u;h++)d[h-1]=arguments[h];c[l].fn.apply(c[l].context,d)}}return!0};ti.prototype.on=function(e,r,n){return w9(this,e,r,n,!1)};ti.prototype.once=function(e,r,n){return w9(this,e,r,n,!0)};ti.prototype.removeListener=function(e,r,n,s){var a=_i?_i+e:e;if(!this._events[a])return this;if(!r)return gP(this,a),this;var o=this._events[a];if(o.fn)o.fn===r&&(!s||o.once)&&(!n||o.context===n)&&gP(this,a);else{for(var i=0,c=[],u=o.length;i<u;i++)(o[i].fn!==r||s&&!o[i].once||n&&o[i].context!==n)&&c.push(o[i]);c.length?this._events[a]=c.length===1?c[0]:c:gP(this,a)}return this};ti.prototype.removeAllListeners=function(e){var r;return e?(r=_i?_i+e:e,this._events[r]&&gP(this,r)):(this._events=new Ow,this._eventsCount=0),this};ti.prototype.off=ti.prototype.removeListener;ti.prototype.addListener=ti.prototype.on;ti.prefixed=_i;ti.EventEmitter=ti;typeof _A<"u"&&(_A.exports=ti)});w();w();var cm=(r=>(r.Reject="reject",r.PurgeOldest="purgeOldest",r))(cm||{});w();w();ln();Oa();w();w();var Cm=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,UD=new Set,r2=typeof process=="object"&&process?process:{},LD=(t,e,r,n)=>{typeof r2.emitWarning=="function"?r2.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},T0=globalThis.AbortController,ND=globalThis.AbortSignal;if(typeof T0>"u"){ND=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,s){this._onabort.push(s)}},T0=class{constructor(){e()}signal=new ND;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let s of this.signal._onabort)s(n);this.signal.onabort?.(n)}}};let t=r2.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,LD("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var IF=t=>!UD.has(t),Hhe=Symbol("type"),Ld=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),KD=t=>Ld(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?hp:null:null,hp=class extends Array{constructor(e){super(e),this.fill(0)}},n2=class t{heap;length;static#c=!1;static create(e){let r=KD(e);if(!r)return[];t.#c=!0;let n=new t(e,r);return t.#c=!1,n}constructor(e,r){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},I0=class t{#c;#l;#w;#h;#A;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#m;#s;#r;#e;#d;#f;#a;#i;#y;#o;#x;#S;#g;#v;#_;#u;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#g,sizes:e.#x,keyMap:e.#s,keyList:e.#r,valList:e.#e,next:e.#d,prev:e.#f,get head(){return e.#a},get tail(){return e.#i},free:e.#y,isBackgroundFetch:r=>e.#t(r),backgroundFetch:(r,n,s,a)=>e.#C(r,n,s,a),moveToTail:r=>e.#I(r),indexes:r=>e.#b(r),rindexes:r=>e.#P(r),isStale:r=>e.#p(r)}}get max(){return this.#c}get maxSize(){return this.#l}get calculatedSize(){return this.#m}get size(){return this.#n}get fetchMethod(){return this.#A}get dispose(){return this.#w}get disposeAfter(){return this.#h}constructor(e){let{max:r=0,ttl:n,ttlResolution:s=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:i,allowStale:c,dispose:u,disposeAfter:d,noDisposeOnSet:l,noUpdateTTL:f,maxSize:h=0,maxEntrySize:p=0,sizeCalculation:m,fetchMethod:y,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:k,ignoreFetchAbort:A}=e;if(r!==0&&!Ld(r))throw new TypeError("max option must be a nonnegative integer");let D=r?KD(r):Array;if(!D)throw new Error("invalid max value: "+r);if(this.#c=r,this.#l=h,this.maxEntrySize=p||this.#l,this.sizeCalculation=m,this.sizeCalculation){if(!this.#l&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#A=y,this.#_=!!y,this.#s=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#d=new D(r),this.#f=new D(r),this.#a=0,this.#i=0,this.#y=n2.create(r),this.#n=0,this.#m=0,typeof u=="function"&&(this.#w=u),typeof d=="function"?(this.#h=d,this.#o=[]):(this.#h=void 0,this.#o=void 0),this.#v=!!this.#w,this.#u=!!this.#h,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!k,this.ignoreFetchAbort=!!A,this.maxEntrySize!==0){if(this.#l!==0&&!Ld(this.#l))throw new TypeError("maxSize must be a positive integer if specified");if(!Ld(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#N()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!i,this.ttlResolution=Ld(s)||s===0?s:1,this.ttlAutopurge=!!a,this.ttl=n||0,this.ttl){if(!Ld(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#j()}if(this.#c===0&&this.ttl===0&&this.#l===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#l){let B="LRU_CACHE_UNBOUNDED";IF(B)&&(UD.add(B),LD("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",B,t))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#j(){let e=new hp(this.#c),r=new hp(this.#c);this.#g=e,this.#S=r,this.#$=(a,o,i=Cm.now())=>{if(r[a]=o!==0?i:0,e[a]=o,o!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#p(a)&&this.delete(this.#r[a])},o+1);c.unref&&c.unref()}},this.#k=a=>{r[a]=e[a]!==0?Cm.now():0},this.#E=(a,o)=>{if(e[o]){let i=e[o],c=r[o];a.ttl=i,a.start=c,a.now=n||s();let u=a.now-c;a.remainingTTL=i-u}};let n=0,s=()=>{let a=Cm.now();if(this.ttlResolution>0){n=a;let o=setTimeout(()=>n=0,this.ttlResolution);o.unref&&o.unref()}return a};this.getRemainingTTL=a=>{let o=this.#s.get(a);if(o===void 0)return 0;let i=e[o],c=r[o];if(i===0||c===0)return 1/0;let u=(n||s())-c;return i-u},this.#p=a=>e[a]!==0&&r[a]!==0&&(n||s())-r[a]>e[a]}#k=()=>{};#E=()=>{};#$=()=>{};#p=()=>!1;#N(){let e=new hp(this.#c);this.#m=0,this.#x=e,this.#T=r=>{this.#m-=e[r],e[r]=0},this.#M=(r,n,s,a)=>{if(this.#t(n))return 0;if(!Ld(s))if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(s=a(n,r),!Ld(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return s},this.#R=(r,n,s)=>{if(e[r]=n,this.#l){let a=this.#l-e[r];for(;this.#m>a;)this.#D(!0)}this.#m+=e[r],s&&(s.entrySize=n,s.totalCalculatedSize=this.#m)}}#T=e=>{};#R=(e,r,n)=>{};#M=(e,r,n,s)=>{if(n||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#b({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#i;!(!this.#O(r)||((e||!this.#p(r))&&(yield r),r===this.#a));)r=this.#f[r]}*#P({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#a;!(!this.#O(r)||((e||!this.#p(r))&&(yield r),r===this.#i));)r=this.#d[r]}#O(e){return e!==void 0&&this.#s.get(this.#r[e])===e}*entries(){for(let e of this.#b())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*rentries(){for(let e of this.#P())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*keys(){for(let e of this.#b()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*rkeys(){for(let e of this.#P()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*values(){for(let e of this.#b())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#P())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}find(e,r={}){for(let n of this.#b()){let s=this.#e[n],a=this.#t(s)?s.__staleWhileFetching:s;if(a!==void 0&&e(a,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(e,r=this){for(let n of this.#b()){let s=this.#e[n],a=this.#t(s)?s.__staleWhileFetching:s;a!==void 0&&e.call(r,a,this.#r[n],this)}}rforEach(e,r=this){for(let n of this.#P()){let s=this.#e[n],a=this.#t(s)?s.__staleWhileFetching:s;a!==void 0&&e.call(r,a,this.#r[n],this)}}purgeStale(){let e=!1;for(let r of this.#P({allowStale:!0}))this.#p(r)&&(this.delete(this.#r[r]),e=!0);return e}dump(){let e=[];for(let r of this.#b({allowStale:!0})){let n=this.#r[r],s=this.#e[r],a=this.#t(s)?s.__staleWhileFetching:s;if(a===void 0||n===void 0)continue;let o={value:a};if(this.#g&&this.#S){o.ttl=this.#g[r];let i=Cm.now()-this.#S[r];o.start=Math.floor(Date.now()-i)}this.#x&&(o.size=this.#x[r]),e.unshift([n,o])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let s=Date.now()-n.start;n.start=Cm.now()-s}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:s=this.ttl,start:a,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:i=this.sizeCalculation,status:c}=n,{noUpdateTTL:u=this.noUpdateTTL}=n,d=this.#M(e,r,n.size||0,i);if(this.maxEntrySize&&d>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.delete(e),this;let l=this.#n===0?void 0:this.#s.get(e);if(l===void 0)l=this.#n===0?this.#i:this.#y.length!==0?this.#y.pop():this.#n===this.#c?this.#D(!1):this.#n,this.#r[l]=e,this.#e[l]=r,this.#s.set(e,l),this.#d[this.#i]=l,this.#f[l]=this.#i,this.#i=l,this.#n++,this.#R(l,d,c),c&&(c.set="add"),u=!1;else{this.#I(l);let f=this.#e[l];if(r!==f){if(this.#_&&this.#t(f)?f.__abortController.abort(new Error("replaced")):o||(this.#v&&this.#w?.(f,e,"set"),this.#u&&this.#o?.push([f,e,"set"])),this.#T(l),this.#R(l,d,c),this.#e[l]=r,c){c.set="replace";let h=f&&this.#t(f)?f.__staleWhileFetching:f;h!==void 0&&(c.oldValue=h)}}else c&&(c.set="update")}if(s!==0&&!this.#g&&this.#j(),this.#g&&(u||this.#$(l,s,a),c&&this.#E(c,l)),!o&&this.#u&&this.#o){let f=this.#o,h;for(;h=f?.shift();)this.#h?.(...h)}return this}pop(){try{for(;this.#n;){let e=this.#e[this.#a];if(this.#D(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#u&&this.#o){let e=this.#o,r;for(;r=e?.shift();)this.#h?.(...r)}}}#D(e){let r=this.#a,n=this.#r[r],s=this.#e[r];return this.#_&&this.#t(s)?s.__abortController.abort(new Error("evicted")):(this.#v||this.#u)&&(this.#v&&this.#w?.(s,n,"evict"),this.#u&&this.#o?.push([s,n,"evict"])),this.#T(r),e&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#y.push(r)),this.#n===1?(this.#a=this.#i=0,this.#y.length=0):this.#a=this.#d[r],this.#s.delete(n),this.#n--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:s}=r,a=this.#s.get(e);if(a!==void 0){let o=this.#e[a];if(this.#t(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#p(a))s&&(s.has="stale",this.#E(s,a));else return n&&this.#k(a),s&&(s.has="hit",this.#E(s,a)),!0}else s&&(s.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,s=this.#s.get(e);if(s!==void 0&&(n||!this.#p(s))){let a=this.#e[s];return this.#t(a)?a.__staleWhileFetching:a}}#C(e,r,n,s){let a=r===void 0?void 0:this.#e[r];if(this.#t(a))return a;let o=new T0,{signal:i}=n;i?.addEventListener("abort",()=>o.abort(i.reason),{signal:o.signal});let c={signal:o.signal,options:n,context:s},u=(m,y=!1)=>{let{aborted:S}=o.signal,v=n.ignoreFetchAbort&&m!==void 0;if(n.status&&(S&&!y?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,v&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),S&&!v&&!y)return l(o.signal.reason);let E=h;return this.#e[r]===h&&(m===void 0?E.__staleWhileFetching?this.#e[r]=E.__staleWhileFetching:this.delete(e):(n.status&&(n.status.fetchUpdated=!0),this.set(e,m,c.options))),m},d=m=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=m),l(m)),l=m=>{let{aborted:y}=o.signal,S=y&&n.allowStaleOnFetchAbort,v=S||n.allowStaleOnFetchRejection,E=v||n.noDeleteOnFetchRejection,k=h;if(this.#e[r]===h&&(!E||k.__staleWhileFetching===void 0?this.delete(e):S||(this.#e[r]=k.__staleWhileFetching)),v)return n.status&&k.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),k.__staleWhileFetching;if(k.__returned===k)throw m},f=(m,y)=>{let S=this.#A?.(e,a,c);S&&S instanceof Promise&&S.then(v=>m(v),y),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(m(),n.allowStaleOnFetchAbort&&(m=v=>u(v,!0)))})};n.status&&(n.status.fetchDispatched=!0);let h=new Promise(f).then(u,d),p=Object.assign(h,{__abortController:o,__staleWhileFetching:a,__returned:void 0});return r===void 0?(this.set(e,p,{...c.options,status:void 0}),r=this.#s.get(e)):this.#e[r]=p,p}#t(e){if(!this.#_)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof T0}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:i=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:y=!1,status:S,signal:v}=r;if(!this.#_)return S&&(S.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:a,status:S});let E={allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:a,ttl:o,noDisposeOnSet:i,size:c,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:p,ignoreFetchAbort:h,status:S,signal:v},k=this.#s.get(e);if(k===void 0){S&&(S.fetch="miss");let A=this.#C(e,k,E,m);return A.__returned=A}else{let A=this.#e[k];if(this.#t(A)){let q=n&&A.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",q&&(S.returnedStale=!0)),q?A.__staleWhileFetching:A.__returned=A}let D=this.#p(k);if(!y&&!D)return S&&(S.fetch="hit"),this.#I(k),s&&this.#k(k),S&&this.#E(S,k),A;let B=this.#C(e,k,E,m),F=B.__staleWhileFetching!==void 0&&n;return S&&(S.fetch=D?"stale":"refresh",F&&D&&(S.returnedStale=!0)),F?B.__staleWhileFetching:B.__returned=B}}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:o}=r,i=this.#s.get(e);if(i!==void 0){let c=this.#e[i],u=this.#t(c);return o&&this.#E(o,i),this.#p(i)?(o&&(o.get="stale"),u?(o&&n&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),n?c.__staleWhileFetching:void 0):(a||this.delete(e),o&&n&&(o.returnedStale=!0),n?c:void 0)):(o&&(o.get="hit"),u?c.__staleWhileFetching:(this.#I(i),s&&this.#k(i),c))}else o&&(o.get="miss")}#B(e,r){this.#f[r]=e,this.#d[e]=r}#I(e){e!==this.#i&&(e===this.#a?this.#a=this.#d[e]:this.#B(this.#f[e],this.#d[e]),this.#B(this.#i,e),this.#i=e)}delete(e){let r=!1;if(this.#n!==0){let n=this.#s.get(e);if(n!==void 0)if(r=!0,this.#n===1)this.clear();else{this.#T(n);let s=this.#e[n];this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#v||this.#u)&&(this.#v&&this.#w?.(s,e,"delete"),this.#u&&this.#o?.push([s,e,"delete"])),this.#s.delete(e),this.#r[n]=void 0,this.#e[n]=void 0,n===this.#i?this.#i=this.#f[n]:n===this.#a?this.#a=this.#d[n]:(this.#d[this.#f[n]]=this.#d[n],this.#f[this.#d[n]]=this.#f[n]),this.#n--,this.#y.push(n)}}if(this.#u&&this.#o?.length){let n=this.#o,s;for(;s=n?.shift();)this.#h?.(...s)}return r}clear(){for(let e of this.#P({allowStale:!0})){let r=this.#e[e];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let n=this.#r[e];this.#v&&this.#w?.(r,n,"delete"),this.#u&&this.#o?.push([r,n,"delete"])}}if(this.#s.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#g&&this.#S&&(this.#g.fill(0),this.#S.fill(0)),this.#x&&this.#x.fill(0),this.#a=0,this.#i=0,this.#y.length=0,this.#m=0,this.#n=0,this.#u&&this.#o){let e=this.#o,r;for(;r=e?.shift();)this.#h?.(...r)}}};var A0=class{constructor(e){this.timeToLiveInSeconds=e;this.cache=new I0({max:1e5,ttl:e*1e3})}cache;async set(e,r){try{this.cache.set(e,r)}catch{}}async get(e){return this.cache.get(e)}};C0();ht();var zd=class t{static _singleton;cache;constructor(e){this.cache=e||new A0(600)}static get singleton(){return t._singleton===void 0&&(t._singleton=new t),t._singleton}static async verifySignatures(e,r){return await t.singleton.verifySignatures(e,r)}async verifySignatures(e,r){let n=[];for(let s of e.signatures){let a,o=Te.base64UrlToObject(s.protected),{kid:i,alg:c}=o;if(i===void 0||typeof i!="string")throw new ne("GeneralJwsVerifierMissingKid","JWS protected header is missing required 'kid' property");if(c===void 0||typeof c!="string")throw new ne("GeneralJwsVerifierMissingAlg","JWS protected header is missing required 'alg' property");let u=`${s.protected}.${e.payload}.${s.signature}`,d=await this.cache.get(u);if(d===void 0){let f=await t.getPublicKey(i,r);a=await vt.verifySignature(e.payload,s,f),await this.cache.set(u,a)}else a=d;let l=vt.extractDid(i);if(a)n.push(l);else throw new ne("GeneralJwsVerifierInvalidSignature",`Signature verification failed for ${l}`)}return{signers:n}}static async getPublicKey(e,r){let n=vt.extractDid(e),{didDocument:s}=await r.resolve(n),{verificationMethod:a=[]}=s||{},o;for(let c of a)if(e.endsWith(c.id)){o=c;break}if(!o)throw new ne("GeneralJwsVerifierGetPublicKeyNotFound","public key needed to verify signature not found in DID Document");Lc("JwkVerificationMethod",o);let{publicKeyJwk:i}=o;return i}};vi();ht();async function on(t,e,r){if(t===void 0)throw new ne("AuthenticateJwsMissing","Missing JWS.");if(await zd.verifySignatures(t.signature,e),t.ownerSignature!==void 0&&await zd.verifySignatures(t.ownerSignature,e),t.authorDelegatedGrant!==void 0){let n=await St.parse(t.authorDelegatedGrant);await zd.verifySignatures(n.message.authorization.signature,e)}if(t.ownerDelegatedGrant!==void 0){let n=await St.parse(t.ownerDelegatedGrant);await zd.verifySignatures(n.message.authorization.signature,e)}r!==void 0&&await zd.verifySignatures(r,e)}w();var ag=class{_protocols=new Map;register(e){this._protocols.set(e.uri,e)}get(e){return this._protocols.get(e)}getDefinition(e){return this._protocols.get(e)?.definition}has(e){return this._protocols.has(e)}all(){return[...this._protocols.values()]}mapErrorToStatusCode(e){for(let r of this._protocols.values()){let n=r.mapErrorToStatusCode?.(e);if(n!==void 0)return n}}};KE();w();var cg=class{async isActiveTenant(e){return{isActiveTenant:!0}}};Vc();w();w();Oa();ir();var bn=class{_message;get message(){return this._message}_signer;get signer(){return this._signer}_author;get author(){return this._author}_signaturePayload;get signaturePayload(){return this._signaturePayload}get isSignedByAuthorDelegate(){return we.isSignedByAuthorDelegate(this._message)}constructor(e){this._message=e,e.authorization!==void 0&&(this._signer=we.getSigner(e),e.authorization.authorDelegatedGrant!==void 0?this._author=we.getSigner(e.authorization.authorDelegatedGrant):this._author=this._signer,this._signaturePayload=vt.decodePlainObjectPayload(e.authorization.signature))}toJSON(){return this.message}};ir();la();$n();Ya();hs();Vs();ht();Qt();Ao();var Hl=class t extends bn{static async parse(e){let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne("RecordsCountFilterMissingRequiredProperties","Role-authorized counts must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&zn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Za(e.descriptor.filter.schema),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Records",method:"Count",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:ke.normalizeFilter(e.filter)};qt(r);let n=e.signer,s;n&&(s=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Zr.parse(this.message.authorization.authorDelegatedGrant);await Sn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}};w();Il();ir();la();$n();Ya();hs();Vs();ht();Qt();Ao();var Jl=class t extends bn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort==="publishedAscending"||e.descriptor.dateSort==="publishedDescending"))throw new ne("RecordsQueryParseFilterPublishedSortInvalid",`queries must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne("RecordsQueryFilterMissingRequiredProperties","Role-authorized queries must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&zn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Za(e.descriptor.filter.schema),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Records",method:"Query",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:ke.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination};if(e.filter.published===!1&&(e.dateSort==="publishedAscending"||e.dateSort==="publishedDescending"))throw new ne("RecordsQueryCreateFilterPublishedSortInvalid",`queries must not filter for \`published:false\` and sort by ${e.dateSort}`);qt(r);let n=e.signer,s;n&&(s=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Zr.parse(this.message.authorization.authorDelegatedGrant);await Sn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantee:this.signer,expectedGrantor:this.author,permissionGrant:r,messageStore:e})}};Vd();Kp();w();ir();w();function ut(t,e){let r=t instanceof Error?t.message:"Error";return{status:{code:e,detail:r}}}w();Vd();ln();w();Qt();$v();w();w();var dc=class{static maxDataSizeAllowedToBeEncoded=3e4};ln();ya();ir();la();w();ln();ir();ht();var dg=class t{id;requester;description;delegated;scope;conditions;static parse(e){return t.validateMessage(e),new t(e)}static validateMessage(e){if(e.encodedData===void 0||e.encodedData===null)throw new ne("PermissionRequestParseMissingEncodedData","permission request message is missing encodedData");if(we.getSigner(e)===void 0)throw new ne("PermissionRequestParseMissingAuthorization","permission request message is missing authorization (unable to extract requester)");if(Te.base64UrlToObject(e.encodedData).scope===void 0)throw new ne("PermissionRequestParseMissingScope","permission request data is missing required property `scope`")}constructor(e){this.id=e.recordId,this.requester=we.getSigner(e);let r=e.encodedData,n=Te.base64UrlToObject(r);this.delegated=n.delegated,this.description=n.description,this.scope=n.scope,this.conditions=n.conditions}};$n();vi();Vs();C0();ht();Qt();Ao();var Tr=class t{static uri="https://identity.foundation/dwn/permissions";static requestPath="request";static grantPath="grant";static revocationPath="grant/revocation";static definition={published:!0,protocol:t.uri,types:{request:{dataFormats:["application/json"]},grant:{dataFormats:["application/json"]},revocation:{dataFormats:["application/json"]}},structure:{request:{$size:{max:1e4},$actions:[{who:"anyone",can:["create"]}]},grant:{$size:{max:1e4},$actions:[{who:"recipient",of:"grant",can:["read"]}],revocation:{$size:{max:1e4},$actions:[{who:"anyone",can:["read"]}]}}}};get uri(){return t.uri}get definition(){return t.definition}validateRecord(e,r){t.validateSchema(e,r)}async preProcessWrite(e,r,n){if(r.descriptor.protocolPath!==t.revocationPath)return;let s=r.descriptor.parentId,a=await t.fetchGrant(e,n,s),o=r.descriptor.tags?.protocol,i="protocol"in a.scope?a.scope.protocol:void 0;if(i!==o)throw new ne("PermissionsProtocolValidateRevocationProtocolTagMismatch",`Revocation protocol ${o} does not match grant protocol ${i}`)}async postProcessWrite(e,r,n){if(r.message.descriptor.protocolPath!==t.revocationPath)return;let a={permissionGrantId:r.message.descriptor.parentId,dateCreated:{gte:r.message.descriptor.messageTimestamp}},{messages:o}=await n.messageStore.query(e,[a]);if(o.length===0)return;for(let c of o)if(c.descriptor.method==="Write"){let u=c;u.descriptor.dataSize>dc.maxDataSizeAllowedToBeEncoded&&await n.dataStore.delete(e,u.recordId,u.descriptor.dataCid)}let i=await Promise.all(o.map(c=>we.getCid(c)));await n.stateIndex.delete(e,i),await Promise.all(i.map(c=>n.messageStore.delete(e,c)))}mapErrorToStatusCode(e){if(e.startsWith("PermissionsProtocolValidate"))return 400}constructAdditionalMessageFilter(e){let{protocol:r,messageTimestamp:n}=e;if(r===void 0)return;let s={protocol:t.uri,...ke.convertTagsFilter({protocol:r})};if(n!==void 0){let a=Wt.convertRangeCriterion(n);a&&(s.messageTimestamp=a)}return s}static parseRequest(e){return Te.base64UrlToObject(e)}static async createRequest(e){if(this.isRecordPermissionScope(e.scope)&&e.scope.protocol===void 0)throw new ne("PermissionsProtocolCreateRequestRecordsScopeMissingProtocol","Permission request for Records must have a scope with a `protocol` property");let r=t.normalizePermissionScope(e.scope),n={description:e.description,delegated:e.delegated,scope:r,conditions:e.conditions},s;this.hasProtocolScope(r)&&(s={protocol:r.protocol});let a=Te.objectToBytes(n),o=await St.create({signer:e.signer,messageTimestamp:e.dateRequested,protocol:t.uri,protocolPath:t.requestPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:Te.bytesToBase64Url(a)};return{recordsWrite:o,permissionRequestData:n,permissionRequestBytes:a,dataEncodedMessage:i}}static async createGrant(e){if(this.isRecordPermissionScope(e.scope)&&e.scope.protocol===void 0)throw new ne("PermissionsProtocolCreateGrantRecordsScopeMissingProtocol","Permission grants for Records must have a scope with a `protocol` property");let r=t.normalizePermissionScope(e.scope),n={dateExpires:e.dateExpires,requestId:e.requestId,description:e.description,delegated:e.delegated,scope:r,conditions:e.conditions},s;this.hasProtocolScope(r)&&(s={protocol:r.protocol});let a=Te.objectToBytes(n),o=await St.create({signer:e.signer,messageTimestamp:e.dateGranted,dateCreated:e.dateGranted,recipient:e.grantedTo,protocol:t.uri,protocolPath:t.grantPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:Te.bytesToBase64Url(a)};return{recordsWrite:o,permissionGrantData:n,permissionGrantBytes:a,dataEncodedMessage:i}}static async createRevocation(e){let r={description:e.description},n=e.grant.id,s;this.hasProtocolScope(e.grant.scope)&&(s={protocol:pi(e.grant.scope.protocol)});let a=Te.objectToBytes(r),o=await St.create({signer:e.signer,parentContextId:n,protocol:t.uri,protocolPath:t.revocationPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:Te.bytesToBase64Url(a)};return{recordsWrite:o,permissionRevocationData:r,permissionRevocationBytes:a,dataEncodedMessage:i}}static validateSchema(e,r){let n=Te.bytesToString(r),s=JSON.parse(n);if(e.descriptor.protocolPath===t.requestPath){let a=s;Lc("PermissionRequestData",a),t.validateScopeAndTags(a.scope,e)}else if(e.descriptor.protocolPath===t.grantPath){Lc("PermissionGrantData",s);let a=s;t.validateScopeAndTags(a.scope,e),yt.validateTimestamp(a.dateExpires)}else if(e.descriptor.protocolPath===t.revocationPath)Lc("PermissionRevocationData",s);else throw new ne("PermissionsProtocolValidateSchemaUnexpectedRecord",`Unexpected permission record: ${e.descriptor.protocolPath}`)}static async fetchGrant(e,r,n){let s={recordId:n,isLatestBaseState:!0},{messages:a}=await r.query(e,[s]),o=a[0],i=o?.descriptor.interface,c=o?.descriptor.method;if(i!=="Records"||c!=="Write"||o.descriptor.protocolPath!==t.grantPath)throw new ne("GrantAuthorizationGrantMissing",`Could not find permission grant with record ID ${n}.`);let u=o;return Zr.parse(u)}static async getScopeFromPermissionRecord(e,r,n){if(n.descriptor.protocol!==t.uri)throw new ne("PermissionsProtocolGetScopeInvalidProtocol",`Unexpected protocol for permission record: ${n.descriptor.protocol}`);return n.descriptor.protocolPath===t.revocationPath?(await t.fetchGrant(e,r,n.descriptor.parentId)).scope:n.descriptor.protocolPath===t.grantPath?Zr.parse(n).scope:dg.parse(n).scope}static normalizePermissionScope(e){let r={...e};return t.hasProtocolScope(r)&&(r.protocol=pi(r.protocol)),r}static isRecordPermissionScope(e){return e.interface==="Records"}static hasProtocolScope(e){return"protocol"in e&&e.protocol!==void 0}static validateTags(e,r){if(e.descriptor.tags===void 0||e.descriptor.tags.protocol===void 0)throw new ne("PermissionsProtocolValidateScopeMissingProtocolTag","Permission grants must have a `tags` property that contains a protocol tag");let n=e.descriptor.tags.protocol;if(n!==r)throw new ne("PermissionsProtocolValidateScopeProtocolMismatch",`Permission grants must have a scope with a protocol that matches the tagged protocol: ${n}`)}static validateScopeAndTags(e,r){if(this.hasProtocolScope(e)&&(zn(e.protocol),this.validateTags(r,e.protocol)),!!this.isRecordPermissionScope(e)&&e.contextId!==void 0&&e.protocolPath!==void 0)throw new ne("PermissionsProtocolValidateScopeContextIdProhibitedProperties","Permission grants cannot have both `contextId` and `protocolPath` present")}};$n();vi();ht();var gu=class t{static async authorizeMessagesRead(e){let{messagesReadMessage:r,messageToRead:n,expectedGrantor:s,expectedGrantee:a,permissionGrant:o,messageStore:i}=e;await ro.performBaseValidation({incomingMessage:r,expectedGrantor:s,expectedGrantee:a,permissionGrant:o,messageStore:i});let c=o.scope;await t.verifyScope(s,n,c,i)}static async authorizeSubscribeOrSync(e){let{incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}=e;if(await ro.performBaseValidation({incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}),Tr.hasProtocolScope(a.scope)){let i=a.scope.protocol;if("action"in r.descriptor){let c=r;if(c.descriptor.protocol!==i)throw new ne("EventsGrantAuthorizationMismatchedProtocol",`The protocol ${c.descriptor.protocol} does not match the scoped protocol ${i}`)}else{let c=r;for(let u of c.descriptor.filters)if(u.protocol!==i)throw new ne("EventsGrantAuthorizationMismatchedProtocol",`The protocol ${u.protocol} does not match the scoped protocol ${i}`)}}}static async verifyScope(e,r,n,s){if(n.protocol!==void 0){if(r.descriptor.interface==="Records"){let a=r,o=ke.isRecordsWrite(a)?a:await St.fetchNewestRecordsWrite(s,e,a.descriptor.recordId);if(o.descriptor.protocol===n.protocol)return;if(o.descriptor.protocol===Tr.uri){let i=await Tr.getScopeFromPermissionRecord(e,s,o);if(Tr.hasProtocolScope(i)&&i.protocol===n.protocol)return}}else if(r.descriptor.interface==="Protocols"&&r.descriptor.definition.protocol===n.protocol)return;throw new ne("MessagesReadVerifyScopeFailed","record message failed scope authorization")}}};w();Vc();ir();Vs();ht();Qt();var Zl=class t extends bn{static async parse(e){return we.validateJsonSchema(e),this.validateMessageCid(e.descriptor.messageCid),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let{signer:r,permissionGrantId:n}=e,s={interface:"Messages",method:"Read",messageCid:e.messageCid,messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),...n!==void 0&&{permissionGrantId:n}},a=await we.createAuthorization({descriptor:s,signer:r,permissionGrantId:n}),o={descriptor:s,authorization:a};return we.validateJsonSchema(o),t.validateMessageCid(e.messageCid),new t(o)}static validateMessageCid(e){try{Ar.parseCid(e)}catch{throw new ne("MessagesReadInvalidCid",`${e} is not a valid CID`)}}};$n();ht();var vb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Zl.parse(r)}catch(o){return ut(o,400)}try{await on(r.authorization,this.deps.didResolver)}catch(o){return ut(o,401)}let s=await this.deps.messageStore.get(e,r.descriptor.messageCid);if(s===void 0)return{status:{code:404,detail:"Not Found"}};try{await t.authorizeMessagesRead(e,n,s,this.deps.messageStore)}catch(o){return ut(o,401)}let a={message:s,messageCid:r.descriptor.messageCid};if(ke.isRecordsWrite(s)){let o=a.message;if(o.encodedData!==void 0){let i=Te.base64UrlToBytes(o.encodedData);a.data=ts.fromBytes(i),delete o.encodedData}else{let i=await this.deps.dataStore.get(e,o.recordId,o.descriptor.dataCid);i?.dataStream!==void 0&&(a.data=i.dataStream)}}return{status:{code:200,detail:"OK"},entry:a}}static async authorizeMessagesRead(e,r,n,s){if(r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let a=await Tr.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await gu.authorizeMessagesRead({messagesReadMessage:r.message,messageToRead:n,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:a,messageStore:s})}else throw new ne("MessagesReadAuthorizationFailed","protocol message failed authorization")}};w();ir();w();ya();Ao();hs();var bb=class{static normalizeFilters(e){let r=[];for(let n of e){let s=n.protocol!==void 0?pi(n.protocol):void 0,a={...n,protocol:s};qt(a),Tl(a)||r.push(a)}return r}static convertFilters(e,r){let n=[];for(let s of e){if(r!==void 0)for(let a of r.all()){let o=a.constructAdditionalMessageFilter?.(s);o!==void 0&&n.push(o)}n.push(this.convertFilter(s))}return n}static convertFilter(e){let r={...e},{messageTimestamp:n}=e,s=n?Wt.convertRangeCriterion(n):void 0;return s&&(r.messageTimestamp=s,delete r.dateUpdated),r}};w();ir();hs();Vs();Ao();Qt();var Yl=class t extends bn{static async parse(e){we.validateJsonSchema(e),await we.validateSignatureStructure(e.authorization.signature,e.descriptor);for(let r of e.descriptor.filters)"protocol"in r&&r.protocol!==void 0&&zn(r.protocol);return yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r=yt.getCurrentTimestamp(),n={interface:"Messages",method:"Subscribe",filters:e.filters??[],messageTimestamp:e.messageTimestamp??r,permissionGrantId:e.permissionGrantId,cursor:e.cursor};qt(n);let{permissionGrantId:s,signer:a}=e,o=await we.createAuthorization({descriptor:n,signer:a,permissionGrantId:s}),i={descriptor:n,authorization:o};return we.validateJsonSchema(i),new t(i)}};ht();var Pb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return ut(new ne("MessagesSubscribeEventLogUnimplemented","Subscriptions are not supported"),501);let s;try{s=await Yl.parse(r)}catch(u){return ut(u,400)}try{await on(r.authorization,this.deps.didResolver),await t.authorizeMessagesSubscribe(e,s,this.deps.messageStore)}catch(u){return ut(u,401)}let{filters:a,cursor:o}=r.descriptor,i=bb.convertFilters(a,this.deps.coreProtocols),c=await we.getCid(r);try{let u=await this.deps.eventLog.subscribe(e,c,n,{cursor:o,filters:i});return{status:{code:200,detail:"OK"},subscription:u}}catch(u){return ut(u,500)}}static async authorizeMessagesSubscribe(e,r,n){if(r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await Tr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await gu.authorizeSubscribeOrSync({incomingMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new ne("MessagesSubscribeAuthorizationFailed","message failed authorization")}};w();ln();vu();w();ir();hs();Vs();Ao();Qt();var lg=class t extends bn{static async parse(e){return we.validateJsonSchema(e),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.protocol!==void 0&&zn(e.descriptor.protocol),new t(e)}static async create(e){let r={interface:"Messages",method:"Sync",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),action:e.action,protocol:e.protocol,prefix:e.prefix,permissionGrantId:e.permissionGrantId,hashes:e.hashes,depth:e.depth};qt(r);let{permissionGrantId:n,signer:s}=e,a=await we.createAuthorization({descriptor:r,signer:s,permissionGrantId:n}),o={descriptor:r,authorization:a};return we.validateJsonSchema(o),new t(o)}};ht();var bZ=262144,xb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await lg.parse(r)}catch(i){return ut(i,400)}try{await on(r.authorization,this.deps.didResolver),await t.authorizeMessagesSync(e,n,this.deps.messageStore)}catch(i){return ut(i,401)}let{action:s,protocol:a,prefix:o}=r.descriptor;try{switch(s){case"root":{let i=a!==void 0?await this.deps.stateIndex.getProtocolRoot(e,a):await this.deps.stateIndex.getRoot(e);return{status:{code:200,detail:"OK"},root:Vn(i)}}case"subtree":{let i=t.parseBitPrefix(o),c=a!==void 0?await this.deps.stateIndex.getProtocolSubtreeHash(e,a,i):await this.deps.stateIndex.getSubtreeHash(e,i);return{status:{code:200,detail:"OK"},hash:Vn(c)}}case"leaves":{let i=t.parseBitPrefix(o),c=a!==void 0?await this.deps.stateIndex.getProtocolLeaves(e,a,i):await this.deps.stateIndex.getLeaves(e,i);return{status:{code:200,detail:"OK"},entries:c}}case"diff":return this.handleDiff(e,r);default:return{status:{code:400,detail:`Unknown action: ${s}`}}}}catch(i){return ut(i,500)}}async handleDiff(e,r){let{protocol:n,hashes:s,depth:a}=r.descriptor;if(!s||a===void 0)return{status:{code:400,detail:"diff action requires hashes and depth"}};let o=this.deps.stateIndex,i=[],c=[],u=await this.getDefaultHashHex(a),d=new Set;for(let[h,p]of Object.entries(s))p!==u&&d.add(h);let l=await this.collectSubtreeHashes(e,n,a);for(let h of Object.keys(l))d.add(h);for(let h of d){let p=s[h],m=l[h];if(p===m)continue;if(m===void 0){c.push(h);continue}if(p===void 0){let v=t.parseBitPrefix(h),E=n!==void 0?await o.getProtocolLeaves(e,n,v):await o.getLeaves(e,v);i.push(...E);continue}let y=t.parseBitPrefix(h),S=n!==void 0?await o.getProtocolLeaves(e,n,y):await o.getLeaves(e,y);i.push(...S),c.push(h)}let f=await this.buildDiffEntries(e,i);return{status:{code:200,detail:"OK"},onlyRemote:f,onlyLocal:c}}async collectSubtreeHashes(e,r,n){let s=this.deps.stateIndex,a={},o=await this.getDefaultHashHex(n),i=async(c,u)=>{let d=t.parseBitPrefix(c),l=r!==void 0?await s.getProtocolSubtreeHash(e,r,d):await s.getSubtreeHash(e,d),f=Vn(l);if(f!==o){if(u>=n){a[c]=f;return}await Promise.all([i(c+"0",u+1),i(c+"1",u+1)])}};return await i("",0),a}_defaultHashHexCache;async getDefaultHashHex(e){if(this._defaultHashHexCache===void 0){let{initDefaultHashes:r}=await Promise.resolve().then(()=>(vu(),gO)),n=await r();this._defaultHashHexCache=new Map;for(let s=0;s<=256;s++)this._defaultHashHexCache.set(s,Vn(n[s]))}return this._defaultHashHexCache.get(e)??""}async buildDiffEntries(e,r){let n=[];for(let s of r){let{message:a,encodedData:o,data:i}=await this.readMessageByCid(e,s);if(!a)continue;let c={messageCid:s,message:a};if(o)c.encodedData=o;else if(i){let u=await t.streamToBytes(i);u.byteLength<=bZ&&(c.encodedData=Te.bytesToBase64Url(u))}n.push(c)}return n}async readMessageByCid(e,r){let n=await this.deps.messageStore.get(e,r);if(!n)return{};let s;"encodedData"in n&&(s=n.encodedData,delete n.encodedData);let a;if(n.descriptor.interface==="Records"&&n.descriptor.method==="Write"){let o=n.descriptor?.dataCid;if(o&&this.deps.dataStore){let i=n.descriptor?.recordId;if(i){let c=await this.deps.dataStore.get(e,i,o);c?.dataStream&&(a=c.dataStream)}}}return{message:n,encodedData:s,data:a}}static async streamToBytes(e){let r=e.getReader(),n=[],s=0;for(;;){let{done:i,value:c}=await r.read();if(i)break;n.push(c),s+=c.byteLength}let a=new Uint8Array(s),o=0;for(let i of n)a.set(i,o),o+=i.byteLength;return a}static parseBitPrefix(e){if(!/^[01]*$/.test(e))throw new ne("MessagesSyncInvalidPrefix",`Invalid prefix: must contain only '0' and '1' characters, got: ${e}`);if(e.length>256)throw new ne("MessagesSyncInvalidPrefix",`Invalid prefix: length must be <= 256, got: ${e.length}`);return Array.from(e,r=>r==="1")}static async authorizeMessagesSync(e,r,n){if(r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await Tr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await gu.authorizeSubscribeOrSync({incomingMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new ne("MessagesSyncAuthorizationFailed","message failed authorization")}};w();ir();w();var lN=Nn(rI(),1);ir();la();w();$v();ht();var Iu=class t{static async authorizeConfigure(e){let{protocolsConfigureMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}=e;await ro.performBaseValidation({incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}),t.verifyScope(r,a.scope)}static async authorizeQuery(e){let{expectedGrantee:r,expectedGrantor:n,incomingMessage:s,permissionGrant:a,messageStore:o}=e;await ro.performBaseValidation({incomingMessage:s,expectedGrantor:n,expectedGrantee:r,permissionGrant:a,messageStore:o});let c=a.scope.protocol,u=s.descriptor.filter?.protocol;if(c!==void 0&&u!==c)throw new ne("ProtocolsGrantAuthorizationQueryProtocolScopeMismatch",`Grant protocol scope ${c} does not match protocol in message ${u}`)}static verifyScope(e,r){if(r.protocol!==void 0&&r.protocol!==e.descriptor.definition.protocol)throw new ne("ProtocolsGrantAuthorizationScopeProtocolMismatch","Grant scope specifies different protocol than what appears in the configure message.")}};Vs();ht();Qt();w();Up();Kp();function Bi(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 pf(t){return t.includes(":")}function n1(t){return t.split("/").slice(-1)[0]}function ld(t,e){let r=t.split("/"),n,s=e;for(let a of r){if(!Object.hasOwn(s,a))return;n=s[a],s=n}return n}var nI=class{static async deriveAndInjectPublicEncryptionKeys(e,r,n){let s=JSON.parse(JSON.stringify(e));if(typeof r!="string"){let u=r,d=["protocolPath",e.protocol];async function l(f,h){for(let p in f)if(!p.startsWith("$")){let m=[...h,p],y=f[p];if(y.$ref!==void 0){await l(y,m);continue}let S=await u.derivePublicKey(m);y.$encryption={rootKeyId:u.rootKeyId,publicKeyJwk:S},await l(y,m)}}return await l(s.structure,d),s}let a=r;async function o(u,d){for(let l in u)if(!l.startsWith("$")){let f=await Va.derivePrivateKey(d,[l]),h=u[l];if(h.$ref!==void 0){await o(h,f);continue}let p=await gn.getPublicKey({key:f.derivedPrivateKey});h.$encryption={rootKeyId:a,publicKeyJwk:p},await o(h,f)}}let i={derivationScheme:"protocolPath",derivedPrivateKey:n,rootKeyId:a},c=await Va.derivePrivateKey(i,["protocolPath",e.protocol]);return await o(s.structure,c),s}};Ao();var fd=class t extends bn{static async parse(e){return we.validateJsonSchema(e),t.validateProtocolDefinition(e.descriptor.definition),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Protocols",method:"Configure",messageTimestamp:e.messageTimestamp??yt.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}),s={descriptor:r,authorization:n};return we.validateJsonSchema(s),t.validateProtocolDefinition(s.descriptor.definition),new t(s)}async authorizeAuthorDelegate(e){let r=Zr.parse(this.message.authorization.authorDelegatedGrant);await Iu.authorizeConfigure({protocolsConfigureMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}static validateProtocolDefinition(e){let{protocol:r,types:n,uses:s}=e;zn(r);for(let a in n){let o=n[a].schema;o!==void 0&&Za(o)}s!==void 0&&t.validateUses(s,r),t.validateStructure(e)}static validateUses(e,r){let n=/^[a-zA-Z][a-zA-Z0-9_-]*$/;for(let s in e){if(!n.test(s))throw new ne("ProtocolsConfigureInvalidUsesAlias",`invalid 'uses' alias '${s}': must match pattern ${n.toString()}.`);try{zn(e[s])}catch{throw new ne("ProtocolsConfigureInvalidUsesProtocolUrl",`invalid 'uses' protocol URL for alias '${s}': '${e[s]}' is not a valid normalized protocol URL.`)}if(e[s]===r)throw new ne("ProtocolsConfigureInvalidUsesSelfReference",`'uses' alias '${s}' references the protocol's own URI '${r}'. a protocol cannot compose itself.`)}}static validateStructure(e){let{uses:r}=e,n=Object.keys(e.types),s=t.fetchAllRolePathsRecursively("",e.structure,[]);t.validateRuleSetRecursively({ruleSet:e.structure,ruleSetProtocolPath:"",recordTypes:n,roles:s,uses:r,types:e.types})}static fetchAllRolePathsRecursively(e,r,n){if(e.split("/").length>10)throw new ne("ProtocolsConfigureRecordNestingDepthExceeded","Record nesting depth exceeded 10 levels.");for(let s in r){if(s.startsWith("$"))continue;let a=r[s],o;e===""?o=s:o=`${e}/${s}`,a.$role?n.push(o):t.fetchAllRolePathsRecursively(o,a,n)}return n}static validateRuleSetRecursively(e){let{ruleSet:r,ruleSetProtocolPath:n,recordTypes:s,roles:a,uses:o,types:i}=e;if(r.$ref!==void 0){if(n.includes("/"))throw new 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,o)}if(r.$size!==void 0){let{min:u=0,max:d}=r.$size;if(d!==void 0&&d<u)throw new ne("ProtocolsConfigureInvalidSize",`Invalid size range found: max limit ${d} less than min limit ${u} at protocol path '${n}'`)}if(r.$recordLimit!==void 0){let{max:u,strategy:d}=r.$recordLimit;if(!Number.isInteger(u)||u<1)throw new ne("ProtocolsConfigureInvalidRecordLimit",`Invalid $recordLimit.max value ${u} at protocol path '${n}': must be an integer >= 1.`);let l=Object.values(cm);if(!l.includes(d))throw new ne("ProtocolsConfigureInvalidRecordLimit",`Invalid $recordLimit.strategy '${d}' at protocol path '${n}': must be one of ${l.join(", ")}.`)}if(r.$tags){let u=new lN.default.default,{$allowUndefinedTags:d,$requiredTags:l,...f}=r.$tags;for(let h in f){let p=f[h];if(!u.validateSchema(p)){let m=u.errorsText(u.errors,{dataVar:`${n}/$tags/${h}`});throw new ne("ProtocolsConfigureInvalidTagSchema",`tags schema validation error: ${m}`)}}}let c=r.$actions??[];for(let u=0;u<c.length;u++){let d=c[u];if(d.role!==void 0){if(pf(d.role))t.validateCrossProtocolAlias(d.role,o,n,"role");else if(!a.includes(d.role))throw new ne("ProtocolsConfigureRoleDoesNotExistAtGivenPath",`Role in action ${JSON.stringify(d)} for rule set ${n} does not exist.`)}if(d.who==="anyone"&&d.of)throw new ne("ProtocolsConfigureInvalidActionOfNotAllowed",`'of' is not allowed at rule set protocol path (${n})`);if(d.who==="recipient"&&d.of===void 0&&d.can.some(f=>!["co-update","co-delete","co-prune"].includes(f)))throw new ne("ProtocolsConfigureInvalidRecipientOfAction","Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`.");if(d.who==="author"&&!d.of)throw new ne("ProtocolsConfigureInvalidActionMissingOf","'of' is required when 'author' is specified as 'who'");if(d.of!==void 0&&n!==""){if(pf(d.of))t.validateCrossProtocolAlias(d.of,o,n,"of");else if(!(n===d.of||n.startsWith(d.of+"/")))throw new ne("ProtocolsConfigureInvalidActionOfNotAnAncestor",`'of' value '${d.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(d)}.`)}if(d.can!==void 0){if(d.can.includes("update")&&!d.can.includes("create"))throw new ne("ProtocolsConfigureInvalidActionUpdateWithoutCreate",`Action rule ${JSON.stringify(d)} contains 'update' action but missing the required 'create' action.`);if(d.can.includes("delete")&&!d.can.includes("create"))throw new ne("ProtocolsConfigureInvalidActionDeleteWithoutCreate",`Action rule ${JSON.stringify(d)} contains 'delete' action but missing the required 'create' action.`);if(d.can.includes("prune")&&!d.can.includes("create"))throw new ne("ProtocolsConfigureInvalidActionPruneWithoutCreate",`Action rule ${JSON.stringify(d)} contains 'prune' action but missing the required 'create' action.`)}for(let l=u+1;l<c.length;l++){let f=c[l];if(d.who!==void 0){if(d.who===f.who&&d.of===f.of)throw new ne("ProtocolsConfigureDuplicateActorInRuleSet",`More than one action rule per actor ${d.who} of ${d.of} not allowed within a rule set: ${JSON.stringify(d)}`)}else if(d.role===f.role)throw new ne("ProtocolsConfigureDuplicateRoleInRuleSet",`More than one action rule per role ${d.role} not allowed within a rule set: ${JSON.stringify(d)}`)}}if(n!==""){let u=n.split("/").pop();i[u]?.encryptionRequired===!0&&c.some(f=>f.who==="anyone"&&f.can.includes("read"))&&console.warn(`ProtocolsConfigure: type '${u}' 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&&c.length>0&&c.some(d=>d.can.includes("update")||d.can.includes("co-update"))&&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 u in r){if(u.startsWith("$"))continue;let d=r[u];if(d.$ref===void 0&&!s.includes(u))throw new ne("ProtocolsConfigureInvalidRuleSetRecordType",`Rule set ${u} is not declared as an allowed type in the protocol definition.`);let l;n===""?l=u:l=`${n}/${u}`,t.validateRuleSetRecursively({ruleSet:d,ruleSetProtocolPath:l,recordTypes:s,roles:a,uses:o,types:i})}}static validateRefNode(e,r,n){let s=e.$ref,a=Bi(s);if(a===void 0)throw new ne("ProtocolsConfigureInvalidRefAlias",`'$ref' value '${s}' at protocol path '${r}' must be in 'alias:typePath' format.`);if(n===void 0||n[a.alias]===void 0)throw new ne("ProtocolsConfigureInvalidRefAlias",`'$ref' alias '${a.alias}' at protocol path '${r}' does not exist in the 'uses' map.`);let o=["$actions","$role","$size","$tags","$encryption","$recordLimit","$immutable","$delivery","$squash"];for(let i of o)if(e[i]!==void 0)throw new ne("ProtocolsConfigureInvalidRefNodeHasDirectives",`'$ref' node at protocol path '${r}' must not have '${i}'. $ref nodes are pure attachment points \u2014 directives belong on child rule sets.`)}static validateCrossProtocolAlias(e,r,n,s){let a=Bi(e);if(a===void 0){let o=s==="role"?"ProtocolsConfigureInvalidCrossProtocolRole":"ProtocolsConfigureInvalidCrossProtocolOf";throw new ne(o,`cross-protocol '${s}' 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 o=s==="role"?"ProtocolsConfigureInvalidCrossProtocolRole":"ProtocolsConfigureInvalidCrossProtocolOf";throw new ne(o,`cross-protocol '${s}' alias '${a.alias}' in '${e}' at protocol path '${n}' does not exist in the 'uses' map.`)}}static normalizeDefinition(e){let r={};for(let s in e.types)r[s]={...e.types[s]};for(let s in r){let a=r[s].schema;a!==void 0&&(r[s].schema=Dl(a))}let n;if(e.uses!==void 0){n={};for(let s in e.uses)try{n[s]=pi(e.uses[s])}catch{n[s]=e.uses[s]}}return{...e,protocol:pi(e.protocol),types:r,...n!==void 0&&{uses:n}}}};ht();Qt();var s1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await fd.parse(r)}catch(u){return ut(u,400)}try{await on(r.authorization,this.deps.didResolver),await t.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(u){return ut(u,401)}try{await t.validateCompositionDependencies(e,r.descriptor.definition,this.deps.messageStore)}catch(u){return ut(u,400)}let s={interface:"Protocols",method:"Configure",protocol:r.descriptor.definition.protocol},{messages:a}=await this.deps.messageStore.query(e,[s]),o=await we.getNewestMessage(a),i=!1;(o===void 0||await we.isNewer(r,o))&&(i=!0,o=r);let c;if(i){let u=t.constructIndexes(n,!0);await this.deps.messageStore.put(e,r,u);let d=await we.getCid(r);await this.deps.stateIndex.insert(e,d,u),this.deps.eventLog!==void 0&&await this.deps.eventLog.emit(e,{message:r},u),c={status:{code:202,detail:"Accepted"}}}else{let u=t.constructIndexes(n,!1);await this.deps.messageStore.put(e,r,u);let d=await we.getCid(r);await this.deps.stateIndex.insert(e,d,u),c={status:{code:202,detail:"Accepted"}}}for(let u of a)if(u!==o){let d=await fd.parse(u),l=t.constructIndexes(d,!1),f=await we.getCid(u);await this.deps.messageStore.delete(e,f),await this.deps.messageStore.put(e,u,l)}return c}static constructIndexes(e,r){let{definition:n,...s}=e.message.descriptor,{author:a}=e;return{...s,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 s=await Tr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await Iu.authorizeConfigure({protocolsConfigureMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new ne("ProtocolsConfigureAuthorizationFailed","message failed authorization")}static async validateCompositionDependencies(e,r,n){let{uses:s}=r;if(s===void 0)return;let a=new Map;for(let o in s){let i=s[o],c=await t.fetchInstalledProtocolDefinition(e,i,n);if(c===void 0)throw new ne("ProtocolsConfigureComposedProtocolNotInstalled",`composed protocol '${i}' (alias '${o}') is not installed for tenant '${e}'.`);a.set(o,c)}t.validateRefsAndRolesRecursively(r.structure,"",a)}static async fetchInstalledProtocolDefinition(e,r,n){let s={interface:"Protocols",method:"Configure",protocol:r,isLatestBaseState:!0},{messages:a}=await n.query(e,[s]);if(a.length!==0)return a[0].descriptor.definition}static validateRefsAndRolesRecursively(e,r,n){for(let s in e){if(s.startsWith("$"))continue;let a=e[s],o=r===""?s:`${r}/${s}`;if(a.$ref!==void 0){let c=Bi(a.$ref);if(c!==void 0){let u=n.get(c.alias);if(u===void 0)throw new ne("ProtocolsConfigureInvalidRefAlias",`'$ref' alias '${c.alias}' at protocol path '${o}' was not found in the referenced definitions map.`);let d=c.protocolPath.split("/"),l=u.structure;for(let f=0;f<d.length;f++){let h=d[f],p=l[h];if(p===void 0)throw new ne("ProtocolsConfigureInvalidRefProtocolPath",`'$ref' at protocol path '${o}' references type path '${c.protocolPath}' which does not exist in protocol '${u.protocol}'.`);if(p.$ref!==void 0){let m=d.slice(0,f+1).join("/");throw new ne("ProtocolsConfigureInvalidRefTargetThroughRef",`'$ref' at protocol path '${o}' references type path '${c.protocolPath}' in protocol '${u.protocol}', but the node '${m}' is itself a '$ref' composition point. multi-level composition (chaining through '$ref' nodes) is not supported.`)}l=p}}}let i=a.$actions??[];for(let c of i){if(c.role!==void 0){let u=Bi(c.role);if(u!==void 0){let d=n.get(u.alias);if(d===void 0)throw new ne("ProtocolsConfigureInvalidCrossProtocolRole",`cross-protocol role alias '${u.alias}' in '${c.role}' at protocol path '${o}' was not found in the referenced definitions map.`);let l=ld(u.protocolPath,d.structure);if(l===void 0||!l.$role)throw new ne("ProtocolsConfigureInvalidCrossProtocolRole",`cross-protocol role '${c.role}' at protocol path '${o}' does not point to a valid role ($role: true) in protocol '${d.protocol}'.`)}}if(c.of!==void 0){let u=Bi(c.of);if(u!==void 0){let d=n.get(u.alias);if(d===void 0)throw new ne("ProtocolsConfigureInvalidCrossProtocolOf",`cross-protocol 'of' alias '${u.alias}' in '${c.of}' at protocol path '${o}' was not found in the referenced definitions map.`);if(ld(u.protocolPath,d.structure)===void 0)throw new ne("ProtocolsConfigureInvalidCrossProtocolOf",`cross-protocol 'of' reference '${c.of}' at protocol path '${o}' does not point to a valid type path in protocol '${d.protocol}'.`)}}}t.validateRefsAndRolesRecursively(a,o,n)}}};w();ht();w();ir();hs();Vs();ht();Qt();Ao();var hf=class t extends bn{static async parse(e){return e.authorization!==void 0&&await we.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&zn(e.descriptor.filter.protocol),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Protocols",method:"Query",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:e.filter?t.normalizeFilter(e.filter):void 0,permissionGrantId:e.permissionGrantId};qt(r);let n;e.signer!==void 0&&(n=await we.createAuthorization({descriptor:r,signer:e.signer,permissionGrantId:e.permissionGrantId}));let s={descriptor:r,authorization:n};return we.validateJsonSchema(s),new t(s)}static normalizeFilter(e){return{...e,protocol:pi(e.protocol)}}async authorize(e,r){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await Tr.fetchGrant(e,r,this.signaturePayload.permissionGrantId);await Iu.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:r})}else throw new ne("ProtocolsQueryUnauthorized","The ProtocolsQuery failed authorization")}};hs();Qt();var i1=class{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await hf.parse(r)}catch(o){return ut(o,400)}try{await on(r.authorization,this.deps.didResolver),await n.authorize(e,this.deps.messageStore)}catch(o){if(o.code==="AuthenticateJwsMissing"||o.code==="ProtocolsQueryUnauthorized"||o.code==="ProtocolsGrantAuthorizationQueryProtocolScopeMismatch"){let i=await this.fetchPublishedProtocolsConfigure(e,n);return{status:{code:200,detail:"OK"},entries:i}}else return ut(o,401)}let s={...r.descriptor.filter,interface:"Protocols",method:"Configure",isLatestBaseState:!0};qt(s);let{messages:a}=await this.deps.messageStore.query(e,[s]);return{status:{code:200,detail:"OK"},entries:a}}async fetchPublishedProtocolsConfigure(e,r){let n={...r.message.descriptor.filter,interface:"Protocols",method:"Configure",published:!0,isLatestBaseState:!0},{messages:s}=await this.deps.messageStore.query(e,[n]);return s}};w();ir();w();Ja();ht();Qt();w();ya();vi();ht();Qt();async function qg(t,e,r,n,s,a,o,i){let c=e.signaturePayload?.protocolRole;if(c===void 0)return;let u=r,d=c;if(pf(c)){let p=Bi(c);if(p===void 0)throw new ne("ProtocolAuthorizationNotARole",`Cross-protocol role '${c}' could not be parsed as a valid 'alias:path' format.`);if(s.uses===void 0||s.uses[p.alias]===void 0)throw new ne("ProtocolAuthorizationNotARole",`Cross-protocol role alias '${p.alias}' in '${c}' does not exist in the protocol's 'uses' map.`);u=s.uses[p.alias],d=p.protocolPath;let m=await o(t,u,a,i),y=ld(d,m.structure);if(y===void 0||!y.$role)throw new ne("ProtocolAuthorizationNotARole",`Cross-protocol role path ${c} does not match role record type.`)}else{let p=ld(c,s.structure);if(p===void 0||!p.$role)throw new ne("ProtocolAuthorizationNotARole",`Protocol path ${c} does not match role record type.`)}let l={interface:"Records",method:"Write",protocol:u,protocolPath:d,recipient:e.author,isLatestBaseState:!0},f=d.split("/").length-1;if(n===void 0&&f>0)throw new ne("ProtocolAuthorizationMissingContextId","Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=Wt.constructPrefixFilterAsRangeFilter(m);l.contextId=y}let{messages:h}=await a.query(t,[l]);if(h.length===0)throw new ne("ProtocolAuthorizationMatchingRoleRecordNotFound",`No matching role record found for protocol path ${d}`)}async function Hre(t,e,r){switch(e.message.descriptor.method){case"Delete":let n=e,s=n.message.descriptor.recordId,a=await St.fetchInitialRecordsWrite(r,t,s);if(a===void 0)return[];let o=[];return n.message.descriptor.prune?(o.push("co-prune"),e.author===a.author&&o.push("prune")):(o.push("co-delete"),e.author===a.author&&o.push("delete")),o;case"Count":return["read"];case"Query":return["read"];case"Read":return["read"];case"Subscribe":return["read"];case"Write":let c=e;if(await c.isInitialWrite())return c.message.descriptor.squash===!0?["squash","create"]:["create"];{let u=e.message.recordId,d=await St.fetchInitialRecordsWrite(r,t,u);return d===void 0?[]:e.author===d.author?["co-update","update"]:["co-update"]}}return[]}async function Fg(t,e,r,n,s,a){let o=e.message.descriptor.method,i=await Hre(t,e,s),c=e.author,u=r.$actions;if(u===void 0)throw new ne("ProtocolAuthorizationActionRulesNotFound",`no action rule defined for Records${o}, ${c} is unauthorized`);let d=e.signaturePayload?.protocolRole;for(let l of u){if(!l.can.some(p=>i.includes(p)))continue;if(l.who==="anyone")return;if(c===void 0)continue;if(d!==void 0){if(l.role===d)return;continue}if(l.who==="recipient"&&l.of===void 0){let p;if(e.message.descriptor.method==="Write"?p=e.message:p=n[n.length-1],p.descriptor.recipient===c)return;continue}if(await Jre(c,l,n,a))return}throw new ne("ProtocolAuthorizationActionNotAllowed",`Inbound message action Records${o} by author ${e.author} not allowed.`)}async function Jre(t,e,r,n){let s=e.of;if(s===void 0)return!1;let a;if(pf(s)&&n?.uses!==void 0){let o=Bi(s);if(o!==void 0){let i=n.uses[o.alias];i!==void 0&&(a=r.find(c=>c.descriptor.protocol===i&&c.descriptor.protocolPath===o.protocolPath))}}else a=r.find(o=>o.descriptor.protocolPath===s);if(a===void 0)return!1;if(e.who==="recipient")return t===a.descriptor.recipient;{let o=(await St.parse(a)).author;return t===o}}w();vi();ht();Qt();async function Ah(t,e,r){let n={interface:"Records",method:"Write",recordId:e},{messages:s}=await r.query(t,[n]);return s.length===0?void 0:await St.getInitialWrite(s)}async function Gg(t,e,r){if(e===void 0)return[];let n=[],s=e;for(;s!==void 0;){let a=await Ah(t,s,r);if(a===void 0)throw new ne("ProtocolAuthorizationParentNotFoundConstructingRecordChain",`Unexpected error that should never trigger: no parent found with ID ${s} when constructing record chain.`);n.push(a),s=a.descriptor.parentId}return n.reverse()}async function sI(t,e,r){let n=await Ah(t,e.message.recordId,r);if(n!==void 0)return n.descriptor.messageTimestamp}w();var fN=Nn(rI(),1);ya();$n();ht();Qt();async function pN(t,e,r,n,s){let a=e.message.descriptor.protocolPath,o=n1(a),i=e.message.descriptor.parentId;if(i===void 0){if(a!==o)throw new ne("ProtocolAuthorizationParentlessIncorrectProtocolPath",`Declared protocol path '${a}' is not valid for records with no parent'.`);return}let c=e.message.descriptor.protocol,u=await Zre(t,c,a,r,n,s),d={isLatestBaseState:!0,interface:"Records",method:"Write",protocol:u,recordId:i},{messages:l}=await r.query(t,[d]),f=l[0];if(f===void 0)throw u!==c?new ne("ProtocolAuthorizationCrossProtocolParentNotFound",`Could not find parent record '${i}' in protocol '${u}' for cross-protocol child at path '${a}'.`):new ne("ProtocolAuthorizationIncorrectProtocolPath",`Could not find matching parent record to verify declared protocol path '${a}'.`);if(`${f.descriptor.protocolPath}/${o}`!==a)throw new 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 ne("ProtocolAuthorizationIncorrectContextId",`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function Zre(t,e,r,n,s,a){let o=r.split("/");if(o.length<=1)return e;let i=await s(t,e,n,a),c=i.structure[o[0]];if(c?.$ref!==void 0){let u=Bi(c.$ref);if(u!==void 0&&i.uses!==void 0){let d=i.uses[u.alias];if(d!==void 0)return o.length===2?d:e}}return e}async function hN(t,e,r,n,s,a){let o=e.descriptor.protocolPath,i=n1(o),c=await Yre(t,o,r,n,s,a);Qre(e,c,i)}async function Yre(t,e,r,n,s,a){let o=e.split("/"),i=r.structure[o[0]];if(i?.$ref!==void 0&&o.length===1){let c=Bi(i.$ref);if(c!==void 0&&r.uses!==void 0){let u=r.uses[c.alias];if(u!==void 0)return(await s(t,u,n,a)).types}}return r.types}function Qre(t,e,r){let n=r??n1(t.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new ne("ProtocolAuthorizationInvalidType",`record with type ${n} not allowed in protocol`);let a=e[n],{schema:o}=t.descriptor;if(a.schema!==void 0&&a.schema!==o)throw new ne("ProtocolAuthorizationInvalidSchema",`type '${n}' must have schema '${a.schema}', instead has '${o}'`);let{dataFormat:i}=t.descriptor;if(a.dataFormats!==void 0&&!a.dataFormats.includes(i))throw new ne("ProtocolAuthorizationIncorrectDataFormat",`type '${n}' must have data format in (${a.dataFormats}), instead has '${i}'`);if(a.encryptionRequired===!0&&t.encryption===void 0)throw new ne("ProtocolAuthorizationEncryptionRequired",`type '${n}' requires encryption but message has no encryption metadata`)}function mN(t,e){let{min:r=0,max:n}=e.$size||{},s=t.message.descriptor.dataSize;if(s<r)throw new ne("ProtocolAuthorizationMinSizeInvalid",`data size ${s} is less than allowed ${r}`);if(n!==void 0&&s>n)throw new ne("ProtocolAuthorizationMaxSizeInvalid",`data size ${s} is more than allowed ${n}`)}function yN(t,e){if(e.$tags!==void 0){let{tags:r={},protocol:n,protocolPath:s}=t.message.descriptor,{$allowUndefinedTags:a,$requiredTags:o,...i}=e.$tags,c=a||!1,u=o||[],d=new fN.default.default,l=d.compile({type:"object",properties:i,required:u,additionalProperties:c});if(!l(r)){let h=d.errorsText(l.errors,{dataVar:`${n}/${s}/$tags`});throw new ne("ProtocolAuthorizationTagsInvalidSchema",`tags schema validation error: ${h}`)}}}async function gN(t,e,r,n){if(!r.$role)return;let s=e,a=s.message.descriptor.recipient;if(a===void 0)throw new ne("ProtocolAuthorizationRoleMissingRecipient","Role records must have a recipient");let o=s.message.descriptor.protocolPath,i={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:s.message.descriptor.protocol,protocolPath:o,recipient:a},c=ke.getParentContextFromOfContextId(s.message.contextId);if(c!==""){let f=Wt.constructPrefixFilterAsRangeFilter(c);i.contextId=f}let{messages:u}=await n.query(t,[i]);if(u.filter(f=>f.recordId!==s.message.recordId).length>0)throw new ne("ProtocolAuthorizationDuplicateRoleRecipient",`DID '${a}' is already recipient of a role record at protocol path '${o} under the parent context ${c}.`)}async function wN(t,e,r,n){if(r.$recordLimit===void 0||!await e.isInitialWrite())return;let{max:a,strategy:o}=r.$recordLimit,i=e.message.descriptor.protocolPath,c={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:e.message.descriptor.protocol,protocolPath:i},u=ke.getParentContextFromOfContextId(e.message.contextId);if(u!==""){let l=Wt.constructPrefixFilterAsRangeFilter(u);c.contextId=l}if(await n.count(t,[c])>=a)throw o==="reject"?new ne("ProtocolAuthorizationRecordLimitExceeded",`record limit of ${a} reached at protocol path '${i}'${u!==""?` under parent context '${u}'`:""}: new records are rejected until existing records are deleted.`):new ne("ProtocolAuthorizationRecordLimitStrategyNotImplemented",`record limit strategy '${o}' is not yet implemented.`)}async function vN(t,e){if(t.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new 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 ne("ProtocolAuthorizationSquashNotInitialWrite","squash write must be an initial write (a new record): updates cannot be squash writes.")}async function bN(t,e){if(!(e.$immutable!==!0||await t.isInitialWrite()))throw new ne("ProtocolAuthorizationImmutableRecord",`record at protocol path '${t.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var Ys=class t{static async validateReferentialIntegrity(e,r,n,s){let a=await sI(e,r,n),o=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,a,s),i=t.createBoundFetchDefinition(s);await hN(e,r.message,o,n,i,a),await pN(e,r,n,i,a);let c=t.getRuleSet(r.message.descriptor.protocolPath,o);await gN(e,r,c,n),mN(r,c),yN(r,c),await bN(r,c),await vN(r,c),await wN(e,r,c,n)}static async authorizeWrite(e,r,n,s){let a=await Ah(e,r.message.recordId,n),o;a===void 0?o=await Gg(e,r.message.descriptor.parentId,n):o=await Gg(e,r.message.recordId,n);let i=await sI(e,r,n),c=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,i,s),u=t.getRuleSet(r.message.descriptor.protocolPath,c),d=t.createBoundFetchDefinition(s);await qg(e,r,r.message.descriptor.protocol,r.message.contextId,c,n,d,i),await Fg(e,r,u,o,n,c)}static async authorizeRead(e,r,n,s,a){let o=await Gg(e,n.message.recordId,s),i=await Ah(e,n.message.recordId,s),c=i!==void 0?i.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,u=await t.fetchProtocolDefinition(e,n.message.descriptor.protocol,s,c,a),d=t.getRuleSet(n.message.descriptor.protocolPath,u),l=t.createBoundFetchDefinition(a);await qg(e,r,n.message.descriptor.protocol,n.message.contextId,u,s,l,c),await Fg(e,r,d,o,s,u)}static async authorizeQueryOrSubscribe(e,r,n,s){let{protocol:a,protocolPath:o,contextId:i}=r.message.descriptor.filter,c=await t.fetchProtocolDefinition(e,a,n,void 0,s),u=t.getRuleSet(o,c),d=t.createBoundFetchDefinition(s);await qg(e,r,a,i,c,n,d),await Fg(e,r,u,[],n,c)}static async authorizeDelete(e,r,n,s,a){let o=await Gg(e,r.message.descriptor.recordId,s),i=await Ah(e,r.message.descriptor.recordId,s),c=i!==void 0?i.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,u=await t.fetchProtocolDefinition(e,n.message.descriptor.protocol,s,c,a),d=t.getRuleSet(n.message.descriptor.protocolPath,u),l=t.createBoundFetchDefinition(a);await qg(e,r,n.message.descriptor.protocol,n.message.contextId,u,s,l,c),await Fg(e,r,d,o,s,u)}static async fetchProtocolDefinition(e,r,n,s,a){if(a!==void 0){let u=a.getDefinition(r);if(u!==void 0)return u}let o={interface:"Protocols",method:"Configure",protocol:r};s!==void 0?o.messageTimestamp={lte:s}:o.isLatestBaseState=!0;let{messages:i}=await n.query(e,[o],{messageTimestamp:-1},{limit:1});if(i.length===0)throw new ne("ProtocolAuthorizationProtocolNotFound",`unable to find protocol definition for ${r}`);return i[0].descriptor.definition}static createBoundFetchDefinition(e){return(r,n,s,a)=>t.fetchProtocolDefinition(r,n,s,a,e)}static getRuleSet(e,r){let n=ld(e,r.structure);if(n===void 0)throw new ne("ProtocolAuthorizationMissingRuleSet",`No rule set defined for protocolPath ${e}`);return n}};$n();Qt();var o1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Hl.parse(r)}catch(a){return ut(a,400)}let s;if(ke.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)s=await this.countPublishedRecords(e,n);else{try{await on(r.authorization,this.deps.didResolver),await t.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(a){return ut(a,401)}n.author===e?s=await this.countRecordsAsOwner(e,n):s=await this.countRecordsAsNonOwner(e,n)}return{status:{code:200,detail:"OK"},count:s}}async countRecordsAsOwner(e,r){let{filter:n}=r.message.descriptor,s={...ke.convertFilter(n),interface:"Records",method:"Write",isLatestBaseState:!0};return this.deps.messageStore.count(e,[s])}async countRecordsAsNonOwner(e,r){let{filter:n}=r.message.descriptor,s=[];return ke.filterIncludesPublishedRecords(n)&&s.push(t.buildPublishedRecordsFilter(r)),ke.filterIncludesUnpublishedRecords(n)&&(ke.shouldBuildUnpublishedAuthorFilter(n,r.author)&&s.push(t.buildUnpublishedRecordsByCountAuthorFilter(r)),ke.shouldProtocolAuthorize(r.signaturePayload)&&s.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),ke.shouldBuildUnpublishedRecipientFilter(n,r.author)&&s.push(t.buildUnpublishedRecordsForCountAuthorFilter(r))),this.deps.messageStore.count(e,s)}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{...ke.convertFilter(r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{...ke.convertFilter(r),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:r}=e.message.descriptor;return{...ke.convertFilter(r),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{...ke.convertFilter(r),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,r,n,s){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),ke.shouldProtocolAuthorize(r.signaturePayload)&&await Ys.authorizeQueryOrSubscribe(e,r,n,s)}};w();Qt();ir();$n();w();ir();la();$n();Ya();hs();Vs();Qt();var pd=class t extends bn{static async parse(e){let r;return e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r=e.recordId,n=yt.getCurrentTimestamp(),s={interface:"Records",method:"Delete",messageTimestamp:e.messageTimestamp??n,recordId:r,prune:e.prune??!1},a=await we.createAuthorization({descriptor:s,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),o={descriptor:s,authorization:a};return we.validateJsonSchema(o),new t(o)}constructIndexes(e){let n={...this.message.descriptor},{protocol:s,protocolPath:a,recipient:o,schema:i,parentId:c,dateCreated:u}=e.descriptor,d={isLatestBaseState:!0,protocol:s,protocolPath:a,recipient:o,schema:i,parentId:c,dateCreated:u,contextId:e.contextId,author:this.author,...n};return qt(d),d}async authorizeDelegate(e,r){let n=Zr.parse(this.message.authorization.authorDelegatedGrant);await Sn.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}};Ya();vi();w();var a1=class t{constructor(e,r){this.resumableTaskStore=e;this.resumableTaskHandlers={RecordsDelete:async n=>await r.performRecordsDelete(n),RecordsSquash:async n=>await r.performRecordsSquash(n)}}static timeoutExtensionFrequencyInSeconds=30;resumableTaskBatchSize=100;resumableTaskHandlers;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 s=this.resumableTaskHandlers[e.task.name];await s(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 s of n)try{await this.runWithAutomaticTimeoutExtension(s)}catch(a){console.error("Error while running resumable task:",a),console.error("Resumable task:",s),r.push(s)}}}};var c1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await pd.parse(r)}catch(u){return ut(u,400)}try{await on(r.authorization,this.deps.didResolver)}catch(u){return ut(u,401)}let s={interface:"Records",recordId:r.descriptor.recordId},{messages:a}=await this.deps.messageStore.query(e,[s]),o=await we.getNewestMessage(a);if(!ke.canPerformDeleteAgainstRecord(r,o))return{status:{code:404,detail:"Not Found"}};if(!await we.isNewer(r,o))return{status:{code:409,detail:"Conflict"}};try{let u=await St.fetchInitialRecordsWrite(this.deps.messageStore,e,r.descriptor.recordId);await t.authorizeRecordsDelete(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return ut(u,401)}return await this.deps.resumableTaskManager.run({name:"RecordsDelete",data:{tenant:e,message:r}}),{status:{code:202,detail:"Accepted"}}}static async authorizeRecordsDelete(e,r,n,s,a){if(we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n.message,s),r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let o=await Tr.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await Sn.authorizeDelete({recordsDeleteMessage:r.message,recordsWriteToDelete:n.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:o,messageStore:s})}else await Ys.authorizeDelete(e,r,n,s,a)}};w();Il();ir();$n();vi();Ja();Qt();var d1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Jl.parse(r)}catch(o){return ut(o,400)}let s,a;if(ke.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0){let o=await this.fetchPublishedRecords(e,n);s=o.messages,a=o.cursor}else{try{await on(r.authorization,this.deps.didResolver),await t.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(o){return ut(o,401)}if(n.author===e){let o=await this.fetchRecordsAsOwner(e,n);s=o.messages,a=o.cursor}else{let o=await this.fetchRecordsAsNonOwner(e,n);s=o.messages,a=o.cursor}}for(let o of s)if(!await St.isInitialWrite(o)){let c=(await this.deps.messageStore.query(e,[{recordId:o.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete c.encodedData,o.initialWrite=c}return{status:{code:200,detail:"OK"},entries:s,cursor:a}}convertDateSort(e){switch(e){case"createdAscending":return{dateCreated:1};case"createdDescending":return{dateCreated:-1};case"publishedAscending":return{datePublished:1};case"publishedDescending":return{datePublished:-1};case"updatedAscending":return{messageTimestamp:1};case"updatedDescending":return{messageTimestamp:-1};default:return{dateCreated:1}}}async fetchRecordsAsOwner(e,r){let{dateSort:n,filter:s,pagination:a}=r.message.descriptor,o={...ke.convertFilter(s,n),interface:"Records",method:"Write",isLatestBaseState:!0},i=this.convertDateSort(n);return this.deps.messageStore.query(e,[o],i,a)}async fetchRecordsAsNonOwner(e,r){let{dateSort:n,pagination:s,filter:a}=r.message.descriptor,o=[];ke.filterIncludesPublishedRecords(a)&&o.push(t.buildPublishedRecordsFilter(r)),ke.filterIncludesUnpublishedRecords(a)&&(ke.shouldBuildUnpublishedAuthorFilter(a,r.author)&&o.push(t.buildUnpublishedRecordsByQueryAuthorFilter(r)),ke.shouldProtocolAuthorize(r.signaturePayload)&&o.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),ke.shouldBuildUnpublishedRecipientFilter(a,r.author)&&o.push(t.buildUnpublishedRecordsForQueryAuthorFilter(r)));let i=this.convertDateSort(n);return this.deps.messageStore.query(e,o,i,s)}async fetchPublishedRecords(e,r){let{dateSort:n,pagination:s}=r.message.descriptor,a=t.buildPublishedRecordsFilter(r),o=this.convertDateSort(n);return this.deps.messageStore.query(e,[a],o,s)}static buildPublishedRecordsFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,r),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,r),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,r),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,r,n,s){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),ke.shouldProtocolAuthorize(r.signaturePayload)&&await Ys.authorizeQueryOrSubscribe(e,r,n,s)}};w();Vd();ln();ir();$n();Ya();w();Il();ir();la();$n();Ya();hs();Vs();ht();Qt();var Wg=class t extends bn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort==="publishedAscending"||e.descriptor.dateSort==="publishedDescending"))throw new 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 ke.validateDelegatedGrantReferentialIntegrity(e,r),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let{filter:r,signer:n,permissionGrantId:s,protocolRole:a,dateSort:o}=e,i=yt.getCurrentTimestamp();if(e.filter.published===!1&&(o==="publishedAscending"||o==="publishedDescending"))throw new ne("RecordsReadCreateFilterPublishedSortInvalid",`reads must not filter for \`published:false\` and sort by ${o}`);let c={interface:"Records",method:"Read",filter:ke.normalizeFilter(r),messageTimestamp:e.messageTimestamp??i,permissionGrantId:s,dateSort:o};qt(c);let u;n!==void 0&&(u=await we.createAuthorization({descriptor:c,signer:n,permissionGrantId:s,protocolRole:a,delegatedGrant:e.delegatedGrant}));let d={descriptor:c,authorization:u};return we.validateJsonSchema(d),new t(d)}async authorizeDelegate(e,r){let n=Zr.parse(this.message.authorization.authorDelegatedGrant);await Sn.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}};vi();ht();Qt();var u1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Wg.parse(r)}catch(l){return ut(l,400)}try{n.author!==void 0&&await on(r.authorization,this.deps.didResolver)}catch(l){return ut(l,401)}let s={interface:"Records",isLatestBaseState:!0,...ke.convertFilter(r.descriptor.filter)},a=ke.convertDateSort(r.descriptor.dateSort),{messages:o}=await this.deps.messageStore.query(e,[s],a,{limit:1});if(o.length===0)return{status:{code:404,detail:"Not Found"}};let i=o[0];if(i.descriptor.method==="Delete"){let l=i,f=l.descriptor.recordId,h=await St.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(h===void 0)return ut(new ne("RecordsReadInitialWriteNotFound","initial write for deleted record not found"),400);let p;try{p=await St.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{p=h}let m=await St.parse(p);try{await t.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return ut(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:l,initialWrite:h}}}let c=i;try{let l=await St.parse(c);await t.authorizeRecordsRead(e,n,l,this.deps.messageStore,this.deps.coreProtocols)}catch(l){return ut(l,401)}let u;if(c.encodedData!==void 0){let l=Te.base64UrlToBytes(c.encodedData);u=ts.fromBytes(l),delete c.encodedData}else{let l=await this.deps.dataStore.get(e,c.recordId,c.descriptor.dataCid);if(l?.dataStream===void 0)return{status:{code:410,detail:"Record data not available"},entry:{recordsWrite:c}};u=l.dataStream}let d={status:{code:200,detail:"OK"},entry:{recordsWrite:c,data:u}};if(!await St.isInitialWrite(c)){let f=(await this.deps.messageStore.query(e,[{recordId:c.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete f.encodedData,d.entry.initialWrite=f}return d}static async authorizeRecordsRead(e,r,n,s,a){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n.message,s);let{descriptor:o}=n.message;if(r.author!==e){if(o.published===!0)return;if(r.author!==void 0&&(r.author===o.recipient||r.author===n.author))return;if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let i=await Tr.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await Sn.authorizeRead({recordsReadMessage:r.message,recordsWriteMessageToBeRead:n.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:i,messageStore:s})}else await Ys.authorizeRead(e,r,n,s,a)}}};w();Il();ir();$n();w();ir();la();$n();Ya();hs();Vs();ht();Qt();Ao();var mf=class t extends bn{static async parse(e){let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne("RecordsSubscribeFilterMissingRequiredProperties","Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&zn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Za(e.descriptor.filter.schema),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Records",method:"Subscribe",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:ke.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};qt(r);let n=e.signer,s;n&&(s=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Zr.parse(this.message.authorization.authorDelegatedGrant);await Sn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}};vi();Ja();ht();Qt();var l1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return ut(new ne("RecordsSubscribeEventLogUnimplemented","Subscriptions are not supported"),501);let s;try{s=await mf.parse(r)}catch(f){return ut(f,400)}let a=[],o=[];if(ke.filterIncludesPublishedRecords(s.message.descriptor.filter)&&s.author===void 0)a=[t.buildPublishedEventFilter(s)],o=[t.buildPublishedQueryFilter(s)],delete r.authorization;else{try{await on(r.authorization,this.deps.didResolver),await t.authorizeRecordsSubscribe(e,s,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return ut(f,401)}s.author===e?(a=t.buildOwnerEventFilters(s),o=t.buildOwnerQueryFilters(s)):(a=t.buildNonOwnerEventFilters(s),o=t.buildNonOwnerQueryFilters(s))}let i=await we.getCid(r),{cursor:c}=s.message.descriptor;if(c!==void 0)try{let f=await this.deps.eventLog.subscribe(e,i,n,{cursor:c,filters:a});return{status:{code:200,detail:"OK"},subscription:f}}catch(f){return ut(f,500)}let u=await this.deps.eventLog.subscribe(e,i,n,{filters:a}),d,l;try{let{dateSort:f,pagination:h}=s.message.descriptor,p=t.convertDateSort(f),m=await this.deps.messageStore.query(e,o,p,h);d=m.messages,l=m.cursor;for(let y of d)if(!await St.isInitialWrite(y)){let v=(await this.deps.messageStore.query(e,[{recordId:y.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete v.encodedData,y.initialWrite=v}}catch(f){return await u.close(),ut(f,500)}return{status:{code:200,detail:"OK"},subscription:u,entries:d,cursor:l}}static convertDateSort(e){switch(e){case"createdAscending":return{dateCreated:1};case"createdDescending":return{dateCreated:-1};case"publishedAscending":return{datePublished:1};case"publishedDescending":return{datePublished:-1};case"updatedAscending":return{messageTimestamp:1};case"updatedDescending":return{messageTimestamp:-1};default:return{dateCreated:1}}}static buildOwnerEventFilters(e){let{filter:r}=e.message.descriptor;return[{...ke.convertFilter(r),interface:"Records",method:["Write","Delete"]}]}static buildNonOwnerEventFilters(e){let r=[],{filter:n}=e.message.descriptor;return ke.filterIncludesPublishedRecords(n)&&r.push(t.buildPublishedEventFilter(e)),ke.filterIncludesUnpublishedRecords(n)&&(ke.shouldBuildUnpublishedAuthorFilter(n,e.author)&&r.push({...ke.convertFilter(n),author:e.author,interface:"Records",method:["Write","Delete"],published:!1}),ke.shouldProtocolAuthorize(e.signaturePayload)&&r.push({...ke.convertFilter(n),interface:"Records",method:["Write","Delete"],published:!1}),ke.shouldBuildUnpublishedRecipientFilter(n,e.author)&&r.push({...ke.convertFilter(n),interface:"Records",method:["Write","Delete"],recipient:e.author,published:!1})),r}static buildPublishedEventFilter(e){return{...ke.convertFilter(e.message.descriptor.filter),interface:"Records",method:["Write","Delete"],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:r,filter:n}=e.message.descriptor;return[{...ke.convertFilter(n,r),interface:"Records",method:"Write",isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let r=[],{dateSort:n,filter:s}=e.message.descriptor;return ke.filterIncludesPublishedRecords(s)&&r.push(t.buildPublishedQueryFilter(e)),ke.filterIncludesUnpublishedRecords(s)&&(ke.shouldBuildUnpublishedAuthorFilter(s,e.author)&&r.push({...ke.convertFilter(s,n),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}),ke.shouldProtocolAuthorize(e.signaturePayload)&&r.push({...ke.convertFilter(s,n),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}),ke.shouldBuildUnpublishedRecipientFilter(s,e.author)&&r.push({...ke.convertFilter(s,n),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1})),r}static buildPublishedQueryFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,r,n,s){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),ke.shouldProtocolAuthorize(r.signaturePayload)&&await Ys.authorizeQueryOrSubscribe(e,r,n,s)}};w();Vc();Vd();ln();ya();ir();$n();Ya();vi();Ja();w();ya();ir();$n();vi();Qt();var Rh=class t{messageStore;dataStore;stateIndex;eventLog;constructor({messageStore:e,dataStore:r,stateIndex:n,eventLog:s}){this.messageStore=e,this.dataStore=r,this.stateIndex=n,this.eventLog=s}async performRecordsDelete({tenant:e,message:r}){let n={interface:"Records",recordId:r.descriptor.recordId},{messages:s}=await this.messageStore.query(e,[n]),a=await we.getNewestMessage(s);if(!ke.canPerformDeleteAgainstRecord(r,a))return;let o=await pd.parse(r),i=await St.getInitialWrite(s),c=o.constructIndexes(i),u=await we.getCid(r);await this.messageStore.put(e,r,c),await this.stateIndex.insert(e,u,c),this.eventLog!==void 0&&await this.eventLog.emit(e,{message:r,initialWrite:i},c),r.descriptor.prune&&await t.purgeRecordDescendants(e,r.descriptor.recordId,this.messageStore,this.dataStore,this.stateIndex),await t.deleteAllOlderMessagesButKeepInitialWrite(e,s,r,this.messageStore,this.dataStore,this.stateIndex)}async performRecordsSquash({tenant:e,message:r}){let{protocol:n,protocolPath:s,messageTimestamp:a}=r.descriptor,o={interface:"Records",protocol:n,protocolPath:s},i=ke.getParentContextFromOfContextId(r.contextId);if(i!==void 0&&i!==""){let d=Wt.constructPrefixFilterAsRangeFilter(i);o.contextId=d}let{messages:c}=await this.messageStore.query(e,[o]),u=new Map;for(let d of c){let l;ke.isRecordsWrite(d)?l=d.recordId:l=d.descriptor.recordId;let f=u.get(l);f!==void 0?f.push(d):u.set(l,[d])}for(let[d,l]of u){if(d===r.recordId)continue;let f=await we.getNewestMessage(l);if(f===void 0)continue;f.descriptor.messageTimestamp<a&&await t.purgeRecordMessages(e,l,this.messageStore,this.dataStore,this.stateIndex)}}static async deleteFromDataStoreIfNeeded(e,r,n,s){if(n.descriptor.method!=="Write")return;let a=n;a.descriptor.dataSize<=dc.maxDataSizeAllowedToBeEncoded||a.descriptor.dataCid!==s.descriptor.dataCid&&await e.delete(r,a.recordId,a.descriptor.dataCid)}static async purgeRecordDescendants(e,r,n,s,a){let o={interface:"Records",parentId:r},{messages:i}=await n.query(e,[o]),c=new Map;for(let u of i){let d;ke.isRecordsWrite(u)?d=u.recordId:d=u.descriptor.recordId;let l=c.get(d);l?l.push(u):c.set(d,[u])}for(let u of c.keys())await t.purgeRecordDescendants(e,u,n,s,a);for(let u of c.keys())await t.purgeRecordMessages(e,c.get(u),n,s,a)}static async purgeRecordMessages(e,r,n,s,a){let o=r.filter(u=>u.descriptor.method==="Write"),i=await we.getNewestMessage(o);await s.delete(e,i.recordId,i.descriptor.dataCid);let c=await Promise.all(r.map(u=>we.getCid(u)));await a.delete(e,c),await Promise.all(c.map(u=>n.delete(e,u)))}static async deleteAllOlderMessagesButKeepInitialWrite(e,r,n,s,a,o){let i=[];for(let c of r){if(await we.isOlder(c,n)){await t.deleteFromDataStoreIfNeeded(a,e,c,n);let d=await we.getCid(c);if(await s.delete(e,d),await St.isInitialWrite(c)){let p=await(await St.parse(c)).constructIndexes(!1),m=c;delete m.encodedData,await s.put(e,m,p)}else{let f=await we.getCid(c);i.push(f)}}await o.delete(e,i)}}};ht();Qt();var f1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,dataStream:n}){let s;try{s=await St.parse(r),await Ys.validateReferentialIntegrity(e,s,this.deps.messageStore,this.deps.coreProtocols)}catch(p){return ut(p,400)}try{await on(r.authorization,this.deps.didResolver,r.attestation),await this.authorizeRecordsWrite(e,s,this.deps.messageStore)}catch(p){return ut(p,401)}let a={interface:"Records",recordId:r.recordId},{messages:o}=await this.deps.messageStore.query(e,[a]),i=await s.isInitialWrite(),c;if(!i)try{c=await St.getInitialWrite(o),St.verifyEqualityOfImmutableProperties(c,r)}catch(p){return ut(p,400)}try{await this.enforceSquashBackstop(e,r)}catch(p){return ut(p,409)}let u=await we.getNewestMessage(o),d=!1,l;if(u===void 0||await we.isNewer(r,u)?(d=!0,l=r):l=u,!d)return{status:{code:409,detail:"Conflict"}};let f=r.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(r.descriptor.protocol):void 0;try{if(u?.descriptor.method==="Delete")throw new 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(!i){let S=u;m=await this.processMessageWithoutDataStream(e,r,S),p=!0}let y=await s.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:c},y)}catch(p){if(p instanceof ne&&(p.code==="RecordsWriteMissingEncodedDataInPrevious"||p.code==="RecordsWriteMissingDataInPrevious"||p.code==="RecordsWriteNotAllowedAfterDelete"||p.code==="RecordsWriteDataCidMismatch"||p.code==="RecordsWriteDataSizeMismatch"||p.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(p.code)!==void 0))return ut(p,400);throw p}let h={status:i&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await Rh.deleteAllOlderMessagesButKeepInitialWrite(e,o,l,this.deps.messageStore,this.deps.dataStore,this.deps.stateIndex),r.descriptor.squash===!0&&await this.deps.resumableTaskManager.run({name:"RecordsSquash",data:{tenant:e,message:r}}),f?.postProcessWrite!==void 0&&await f.postProcessWrite(e,s,{messageStore:this.deps.messageStore,dataStore:this.deps.dataStore,stateIndex:this.deps.stateIndex}),h}async cloneAndAddEncodedData(e,r){let n={...e};return n.encodedData=Te.bytesToBase64Url(r),n}async processMessageWithDataStream(e,r,n){let s=r;if(r.descriptor.dataSize<=dc.maxDataSizeAllowedToBeEncoded){let a=await ts.toBytes(n),o=await Ar.computeDagPbCidFromBytes(a);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,o,a.length);let i=r.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(r.descriptor.protocol):void 0;i?.validateRecord!==void 0&&i.validateRecord(r,a),s=await this.cloneAndAddEncodedData(r,a)}else{let[a,o]=ts.duplicateDataStream(n,2);try{let[i,c]=await Promise.all([Ar.computeDagPbCidFromStream(a),this.deps.dataStore.put(e,r.recordId,r.descriptor.dataCid,o)]);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,i,c.dataSize)}catch(i){throw await this.deps.dataStore.delete(e,r.recordId,r.descriptor.dataCid),i}}return s}async processMessageWithoutDataStream(e,r,n){let s={...r},{dataCid:a,dataSize:o}=r.descriptor;if(t.validateDataIntegrity(a,o,n.descriptor.dataCid,n.descriptor.dataSize),o<=dc.maxDataSizeAllowedToBeEncoded)if(n.encodedData!==void 0)s.encodedData=n.encodedData;else throw new 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 ne("RecordsWriteMissingDataInPrevious","No dataStream was provided and unable to get data from previous message");return s}static validateDataIntegrity(e,r,n,s){if(e!==n)throw new ne("RecordsWriteDataCidMismatch",`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(r!==s)throw new ne("RecordsWriteDataSizeMismatch",`actual data size ${s} 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(d){console.warn(`enforceSquashBackstop: failed to fetch protocol definition for '${r.descriptor.protocol}':`,d);return}let s=r.descriptor.protocolPath.split("/"),a=n.structure[s[0]];for(let d=1;d<s.length&&a!==void 0;d++)a=a[s[d]];if(a===void 0||a.$squash!==!0)return;let o={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:r.descriptor.protocol,protocolPath:r.descriptor.protocolPath,squash:!0},i=ke.getParentContextFromOfContextId(r.contextId);if(i!==void 0&&i!==""){let d=Wt.constructPrefixFilterAsRangeFilter(i);o.contextId=d}let{messages:c}=await this.deps.messageStore.query(e,[o],{messageTimestamp:-1},{limit:1});if(c.length===0)return;let u=c[0];if(r.descriptor.messageTimestamp<=u.descriptor.messageTimestamp)throw new ne("ProtocolAuthorizationSquashBackstop",`incoming message timestamp '${r.descriptor.messageTimestamp}' is not newer than the most recent squash record timestamp '${u.descriptor.messageTimestamp}' at protocol path '${r.descriptor.protocolPath}'.`)}async authorizeRecordsWrite(e,r,n){if(r.owner!==void 0&&r.owner!==e)throw new 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 s=await Tr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await Sn.authorizeWrite({recordsWriteMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else await Ys.authorizeWrite(e,r,n,this.deps.coreProtocols)}}};w();var ene=Object.create,OI=Object.defineProperty,tne=Object.getOwnPropertyDescriptor,rne=Object.getOwnPropertyNames,nne=Object.getPrototypeOf,sne=Object.prototype.hasOwnProperty,Kt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),BI=(t,e)=>{for(var r in e)OI(t,r,{get:e[r],enumerable:!0})},ine=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of rne(e))!sne.call(t,s)&&s!==r&&OI(t,s,{get:()=>e[s],enumerable:!(n=tne(e,s))||n.enumerable});return t},Rf=(t,e,r)=>(r=t!=null?ene(nne(t)):{},ine(e||!t||!t.__esModule?OI(r,"default",{value:t,enumerable:!0}):r,t)),one=Kt((t,e)=>{var r=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,n=()=>r.now(),s=i=>i&&i===Math.floor(i)&&i>0&&isFinite(i),a=i=>i===1/0||s(i),o=class BU{constructor({max:c=1/0,ttl:u,updateAgeOnGet:d=!1,checkAgeOnGet:l=!1,noUpdateTTL:f=!1,dispose:h,noDisposeOnSet:p=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,u!==void 0&&!a(u))throw new TypeError("ttl must be positive integer or Infinity if set");if(!a(c))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=u,this.max=c,this.updateAgeOnGet=!!d,this.checkAgeOnGet=!!l,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(c,u){if(this.timerExpiration<c)return;this.timer&&clearTimeout(this.timer);let d=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let l in this.expirations){this.setTimer(l,l-n());break}},u);d.unref&&d.unref(),this.timerExpiration=c,this.timer=d}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return process.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){let c=this.dispose!==BU.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[u,d]of c)this.dispose(d,u,"delete")}setTTL(c,u=this.ttl){let d=this.expirationMap.get(c);if(d!==void 0){let l=this.expirations[d];!l||l.length<=1?delete this.expirations[d]:this.expirations[d]=l.filter(f=>f!==c)}if(u!==1/0){let l=Math.floor(n()+u);this.expirationMap.set(c,l),this.expirations[l]||(this.expirations[l]=[],this.setTimer(l,u)),this.expirations[l].push(c)}else this.expirationMap.set(c,1/0)}set(c,u,{ttl:d=this.ttl,noUpdateTTL:l=this.noUpdateTTL,noDisposeOnSet:f=this.noDisposeOnSet}={}){if(!a(d))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(c)){l||this.setTTL(c,d);let h=this.data.get(c);h!==u&&(this.data.set(c,u),f||this.dispose(h,c,"set"))}else this.setTTL(c,d),this.data.set(c,u);for(;this.size>this.max;)this.purgeToCapacity();return this}has(c){return this.data.has(c)}getRemainingTTL(c){let u=this.expirationMap.get(c);return u===1/0?u:u!==void 0?Math.max(0,Math.ceil(u-n())):0}get(c,{updateAgeOnGet:u=this.updateAgeOnGet,ttl:d=this.ttl,checkAgeOnGet:l=this.checkAgeOnGet}={}){let f=this.data.get(c);if(l&&this.getRemainingTTL(c)===0){this.delete(c);return}return u&&this.setTTL(c,d),f}dispose(c,u){}delete(c){let u=this.expirationMap.get(c);if(u!==void 0){let d=this.data.get(c);this.data.delete(c),this.expirationMap.delete(c);let l=this.expirations[u];return l&&(l.length<=1?delete this.expirations[u]:this.expirations[u]=l.filter(f=>f!==c)),this.dispose(d,c,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let c in this.expirations){let u=this.expirations[c];if(this.size-u.length>=this.max){delete this.expirations[c];let d=[];for(let l of u)d.push([l,this.data.get(l)]),this.data.delete(l),this.expirationMap.delete(l);for(let[l,f]of d)this.dispose(f,l,"evict")}else{let d=this.size-this.max,l=[];for(let f of u.splice(0,d))l.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of l)this.dispose(h,f,"evict");return}}}get size(){return this.data.size}purgeStale(){let c=Math.ceil(n());for(let u in this.expirations){if(u==="Infinity"||u>c)return;let d=[...this.expirations[u]||[]],l=[];delete this.expirations[u];for(let f of d)l.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of l)this.dispose(h,f,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let c in this.expirations)for(let u of this.expirations[c])yield[u,this.data.get(u)]}*keys(){for(let c in this.expirations)for(let u of this.expirations[c])yield u}*values(){for(let c in this.expirations)for(let u of this.expirations[c])yield this.data.get(u)}[Symbol.iterator](){return this.entries()}};e.exports=o}),ane=Kt(t=>{"use strict";t.supports=function(...e){let r=e.reduce((n,s)=>Object.assign(n,s),{});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)})}}),_c=Kt((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)}}}),cne=Kt(t=>{"use strict";t.byteLength=c,t.toByteArray=d,t.fromByteArray=h;var e=[],r=[],n=typeof Uint8Array<"u"?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(a=0,o=s.length;a<o;++a)e[a]=s[a],r[s.charCodeAt(a)]=a;var a,o;r[45]=62,r[95]=63;function i(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 S=y===m?0:4-y%4;return[y,S]}function c(p){var m=i(p),y=m[0],S=m[1];return(y+S)*3/4-S}function u(p,m,y){return(m+y)*3/4-y}function d(p){var m,y=i(p),S=y[0],v=y[1],E=new n(u(p,S,v)),k=0,A=v>0?S-4:S,D;for(D=0;D<A;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)],E[k++]=m>>16&255,E[k++]=m>>8&255,E[k++]=m&255;return v===2&&(m=r[p.charCodeAt(D)]<<2|r[p.charCodeAt(D+1)]>>4,E[k++]=m&255),v===1&&(m=r[p.charCodeAt(D)]<<10|r[p.charCodeAt(D+1)]<<4|r[p.charCodeAt(D+2)]>>2,E[k++]=m>>8&255,E[k++]=m&255),E}function l(p){return e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63]}function f(p,m,y){for(var S,v=[],E=m;E<y;E+=3)S=(p[E]<<16&16711680)+(p[E+1]<<8&65280)+(p[E+2]&255),v.push(l(S));return v.join("")}function h(p){for(var m,y=p.length,S=y%3,v=[],E=16383,k=0,A=y-S;k<A;k+=E)v.push(f(p,k,k+E>A?A:k+E));return S===1?(m=p[y-1],v.push(e[m>>2]+e[m<<4&63]+"==")):S===2&&(m=(p[y-2]<<8)+p[y-1],v.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),v.join("")}}),dne=Kt(t=>{t.read=function(e,r,n,s,a){var o,i,c=a*8-s-1,u=(1<<c)-1,d=u>>1,l=-7,f=n?a-1:0,h=n?-1:1,p=e[r+f];for(f+=h,o=p&(1<<-l)-1,p>>=-l,l+=c;l>0;o=o*256+e[r+f],f+=h,l-=8);for(i=o&(1<<-l)-1,o>>=-l,l+=s;l>0;i=i*256+e[r+f],f+=h,l-=8);if(o===0)o=1-d;else{if(o===u)return i?NaN:(p?-1:1)*(1/0);i=i+Math.pow(2,s),o=o-d}return(p?-1:1)*i*Math.pow(2,o-s)},t.write=function(e,r,n,s,a,o){var i,c,u,d=o*8-a-1,l=(1<<d)-1,f=l>>1,h=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:o-1,m=s?1:-1,y=r<0||r===0&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(c=isNaN(r)?1:0,i=l):(i=Math.floor(Math.log(r)/Math.LN2),r*(u=Math.pow(2,-i))<1&&(i--,u*=2),i+f>=1?r+=h/u:r+=h*Math.pow(2,1-f),r*u>=2&&(i++,u/=2),i+f>=l?(c=0,i=l):i+f>=1?(c=(r*u-1)*Math.pow(2,a),i=i+f):(c=r*Math.pow(2,f-1)*Math.pow(2,a),i=0));a>=8;e[n+p]=c&255,p+=m,c/=256,a-=8);for(i=i<<a|c,d+=a;d>0;e[n+p]=i&255,p+=m,i/=256,d-=8);e[n+p-m]|=y*128}}),NI=Kt(t=>{"use strict";var e=cne(),r=dne(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=i,t.SlowBuffer=v,t.INSPECT_MAX_BYTES=50;var s=2147483647;t.kMaxLength=s,i.TYPED_ARRAY_SUPPORT=a(),!i.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let T=new Uint8Array(1),M={foo:function(){return 42}};return Object.setPrototypeOf(M,Uint8Array.prototype),Object.setPrototypeOf(T,M),T.foo()===42}catch{return!1}}Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}});function o(T){if(T>s)throw new RangeError('The value "'+T+'" is invalid for option "size"');let M=new Uint8Array(T);return Object.setPrototypeOf(M,i.prototype),M}function i(T,M,L){if(typeof T=="number"){if(typeof M=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return l(T)}return c(T,M,L)}i.poolSize=8192;function c(T,M,L){if(typeof T=="string")return f(T,M);if(ArrayBuffer.isView(T))return p(T);if(T==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T);if(Se(T,ArrayBuffer)||T&&Se(T.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Se(T,SharedArrayBuffer)||T&&Se(T.buffer,SharedArrayBuffer)))return m(T,M,L);if(typeof T=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let te=T.valueOf&&T.valueOf();if(te!=null&&te!==T)return i.from(te,M,L);let ae=y(T);if(ae)return ae;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof T[Symbol.toPrimitive]=="function")return i.from(T[Symbol.toPrimitive]("string"),M,L);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T)}i.from=function(T,M,L){return c(T,M,L)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function u(T){if(typeof T!="number")throw new TypeError('"size" argument must be of type number');if(T<0)throw new RangeError('The value "'+T+'" is invalid for option "size"')}function d(T,M,L){return u(T),T<=0?o(T):M!==void 0?typeof L=="string"?o(T).fill(M,L):o(T).fill(M):o(T)}i.alloc=function(T,M,L){return d(T,M,L)};function l(T){return u(T),o(T<0?0:S(T)|0)}i.allocUnsafe=function(T){return l(T)},i.allocUnsafeSlow=function(T){return l(T)};function f(T,M){if((typeof M!="string"||M==="")&&(M="utf8"),!i.isEncoding(M))throw new TypeError("Unknown encoding: "+M);let L=E(T,M)|0,te=o(L),ae=te.write(T,M);return ae!==L&&(te=te.slice(0,ae)),te}function h(T){let M=T.length<0?0:S(T.length)|0,L=o(M);for(let te=0;te<M;te+=1)L[te]=T[te]&255;return L}function p(T){if(Se(T,Uint8Array)){let M=new Uint8Array(T);return m(M.buffer,M.byteOffset,M.byteLength)}return h(T)}function m(T,M,L){if(M<0||T.byteLength<M)throw new RangeError('"offset" is outside of buffer bounds');if(T.byteLength<M+(L||0))throw new RangeError('"length" is outside of buffer bounds');let te;return M===void 0&&L===void 0?te=new Uint8Array(T):L===void 0?te=new Uint8Array(T,M):te=new Uint8Array(T,M,L),Object.setPrototypeOf(te,i.prototype),te}function y(T){if(i.isBuffer(T)){let M=S(T.length)|0,L=o(M);return L.length===0||T.copy(L,0,0,M),L}if(T.length!==void 0)return typeof T.length!="number"||et(T.length)?o(0):h(T);if(T.type==="Buffer"&&Array.isArray(T.data))return h(T.data)}function S(T){if(T>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return T|0}function v(T){return+T!=T&&(T=0),i.alloc(+T)}i.isBuffer=function(T){return T!=null&&T._isBuffer===!0&&T!==i.prototype},i.compare=function(T,M){if(Se(T,Uint8Array)&&(T=i.from(T,T.offset,T.byteLength)),Se(M,Uint8Array)&&(M=i.from(M,M.offset,M.byteLength)),!i.isBuffer(T)||!i.isBuffer(M))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(T===M)return 0;let L=T.length,te=M.length;for(let ae=0,he=Math.min(L,te);ae<he;++ae)if(T[ae]!==M[ae]){L=T[ae],te=M[ae];break}return L<te?-1:te<L?1:0},i.isEncoding=function(T){switch(String(T).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(T,M){if(!Array.isArray(T))throw new TypeError('"list" argument must be an Array of Buffers');if(T.length===0)return i.alloc(0);let L;if(M===void 0)for(M=0,L=0;L<T.length;++L)M+=T[L].length;let te=i.allocUnsafe(M),ae=0;for(L=0;L<T.length;++L){let he=T[L];if(Se(he,Uint8Array))ae+he.length>te.length?(i.isBuffer(he)||(he=i.from(he)),he.copy(te,ae)):Uint8Array.prototype.set.call(te,he,ae);else if(i.isBuffer(he))he.copy(te,ae);else throw new TypeError('"list" argument must be an Array of Buffers');ae+=he.length}return te};function E(T,M){if(i.isBuffer(T))return T.length;if(ArrayBuffer.isView(T)||Se(T,ArrayBuffer))return T.byteLength;if(typeof T!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof T);let L=T.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&L===0)return 0;let ae=!1;for(;;)switch(M){case"ascii":case"latin1":case"binary":return L;case"utf8":case"utf-8":return ge(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L*2;case"hex":return L>>>1;case"base64":return qe(T).length;default:if(ae)return te?-1:ge(T).length;M=(""+M).toLowerCase(),ae=!0}}i.byteLength=E;function k(T,M,L){let te=!1;if((M===void 0||M<0)&&(M=0),M>this.length||((L===void 0||L>this.length)&&(L=this.length),L<=0)||(L>>>=0,M>>>=0,L<=M))return"";for(T||(T="utf8");;)switch(T){case"hex":return _(this,M,L);case"utf8":case"utf-8":return R(this,M,L);case"ascii":return x(this,M,L);case"latin1":case"binary":return P(this,M,L);case"base64":return ee(this,M,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,M,L);default:if(te)throw new TypeError("Unknown encoding: "+T);T=(T+"").toLowerCase(),te=!0}}i.prototype._isBuffer=!0;function A(T,M,L){let te=T[M];T[M]=T[L],T[L]=te}i.prototype.swap16=function(){let T=this.length;if(T%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let M=0;M<T;M+=2)A(this,M,M+1);return this},i.prototype.swap32=function(){let T=this.length;if(T%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let M=0;M<T;M+=4)A(this,M,M+3),A(this,M+1,M+2);return this},i.prototype.swap64=function(){let T=this.length;if(T%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let M=0;M<T;M+=8)A(this,M,M+7),A(this,M+1,M+6),A(this,M+2,M+5),A(this,M+3,M+4);return this},i.prototype.toString=function(){let T=this.length;return T===0?"":arguments.length===0?R(this,0,T):k.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(T){if(!i.isBuffer(T))throw new TypeError("Argument must be a Buffer");return this===T?!0:i.compare(this,T)===0},i.prototype.inspect=function(){let T="",M=t.INSPECT_MAX_BYTES;return T=this.toString("hex",0,M).replace(/(.{2})/g,"$1 ").trim(),this.length>M&&(T+=" ... "),"<Buffer "+T+">"},n&&(i.prototype[n]=i.prototype.inspect),i.prototype.compare=function(T,M,L,te,ae){if(Se(T,Uint8Array)&&(T=i.from(T,T.offset,T.byteLength)),!i.isBuffer(T))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof T);if(M===void 0&&(M=0),L===void 0&&(L=T?T.length:0),te===void 0&&(te=0),ae===void 0&&(ae=this.length),M<0||L>T.length||te<0||ae>this.length)throw new RangeError("out of range index");if(te>=ae&&M>=L)return 0;if(te>=ae)return-1;if(M>=L)return 1;if(M>>>=0,L>>>=0,te>>>=0,ae>>>=0,this===T)return 0;let he=ae-te,xe=L-M,Mt=Math.min(he,xe),Bn=this.slice(te,ae),$r=T.slice(M,L);for(let pr=0;pr<Mt;++pr)if(Bn[pr]!==$r[pr]){he=Bn[pr],xe=$r[pr];break}return he<xe?-1:xe<he?1:0};function D(T,M,L,te,ae){if(T.length===0)return-1;if(typeof L=="string"?(te=L,L=0):L>2147483647?L=2147483647:L<-2147483648&&(L=-2147483648),L=+L,et(L)&&(L=ae?0:T.length-1),L<0&&(L=T.length+L),L>=T.length){if(ae)return-1;L=T.length-1}else if(L<0)if(ae)L=0;else return-1;if(typeof M=="string"&&(M=i.from(M,te)),i.isBuffer(M))return M.length===0?-1:B(T,M,L,te,ae);if(typeof M=="number")return M=M&255,typeof Uint8Array.prototype.indexOf=="function"?ae?Uint8Array.prototype.indexOf.call(T,M,L):Uint8Array.prototype.lastIndexOf.call(T,M,L):B(T,[M],L,te,ae);throw new TypeError("val must be string, number or Buffer")}function B(T,M,L,te,ae){let he=1,xe=T.length,Mt=M.length;if(te!==void 0&&(te=String(te).toLowerCase(),te==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(T.length<2||M.length<2)return-1;he=2,xe/=2,Mt/=2,L/=2}function Bn(pr,sr){return he===1?pr[sr]:pr.readUInt16BE(sr*he)}let $r;if(ae){let pr=-1;for($r=L;$r<xe;$r++)if(Bn(T,$r)===Bn(M,pr===-1?0:$r-pr)){if(pr===-1&&(pr=$r),$r-pr+1===Mt)return pr*he}else pr!==-1&&($r-=$r-pr),pr=-1}else for(L+Mt>xe&&(L=xe-Mt),$r=L;$r>=0;$r--){let pr=!0;for(let sr=0;sr<Mt;sr++)if(Bn(T,$r+sr)!==Bn(M,sr)){pr=!1;break}if(pr)return $r}return-1}i.prototype.includes=function(T,M,L){return this.indexOf(T,M,L)!==-1},i.prototype.indexOf=function(T,M,L){return D(this,T,M,L,!0)},i.prototype.lastIndexOf=function(T,M,L){return D(this,T,M,L,!1)};function j(T,M,L,te){L=Number(L)||0;let ae=T.length-L;te?(te=Number(te),te>ae&&(te=ae)):te=ae;let he=M.length;te>he/2&&(te=he/2);let xe;for(xe=0;xe<te;++xe){let Mt=parseInt(M.substr(xe*2,2),16);if(et(Mt))return xe;T[L+xe]=Mt}return xe}function F(T,M,L,te){return Et(ge(M,T.length-L),T,L,te)}function q(T,M,L,te){return Et(Me(M),T,L,te)}function N(T,M,L,te){return Et(qe(M),T,L,te)}function W(T,M,L,te){return Et(Le(M,T.length-L),T,L,te)}i.prototype.write=function(T,M,L,te){if(M===void 0)te="utf8",L=this.length,M=0;else if(L===void 0&&typeof M=="string")te=M,L=this.length,M=0;else if(isFinite(M))M=M>>>0,isFinite(L)?(L=L>>>0,te===void 0&&(te="utf8")):(te=L,L=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let ae=this.length-M;if((L===void 0||L>ae)&&(L=ae),T.length>0&&(L<0||M<0)||M>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");let he=!1;for(;;)switch(te){case"hex":return j(this,T,M,L);case"utf8":case"utf-8":return F(this,T,M,L);case"ascii":case"latin1":case"binary":return q(this,T,M,L);case"base64":return N(this,T,M,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,T,M,L);default:if(he)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),he=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ee(T,M,L){return M===0&&L===T.length?e.fromByteArray(T):e.fromByteArray(T.slice(M,L))}function R(T,M,L){L=Math.min(T.length,L);let te=[],ae=M;for(;ae<L;){let he=T[ae],xe=null,Mt=he>239?4:he>223?3:he>191?2:1;if(ae+Mt<=L){let Bn,$r,pr,sr;switch(Mt){case 1:he<128&&(xe=he);break;case 2:Bn=T[ae+1],(Bn&192)===128&&(sr=(he&31)<<6|Bn&63,sr>127&&(xe=sr));break;case 3:Bn=T[ae+1],$r=T[ae+2],(Bn&192)===128&&($r&192)===128&&(sr=(he&15)<<12|(Bn&63)<<6|$r&63,sr>2047&&(sr<55296||sr>57343)&&(xe=sr));break;case 4:Bn=T[ae+1],$r=T[ae+2],pr=T[ae+3],(Bn&192)===128&&($r&192)===128&&(pr&192)===128&&(sr=(he&15)<<18|(Bn&63)<<12|($r&63)<<6|pr&63,sr>65535&&sr<1114112&&(xe=sr))}}xe===null?(xe=65533,Mt=1):xe>65535&&(xe-=65536,te.push(xe>>>10&1023|55296),xe=56320|xe&1023),te.push(xe),ae+=Mt}return b(te)}var $=4096;function b(T){let M=T.length;if(M<=$)return String.fromCharCode.apply(String,T);let L="",te=0;for(;te<M;)L+=String.fromCharCode.apply(String,T.slice(te,te+=$));return L}function x(T,M,L){let te="";L=Math.min(T.length,L);for(let ae=M;ae<L;++ae)te+=String.fromCharCode(T[ae]&127);return te}function P(T,M,L){let te="";L=Math.min(T.length,L);for(let ae=M;ae<L;++ae)te+=String.fromCharCode(T[ae]);return te}function _(T,M,L){let te=T.length;(!M||M<0)&&(M=0),(!L||L<0||L>te)&&(L=te);let ae="";for(let he=M;he<L;++he)ae+=wt[T[he]];return ae}function I(T,M,L){let te=T.slice(M,L),ae="";for(let he=0;he<te.length-1;he+=2)ae+=String.fromCharCode(te[he]+te[he+1]*256);return ae}i.prototype.slice=function(T,M){let L=this.length;T=~~T,M=M===void 0?L:~~M,T<0?(T+=L,T<0&&(T=0)):T>L&&(T=L),M<0?(M+=L,M<0&&(M=0)):M>L&&(M=L),M<T&&(M=T);let te=this.subarray(T,M);return Object.setPrototypeOf(te,i.prototype),te};function O(T,M,L){if(T%1!==0||T<0)throw new RangeError("offset is not uint");if(T+M>L)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=this[T],ae=1,he=0;for(;++he<M&&(ae*=256);)te+=this[T+he]*ae;return te},i.prototype.readUintBE=i.prototype.readUIntBE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=this[T+--M],ae=1;for(;M>0&&(ae*=256);)te+=this[T+--M]*ae;return te},i.prototype.readUint8=i.prototype.readUInt8=function(T,M){return T=T>>>0,M||O(T,1,this.length),this[T]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(T,M){return T=T>>>0,M||O(T,2,this.length),this[T]|this[T+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(T,M){return T=T>>>0,M||O(T,2,this.length),this[T]<<8|this[T+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(T,M){return T=T>>>0,M||O(T,4,this.length),(this[T]|this[T+1]<<8|this[T+2]<<16)+this[T+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(T,M){return T=T>>>0,M||O(T,4,this.length),this[T]*16777216+(this[T+1]<<16|this[T+2]<<8|this[T+3])},i.prototype.readBigUInt64LE=xt(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=M+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24,ae=this[++T]+this[++T]*2**8+this[++T]*2**16+L*2**24;return BigInt(te)+(BigInt(ae)<<BigInt(32))}),i.prototype.readBigUInt64BE=xt(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=M*2**24+this[++T]*2**16+this[++T]*2**8+this[++T],ae=this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+L;return(BigInt(te)<<BigInt(32))+BigInt(ae)}),i.prototype.readIntLE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=this[T],ae=1,he=0;for(;++he<M&&(ae*=256);)te+=this[T+he]*ae;return ae*=128,te>=ae&&(te-=Math.pow(2,8*M)),te},i.prototype.readIntBE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=M,ae=1,he=this[T+--te];for(;te>0&&(ae*=256);)he+=this[T+--te]*ae;return ae*=128,he>=ae&&(he-=Math.pow(2,8*M)),he},i.prototype.readInt8=function(T,M){return T=T>>>0,M||O(T,1,this.length),this[T]&128?(255-this[T]+1)*-1:this[T]},i.prototype.readInt16LE=function(T,M){T=T>>>0,M||O(T,2,this.length);let L=this[T]|this[T+1]<<8;return L&32768?L|4294901760:L},i.prototype.readInt16BE=function(T,M){T=T>>>0,M||O(T,2,this.length);let L=this[T+1]|this[T]<<8;return L&32768?L|4294901760:L},i.prototype.readInt32LE=function(T,M){return T=T>>>0,M||O(T,4,this.length),this[T]|this[T+1]<<8|this[T+2]<<16|this[T+3]<<24},i.prototype.readInt32BE=function(T,M){return T=T>>>0,M||O(T,4,this.length),this[T]<<24|this[T+1]<<16|this[T+2]<<8|this[T+3]},i.prototype.readBigInt64LE=xt(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=this[T+4]+this[T+5]*2**8+this[T+6]*2**16+(L<<24);return(BigInt(te)<<BigInt(32))+BigInt(M+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24)}),i.prototype.readBigInt64BE=xt(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=(M<<24)+this[++T]*2**16+this[++T]*2**8+this[++T];return(BigInt(te)<<BigInt(32))+BigInt(this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+L)}),i.prototype.readFloatLE=function(T,M){return T=T>>>0,M||O(T,4,this.length),r.read(this,T,!0,23,4)},i.prototype.readFloatBE=function(T,M){return T=T>>>0,M||O(T,4,this.length),r.read(this,T,!1,23,4)},i.prototype.readDoubleLE=function(T,M){return T=T>>>0,M||O(T,8,this.length),r.read(this,T,!0,52,8)},i.prototype.readDoubleBE=function(T,M){return T=T>>>0,M||O(T,8,this.length),r.read(this,T,!1,52,8)};function z(T,M,L,te,ae,he){if(!i.isBuffer(T))throw new TypeError('"buffer" argument must be a Buffer instance');if(M>ae||M<he)throw new RangeError('"value" argument is out of bounds');if(L+te>T.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(T,M,L,te){if(T=+T,M=M>>>0,L=L>>>0,!te){let xe=Math.pow(2,8*L)-1;z(this,T,M,L,xe,0)}let ae=1,he=0;for(this[M]=T&255;++he<L&&(ae*=256);)this[M+he]=T/ae&255;return M+L},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(T,M,L,te){if(T=+T,M=M>>>0,L=L>>>0,!te){let xe=Math.pow(2,8*L)-1;z(this,T,M,L,xe,0)}let ae=L-1,he=1;for(this[M+ae]=T&255;--ae>=0&&(he*=256);)this[M+ae]=T/he&255;return M+L},i.prototype.writeUint8=i.prototype.writeUInt8=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,1,255,0),this[M]=T&255,M+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,2,65535,0),this[M]=T&255,this[M+1]=T>>>8,M+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,2,65535,0),this[M]=T>>>8,this[M+1]=T&255,M+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,4,4294967295,0),this[M+3]=T>>>24,this[M+2]=T>>>16,this[M+1]=T>>>8,this[M]=T&255,M+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,4,4294967295,0),this[M]=T>>>24,this[M+1]=T>>>16,this[M+2]=T>>>8,this[M+3]=T&255,M+4};function G(T,M,L,te,ae){de(M,te,ae,T,L,7);let he=Number(M&BigInt(4294967295));T[L++]=he,he=he>>8,T[L++]=he,he=he>>8,T[L++]=he,he=he>>8,T[L++]=he;let xe=Number(M>>BigInt(32)&BigInt(4294967295));return T[L++]=xe,xe=xe>>8,T[L++]=xe,xe=xe>>8,T[L++]=xe,xe=xe>>8,T[L++]=xe,L}function V(T,M,L,te,ae){de(M,te,ae,T,L,7);let he=Number(M&BigInt(4294967295));T[L+7]=he,he=he>>8,T[L+6]=he,he=he>>8,T[L+5]=he,he=he>>8,T[L+4]=he;let xe=Number(M>>BigInt(32)&BigInt(4294967295));return T[L+3]=xe,xe=xe>>8,T[L+2]=xe,xe=xe>>8,T[L+1]=xe,xe=xe>>8,T[L]=xe,L+8}i.prototype.writeBigUInt64LE=xt(function(T,M=0){return G(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=xt(function(T,M=0){return V(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(T,M,L,te){if(T=+T,M=M>>>0,!te){let Mt=Math.pow(2,8*L-1);z(this,T,M,L,Mt-1,-Mt)}let ae=0,he=1,xe=0;for(this[M]=T&255;++ae<L&&(he*=256);)T<0&&xe===0&&this[M+ae-1]!==0&&(xe=1),this[M+ae]=(T/he>>0)-xe&255;return M+L},i.prototype.writeIntBE=function(T,M,L,te){if(T=+T,M=M>>>0,!te){let Mt=Math.pow(2,8*L-1);z(this,T,M,L,Mt-1,-Mt)}let ae=L-1,he=1,xe=0;for(this[M+ae]=T&255;--ae>=0&&(he*=256);)T<0&&xe===0&&this[M+ae+1]!==0&&(xe=1),this[M+ae]=(T/he>>0)-xe&255;return M+L},i.prototype.writeInt8=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,1,127,-128),T<0&&(T=255+T+1),this[M]=T&255,M+1},i.prototype.writeInt16LE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,2,32767,-32768),this[M]=T&255,this[M+1]=T>>>8,M+2},i.prototype.writeInt16BE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,2,32767,-32768),this[M]=T>>>8,this[M+1]=T&255,M+2},i.prototype.writeInt32LE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,4,2147483647,-2147483648),this[M]=T&255,this[M+1]=T>>>8,this[M+2]=T>>>16,this[M+3]=T>>>24,M+4},i.prototype.writeInt32BE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,4,2147483647,-2147483648),T<0&&(T=4294967295+T+1),this[M]=T>>>24,this[M+1]=T>>>16,this[M+2]=T>>>8,this[M+3]=T&255,M+4},i.prototype.writeBigInt64LE=xt(function(T,M=0){return G(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=xt(function(T,M=0){return V(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function H(T,M,L,te,ae,he){if(L+te>T.length)throw new RangeError("Index out of range");if(L<0)throw new RangeError("Index out of range")}function Y(T,M,L,te,ae){return M=+M,L=L>>>0,ae||H(T,M,L,4,34028234663852886e22,-34028234663852886e22),r.write(T,M,L,te,23,4),L+4}i.prototype.writeFloatLE=function(T,M,L){return Y(this,T,M,!0,L)},i.prototype.writeFloatBE=function(T,M,L){return Y(this,T,M,!1,L)};function K(T,M,L,te,ae){return M=+M,L=L>>>0,ae||H(T,M,L,8,17976931348623157e292,-17976931348623157e292),r.write(T,M,L,te,52,8),L+8}i.prototype.writeDoubleLE=function(T,M,L){return K(this,T,M,!0,L)},i.prototype.writeDoubleBE=function(T,M,L){return K(this,T,M,!1,L)},i.prototype.copy=function(T,M,L,te){if(!i.isBuffer(T))throw new TypeError("argument should be a Buffer");if(L||(L=0),!te&&te!==0&&(te=this.length),M>=T.length&&(M=T.length),M||(M=0),te>0&&te<L&&(te=L),te===L||T.length===0||this.length===0)return 0;if(M<0)throw new RangeError("targetStart out of bounds");if(L<0||L>=this.length)throw new RangeError("Index out of range");if(te<0)throw new RangeError("sourceEnd out of bounds");te>this.length&&(te=this.length),T.length-M<te-L&&(te=T.length-M+L);let ae=te-L;return this===T&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(M,L,te):Uint8Array.prototype.set.call(T,this.subarray(L,te),M),ae},i.prototype.fill=function(T,M,L,te){if(typeof T=="string"){if(typeof M=="string"?(te=M,M=0,L=this.length):typeof L=="string"&&(te=L,L=this.length),te!==void 0&&typeof te!="string")throw new TypeError("encoding must be a string");if(typeof te=="string"&&!i.isEncoding(te))throw new TypeError("Unknown encoding: "+te);if(T.length===1){let he=T.charCodeAt(0);(te==="utf8"&&he<128||te==="latin1")&&(T=he)}}else typeof T=="number"?T=T&255:typeof T=="boolean"&&(T=Number(T));if(M<0||this.length<M||this.length<L)throw new RangeError("Out of range index");if(L<=M)return this;M=M>>>0,L=L===void 0?this.length:L>>>0,T||(T=0);let ae;if(typeof T=="number")for(ae=M;ae<L;++ae)this[ae]=T;else{let he=i.isBuffer(T)?T:i.from(T,te),xe=he.length;if(xe===0)throw new TypeError('The value "'+T+'" is invalid for argument "value"');for(ae=0;ae<L-M;++ae)this[ae+M]=he[ae%xe]}return this};var Q={};function se(T,M,L){Q[T]=class extends L{constructor(){super(),Object.defineProperty(this,"message",{value:M.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${T}]`,this.stack,delete this.name}get code(){return T}set code(te){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:te,writable:!0})}toString(){return`${this.name} [${T}]: ${this.message}`}}}se("ERR_BUFFER_OUT_OF_BOUNDS",function(T){return T?`${T} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),se("ERR_INVALID_ARG_TYPE",function(T,M){return`The "${T}" argument must be of type number. Received type ${typeof M}`},TypeError),se("ERR_OUT_OF_RANGE",function(T,M,L){let te=`The value of "${T}" is out of range.`,ae=L;return Number.isInteger(L)&&Math.abs(L)>2**32?ae=re(String(L)):typeof L=="bigint"&&(ae=String(L),(L>BigInt(2)**BigInt(32)||L<-(BigInt(2)**BigInt(32)))&&(ae=re(ae)),ae+="n"),te+=` It must be ${M}. Received ${ae}`,te},RangeError);function re(T){let M="",L=T.length,te=T[0]==="-"?1:0;for(;L>=te+4;L-=3)M=`_${T.slice(L-3,L)}${M}`;return`${T.slice(0,L)}${M}`}function Z(T,M,L){le(M,"offset"),(T[M]===void 0||T[M+L]===void 0)&&pe(M,T.length-(L+1))}function de(T,M,L,te,ae,he){if(T>L||T<M){let xe=typeof M=="bigint"?"n":"",Mt;throw he>3?M===0||M===BigInt(0)?Mt=`>= 0${xe} and < 2${xe} ** ${(he+1)*8}${xe}`:Mt=`>= -(2${xe} ** ${(he+1)*8-1}${xe}) and < 2 ** ${(he+1)*8-1}${xe}`:Mt=`>= ${M}${xe} and <= ${L}${xe}`,new Q.ERR_OUT_OF_RANGE("value",Mt,T)}Z(te,ae,he)}function le(T,M){if(typeof T!="number")throw new Q.ERR_INVALID_ARG_TYPE(M,"number",T)}function pe(T,M,L){throw Math.floor(T)!==T?(le(T,L),new Q.ERR_OUT_OF_RANGE(L||"offset","an integer",T)):M<0?new Q.ERR_BUFFER_OUT_OF_BOUNDS:new Q.ERR_OUT_OF_RANGE(L||"offset",`>= ${L?1:0} and <= ${M}`,T)}var ve=/[^+/0-9A-Za-z-_]/g;function ce(T){if(T=T.split("=")[0],T=T.trim().replace(ve,""),T.length<2)return"";for(;T.length%4!==0;)T=T+"=";return T}function ge(T,M){M=M||1/0;let L,te=T.length,ae=null,he=[];for(let xe=0;xe<te;++xe){if(L=T.charCodeAt(xe),L>55295&&L<57344){if(!ae){if(L>56319){(M-=3)>-1&&he.push(239,191,189);continue}else if(xe+1===te){(M-=3)>-1&&he.push(239,191,189);continue}ae=L;continue}if(L<56320){(M-=3)>-1&&he.push(239,191,189),ae=L;continue}L=(ae-55296<<10|L-56320)+65536}else ae&&(M-=3)>-1&&he.push(239,191,189);if(ae=null,L<128){if((M-=1)<0)break;he.push(L)}else if(L<2048){if((M-=2)<0)break;he.push(L>>6|192,L&63|128)}else if(L<65536){if((M-=3)<0)break;he.push(L>>12|224,L>>6&63|128,L&63|128)}else if(L<1114112){if((M-=4)<0)break;he.push(L>>18|240,L>>12&63|128,L>>6&63|128,L&63|128)}else throw new Error("Invalid code point")}return he}function Me(T){let M=[];for(let L=0;L<T.length;++L)M.push(T.charCodeAt(L)&255);return M}function Le(T,M){let L,te,ae,he=[];for(let xe=0;xe<T.length&&!((M-=2)<0);++xe)L=T.charCodeAt(xe),te=L>>8,ae=L%256,he.push(ae),he.push(te);return he}function qe(T){return e.toByteArray(ce(T))}function Et(T,M,L,te){let ae;for(ae=0;ae<te&&!(ae+L>=M.length||ae>=T.length);++ae)M[ae+L]=T[ae];return ae}function Se(T,M){return T instanceof M||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===M.name}function et(T){return T!==T}var wt=function(){let T="0123456789abcdef",M=new Array(256);for(let L=0;L<16;++L){let te=L*16;for(let ae=0;ae<16;++ae)M[te+ae]=T[L]+T[ae]}return M}();function xt(T){return typeof BigInt>"u"?$t:T}function $t(){throw new Error("BigInt not supported")}}),NU=Kt((t,e)=>{"use strict";var r=null;e.exports=function(){return r===null&&(r={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),r}}),UU=Kt(t=>{"use strict";var e=_c(),r=new Set(["buffer","view","utf8"]),n=class{constructor(s){if(this.encode=s.encode||this.encode,this.decode=s.decode||this.decode,this.name=s.name||this.name,this.format=s.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'");s.createViewTranscoder&&(this.createViewTranscoder=s.createViewTranscoder),s.createBufferTranscoder&&(this.createBufferTranscoder=s.createBufferTranscoder),s.createUTF8Transcoder&&(this.createUTF8Transcoder=s.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}),LU=Kt(t=>{"use strict";var{Buffer:e}=NI()||{},{Encoding:r}=UU(),n=NU(),s=class extends r{constructor(i){super({...i,format:"buffer"})}createViewTranscoder(){return new a({encode:this.encode,decode:i=>this.decode(e.from(i.buffer,i.byteOffset,i.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},a=class extends r{constructor(i){super({...i,format:"view"})}createBufferTranscoder(){return new s({encode:i=>{let c=this.encode(i);return e.from(c.buffer,c.byteOffset,c.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},o=class extends r{constructor(i){super({...i,format:"utf8"})}createBufferTranscoder(){return new s({encode:i=>e.from(this.encode(i),"utf8"),decode:i=>this.decode(i.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:i,textDecoder:c}=n();return new a({encode:u=>i.encode(this.encode(u)),decode:u=>this.decode(c.decode(u)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};t.BufferFormat=s,t.ViewFormat=a,t.UTF8Format=o}),une=Kt(t=>{"use strict";var{Buffer:e}=NI()||{Buffer:{isBuffer:()=>!1}},{textEncoder:r,textDecoder:n}=NU()(),{BufferFormat:s,ViewFormat:a,UTF8Format:o}=LU(),i=c=>c;t.utf8=new o({encode:function(c){return e.isBuffer(c)?c.toString("utf8"):ArrayBuffer.isView(c)?n.decode(c):String(c)},decode:i,name:"utf8",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:r.encode(c)},decode:function(c){return n.decode(c)},name:`${this.name}+view`})},createBufferTranscoder(){return new s({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:function(c){return c.toString("utf8")},name:`${this.name}+buffer`})}}),t.json=new o({encode:JSON.stringify,decode:JSON.parse,name:"json"}),t.buffer=new s({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:i,name:"buffer",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:e.from(String(c),"utf8")},decode:function(c){return e.from(c.buffer,c.byteOffset,c.byteLength)},name:`${this.name}+view`})}}),t.view=new a({encode:function(c){return ArrayBuffer.isView(c)?c:r.encode(c)},decode:i,name:"view",createBufferTranscoder(){return new s({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:i,name:`${this.name}+buffer`})}}),t.hex=new s({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"hex")},decode:function(c){return c.toString("hex")},name:"hex"}),t.base64=new s({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"base64")},decode:function(c){return c.toString("base64")},name:"base64"})}),lne=Kt(t=>{"use strict";var e=_c(),r=une(),{Encoding:n}=UU(),{BufferFormat:s,ViewFormat:a,UTF8Format:o}=LU(),i=Symbol("formats"),c=Symbol("encodings"),u=new Set(["buffer","view","utf8"]),d=class{constructor(y){if(Array.isArray(y)){if(!y.every(S=>u.has(S)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[c]=new Map,this[i]=new Set(y);for(let S in r)try{this.encoding(S)}catch(v){if(v.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw v}}encodings(){return Array.from(new Set(this[c].values()))}encoding(y){let S=this[c].get(y);if(S===void 0){if(typeof y=="string"&&y!==""){if(S=p[y],!S)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");S=l(y)}let{name:v,format:E}=S;if(!this[i].has(E))if(this[i].has("view"))S=S.createViewTranscoder();else if(this[i].has("buffer"))S=S.createBufferTranscoder();else if(this[i].has("utf8"))S=S.createUTF8Transcoder();else throw new e(`Encoding '${v}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let k of[y,v,S.name,S.commonName])this[c].set(k,S)}return S}};t.Transcoder=d;function l(y){if(y instanceof n)return y;let S="type"in y&&typeof y.type=="string"?y.type:void 0,v=y.name||S||`anonymous-${m++}`;switch(f(y)){case"view":return new a({...y,name:v});case"utf8":return new o({...y,name:v});case"buffer":return new s({...y,name:v});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}),fne=Kt((t,e)=>{"use strict";var r=Object.prototype.hasOwnProperty,n="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(n=!1));function a(u,d,l){this.fn=u,this.context=d,this.once=l||!1}function o(u,d,l,f,h){if(typeof l!="function")throw new TypeError("The listener must be a function");var p=new a(l,f||u,h),m=n?n+d:d;return u._events[m]?u._events[m].fn?u._events[m]=[u._events[m],p]:u._events[m].push(p):(u._events[m]=p,u._eventsCount++),u}function i(u,d){--u._eventsCount===0?u._events=new s:delete u._events[d]}function c(){this._events=new s,this._eventsCount=0}c.prototype.eventNames=function(){var u=[],d,l;if(this._eventsCount===0)return u;for(l in d=this._events)r.call(d,l)&&u.push(n?l.slice(1):l);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},c.prototype.listeners=function(u){var d=n?n+u:u,l=this._events[d];if(!l)return[];if(l.fn)return[l.fn];for(var f=0,h=l.length,p=new Array(h);f<h;f++)p[f]=l[f].fn;return p},c.prototype.listenerCount=function(u){var d=n?n+u:u,l=this._events[d];return l?l.fn?1:l.length:0},c.prototype.emit=function(u,d,l,f,h,p){var m=n?n+u:u;if(!this._events[m])return!1;var y=this._events[m],S=arguments.length,v,E;if(y.fn){switch(y.once&&this.removeListener(u,y.fn,void 0,!0),S){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,l),!0;case 4:return y.fn.call(y.context,d,l,f),!0;case 5:return y.fn.call(y.context,d,l,f,h),!0;case 6:return y.fn.call(y.context,d,l,f,h,p),!0}for(E=1,v=new Array(S-1);E<S;E++)v[E-1]=arguments[E];y.fn.apply(y.context,v)}else{var k=y.length,A;for(E=0;E<k;E++)switch(y[E].once&&this.removeListener(u,y[E].fn,void 0,!0),S){case 1:y[E].fn.call(y[E].context);break;case 2:y[E].fn.call(y[E].context,d);break;case 3:y[E].fn.call(y[E].context,d,l);break;case 4:y[E].fn.call(y[E].context,d,l,f);break;default:if(!v)for(A=1,v=new Array(S-1);A<S;A++)v[A-1]=arguments[A];y[E].fn.apply(y[E].context,v)}}return!0},c.prototype.on=function(u,d,l){return o(this,u,d,l,!1)},c.prototype.once=function(u,d,l){return o(this,u,d,l,!0)},c.prototype.removeListener=function(u,d,l,f){var h=n?n+u:u;if(!this._events[h])return this;if(!d)return i(this,h),this;var p=this._events[h];if(p.fn)p.fn===d&&(!f||p.once)&&(!l||p.context===l)&&i(this,h);else{for(var m=0,y=[],S=p.length;m<S;m++)(p[m].fn!==d||f&&!p[m].once||l&&p[m].context!==l)&&y.push(p[m]);y.length?this._events[h]=y.length===1?y[0]:y:i(this,h)}return this},c.prototype.removeAllListeners=function(u){var d;return u?(d=n?n+u:u,this._events[d]&&i(this,d)):(this._events=new s,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,typeof e<"u"&&(e.exports=c)}),pne=Kt((t,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:r=>Promise.resolve().then(r)}),X1=Kt(t=>{"use strict";var e=pne();t.fromCallback=function(r,n){if(r===void 0){var s=new Promise(function(a,o){r=function(i,c){i?o(i):a(c)}});r[n!==void 0?n:"promise"]=s}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(s){e(()=>n(null,s))}).catch(function(s){e(()=>n(s))})}}),UI=Kt(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:{}}}),Sf=Kt(t=>{"use strict";var{fromCallback:e}=X1(),r=_c(),{getOptions:n,getCallback:s}=UI(),a=Symbol("promise"),o=Symbol("callback"),i=Symbol("working"),c=Symbol("handleOne"),u=Symbol("handleMany"),d=Symbol("autoClose"),l=Symbol("finishWork"),f=Symbol("returnMany"),h=Symbol("closing"),p=Symbol("handleClose"),m=Symbol("closed"),y=Symbol("closeCallbacks"),S=Symbol("keyEncoding"),v=Symbol("valueEncoding"),E=Symbol("abortOnClose"),k=Symbol("legacy"),A=Symbol("keys"),D=Symbol("values"),B=Symbol("limit"),j=Symbol("count"),F=Object.freeze({}),q=()=>{},N=!1,W=class{constructor(x,P,_){if(typeof x!="object"||x===null){let I=x===null?"null":typeof x;throw new TypeError(`The first argument must be an abstract-level database, received ${I}`)}if(typeof P!="object"||P===null)throw new TypeError("The second argument must be an options object");this[m]=!1,this[y]=[],this[i]=!1,this[h]=!1,this[d]=!1,this[o]=null,this[c]=this[c].bind(this),this[u]=this[u].bind(this),this[p]=this[p].bind(this),this[S]=P[S],this[v]=P[v],this[k]=_,this[B]=Number.isInteger(P.limit)&&P.limit>=0?P.limit:1/0,this[j]=0,this[E]=!!P.abortOnClose,this.db=x,this.db.attachResource(this),this.nextTick=x.nextTick}get count(){return this[j]}get limit(){return this[B]}next(x){let P;if(x===void 0)P=new Promise((_,I)=>{x=(O,z,G)=>{O?I(O):this[k]?z===void 0&&G===void 0?_():_([z,G]):_(z)}});else if(typeof x!="function")throw new TypeError("Callback must be a function");return this[h]?this.nextTick(x,new r("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(x,new r("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[i]=!0,this[o]=x,this[j]>=this[B]?this.nextTick(this[c],null):this._next(this[c])),P}_next(x){this.nextTick(x)}nextv(x,P,_){return _=s(P,_),_=e(_,a),P=n(P,F),Number.isInteger(x)?(this[h]?this.nextTick(_,new r("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(_,new r("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(x<1&&(x=1),this[B]<1/0&&(x=Math.min(x,this[B]-this[j])),this[i]=!0,this[o]=_,x<=0?this.nextTick(this[u],null,[]):this._nextv(x,P,this[u])),_[a]):(this.nextTick(_,new TypeError("The first argument 'size' must be an integer")),_[a])}_nextv(x,P,_){let I=[],O=(z,G,V)=>{if(z)return _(z);if(this[k]?G===void 0&&V===void 0:G===void 0)return _(null,I);I.push(this[k]?[G,V]:G),I.length===x?_(null,I):this._next(O)};this._next(O)}all(x,P){return P=s(x,P),P=e(P,a),x=n(x,F),this[h]?this.nextTick(P,new r("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(P,new r("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[i]=!0,this[o]=P,this[d]=!0,this[j]>=this[B]?this.nextTick(this[u],null,[]):this._all(x,this[u])),P[a]}_all(x,P){let _=this[j],I=[],O=()=>{let G=this[B]<1/0?Math.min(1e3,this[B]-_):1e3;G<=0?this.nextTick(P,null,I):this._nextv(G,F,z)},z=(G,V)=>{G?P(G):V.length===0?P(null,I):(I.push.apply(I,V),_+=V.length,O())};O()}[l](){let x=this[o];return this[E]&&x===null?q:(this[i]=!1,this[o]=null,this[h]&&this._close(this[p]),x)}[f](x,P,_){this[d]?this.close(x.bind(null,P,_)):x(P,_)}seek(x,P){if(P=n(P,F),!this[h]){if(this[i])throw new r("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let _=this.db.keyEncoding(P.keyEncoding||this[S]),I=_.format;P.keyEncoding!==I&&(P={...P,keyEncoding:I});let O=this.db.prefixKey(_.encode(x),I);this._seek(O,P)}}}_seek(x,P){throw new r("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(x){return x=e(x,a),this[m]?this.nextTick(x):this[h]?this[y].push(x):(this[h]=!0,this[y].push(x),this[i]?this[E]&&this[l]()(new r("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[p])),x[a]}_close(x){this.nextTick(x)}[p](){this[m]=!0,this.db.detachResource(this);let x=this[y];this[y]=[];for(let P of x)P()}async*[Symbol.asyncIterator](){try{let x;for(;(x=await this.next())!==void 0;)yield x}finally{this[m]||await this.close()}}},ee=class extends W{constructor(x,P){super(x,P,!0),this[A]=P.keys!==!1,this[D]=P.values!==!1}[c](x,P,_){let I=this[l]();if(x)return I(x);try{P=this[A]&&P!==void 0?this[S].decode(P):void 0,_=this[D]&&_!==void 0?this[v].decode(_):void 0}catch(O){return I(new b("entry",O))}P===void 0&&_===void 0||this[j]++,I(null,P,_)}[u](x,P){let _=this[l]();if(x)return this[f](_,x);try{for(let I of P){let O=I[0],z=I[1];I[0]=this[A]&&O!==void 0?this[S].decode(O):void 0,I[1]=this[D]&&z!==void 0?this[v].decode(z):void 0}}catch(I){return this[f](_,new b("entries",I))}this[j]+=P.length,this[f](_,null,P)}end(x){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(x)}},R=class extends W{constructor(x,P){super(x,P,!1)}[c](x,P){let _=this[l]();if(x)return _(x);try{P=P!==void 0?this[S].decode(P):void 0}catch(I){return _(new b("key",I))}P!==void 0&&this[j]++,_(null,P)}[u](x,P){let _=this[l]();if(x)return this[f](_,x);try{for(let I=0;I<P.length;I++){let O=P[I];P[I]=O!==void 0?this[S].decode(O):void 0}}catch(I){return this[f](_,new b("keys",I))}this[j]+=P.length,this[f](_,null,P)}},$=class extends W{constructor(x,P){super(x,P,!1)}[c](x,P){let _=this[l]();if(x)return _(x);try{P=P!==void 0?this[v].decode(P):void 0}catch(I){return _(new b("value",I))}P!==void 0&&this[j]++,_(null,P)}[u](x,P){let _=this[l]();if(x)return this[f](_,x);try{for(let I=0;I<P.length;I++){let O=P[I];P[I]=O!==void 0?this[v].decode(O):void 0}}catch(I){return this[f](_,new b("values",I))}this[j]+=P.length,this[f](_,null,P)}},b=class extends r{constructor(x,P){super(`Iterator could not decode ${x}`,{code:"LEVEL_DECODE_ERROR",cause:P})}};for(let x of["_ended property","_nexting property","_end method"])Object.defineProperty(ee.prototype,x.split(" ")[0],{get(){throw new r(`The ${x} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new r(`The ${x} has been removed`,{code:"LEVEL_LEGACY"})}});ee.keyEncoding=S,ee.valueEncoding=v,t.AbstractIterator=ee,t.AbstractKeyIterator=R,t.AbstractValueIterator=$}),hne=Kt(t=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:r}=Sf(),n=Symbol("iterator"),s=Symbol("callback"),a=Symbol("handleOne"),o=Symbol("handleMany"),i=class extends e{constructor(u,d){super(u,d),this[n]=u.iterator({...d,keys:!0,values:!1}),this[a]=this[a].bind(this),this[o]=this[o].bind(this)}},c=class extends r{constructor(u,d){super(u,d),this[n]=u.iterator({...d,keys:!1,values:!0}),this[a]=this[a].bind(this),this[o]=this[o].bind(this)}};for(let u of[i,c]){let d=u===i,l=d?f=>f[0]:f=>f[1];u.prototype._next=function(f){this[s]=f,this[n].next(this[a])},u.prototype[a]=function(f,h,p){let m=this[s];f?m(f):m(null,d?h:p)},u.prototype._nextv=function(f,h,p){this[s]=p,this[n].nextv(f,h,this[o])},u.prototype._all=function(f,h){this[s]=h,this[n].all(f,this[o])},u.prototype[o]=function(f,h){let p=this[s];f?p(f):p(null,h.map(l))},u.prototype._seek=function(f,h){this[n].seek(f,h)},u.prototype._close=function(f){this[n].close(f)}}t.DefaultKeyIterator=i,t.DefaultValueIterator=c}),mne=Kt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=Sf(),s=_c(),a=Symbol("nut"),o=Symbol("undefer"),i=Symbol("factory"),c=class extends e{constructor(l,f){super(l,f),this[a]=null,this[i]=()=>l.iterator(f),this.db.defer(()=>this[o]())}},u=class extends r{constructor(l,f){super(l,f),this[a]=null,this[i]=()=>l.keys(f),this.db.defer(()=>this[o]())}},d=class extends n{constructor(l,f){super(l,f),this[a]=null,this[i]=()=>l.values(f),this.db.defer(()=>this[o]())}};for(let l of[c,u,d])l.prototype[o]=function(){this.db.status==="open"&&(this[a]=this[i]())},l.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 s("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},l.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 s("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},l.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 s("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},l.prototype._seek=function(f,h){this[a]!==null?this[a]._seek(f,h):this.db.status==="opening"&&this.db.defer(()=>this._seek(f,h))},l.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=c,t.DeferredKeyIterator=u,t.DeferredValueIterator=d}),KU=Kt(t=>{"use strict";var{fromCallback:e}=X1(),r=_c(),{getCallback:n,getOptions:s}=UI(),a=Symbol("promise"),o=Symbol("status"),i=Symbol("operations"),c=Symbol("finishClose"),u=Symbol("closeCallbacks"),d=class{constructor(l){if(typeof l!="object"||l===null){let f=l===null?"null":typeof l;throw new TypeError(`The first argument must be an abstract-level database, received ${f}`)}this[i]=[],this[u]=[],this[o]="open",this[c]=this[c].bind(this),this.db=l,this.db.attachResource(this),this.nextTick=l.nextTick}get length(){return this[i].length}put(l,f,h){if(this[o]!=="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(l)||this.db._checkValue(f);if(p)throw p;let m=h&&h.sublevel!=null?h.sublevel:this.db,y=h,S=m.keyEncoding(h&&h.keyEncoding),v=m.valueEncoding(h&&h.valueEncoding),E=S.format;h={...h,keyEncoding:E,valueEncoding:v.format},m!==this.db&&(h.sublevel=null);let k=m.prefixKey(S.encode(l),E),A=v.encode(f);return this._put(k,A,h),this[i].push({...y,type:"put",key:l,value:f}),this}_put(l,f,h){}del(l,f){if(this[o]!=="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(l);if(h)throw h;let p=f&&f.sublevel!=null?f.sublevel:this.db,m=f,y=p.keyEncoding(f&&f.keyEncoding),S=y.format;return f={...f,keyEncoding:S},p!==this.db&&(f.sublevel=null),this._del(p.prefixKey(y.encode(l),S),f),this[i].push({...m,type:"del",key:l}),this}_del(l,f){}clear(){if(this[o]!=="open")throw new r("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[i]=[],this}_clear(){}write(l,f){return f=n(l,f),f=e(f,a),l=s(l),this[o]!=="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[o]="writing",this._write(l,h=>{this[o]="closing",this[u].push(()=>f(h)),h||this.db.emit("batch",this[i]),this._close(this[c])})),f[a]}_write(l,f){}close(l){return l=e(l,a),this[o]==="closing"?this[u].push(l):this[o]==="closed"?this.nextTick(l):(this[u].push(l),this[o]!=="writing"&&(this[o]="closing",this._close(this[c]))),l[a]}_close(l){this.nextTick(l)}[c](){this[o]="closed",this.db.detachResource(this);let l=this[u];this[u]=[];for(let f of l)f()}};t.AbstractChainedBatch=d}),yne=Kt(t=>{"use strict";var{AbstractChainedBatch:e}=KU(),r=_c(),n=Symbol("encoded"),s=class extends e{constructor(a){super(a),this[n]=[]}_put(a,o,i){this[n].push({...i,type:"put",key:a,value:o})}_del(a,o){this[n].push({...o,type:"del",key:a})}_clear(){this[n]=[]}_write(a,o){this.db.status==="opening"?this.db.defer(()=>this._write(a,o)):this.db.status==="open"?this[n].length===0?this.nextTick(o):this.db._batch(this[n],a,o):this.nextTick(o,new r("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};t.DefaultChainedBatch=s}),gne=Kt((t,e)=>{"use strict";var r=_c(),n=Object.prototype.hasOwnProperty,s=new Set(["lt","lte","gt","gte"]);e.exports=function(a,o){let i={};for(let c in a)if(n.call(a,c)&&!(c==="keyEncoding"||c==="valueEncoding")){if(c==="start"||c==="end")throw new r(`The legacy range option '${c}' has been removed`,{code:"LEVEL_LEGACY"});if(c==="encoding")throw new r("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});s.has(c)?i[c]=o.encode(a[c]):i[c]=a[c]}return i.reverse=!!i.reverse,i.limit=Number.isInteger(i.limit)&&i.limit>=0?i.limit:-1,i}}),zU=Kt((t,e)=>{var r;e.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):n=>(r||(r=Promise.resolve())).then(n).catch(s=>setTimeout(()=>{throw s},0))}),wne=Kt((t,e)=>{"use strict";var r=zU();e.exports=function(n,...s){s.length===0?r(n):r(()=>n(...s))}}),vne=Kt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=Sf(),s=Symbol("unfix"),a=Symbol("iterator"),o=Symbol("handleOne"),i=Symbol("handleMany"),c=Symbol("callback"),u=class extends e{constructor(f,h,p,m){super(f,h),this[a]=p,this[s]=m,this[o]=this[o].bind(this),this[i]=this[i].bind(this),this[c]=null}[o](f,h,p){let m=this[c];if(f)return m(f);h!==void 0&&(h=this[s](h)),m(f,h,p)}[i](f,h){let p=this[c];if(f)return p(f);for(let m of h){let y=m[0];y!==void 0&&(m[0]=this[s](y))}p(f,h)}},d=class extends r{constructor(f,h,p,m){super(f,h),this[a]=p,this[s]=m,this[o]=this[o].bind(this),this[i]=this[i].bind(this),this[c]=null}[o](f,h){let p=this[c];if(f)return p(f);h!==void 0&&(h=this[s](h)),p(f,h)}[i](f,h){let p=this[c];if(f)return p(f);for(let m=0;m<h.length;m++){let y=h[m];y!==void 0&&(h[m]=this[s](y))}p(f,h)}},l=class extends n{constructor(f,h,p){super(f,h),this[a]=p}};for(let f of[u,d])f.prototype._next=function(h){this[c]=h,this[a].next(this[o])},f.prototype._nextv=function(h,p,m){this[c]=m,this[a].nextv(h,p,this[i])},f.prototype._all=function(h,p){this[c]=p,this[a].all(h,this[i])};for(let f of[l])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[u,d,l])f.prototype._seek=function(h,p){this[a].seek(h,p)},f.prototype._close=function(h){this[a].close(h)};t.AbstractSublevelIterator=u,t.AbstractSublevelKeyIterator=d,t.AbstractSublevelValueIterator=l}),bne=Kt((t,e)=>{"use strict";var r=_c(),{Buffer:n}=NI()||{},{AbstractSublevelIterator:s,AbstractSublevelKeyIterator:a,AbstractSublevelValueIterator:o}=vne(),i=Symbol("prefix"),c=Symbol("upperBound"),u=Symbol("prefixRange"),d=Symbol("parent"),l=Symbol("unfix"),f=new TextEncoder,h={separator:"!"};e.exports=function({AbstractLevel:E}){class k extends E{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,B,j){let{separator:F,manifest:q,...N}=k.defaults(j);B=v(B,F);let W=F.charCodeAt(0)+1,ee=D[d]||D;if(!f.encode(B).every(b=>b>W&&b<127))throw new r(`Prefix must use bytes > ${W} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(p(ee,q),N);let R=(D.prefix||"")+F+B+F,$=R.slice(0,-1)+String.fromCharCode(W);this[d]=ee,this[i]=new y(R),this[c]=new y($),this[l]=new S,this.nextTick=ee.nextTick}prefixKey(D,B){if(B==="utf8")return this[i].utf8+D;if(D.byteLength===0)return this[i][B];if(B==="view"){let j=this[i].view,F=new Uint8Array(j.byteLength+D.byteLength);return F.set(j,0),F.set(D,j.byteLength),F}else{let j=this[i].buffer;return n.concat([j,D],j.byteLength+D.byteLength)}}[u](D,B){D.gte!==void 0?D.gte=this.prefixKey(D.gte,B):D.gt!==void 0?D.gt=this.prefixKey(D.gt,B):D.gte=this[i][B],D.lte!==void 0?D.lte=this.prefixKey(D.lte,B):D.lt!==void 0?D.lt=this.prefixKey(D.lt,B):D.lte=this[c][B]}get prefix(){return this[i].utf8}get db(){return this[d]}_open(D,B){this[d].open({passive:!0},B)}_put(D,B,j,F){this[d].put(D,B,j,F)}_get(D,B,j){this[d].get(D,B,j)}_getMany(D,B,j){this[d].getMany(D,B,j)}_del(D,B,j){this[d].del(D,B,j)}_batch(D,B,j){this[d].batch(D,B,j)}_clear(D,B){this[u](D,D.keyEncoding),this[d].clear(D,B)}_iterator(D){this[u](D,D.keyEncoding);let B=this[d].iterator(D),j=this[l].get(this[i].utf8.length,D.keyEncoding);return new s(this,D,B,j)}_keys(D){this[u](D,D.keyEncoding);let B=this[d].keys(D),j=this[l].get(this[i].utf8.length,D.keyEncoding);return new a(this,D,B,j)}_values(D){this[u](D,D.keyEncoding);let B=this[d].values(D);return new o(this,D,B)}}return{AbstractSublevel:k}};var p=function(E,k){return{...E.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...k,encodings:{utf8:m(E,"utf8"),buffer:m(E,"buffer"),view:m(E,"view")}}},m=function(E,k){return E.supports.encodings[k]?E.keyEncoding(k).name===k:!1},y=class{constructor(E){this.utf8=E,this.view=f.encode(E),this.buffer=n?n.from(this.view.buffer,0,this.view.byteLength):{}}},S=class{constructor(){this.cache=new Map}get(E,k){let A=this.cache.get(k);return A===void 0&&(k==="view"?A=(function(D,B){return B.subarray(D)}).bind(null,E):A=(function(D,B){return B.slice(D)}).bind(null,E),this.cache.set(k,A)),A}},v=function(E,k){let A=0,D=E.length;for(;A<D&&E[A]===k;)A++;for(;D>A&&E[D-1]===k;)D--;return E.slice(A,D)}}),PN=Kt(t=>{"use strict";var{supports:e}=ane(),{Transcoder:r}=lne(),{EventEmitter:n}=fne(),{fromCallback:s}=X1(),a=_c(),{AbstractIterator:o}=Sf(),{DefaultKeyIterator:i,DefaultValueIterator:c}=hne(),{DeferredIterator:u,DeferredKeyIterator:d,DeferredValueIterator:l}=mne(),{DefaultChainedBatch:f}=yne(),{getCallback:h,getOptions:p}=UI(),m=gne(),y=Symbol("promise"),S=Symbol("landed"),v=Symbol("resources"),E=Symbol("closeResources"),k=Symbol("operations"),A=Symbol("undefer"),D=Symbol("deferOpen"),B=Symbol("options"),j=Symbol("status"),F=Symbol("defaultOptions"),q=Symbol("transcoder"),N=Symbol("keyEncoding"),W=Symbol("valueEncoding"),ee=()=>{},R=class extends n{constructor(P,_){if(super(),typeof P!="object"||P===null)throw new TypeError("The first argument 'manifest' must be an object");_=p(_);let{keyEncoding:I,valueEncoding:O,passive:z,...G}=_;this[v]=new Set,this[k]=[],this[D]=!0,this[B]=G,this[j]="opening",this.supports=e(P,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:P.snapshots!==!1,permanence:P.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:P.encodings||{},events:Object.assign({},P.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[q]=new r(x(this)),this[N]=this[q].encoding(I||"utf8"),this[W]=this[q].encoding(O||"utf8");for(let V of this[q].encodings())this.supports.encodings[V.commonName]||(this.supports.encodings[V.commonName]=!0);this[F]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[N].commonName,valueEncoding:this[W].commonName}),key:Object.freeze({keyEncoding:this[N].commonName})},this.nextTick(()=>{this[D]&&this.open({passive:!1},ee)})}get status(){return this[j]}keyEncoding(P){return this[q].encoding(P??this[N])}valueEncoding(P){return this[q].encoding(P??this[W])}open(P,_){_=h(P,_),_=s(_,y),P={...this[B],...p(P)},P.createIfMissing=P.createIfMissing!==!1,P.errorIfExists=!!P.errorIfExists;let I=O=>{this[j]==="closing"||this[j]==="opening"?this.once(S,O?()=>I(O):I):this[j]!=="open"?_(new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:O})):_()};return P.passive?this[j]==="opening"?this.once(S,I):this.nextTick(I):this[j]==="closed"||this[D]?(this[D]=!1,this[j]="opening",this.emit("opening"),this._open(P,O=>{if(O){this[j]="closed",this[E](()=>{this.emit(S),I(O)}),this[A]();return}this[j]="open",this[A](),this.emit(S),this[j]==="open"&&this.emit("open"),this[j]==="open"&&this.emit("ready"),I()})):this[j]==="open"?this.nextTick(I):this.once(S,()=>this.open(P,_)),_[y]}_open(P,_){this.nextTick(_)}close(P){P=s(P,y);let _=I=>{this[j]==="opening"||this[j]==="closing"?this.once(S,I?_(I):_):this[j]!=="closed"?P(new a("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:I})):P()};if(this[j]==="open"){this[j]="closing",this.emit("closing");let I=O=>{this[j]="open",this[A](),this.emit(S),_(O)};this[E](()=>{this._close(O=>{if(O)return I(O);this[j]="closed",this[A](),this.emit(S),this[j]==="closed"&&this.emit("closed"),_()})})}else this[j]==="closed"?this.nextTick(_):this.once(S,()=>this.close(P));return P[y]}[E](P){if(this[v].size===0)return this.nextTick(P);let _=this[v].size,I=!0,O=()=>{--_===0&&(I?this.nextTick(P):P())};for(let z of this[v])z.close(O);I=!1,this[v].clear()}_close(P){this.nextTick(P)}get(P,_,I){if(I=h(_,I),I=s(I,y),_=p(_,this[F].entry),this[j]==="opening")return this.defer(()=>this.get(P,_,I)),I[y];if(b(this,I))return I[y];let O=this._checkKey(P);if(O)return this.nextTick(I,O),I[y];let z=this.keyEncoding(_.keyEncoding),G=this.valueEncoding(_.valueEncoding),V=z.format,H=G.format;return(_.keyEncoding!==V||_.valueEncoding!==H)&&(_=Object.assign({},_,{keyEncoding:V,valueEncoding:H})),this._get(this.prefixKey(z.encode(P),V),_,(Y,K)=>{if(Y)return(Y.code==="LEVEL_NOT_FOUND"||Y.notFound||/NotFound/i.test(Y))&&(Y.code||(Y.code="LEVEL_NOT_FOUND"),Y.notFound||(Y.notFound=!0),Y.status||(Y.status=404)),I(Y);try{K=G.decode(K)}catch(Q){return I(new a("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:Q}))}I(null,K)}),I[y]}_get(P,_,I){this.nextTick(I,new Error("NotFound"))}getMany(P,_,I){if(I=h(_,I),I=s(I,y),_=p(_,this[F].entry),this[j]==="opening")return this.defer(()=>this.getMany(P,_,I)),I[y];if(b(this,I))return I[y];if(!Array.isArray(P))return this.nextTick(I,new TypeError("The first argument 'keys' must be an array")),I[y];if(P.length===0)return this.nextTick(I,null,[]),I[y];let O=this.keyEncoding(_.keyEncoding),z=this.valueEncoding(_.valueEncoding),G=O.format,V=z.format;(_.keyEncoding!==G||_.valueEncoding!==V)&&(_=Object.assign({},_,{keyEncoding:G,valueEncoding:V}));let H=new Array(P.length);for(let Y=0;Y<P.length;Y++){let K=P[Y],Q=this._checkKey(K);if(Q)return this.nextTick(I,Q),I[y];H[Y]=this.prefixKey(O.encode(K),G)}return this._getMany(H,_,(Y,K)=>{if(Y)return I(Y);try{for(let Q=0;Q<K.length;Q++)K[Q]!==void 0&&(K[Q]=z.decode(K[Q]))}catch(Q){return I(new a(`Could not decode one or more of ${K.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:Q}))}I(null,K)}),I[y]}_getMany(P,_,I){this.nextTick(I,null,new Array(P.length).fill(void 0))}put(P,_,I,O){if(O=h(I,O),O=s(O,y),I=p(I,this[F].entry),this[j]==="opening")return this.defer(()=>this.put(P,_,I,O)),O[y];if(b(this,O))return O[y];let z=this._checkKey(P)||this._checkValue(_);if(z)return this.nextTick(O,z),O[y];let G=this.keyEncoding(I.keyEncoding),V=this.valueEncoding(I.valueEncoding),H=G.format,Y=V.format;(I.keyEncoding!==H||I.valueEncoding!==Y)&&(I=Object.assign({},I,{keyEncoding:H,valueEncoding:Y}));let K=this.prefixKey(G.encode(P),H),Q=V.encode(_);return this._put(K,Q,I,se=>{if(se)return O(se);this.emit("put",P,_),O()}),O[y]}_put(P,_,I,O){this.nextTick(O)}del(P,_,I){if(I=h(_,I),I=s(I,y),_=p(_,this[F].key),this[j]==="opening")return this.defer(()=>this.del(P,_,I)),I[y];if(b(this,I))return I[y];let O=this._checkKey(P);if(O)return this.nextTick(I,O),I[y];let z=this.keyEncoding(_.keyEncoding),G=z.format;return _.keyEncoding!==G&&(_=Object.assign({},_,{keyEncoding:G})),this._del(this.prefixKey(z.encode(P),G),_,V=>{if(V)return I(V);this.emit("del",P),I()}),I[y]}_del(P,_,I){this.nextTick(I)}batch(P,_,I){if(!arguments.length){if(this[j]==="opening")return new f(this);if(this[j]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof P=="function"?I=P:I=h(_,I),I=s(I,y),_=p(_,this[F].empty),this[j]==="opening")return this.defer(()=>this.batch(P,_,I)),I[y];if(b(this,I))return I[y];if(!Array.isArray(P))return this.nextTick(I,new TypeError("The first argument 'operations' must be an array")),I[y];if(P.length===0)return this.nextTick(I),I[y];let O=new Array(P.length),{keyEncoding:z,valueEncoding:G,...V}=_;for(let H=0;H<P.length;H++){if(typeof P[H]!="object"||P[H]===null)return this.nextTick(I,new TypeError("A batch operation must be an object")),I[y];let Y=Object.assign({},P[H]);if(Y.type!=="put"&&Y.type!=="del")return this.nextTick(I,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),I[y];let K=this._checkKey(Y.key);if(K)return this.nextTick(I,K),I[y];let Q=Y.sublevel!=null?Y.sublevel:this,se=Q.keyEncoding(Y.keyEncoding||z),re=se.format;if(Y.key=Q.prefixKey(se.encode(Y.key),re),Y.keyEncoding=re,Y.type==="put"){let Z=this._checkValue(Y.value);if(Z)return this.nextTick(I,Z),I[y];let de=Q.valueEncoding(Y.valueEncoding||G);Y.value=de.encode(Y.value),Y.valueEncoding=de.format}Q!==this&&(Y.sublevel=null),O[H]=Y}return this._batch(O,V,H=>{if(H)return I(H);this.emit("batch",P),I()}),I[y]}_batch(P,_,I){this.nextTick(I)}sublevel(P,_){return this._sublevel(P,$.defaults(_))}_sublevel(P,_){return new $(this,P,_)}prefixKey(P,_){return P}clear(P,_){if(_=h(P,_),_=s(_,y),P=p(P,this[F].empty),this[j]==="opening")return this.defer(()=>this.clear(P,_)),_[y];if(b(this,_))return _[y];let I=P,O=this.keyEncoding(P.keyEncoding);return P=m(P,O),P.keyEncoding=O.format,P.limit===0?this.nextTick(_):this._clear(P,z=>{if(z)return _(z);this.emit("clear",I),_()}),_[y]}_clear(P,_){this.nextTick(_)}iterator(P){let _=this.keyEncoding(P&&P.keyEncoding),I=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,_),P.keys=P.keys!==!1,P.values=P.values!==!1,P[o.keyEncoding]=_,P[o.valueEncoding]=I,P.keyEncoding=_.format,P.valueEncoding=I.format,this[j]==="opening")return new u(this,P);if(this[j]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(P)}_iterator(P){return new o(this,P)}keys(P){let _=this.keyEncoding(P&&P.keyEncoding),I=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,_),P[o.keyEncoding]=_,P[o.valueEncoding]=I,P.keyEncoding=_.format,P.valueEncoding=I.format,this[j]==="opening")return new d(this,P);if(this[j]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(P)}_keys(P){return new i(this,P)}values(P){let _=this.keyEncoding(P&&P.keyEncoding),I=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,_),P[o.keyEncoding]=_,P[o.valueEncoding]=I,P.keyEncoding=_.format,P.valueEncoding=I.format,this[j]==="opening")return new l(this,P);if(this[j]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(P)}_values(P){return new c(this,P)}defer(P){if(typeof P!="function")throw new TypeError("The first argument must be a function");this[k].push(P)}[A](){if(this[k].length===0)return;let P=this[k];this[k]=[];for(let _ of P)_()}attachResource(P){if(typeof P!="object"||P===null||typeof P.close!="function")throw new TypeError("The first argument must be a resource object");this[v].add(P)}detachResource(P){this[v].delete(P)}_chainedBatch(){return new f(this)}_checkKey(P){if(P==null)return new a("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(P){if(P==null)return new a("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};R.prototype.nextTick=wne();var{AbstractSublevel:$}=bne()({AbstractLevel:R});t.AbstractLevel=R,t.AbstractSublevel=$;var b=function(P,_){return P[j]!=="open"?(P.nextTick(_,new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},x=function(P){return Object.keys(P.supports.encodings).filter(_=>!!P.supports.encodings[_])}}),qU=Kt(t=>{"use strict";t.AbstractLevel=PN().AbstractLevel,t.AbstractSublevel=PN().AbstractSublevel,t.AbstractIterator=Sf().AbstractIterator,t.AbstractKeyIterator=Sf().AbstractKeyIterator,t.AbstractValueIterator=Sf().AbstractValueIterator,t.AbstractChainedBatch=KU().AbstractChainedBatch}),Pne=Kt((t,e)=>{e.exports=n;var r=zU();function n(s,a,o){if(typeof a!="number")throw new Error("second argument must be a Number");let i,c,u,d,l,f=!0,h;Array.isArray(s)?(i=[],u=c=s.length):(d=Object.keys(s),i={},u=c=d.length);function p(y){function S(){o&&o(y,i),o=null}f?r(S):S()}function m(y,S,v){if(i[y]=v,S&&(l=!0),--u===0||S)p(S);else if(!l&&h<c){let E;d?(E=d[h],h+=1,s[E](function(k,A){m(E,k,A)})):(E=h,h+=1,s[E](function(k,A){m(E,k,A)}))}}h=a,u?d?d.some(function(y,S){return s[y](function(v,E){m(y,v,E)}),S===a-1}):s.some(function(y,S){return y(function(v,E){m(S,v,E)}),S===a-1}):p(null),f=!1}}),FU=Kt((t,e)=>{"use strict";e.exports=function(r){let n=r.gte!==void 0?r.gte:r.gt!==void 0?r.gt:void 0,s=r.lte!==void 0?r.lte:r.lt!==void 0?r.lt:void 0,a=r.gte===void 0,o=r.lte===void 0;return n!==void 0&&s!==void 0?IDBKeyRange.bound(n,s,a,o):n!==void 0?IDBKeyRange.lowerBound(n,a):s!==void 0?IDBKeyRange.upperBound(s,o):null}}),GU=Kt((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)}}),xne=Kt(t=>{"use strict";var{AbstractIterator:e}=qU(),r=FU(),n=GU(),s=Symbol("cache"),a=Symbol("finished"),o=Symbol("options"),i=Symbol("currentOptions"),c=Symbol("position"),u=Symbol("location"),d=Symbol("first"),l={},f=class extends e{constructor(p,m,y){super(p,y),this[s]=[],this[a]=this.limit===0,this[o]=y,this[i]={...y},this[c]=void 0,this[u]=m,this[d]=!0}_nextv(p,m,y){if(this[d]=!1,this[a])return this.nextTick(y,null,[]);if(this[s].length>0)return p=Math.min(p,this[s].length),this.nextTick(y,null,this[s].splice(0,p));this[c]!==void 0&&(this[o].reverse?(this[i].lt=this[c],this[i].lte=void 0):(this[i].gt=this[c],this[i].gte=void 0));let S;try{S=r(this[i])}catch{return this[a]=!0,this.nextTick(y,null,[])}let v=this.db.db.transaction([this[u]],"readonly"),E=v.objectStore(this[u]),k=[];if(this[o].reverse){let A=!this[o].values&&E.openKeyCursor?"openKeyCursor":"openCursor";E[A](S,"prev").onsuccess=D=>{let B=D.target.result;if(B){let{key:j,value:F}=B;this[c]=j,k.push([this[o].keys&&j!==void 0?n(j):void 0,this[o].values&&F!==void 0?n(F):void 0]),k.length<p?B.continue():h(v)}else this[a]=!0}}else{let A,D,B=()=>{if(A===void 0||D===void 0)return;let j=Math.max(A.length,D.length);j===0||p===1/0?this[a]=!0:this[c]=A[j-1],k.length=j;for(let F=0;F<j;F++){let q=A[F],N=D[F];k[F]=[this[o].keys&&q!==void 0?n(q):void 0,this[o].values&&N!==void 0?n(N):void 0]}h(v)};this[o].keys||p<1/0?E.getAllKeys(S,p<1/0?p:void 0).onsuccess=j=>{A=j.target.result,B()}:(A=[],this.nextTick(B)),this[o].values?E.getAll(S,p<1/0?p:void 0).onsuccess=j=>{D=j.target.result,B()}:(D=[],this.nextTick(B))}v.onabort=()=>{y(v.error||new Error("aborted by user")),y=null},v.oncomplete=()=>{y(null,k),y=null}}_next(p){if(this[s].length>0){let[m,y]=this[s].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[d]&&(this[d]=!1,m=1),this._nextv(m,l,(y,S)=>{if(y)return p(y);this[s]=S,this._next(p)})}}_all(p,m){this[d]=!1;let y=this[s].splice(0,this[s].length),S=this.limit-this.count-y.length;if(S<=0)return this.nextTick(m,null,y);this._nextv(S,l,(v,E)=>{if(v)return m(v);y.length>0&&(E=y.concat(E)),m(null,E)})}_seek(p,m){this[d]=!0,this[s]=[],this[a]=!1,this[c]=void 0,this[i]={...this[o]};let y;try{y=r(this[o])}catch{this[a]=!0;return}y!==null&&!y.includes(p)?this[a]=!0:this[o].reverse?this[i].lte=p:this[i].gte=p}};t.Iterator=f;function h(p){typeof p.commit=="function"&&p.commit()}}),Sne=Kt((t,e)=>{"use strict";e.exports=function(r,n,s,a,o){if(a.limit===0)return r.nextTick(o);let i=r.db.transaction([n],"readwrite"),c=i.objectStore(n),u=0;i.oncomplete=function(){o()},i.onabort=function(){o(i.error||new Error("aborted by user"))};let d=c.openKeyCursor?"openKeyCursor":"openCursor",l=a.reverse?"prev":"next";c[d](s,l).onsuccess=function(f){let h=f.target.result;h&&(c.delete(h.key).onsuccess=function(){(a.limit<=0||++u<a.limit)&&h.continue()})}}}),Ene=Kt(t=>{"use strict";var{AbstractLevel:e}=qU(),r=_c(),n=Pne(),{fromCallback:s}=X1(),{Iterator:a}=xne(),o=GU(),i=Sne(),c=FU(),u="level-js-",d=Symbol("idb"),l=Symbol("namePrefix"),f=Symbol("location"),h=Symbol("version"),p=Symbol("store"),m=Symbol("onComplete"),y=Symbol("promise"),S=class extends e{constructor(v,E,k){if(typeof E=="function"||typeof k=="function")throw new r("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:A,version:D,...B}=E||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},B),typeof v!="string")throw new Error("constructor requires a location string argument");this[f]=v,this[l]=A??u,this[h]=parseInt(D||1,10),this[d]=null}get location(){return this[f]}get namePrefix(){return this[l]}get version(){return this[h]}get db(){return this[d]}get type(){return"browser-level"}_open(v,E){let k=indexedDB.open(this[l]+this[f],this[h]);k.onerror=function(){E(k.error||new Error("unknown error"))},k.onsuccess=()=>{this[d]=k.result,E()},k.onupgradeneeded=A=>{let D=A.target.result;D.objectStoreNames.contains(this[f])||D.createObjectStore(this[f])}}[p](v){return this[d].transaction([this[f]],v).objectStore(this[f])}[m](v,E){let k=v.transaction;k.onabort=function(){E(k.error||new Error("aborted by user"))},k.oncomplete=function(){E(null,v.result)}}_get(v,E,k){let A=this[p]("readonly"),D;try{D=A.get(v)}catch(B){return this.nextTick(k,B)}this[m](D,function(B,j){if(B)return k(B);if(j===void 0)return k(new r("Entry not found",{code:"LEVEL_NOT_FOUND"}));k(null,o(j))})}_getMany(v,E,k){let A=this[p]("readonly"),D=v.map(B=>j=>{let F;try{F=A.get(B)}catch(q){return j(q)}F.onsuccess=()=>{let q=F.result;j(null,q===void 0?q:o(q))},F.onerror=q=>{q.stopPropagation(),j(F.error)}});n(D,16,k)}_del(v,E,k){let A=this[p]("readwrite"),D;try{D=A.delete(v)}catch(B){return this.nextTick(k,B)}this[m](D,k)}_put(v,E,k,A){let D=this[p]("readwrite"),B;try{B=D.put(E,v)}catch(j){return this.nextTick(A,j)}this[m](B,A)}_iterator(v){return new a(this,this[f],v)}_batch(v,E,k){let A=this[p]("readwrite"),D=A.transaction,B=0,j;D.onabort=function(){k(j||D.error||new Error("aborted by user"))},D.oncomplete=function(){k()};function F(){let q=v[B++],N=q.key,W;try{W=q.type==="del"?A.delete(N):A.put(q.value,N)}catch(ee){j=ee,D.abort();return}B<v.length?W.onsuccess=F:typeof D.commit=="function"&&D.commit()}F()}_clear(v,E){let k,A;try{k=c(v)}catch{return this.nextTick(E)}if(v.limit>=0)return i(this,this[f],k,v,E);try{let D=this[p]("readwrite");A=k?D.delete(k):D.clear()}catch(D){return this.nextTick(E,D)}this[m](A,E)}_close(v){this[d].close(),this.nextTick(v)}};S.destroy=function(v,E,k){typeof E=="function"&&(k=E,E=u),k=s(k,y);let A=indexedDB.deleteDatabase(E+v);return A.onsuccess=function(){k()},A.onerror=function(D){k(D)},k[y]},t.BrowserLevel=S}),WU=Kt(t=>{t.Level=Ene().BrowserLevel}),_ne=Kt((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 J=arguments.length,ie=Array(J),oe=0;oe<J;oe++)ie[oe]=arguments[oe];if(ie.length>1){ie[0]=ie[0].slice(0,-1);for(var ye=ie.length-1,be=1;be<ye;++be)ie[be]=ie[be].slice(1,-1);return ie[ye]=ie[ye].slice(1),ie.join("")}else return ie[0]}function s(J){return"(?:"+J+")"}function a(J){return J===void 0?"undefined":J===null?"null":Object.prototype.toString.call(J).split(" ").pop().split("]").shift().toLowerCase()}function o(J){return J.toUpperCase()}function i(J){return J!=null?J instanceof Array?J:typeof J.length!="number"||J.split||J.setInterval||J.call?[J]:Array.prototype.slice.call(J):[]}function c(J,ie){var oe=J;if(ie)for(var ye in ie)oe[ye]=ie[ye];return oe}function u(J){var ie="[A-Za-z]",oe="[\\x0D]",ye="[0-9]",be="[\\x22]",ze=n(ye,"[A-Fa-f]"),At="[\\x0A]",dr="[\\x20]",Lr=s(s("%[EFef]"+ze+"%"+ze+ze+"%"+ze+ze)+"|"+s("%[89A-Fa-f]"+ze+"%"+ze+ze)+"|"+s("%"+ze+ze)),Kr="[\\:\\/\\?\\#\\[\\]\\@]",er="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",un=n(Kr,er),Cn=J?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",tn=J?"[\\uE000-\\uF8FF]":"[]",wr=n(ie,ye,"[\\-\\.\\_\\~]",Cn),hr=s(ie+n(ie,ye,"[\\+\\-\\.]")+"*"),Bs=s(s(Lr+"|"+n(wr,er,"[\\:]"))+"*"),nm=s(s("25[0-5]")+"|"+s("2[0-4]"+ye)+"|"+s("1"+ye+ye)+"|"+s("[1-9]"+ye)+"|"+ye),ki=s(s("25[0-5]")+"|"+s("2[0-4]"+ye)+"|"+s("1"+ye+ye)+"|"+s("0?[1-9]"+ye)+"|0?0?"+ye),Jo=s(ki+"\\."+ki+"\\."+ki+"\\."+ki),vr=s(ze+"{1,4}"),qi=s(s(vr+"\\:"+vr)+"|"+Jo),vo=s(s(vr+"\\:")+"{6}"+qi),kc=s("\\:\\:"+s(vr+"\\:")+"{5}"+qi),Zu=s(s(vr)+"?\\:\\:"+s(vr+"\\:")+"{4}"+qi),Da=s(s(s(vr+"\\:")+"{0,1}"+vr)+"?\\:\\:"+s(vr+"\\:")+"{3}"+qi),Ww=s(s(s(vr+"\\:")+"{0,2}"+vr)+"?\\:\\:"+s(vr+"\\:")+"{2}"+qi),Vw=s(s(s(vr+"\\:")+"{0,3}"+vr)+"?\\:\\:"+vr+"\\:"+qi),qf=s(s(s(vr+"\\:")+"{0,4}"+vr)+"?\\:\\:"+qi),Ff=s(s(s(vr+"\\:")+"{0,5}"+vr)+"?\\:\\:"+vr),Gf=s(s(s(vr+"\\:")+"{0,6}"+vr)+"?\\:\\:"),Yu=s([vo,kc,Zu,Da,Ww,Vw,qf,Ff,Gf].join("|")),Wf=s(s(wr+"|"+Lr)+"+"),Vf=s(Yu+"\\%25"+Wf),az=s(Yu+s("\\%25|\\%(?!"+ze+"{2})")+Wf),cz=s("[vV]"+ze+"+\\."+n(wr,er,"[\\:]")+"+"),dz=s("\\["+s(az+"|"+Yu+"|"+cz)+"\\]"),YA=s(s(Lr+"|"+n(wr,er))+"*"),sm=s(dz+"|"+Jo+"(?!"+YA+")|"+YA),im=s(ye+"*"),QA=s(s(Bs+"@")+"?"+sm+s("\\:"+im)+"?"),om=s(Lr+"|"+n(wr,er,"[\\:\\@]")),uz=s(om+"*"),XA=s(om+"+"),lz=s(s(Lr+"|"+n(wr,er,"[\\@]"))+"+"),Tc=s(s("\\/"+uz)+"*"),Hf=s("\\/"+s(XA+Tc)+"?"),CP=s(lz+Tc),Hw=s(XA+Tc),Jf="(?!"+om+")",hue=s(Tc+"|"+Hf+"|"+CP+"|"+Hw+"|"+Jf),Zf=s(s(om+"|"+n("[\\/\\?]",tn))+"*"),am=s(s(om+"|[\\/\\?]")+"*"),eR=s(s("\\/\\/"+QA+Tc)+"|"+Hf+"|"+Hw+"|"+Jf),fz=s(hr+"\\:"+eR+s("\\?"+Zf)+"?"+s("\\#"+am)+"?"),pz=s(s("\\/\\/"+QA+Tc)+"|"+Hf+"|"+CP+"|"+Jf),hz=s(pz+s("\\?"+Zf)+"?"+s("\\#"+am)+"?"),mue=s(fz+"|"+hz),yue=s(hr+"\\:"+eR+s("\\?"+Zf)+"?"),gue="^("+hr+")\\:"+s(s("\\/\\/("+s("("+Bs+")@")+"?("+sm+")"+s("\\:("+im+")")+"?)")+"?("+Tc+"|"+Hf+"|"+Hw+"|"+Jf+")")+s("\\?("+Zf+")")+"?"+s("\\#("+am+")")+"?$",wue="^(){0}"+s(s("\\/\\/("+s("("+Bs+")@")+"?("+sm+")"+s("\\:("+im+")")+"?)")+"?("+Tc+"|"+Hf+"|"+CP+"|"+Jf+")")+s("\\?("+Zf+")")+"?"+s("\\#("+am+")")+"?$",vue="^("+hr+")\\:"+s(s("\\/\\/("+s("("+Bs+")@")+"?("+sm+")"+s("\\:("+im+")")+"?)")+"?("+Tc+"|"+Hf+"|"+Hw+"|"+Jf+")")+s("\\?("+Zf+")")+"?$",bue="^"+s("\\#("+am+")")+"?$",Pue="^"+s("("+Bs+")@")+"?("+sm+")"+s("\\:("+im+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",ie,ye,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",wr,er),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",wr,er),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",wr,er),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",wr,er),"g"),NOT_QUERY:new RegExp(n("[^\\%]",wr,er,"[\\:\\@\\/\\?]",tn),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",wr,er,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",wr,er),"g"),UNRESERVED:new RegExp(wr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",wr,un),"g"),PCT_ENCODED:new RegExp(Lr,"g"),IPV4ADDRESS:new RegExp("^("+Jo+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Yu+")"+s(s("\\%25|\\%(?!"+ze+"{2})")+"("+Wf+")")+"?\\]?$")}}var d=u(!1),l=u(!0),f=function(){function J(ie,oe){var ye=[],be=!0,ze=!1,At=void 0;try{for(var dr=ie[Symbol.iterator](),Lr;!(be=(Lr=dr.next()).done)&&(ye.push(Lr.value),!(oe&&ye.length===oe));be=!0);}catch(Kr){ze=!0,At=Kr}finally{try{!be&&dr.return&&dr.return()}finally{if(ze)throw At}}return ye}return function(ie,oe){if(Array.isArray(ie))return ie;if(Symbol.iterator in Object(ie))return J(ie,oe);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),h=function(J){if(Array.isArray(J)){for(var ie=0,oe=Array(J.length);ie<J.length;ie++)oe[ie]=J[ie];return oe}else return Array.from(J)},p=2147483647,m=36,y=1,S=26,v=38,E=700,k=72,A=128,D="-",B=/^xn--/,j=/[^\0-\x7E]/,F=/[\x2E\u3002\uFF0E\uFF61]/g,q={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,W=Math.floor,ee=String.fromCharCode;function R(J){throw new RangeError(q[J])}function $(J,ie){for(var oe=[],ye=J.length;ye--;)oe[ye]=ie(J[ye]);return oe}function b(J,ie){var oe=J.split("@"),ye="";oe.length>1&&(ye=oe[0]+"@",J=oe[1]),J=J.replace(F,".");var be=J.split("."),ze=$(be,ie).join(".");return ye+ze}function x(J){for(var ie=[],oe=0,ye=J.length;oe<ye;){var be=J.charCodeAt(oe++);if(be>=55296&&be<=56319&&oe<ye){var ze=J.charCodeAt(oe++);(ze&64512)==56320?ie.push(((be&1023)<<10)+(ze&1023)+65536):(ie.push(be),oe--)}else ie.push(be)}return ie}var P=function(J){return String.fromCodePoint.apply(String,h(J))},_=function(J){return J-48<10?J-22:J-65<26?J-65:J-97<26?J-97:m},I=function(J,ie){return J+22+75*(J<26)-((ie!=0)<<5)},O=function(J,ie,oe){var ye=0;for(J=oe?W(J/E):J>>1,J+=W(J/ie);J>N*S>>1;ye+=m)J=W(J/N);return W(ye+(N+1)*J/(J+v))},z=function(J){var ie=[],oe=J.length,ye=0,be=A,ze=k,At=J.lastIndexOf(D);At<0&&(At=0);for(var dr=0;dr<At;++dr)J.charCodeAt(dr)>=128&&R("not-basic"),ie.push(J.charCodeAt(dr));for(var Lr=At>0?At+1:0;Lr<oe;){for(var Kr=ye,er=1,un=m;;un+=m){Lr>=oe&&R("invalid-input");var Cn=_(J.charCodeAt(Lr++));(Cn>=m||Cn>W((p-ye)/er))&&R("overflow"),ye+=Cn*er;var tn=un<=ze?y:un>=ze+S?S:un-ze;if(Cn<tn)break;var wr=m-tn;er>W(p/wr)&&R("overflow"),er*=wr}var hr=ie.length+1;ze=O(ye-Kr,hr,Kr==0),W(ye/hr)>p-be&&R("overflow"),be+=W(ye/hr),ye%=hr,ie.splice(ye++,0,be)}return String.fromCodePoint.apply(String,ie)},G=function(J){var ie=[];J=x(J);var oe=J.length,ye=A,be=0,ze=k,At=!0,dr=!1,Lr=void 0;try{for(var Kr=J[Symbol.iterator](),er;!(At=(er=Kr.next()).done);At=!0){var un=er.value;un<128&&ie.push(ee(un))}}catch(Vf){dr=!0,Lr=Vf}finally{try{!At&&Kr.return&&Kr.return()}finally{if(dr)throw Lr}}var Cn=ie.length,tn=Cn;for(Cn&&ie.push(D);tn<oe;){var wr=p,hr=!0,Bs=!1,nm=void 0;try{for(var ki=J[Symbol.iterator](),Jo;!(hr=(Jo=ki.next()).done);hr=!0){var vr=Jo.value;vr>=ye&&vr<wr&&(wr=vr)}}catch(Vf){Bs=!0,nm=Vf}finally{try{!hr&&ki.return&&ki.return()}finally{if(Bs)throw nm}}var qi=tn+1;wr-ye>W((p-be)/qi)&&R("overflow"),be+=(wr-ye)*qi,ye=wr;var vo=!0,kc=!1,Zu=void 0;try{for(var Da=J[Symbol.iterator](),Ww;!(vo=(Ww=Da.next()).done);vo=!0){var Vw=Ww.value;if(Vw<ye&&++be>p&&R("overflow"),Vw==ye){for(var qf=be,Ff=m;;Ff+=m){var Gf=Ff<=ze?y:Ff>=ze+S?S:Ff-ze;if(qf<Gf)break;var Yu=qf-Gf,Wf=m-Gf;ie.push(ee(I(Gf+Yu%Wf,0))),qf=W(Yu/Wf)}ie.push(ee(I(qf,0))),ze=O(be,qi,tn==Cn),be=0,++tn}}}catch(Vf){kc=!0,Zu=Vf}finally{try{!vo&&Da.return&&Da.return()}finally{if(kc)throw Zu}}++be,++ye}return ie.join("")},V=function(J){return b(J,function(ie){return B.test(ie)?z(ie.slice(4).toLowerCase()):ie})},H=function(J){return b(J,function(ie){return j.test(ie)?"xn--"+G(ie):ie})},Y={version:"2.1.0",ucs2:{decode:x,encode:P},decode:z,encode:G,toASCII:H,toUnicode:V},K={};function Q(J){var ie=J.charCodeAt(0),oe=void 0;return ie<16?oe="%0"+ie.toString(16).toUpperCase():ie<128?oe="%"+ie.toString(16).toUpperCase():ie<2048?oe="%"+(ie>>6|192).toString(16).toUpperCase()+"%"+(ie&63|128).toString(16).toUpperCase():oe="%"+(ie>>12|224).toString(16).toUpperCase()+"%"+(ie>>6&63|128).toString(16).toUpperCase()+"%"+(ie&63|128).toString(16).toUpperCase(),oe}function se(J){for(var ie="",oe=0,ye=J.length;oe<ye;){var be=parseInt(J.substr(oe+1,2),16);if(be<128)ie+=String.fromCharCode(be),oe+=3;else if(be>=194&&be<224){if(ye-oe>=6){var ze=parseInt(J.substr(oe+4,2),16);ie+=String.fromCharCode((be&31)<<6|ze&63)}else ie+=J.substr(oe,6);oe+=6}else if(be>=224){if(ye-oe>=9){var At=parseInt(J.substr(oe+4,2),16),dr=parseInt(J.substr(oe+7,2),16);ie+=String.fromCharCode((be&15)<<12|(At&63)<<6|dr&63)}else ie+=J.substr(oe,9);oe+=9}else ie+=J.substr(oe,3),oe+=3}return ie}function re(J,ie){function oe(ye){var be=se(ye);return be.match(ie.UNRESERVED)?be:ye}return J.scheme&&(J.scheme=String(J.scheme).replace(ie.PCT_ENCODED,oe).toLowerCase().replace(ie.NOT_SCHEME,"")),J.userinfo!==void 0&&(J.userinfo=String(J.userinfo).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_USERINFO,Q).replace(ie.PCT_ENCODED,o)),J.host!==void 0&&(J.host=String(J.host).replace(ie.PCT_ENCODED,oe).toLowerCase().replace(ie.NOT_HOST,Q).replace(ie.PCT_ENCODED,o)),J.path!==void 0&&(J.path=String(J.path).replace(ie.PCT_ENCODED,oe).replace(J.scheme?ie.NOT_PATH:ie.NOT_PATH_NOSCHEME,Q).replace(ie.PCT_ENCODED,o)),J.query!==void 0&&(J.query=String(J.query).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_QUERY,Q).replace(ie.PCT_ENCODED,o)),J.fragment!==void 0&&(J.fragment=String(J.fragment).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_FRAGMENT,Q).replace(ie.PCT_ENCODED,o)),J}function Z(J){return J.replace(/^0*(.*)/,"$1")||"0"}function de(J,ie){var oe=J.match(ie.IPV4ADDRESS)||[],ye=f(oe,2),be=ye[1];return be?be.split(".").map(Z).join("."):J}function le(J,ie){var oe=J.match(ie.IPV6ADDRESS)||[],ye=f(oe,3),be=ye[1],ze=ye[2];if(be){for(var At=be.toLowerCase().split("::").reverse(),dr=f(At,2),Lr=dr[0],Kr=dr[1],er=Kr?Kr.split(":").map(Z):[],un=Lr.split(":").map(Z),Cn=ie.IPV4ADDRESS.test(un[un.length-1]),tn=Cn?7:8,wr=un.length-tn,hr=Array(tn),Bs=0;Bs<tn;++Bs)hr[Bs]=er[Bs]||un[wr+Bs]||"";Cn&&(hr[tn-1]=de(hr[tn-1],ie));var nm=hr.reduce(function(vo,kc,Zu){if(!kc||kc==="0"){var Da=vo[vo.length-1];Da&&Da.index+Da.length===Zu?Da.length++:vo.push({index:Zu,length:1})}return vo},[]),ki=nm.sort(function(vo,kc){return kc.length-vo.length})[0],Jo=void 0;if(ki&&ki.length>1){var vr=hr.slice(0,ki.index),qi=hr.slice(ki.index+ki.length);Jo=vr.join(":")+"::"+qi.join(":")}else Jo=hr.join(":");return ze&&(Jo+="%"+ze),Jo}else return J}var pe=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,ve="".match(/(){0}/)[1]===void 0;function ce(J){var ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe={},ye=ie.iri!==!1?l:d;ie.reference==="suffix"&&(J=(ie.scheme?ie.scheme+":":"")+"//"+J);var be=J.match(pe);if(be){ve?(oe.scheme=be[1],oe.userinfo=be[3],oe.host=be[4],oe.port=parseInt(be[5],10),oe.path=be[6]||"",oe.query=be[7],oe.fragment=be[8],isNaN(oe.port)&&(oe.port=be[5])):(oe.scheme=be[1]||void 0,oe.userinfo=J.indexOf("@")!==-1?be[3]:void 0,oe.host=J.indexOf("//")!==-1?be[4]:void 0,oe.port=parseInt(be[5],10),oe.path=be[6]||"",oe.query=J.indexOf("?")!==-1?be[7]:void 0,oe.fragment=J.indexOf("#")!==-1?be[8]:void 0,isNaN(oe.port)&&(oe.port=J.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?be[4]:void 0)),oe.host&&(oe.host=le(de(oe.host,ye),ye)),oe.scheme===void 0&&oe.userinfo===void 0&&oe.host===void 0&&oe.port===void 0&&!oe.path&&oe.query===void 0?oe.reference="same-document":oe.scheme===void 0?oe.reference="relative":oe.fragment===void 0?oe.reference="absolute":oe.reference="uri",ie.reference&&ie.reference!=="suffix"&&ie.reference!==oe.reference&&(oe.error=oe.error||"URI is not a "+ie.reference+" reference.");var ze=K[(ie.scheme||oe.scheme||"").toLowerCase()];if(!ie.unicodeSupport&&(!ze||!ze.unicodeSupport)){if(oe.host&&(ie.domainHost||ze&&ze.domainHost))try{oe.host=Y.toASCII(oe.host.replace(ye.PCT_ENCODED,se).toLowerCase())}catch(At){oe.error=oe.error||"Host's domain name can not be converted to ASCII via punycode: "+At}re(oe,d)}else re(oe,ye);ze&&ze.parse&&ze.parse(oe,ie)}else oe.error=oe.error||"URI can not be parsed.";return oe}function ge(J,ie){var oe=ie.iri!==!1?l:d,ye=[];return J.userinfo!==void 0&&(ye.push(J.userinfo),ye.push("@")),J.host!==void 0&&ye.push(le(de(String(J.host),oe),oe).replace(oe.IPV6ADDRESS,function(be,ze,At){return"["+ze+(At?"%25"+At:"")+"]"})),(typeof J.port=="number"||typeof J.port=="string")&&(ye.push(":"),ye.push(String(J.port))),ye.length?ye.join(""):void 0}var Me=/^\.\.?\//,Le=/^\/\.(\/|$)/,qe=/^\/\.\.(\/|$)/,Et=/^\/?(?:.|\n)*?(?=\/|$)/;function Se(J){for(var ie=[];J.length;)if(J.match(Me))J=J.replace(Me,"");else if(J.match(Le))J=J.replace(Le,"/");else if(J.match(qe))J=J.replace(qe,"/"),ie.pop();else if(J==="."||J==="..")J="";else{var oe=J.match(Et);if(oe){var ye=oe[0];J=J.slice(ye.length),ie.push(ye)}else throw new Error("Unexpected dot segment condition")}return ie.join("")}function et(J){var ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe=ie.iri?l:d,ye=[],be=K[(ie.scheme||J.scheme||"").toLowerCase()];if(be&&be.serialize&&be.serialize(J,ie),J.host&&!oe.IPV6ADDRESS.test(J.host)&&(ie.domainHost||be&&be.domainHost))try{J.host=ie.iri?Y.toUnicode(J.host):Y.toASCII(J.host.replace(oe.PCT_ENCODED,se).toLowerCase())}catch(dr){J.error=J.error||"Host's domain name can not be converted to "+(ie.iri?"Unicode":"ASCII")+" via punycode: "+dr}re(J,oe),ie.reference!=="suffix"&&J.scheme&&(ye.push(J.scheme),ye.push(":"));var ze=ge(J,ie);if(ze!==void 0&&(ie.reference!=="suffix"&&ye.push("//"),ye.push(ze),J.path&&J.path.charAt(0)!=="/"&&ye.push("/")),J.path!==void 0){var At=J.path;!ie.absolutePath&&(!be||!be.absolutePath)&&(At=Se(At)),ze===void 0&&(At=At.replace(/^\/\//,"/%2F")),ye.push(At)}return J.query!==void 0&&(ye.push("?"),ye.push(J.query)),J.fragment!==void 0&&(ye.push("#"),ye.push(J.fragment)),ye.join("")}function wt(J,ie){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},ye=arguments[3],be={};return ye||(J=ce(et(J,oe),oe),ie=ce(et(ie,oe),oe)),oe=oe||{},!oe.tolerant&&ie.scheme?(be.scheme=ie.scheme,be.userinfo=ie.userinfo,be.host=ie.host,be.port=ie.port,be.path=Se(ie.path||""),be.query=ie.query):(ie.userinfo!==void 0||ie.host!==void 0||ie.port!==void 0?(be.userinfo=ie.userinfo,be.host=ie.host,be.port=ie.port,be.path=Se(ie.path||""),be.query=ie.query):(ie.path?(ie.path.charAt(0)==="/"?be.path=Se(ie.path):((J.userinfo!==void 0||J.host!==void 0||J.port!==void 0)&&!J.path?be.path="/"+ie.path:J.path?be.path=J.path.slice(0,J.path.lastIndexOf("/")+1)+ie.path:be.path=ie.path,be.path=Se(be.path)),be.query=ie.query):(be.path=J.path,ie.query!==void 0?be.query=ie.query:be.query=J.query),be.userinfo=J.userinfo,be.host=J.host,be.port=J.port),be.scheme=J.scheme),be.fragment=ie.fragment,be}function xt(J,ie,oe){var ye=c({scheme:"null"},oe);return et(wt(ce(J,ye),ce(ie,ye),ye,!0),ye)}function $t(J,ie){return typeof J=="string"?J=et(ce(J,ie),ie):a(J)==="object"&&(J=ce(et(J,ie),ie)),J}function T(J,ie,oe){return typeof J=="string"?J=et(ce(J,oe),oe):a(J)==="object"&&(J=et(J,oe)),typeof ie=="string"?ie=et(ce(ie,oe),oe):a(ie)==="object"&&(ie=et(ie,oe)),J===ie}function M(J,ie){return J&&J.toString().replace(!ie||!ie.iri?d.ESCAPE:l.ESCAPE,Q)}function L(J,ie){return J&&J.toString().replace(!ie||!ie.iri?d.PCT_ENCODED:l.PCT_ENCODED,se)}var te={scheme:"http",domainHost:!0,parse:function(J,ie){return J.host||(J.error=J.error||"HTTP URIs must have a host."),J},serialize:function(J,ie){var oe=String(J.scheme).toLowerCase()==="https";return(J.port===(oe?443:80)||J.port==="")&&(J.port=void 0),J.path||(J.path="/"),J}},ae={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function he(J){return typeof J.secure=="boolean"?J.secure:String(J.scheme).toLowerCase()==="wss"}var xe={scheme:"ws",domainHost:!0,parse:function(J,ie){var oe=J;return oe.secure=he(oe),oe.resourceName=(oe.path||"/")+(oe.query?"?"+oe.query:""),oe.path=void 0,oe.query=void 0,oe},serialize:function(J,ie){if((J.port===(he(J)?443:80)||J.port==="")&&(J.port=void 0),typeof J.secure=="boolean"&&(J.scheme=J.secure?"wss":"ws",J.secure=void 0),J.resourceName){var oe=J.resourceName.split("?"),ye=f(oe,2),be=ye[0],ze=ye[1];J.path=be&&be!=="/"?be:void 0,J.query=ze,J.resourceName=void 0}return J.fragment=void 0,J}},Mt={scheme:"wss",domainHost:xe.domainHost,parse:xe.parse,serialize:xe.serialize},Bn={},$r=!0,pr="[A-Za-z0-9\\-\\.\\_\\~"+($r?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",sr="[0-9A-Fa-f]",Y9=s(s("%[EFef]"+sr+"%"+sr+sr+"%"+sr+sr)+"|"+s("%[89A-Fa-f]"+sr+"%"+sr+sr)+"|"+s("%"+sr+sr)),Q9="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",X9="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",ez=n(X9,'[\\"\\\\]'),tz="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",rz=new RegExp(pr,"g"),zf=new RegExp(Y9,"g"),nz=new RegExp(n("[^]",Q9,"[\\.]",'[\\"]',ez),"g"),VA=new RegExp(n("[^]",pr,tz),"g"),sz=VA;function DP(J){var ie=se(J);return ie.match(rz)?ie:J}var HA={scheme:"mailto",parse:function(J,ie){var oe=J,ye=oe.to=oe.path?oe.path.split(","):[];if(oe.path=void 0,oe.query){for(var be=!1,ze={},At=oe.query.split("&"),dr=0,Lr=At.length;dr<Lr;++dr){var Kr=At[dr].split("=");switch(Kr[0]){case"to":for(var er=Kr[1].split(","),un=0,Cn=er.length;un<Cn;++un)ye.push(er[un]);break;case"subject":oe.subject=L(Kr[1],ie);break;case"body":oe.body=L(Kr[1],ie);break;default:be=!0,ze[L(Kr[0],ie)]=L(Kr[1],ie);break}}be&&(oe.headers=ze)}oe.query=void 0;for(var tn=0,wr=ye.length;tn<wr;++tn){var hr=ye[tn].split("@");if(hr[0]=L(hr[0]),ie.unicodeSupport)hr[1]=L(hr[1],ie).toLowerCase();else try{hr[1]=Y.toASCII(L(hr[1],ie).toLowerCase())}catch(Bs){oe.error=oe.error||"Email address's domain name can not be converted to ASCII via punycode: "+Bs}ye[tn]=hr.join("@")}return oe},serialize:function(J,ie){var oe=J,ye=i(J.to);if(ye){for(var be=0,ze=ye.length;be<ze;++be){var At=String(ye[be]),dr=At.lastIndexOf("@"),Lr=At.slice(0,dr).replace(zf,DP).replace(zf,o).replace(nz,Q),Kr=At.slice(dr+1);try{Kr=ie.iri?Y.toUnicode(Kr):Y.toASCII(L(Kr,ie).toLowerCase())}catch(tn){oe.error=oe.error||"Email address's domain name can not be converted to "+(ie.iri?"Unicode":"ASCII")+" via punycode: "+tn}ye[be]=Lr+"@"+Kr}oe.path=ye.join(",")}var er=J.headers=J.headers||{};J.subject&&(er.subject=J.subject),J.body&&(er.body=J.body);var un=[];for(var Cn in er)er[Cn]!==Bn[Cn]&&un.push(Cn.replace(zf,DP).replace(zf,o).replace(VA,Q)+"="+er[Cn].replace(zf,DP).replace(zf,o).replace(sz,Q));return un.length&&(oe.query=un.join("&")),oe}},iz=/^([^\:]+)\:(.*)/,JA={scheme:"urn",parse:function(J,ie){var oe=J.path&&J.path.match(iz),ye=J;if(oe){var be=ie.scheme||ye.scheme||"urn",ze=oe[1].toLowerCase(),At=oe[2],dr=be+":"+(ie.nid||ze),Lr=K[dr];ye.nid=ze,ye.nss=At,ye.path=void 0,Lr&&(ye=Lr.parse(ye,ie))}else ye.error=ye.error||"URN can not be parsed.";return ye},serialize:function(J,ie){var oe=ie.scheme||J.scheme||"urn",ye=J.nid,be=oe+":"+(ie.nid||ye),ze=K[be];ze&&(J=ze.serialize(J,ie));var At=J,dr=J.nss;return At.path=(ye||ie.nid)+":"+dr,At}},oz=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,ZA={scheme:"urn:uuid",parse:function(J,ie){var oe=J;return oe.uuid=oe.nss,oe.nss=void 0,!ie.tolerant&&(!oe.uuid||!oe.uuid.match(oz))&&(oe.error=oe.error||"UUID is not valid."),oe},serialize:function(J,ie){var oe=J;return oe.nss=(J.uuid||"").toLowerCase(),oe}};K[te.scheme]=te,K[ae.scheme]=ae,K[xe.scheme]=xe,K[Mt.scheme]=Mt,K[HA.scheme]=HA,K[JA.scheme]=JA,K[ZA.scheme]=ZA,r.SCHEMES=K,r.pctEncChar=Q,r.pctDecChars=se,r.parse=ce,r.removeDotSegments=Se,r.serialize=et,r.resolveComponents=wt,r.resolve=xt,r.normalize=$t,r.equal=T,r.escapeComponent=M,r.unescapeComponent=L,Object.defineProperty(r,"__esModule",{value:!0})})}),kne=Kt((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((s,a,o)=>`${s}${o===0?"":","}${r(a===void 0||typeof a=="symbol"?null:a)}`,"")}]`:`{${Object.keys(n).sort().reduce((s,a)=>{if(n[a]===void 0||typeof n[a]=="symbol")return s;let o=s.length===0?"":",";return`${s}${o}${r(a)}:${r(n[a])}`},"")}}`}}),VU=Kt((t,e)=>{var r=1e3,n=r*60,s=n*60,a=s*24,o=a*7,i=a*365.25;e.exports=function(f,h){h=h||{};var p=typeof f;if(p==="string"&&f.length>0)return c(f);if(p==="number"&&isFinite(f))return h.long?d(f):u(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function c(f){if(f=String(f),!(f.length>100)){var 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*i;case"weeks":case"week":case"w":return p*o;case"days":case"day":case"d":return p*a;case"hours":case"hour":case"hrs":case"hr":case"h":return p*s;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 u(f){var h=Math.abs(f);return h>=a?Math.round(f/a)+"d":h>=s?Math.round(f/s)+"h":h>=n?Math.round(f/n)+"m":h>=r?Math.round(f/r)+"s":f+"ms"}function d(f){var h=Math.abs(f);return h>=a?l(f,h,a,"day"):h>=s?l(f,h,s,"hour"):h>=n?l(f,h,n,"minute"):h>=r?l(f,h,r,"second"):f+" ms"}function l(f,h,p,m){var y=h>=p*1.5;return Math.round(f/p)+" "+m+(y?"s":"")}}),eP=(t=>(t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation",t))(eP||{}),ds={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},Ds=class HU{constructor({method:e,id:r,path:n,query:s,fragment:a,params:o}){this.uri=`did:${e}:${r}`,this.method=e,this.id=r,this.path=n,this.query=s,this.fragment=a,this.params=o}static parse(e){if(!e||e.length>2048)return null;let r=HU.DID_URI_PATTERN.exec(e);if(!r||!r.groups)return null;let{method:n,id:s,path:a,query:o,fragment:i}=r.groups,c={uri:`did:${n}:${s}`,method:n,id:s};if(a&&(c.path=a),o&&(c.query=o.slice(1)),i&&(c.fragment=i.slice(1)),o){let u={},d=o.slice(1).split("&");for(let l of d){let[f,h]=l.split("=");u[f]=h}c.params=u}return c}};Ds.METHOD_PATTERN="([a-z0-9]+)",Ds.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",Ds.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${Ds.PCT_ENCODED_PATTERN})`,Ds.METHOD_ID_PATTERN=`((?:${Ds.ID_CHAR_PATTERN}*:)*(${Ds.ID_CHAR_PATTERN}+))`,Ds.PATH_PATTERN="(/[^#?]*)?",Ds.QUERY_PATTERN="([?][^#]*)?",Ds.FRAGMENT_PATTERN="(#.*)?",Ds.DID_URI_PATTERN=new RegExp("^did:(?<method>"+Ds.METHOD_PATTERN+"):(?<id>"+Ds.METHOD_ID_PATTERN+")(?<path>"+Ds.PATH_PATTERN+")(?<query>"+Ds.QUERY_PATTERN+")(?<fragment>"+Ds.FRAGMENT_PATTERN+")$");var us=Ds,Ze=class JU 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,JU)}},Tne=(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))(Tne||{}),Go=class ZU extends Error{constructor(e,r){super(r),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ZU)}},Li;(function(t){t.AlgorithmNotSupported="algorithmNotSupported",t.EncodingError="encodingError",t.InvalidCoseSign1="invalidCoseSign1",t.InvalidEat="invalidEat",t.InvalidJwe="invalidJwe",t.InvalidJwk="invalidJwk",t.OperationNotSupported="operationNotSupported"})(Li||(Li={}));var Ine=Rf(one(),1);function Ane(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 s=0;s<t.length;s++){var a=t.charAt(s),o=a.charCodeAt(0);if(r[o]!==255)throw new TypeError(a+" is ambiguous");r[o]=s}var i=t.length,c=t.charAt(0),u=Math.log(i)/Math.log(256),d=Math.log(256)/Math.log(i);function l(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,S=0,v=p.length;S!==v&&p[S]===0;)S++,m++;for(var E=(v-S)*d+1>>>0,k=new Uint8Array(E);S!==v;){for(var A=p[S],D=0,B=E-1;(A!==0||D<y)&&B!==-1;B--,D++)A+=256*k[B]>>>0,k[B]=A%i>>>0,A=A/i>>>0;if(A!==0)throw new Error("Non-zero carry");y=D,S++}for(var j=E-y;j!==E&&k[j]===0;)j++;for(var F=c.repeat(m);j<E;++j)F+=t.charAt(k[j]);return F}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,S=0;p[m]===c;)y++,m++;for(var v=(p.length-m)*u+1>>>0,E=new Uint8Array(v);p[m];){var k=r[p.charCodeAt(m)];if(k===255)return;for(var A=0,D=v-1;(k!==0||A<S)&&D!==-1;D--,A++)k+=i*E[D]>>>0,E[D]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");S=A,m++}if(p[m]!==" "){for(var B=v-S;B!==v&&E[B]===0;)B++;for(var j=new Uint8Array(y+(v-B)),F=y;B!==v;)j[F++]=E[B++];return j}}}function h(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:f,decode:h}}var Rne=Ane,Dne=Rne,Cne=Dne,Bje=new Uint8Array(0),jne=(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},LI=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")},$ne=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")}},Mne=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 YU(this,t)}},One=class{constructor(t){this.decoders=t}or(t){return YU(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`)}},YU=(t,e)=>new One({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Bne=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new $ne(t,e,r),this.decoder=new Mne(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},QU=({name:t,prefix:e,encode:r,decode:n})=>new Bne(t,e,r,n),XU=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:s}=Cne(r,e);return QU({prefix:t,name:e,encode:n,decode:a=>LI(s(a))})},Nne=(t,e,r,n)=>{let s={};for(let d=0;d<e.length;++d)s[e[d]]=d;let a=t.length;for(;t[a-1]==="=";)--a;let o=new Uint8Array(a*r/8|0),i=0,c=0,u=0;for(let d=0;d<a;++d){let l=s[t[d]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|l,i+=r,i>=8&&(i-=8,o[u++]=255&c>>i)}if(i>=r||255&c<<8-i)throw new SyntaxError("Unexpected end of data");return o},Une=(t,e,r)=>{let n=e[e.length-1]==="=",s=(1<<r)-1,a="",o=0,i=0;for(let c=0;c<t.length;++c)for(i=i<<8|t[c],o+=8;o>r;)o-=r,a+=e[s&i>>o];if(o&&(a+=e[s&i<<r-o]),n)for(;a.length*r&7;)a+="=";return a},yo=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>QU({prefix:e,name:t,encode(s){return Une(s,n,r)},decode(s){return Nne(s,n,r,t)}}),P1=yo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Nje=yo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Uje=yo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Lje=yo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Kje=yo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zje=yo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),qje=yo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Fje=yo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xN=yo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),qo=XU({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Gje=XU({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Wje=yo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Vje=yo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hd=yo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hje=yo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Lne(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function Kne(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function mI(t){let e=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[r,n]=e;return n}var Vg=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},SN=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(o){return new Promise(function(i,c){o=t[a](o),s(i,c,o.done,o.value)})}}function s(a,o,i,c){Promise.resolve(c).then(function(u){a({value:u,done:i})},o)}},p1=new TextEncoder,yf=new TextDecoder,Qe=class Ni{constructor(e,r){this.data=e,this.format=r}static arrayBuffer(e){return new Ni(e,"ArrayBuffer")}static asyncIterable(e){if(!Kne(e))throw new TypeError("Input must be of type AsyncIterable.");return new Ni(e,"AsyncIterable")}static base32Z(e){return new Ni(e,"Base32Z")}static base58Btc(e){return new Ni(e,"Base58Btc")}static base64Url(e){return new Ni(e,"Base64Url")}static bufferSource(e){return new Ni(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 Ni(e,"Hex")}static multibase(e){return new Ni(e,"Multibase")}static object(e){return new Ni(e,"Object")}static string(e){return new Ni(e,"String")}static uint8Array(e){return new Ni(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return qo.baseDecode(this.data).buffer;case"Base64Url":return hd.baseDecode(this.data).buffer;case"BufferSource":{if(mI(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return Lne(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 Vg(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 xN.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 qo.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return qo.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 hd.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return hd.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=p1.encode(e);return hd.baseEncode(r)}case"String":{let e=p1.encode(this.data);return hd.baseEncode(e)}case"Uint8Array":return hd.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return Vg(this,void 0,void 0,function*(){var e,r,n,s;switch(this.format){case"AsyncIterable":{let c=[];try{for(var a=!0,o=SN(this.data),i;i=yield o.next(),e=i.done,!e;a=!0){s=i.value,a=!1;let u=s;c.push(u)}}catch(u){r={error:u}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}return new Blob(c)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(r,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let r=this.toUint8Array();return Ni.uint8Array(r).toHex()}case"Base64Url":{let r=this.toUint8Array();return Ni.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=hd.baseDecode(this.data),r=yf.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=yf.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return Vg(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 yf.decode(this.data);case"Base64Url":{let e=hd.baseDecode(this.data);return yf.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return yf.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return Vg(this,void 0,void 0,function*(){var e,r,n,s;switch(this.format){case"AsyncIterable":{let c="";try{for(var a=!0,o=SN(this.data),i;i=yield o.next(),e=i.done,!e;a=!0){s=i.value,a=!1;let u=s;typeof u=="string"?c+=u:c+=yf.decode(u,{stream:!0})}}catch(u){r={error:u}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}return c+=yf.decode(void 0,{stream:!1}),c}default:throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`)}})}toUint8Array(){switch(this.format){case"ArrayBuffer":return new Uint8Array(this.data);case"Base32Z":return xN.baseDecode(this.data);case"Base58Btc":return qo.baseDecode(this.data);case"Base64Url":return hd.baseDecode(this.data);case"BufferSource":{let e=mI(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 p1.encode(e)}case"String":return p1.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return Vg(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.`)}})}},mw;(function(t){t.Debug="debug",t.Silent="silent"})(mw||(mw={}));var zne=class{constructor(){this.logLevel=mw.Silent}setLogLevel(t){this.logLevel=t}log(t){this.info(t)}info(t){this.logLevel!==mw.Silent&&console.info(t)}error(t){this.logLevel!==mw.Silent&&console.error(t)}},qne=new zne;typeof window<"u"&&(window.enboxLogger=qne);var ew={};BI(ew,{decode:()=>z1,encodeTo:()=>gw,encodingLength:()=>ww});var Fne=eL,EN=128,Gne=127,Wne=~Gne,Vne=Math.pow(2,31);function eL(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Vne;)e[r++]=t&255|EN,t/=128;for(;t&Wne;)e[r++]=t&255|EN,t>>>=7;return e[r]=t|0,eL.bytes=r-n+1,e}var Hne=yI,Jne=128,_N=127;function yI(t,n){var r=0,n=n||0,s=0,a=n,o,i=t.length;do{if(a>=i)throw yI.bytes=0,new RangeError("Could not decode varint");o=t[a++],r+=s<28?(o&_N)<<s:(o&_N)*Math.pow(2,s),s+=7}while(o>=Jne);return yI.bytes=a-n,r}var Zne=Math.pow(2,7),Yne=Math.pow(2,14),Qne=Math.pow(2,21),Xne=Math.pow(2,28),ese=Math.pow(2,35),tse=Math.pow(2,42),rse=Math.pow(2,49),nse=Math.pow(2,56),sse=Math.pow(2,63),ise=function(t){return t<Zne?1:t<Yne?2:t<Qne?3:t<Xne?4:t<ese?5:t<tse?6:t<rse?7:t<nse?8:t<sse?9:10},ose={encode:Fne,decode:Hne,encodingLength:ise},ase=ose,K1=ase,z1=(t,e=0)=>[K1.decode(t,e),K1.decode.bytes],gw=(t,e,r=0)=>(K1.encode(t,e,r),e),ww=t=>K1.encodingLength(t),cse=(t,e)=>{let r=e.byteLength,n=ww(t),s=n+ww(r),a=new Uint8Array(s+r);return gw(t,a,0),gw(r,a,n),a.set(e,s),new KI(t,r,e,a)},dse=t=>{let e=LI(t),[r,n]=z1(e),[s,a]=z1(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==s)throw new Error("Incorrect length");return new KI(r,s,o,e)},use=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&jne(t.bytes,r.bytes)}},KI=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},kN=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return fse(r,gI(t),e||qo.encoder);default:return pse(r,gI(t),e||P1.encoder)}},TN=new WeakMap,gI=t=>{let e=TN.get(t);if(e==null){let r=new Map;return TN.set(t,r),r}return e},Jje=class Qs{constructor(e,r,n,s){this.code=r,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==Hg)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==hse)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Qs.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=cse(e,r);return Qs.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 Qs.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&use(e.multihash,n.multihash)}toString(e){return kN(this,e)}toJSON(){return{"/":kN(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 Qs)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:s,multihash:a,bytes:o}=r;return new Qs(n,s,a,o||IN(n,s,a.bytes))}else if(r[mse]===!0){let{version:n,multihash:s,code:a}=r,o=dse(s);return Qs.create(n,a,o)}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!==Hg)throw new Error(`Version 0 CID must use dag-pb (code: ${Hg}) block encoding`);return new Qs(e,r,n,n.bytes)}case 1:{let s=IN(e,r,n.bytes);return new Qs(e,r,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return Qs.create(0,Hg,e)}static createV1(e,r){return Qs.create(1,e,r)}static decode(e){let[r,n]=Qs.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=Qs.inspectBytes(e),n=r.size-r.multihashSize,s=LI(e.subarray(n,n+r.multihashSize));if(s.byteLength!==r.multihashSize)throw new Error("Incorrect length");let a=s.subarray(r.multihashSize-r.digestSize),o=new KI(r.multihashCode,r.digestSize,a,s);return[r.version===0?Qs.createV0(o):Qs.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[l,f]=z1(e.subarray(r));return r+=f,l},s=n(),a=Hg;if(s===18?(s=0,r=0):a=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=r,i=n(),c=n(),u=r+c,d=u-o;return{version:s,codec:a,multihashCode:i,digestSize:c,multihashSize:d,size:u}}static parse(e,r){let[n,s]=lse(e,r),a=Qs.decode(s);if(a.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return gI(a).set(n,e),a}},lse=(t,e)=>{switch(t[0]){case"Q":{let r=e||qo;return[qo.prefix,r.decode(`${qo.prefix}${t}`)]}case qo.prefix:{let r=e||qo;return[qo.prefix,r.decode(t)]}case P1.prefix:{let r=e||P1;return[P1.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)]}}},fse=(t,e,r)=>{let{prefix:n}=r;if(n!==qo.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let s=e.get(n);if(s==null){let a=r.encode(t).slice(1);return e.set(n,a),a}else return s},pse=(t,e,r)=>{let{prefix:n}=r,s=e.get(n);if(s==null){let a=r.encode(t);return e.set(n,a),a}else return s},Hg=112,hse=18,IN=(t,e,r)=>{let n=ww(t),s=n+ww(e),a=new Uint8Array(s+r.byteLength);return gw(t,a,0),gw(e,a,n),a.set(r,s),a},mse=Symbol.for("@ipld/js-cid/CID"),Vo=class Uu{static addPrefix(e){var r;let{code:n,data:s,name:a}=e;if(!(a?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=Uu.codeToName.has(n)?n:Uu.nameToCode.get(a),n===void 0)throw new Error(`Unsupported multicodec: ${(r=e.name)!==null&&r!==void 0?r:e.code}`);let o=ew.encodingLength(n),i=new Uint8Array(o+s.byteLength);return i.set(s,o),ew.encodeTo(n,i),i}static getCodeFromData(e){let{prefixedData:r}=e,[n,s]=ew.decode(r);return n}static getCodeFromName(e){let{name:r}=e,n=Uu.nameToCode.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static getNameFromCode(e){let{code:r}=e,n=Uu.codeToName.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static registerCodec(e){Uu.codeToName.set(e.code,e.name),Uu.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:r}=e,[n,s]=ew.decode(r),a=Uu.codeToName.get(n);if(a===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:r.slice(s),name:a}}};Vo.codeToName=new Map;Vo.nameToCode=new Map;Vo.registerCodec({code:237,name:"ed25519-pub"});Vo.registerCodec({code:4864,name:"ed25519-priv"});Vo.registerCodec({code:236,name:"x25519-pub"});Vo.registerCodec({code:4866,name:"x25519-priv"});Vo.registerCodec({code:231,name:"secp256k1-pub"});Vo.registerCodec({code:4865,name:"secp256k1-priv"});function tL(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&tL(t[e])})}var Zje=Rf(WU(),1),Au=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},yse=class{constructor(){this.store=new Map}clear(){return Au(this,void 0,void 0,function*(){this.store.clear()})}open(){return Au(this,void 0,void 0,function*(){})}close(){return Au(this,void 0,void 0,function*(){})}delete(t){return Au(this,void 0,void 0,function*(){return this.store.delete(t)})}get(t){return Au(this,void 0,void 0,function*(){return this.store.get(t)})}has(t){return Au(this,void 0,void 0,function*(){return this.store.has(t)})}list(){return Au(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(t,e){return Au(this,void 0,void 0,function*(){this.store.set(t,e)})}},tP=class{},rL={};BI(rL,{bitGet:()=>Sse,bitLen:()=>xse,bitMask:()=>qI,bitSet:()=>Ese,bytesToHex:()=>Tf,bytesToNumberBE:()=>Ef,bytesToNumberLE:()=>Fu,concatBytes:()=>If,createHmacDrbg:()=>iL,ensureBytes:()=>Rn,equalBytes:()=>bse,hexToBytes:()=>qh,hexToNumber:()=>zI,isBytes:()=>xc,numberToBytesBE:()=>Sc,numberToBytesLE:()=>Fh,numberToHexUnpadded:()=>sL,numberToVarBytesBE:()=>vse,utf8ToBytes:()=>Pse,validateObject:()=>Df});var nL=BigInt(0),rP=BigInt(1),gse=BigInt(2);function xc(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var wse=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Tf(t){if(!xc(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=wse[t[r]];return e}function sL(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function zI(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var md={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function AN(t){if(t>=md._0&&t<=md._9)return t-md._0;if(t>=md._A&&t<=md._F)return t-(md._A-10);if(t>=md._a&&t<=md._f)return t-(md._a-10)}function qh(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 s=0,a=0;s<r;s++,a+=2){let o=AN(t.charCodeAt(a)),i=AN(t.charCodeAt(a+1));if(o===void 0||i===void 0){let c=t[a]+t[a+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+a)}n[s]=o*16+i}return n}function Ef(t){return zI(Tf(t))}function Fu(t){if(!xc(t))throw new Error("Uint8Array expected");return zI(Tf(Uint8Array.from(t).reverse()))}function Sc(t,e){return qh(t.toString(16).padStart(e*2,"0"))}function Fh(t,e){return Sc(t,e).reverse()}function vse(t){return qh(sL(t))}function Rn(t,e,r){let n;if(typeof e=="string")try{n=qh(e)}catch(a){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${a}`)}else if(xc(e))n=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);let s=n.length;if(typeof r=="number"&&s!==r)throw new Error(`${t} expected ${r} bytes, got ${s}`);return n}function If(...t){let e=0;for(let s=0;s<t.length;s++){let a=t[s];if(!xc(a))throw new Error("Uint8Array expected");e+=a.length}let r=new Uint8Array(e),n=0;for(let s=0;s<t.length;s++){let a=t[s];r.set(a,n),n+=a.length}return r}function bse(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 Pse(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function xse(t){let e;for(e=0;t>nL;t>>=rP,e+=1);return e}function Sse(t,e){return t>>BigInt(e)&rP}var Ese=(t,e,r)=>t|(r?rP:nL)<<BigInt(e),qI=t=>(gse<<BigInt(t-1))-rP,iI=t=>new Uint8Array(t),RN=t=>Uint8Array.from(t);function iL(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=iI(t),s=iI(t),a=0,o=()=>{n.fill(1),s.fill(0),a=0},i=(...d)=>r(s,n,...d),c=(d=iI())=>{s=i(RN([0]),d),n=i(),d.length!==0&&(s=i(RN([1]),d),n=i())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,l=[];for(;d<e;){n=i();let f=n.slice();l.push(f),d+=n.length}return If(...l)};return(d,l)=>{o(),c(d);let f;for(;!(f=l(u()));)c();return o(),f}}var _se={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"||xc(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)};function Df(t,e,r={}){let n=(s,a,o)=>{let i=_se[a];if(typeof i!="function")throw new Error(`Invalid validator "${a}", expected function`);let c=t[s];if(!(o&&c===void 0)&&!i(c,t))throw new Error(`Invalid param ${String(s)}=${c} (${typeof c}), expected ${a}`)};for(let[s,a]of Object.entries(e))n(s,a,!1);for(let[s,a]of Object.entries(r))n(s,a,!0);return t}function DN(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function kse(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function oL(t,...e){if(!kse(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 Tse(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");DN(t.outputLen),DN(t.blockLen)}function q1(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 Ise(t,e){oL(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var oI=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function aL(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var aI=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),hc=(t,e)=>t<<32-e|t>>>e,Ase=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ase)throw new Error("Non little-endian hardware is not supported");function cL(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function FI(t){if(typeof t=="string"&&(t=cL(t)),!aL(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function dL(...t){let e=0;for(let n=0;n<t.length;n++){let s=t[n];if(!aL(s))throw new Error("Uint8Array expected");e+=s.length}let r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){let a=t[n];r.set(a,s),s+=a.length}return r}var uL=class{clone(){return this._cloneInto()}},Yje={}.toString;function lL(t){let e=n=>t().update(FI(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function GI(t=32){if(oI&&typeof oI.getRandomValues=="function")return oI.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Rse(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let s=BigInt(32),a=BigInt(4294967295),o=Number(r>>s&a),i=Number(r&a),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,i,n)}var fL=class extends uL{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=aI(this.buffer)}update(t){q1(this);let{view:e,buffer:r,blockLen:n}=this;t=FI(t);let s=t.length;for(let a=0;a<s;){let o=Math.min(n-this.pos,s-a);if(o===n){let i=aI(t);for(;n<=s-a;a+=n)this.process(i,a);continue}r.set(t.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){q1(this),Ise(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:n,isLE:s}=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 d=a;d<n;d++)e[d]=0;Rse(r,n-8,BigInt(this.length*8),s),this.process(r,0);let o=aI(t),i=this.outputLen;if(i%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=i/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,u[d],s)}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:s,destroyed:a,pos:o}=this;return t.length=n,t.pos=o,t.finished=s,t.destroyed=a,n%e&&t.buffer.set(r),t}},Dse=(t,e,r)=>t&e^~t&r,Cse=(t,e,r)=>t&e^t&r^e&r,jse=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]),Ru=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Du=new Uint32Array(64),$se=class extends fL{constructor(){super(64,32,8,!1),this.A=Ru[0]|0,this.B=Ru[1]|0,this.C=Ru[2]|0,this.D=Ru[3]|0,this.E=Ru[4]|0,this.F=Ru[5]|0,this.G=Ru[6]|0,this.H=Ru[7]|0}get(){let{A:t,B:e,C:r,D:n,E:s,F:a,G:o,H:i}=this;return[t,e,r,n,s,a,o,i]}set(t,e,r,n,s,a,o,i){this.A=t|0,this.B=e|0,this.C=r|0,this.D=n|0,this.E=s|0,this.F=a|0,this.G=o|0,this.H=i|0}process(t,e){for(let d=0;d<16;d++,e+=4)Du[d]=t.getUint32(e,!1);for(let d=16;d<64;d++){let l=Du[d-15],f=Du[d-2],h=hc(l,7)^hc(l,18)^l>>>3,p=hc(f,17)^hc(f,19)^f>>>10;Du[d]=p+Du[d-7]+h+Du[d-16]|0}let{A:r,B:n,C:s,D:a,E:o,F:i,G:c,H:u}=this;for(let d=0;d<64;d++){let l=hc(o,6)^hc(o,11)^hc(o,25),f=u+l+Dse(o,i,c)+jse[d]+Du[d]|0,h=(hc(r,2)^hc(r,13)^hc(r,22))+Cse(r,n,s)|0;u=c,c=i,i=o,o=a+f|0,a=s,s=n,n=r,r=f+h|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,i=i+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,s,a,o,i,c,u)}roundClean(){Du.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},pL=lL(()=>new $se),Jn=BigInt(0),en=BigInt(1),vf=BigInt(2),Mse=BigInt(3),wI=BigInt(4),CN=BigInt(5),jN=BigInt(8),Qje=BigInt(9),Ose=BigInt(16);function Ur(t,e){let r=t%e;return r>=Jn?r:e+r}function hL(t,e,r){if(r<=Jn||e<Jn)throw new Error("Expected power/modulo > 0");if(r===en)return Jn;let n=en;for(;e>Jn;)e&en&&(n=n*t%r),t=t*t%r,e>>=en;return n}function an(t,e,r){let n=t;for(;e-- >Jn;)n*=n,n%=r;return n}function vI(t,e){if(t===Jn||e<=Jn)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Ur(t,e),n=e,s=Jn,a=en,o=en,i=Jn;for(;r!==Jn;){let c=n/r,u=n%r,d=s-o*c,l=a-i*c;n=r,r=u,s=o,a=i,o=d,i=l}if(n!==en)throw new Error("invert: does not exist");return Ur(s,e)}function Bse(t){let e=(t-en)/vf,r,n,s;for(r=t-en,n=0;r%vf===Jn;r/=vf,n++);for(s=vf;s<t&&hL(s,e,t)!==t-en;s++);if(n===1){let o=(t+en)/wI;return function(i,c){let u=i.pow(c,o);if(!i.eql(i.sqr(u),c))throw new Error("Cannot find square root");return u}}let a=(r+en)/vf;return function(o,i){if(o.pow(i,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=n,u=o.pow(o.mul(o.ONE,s),r),d=o.pow(i,a),l=o.pow(i,r);for(;!o.eql(l,o.ONE);){if(o.eql(l,o.ZERO))return o.ZERO;let f=1;for(let p=o.sqr(l);f<c&&!o.eql(p,o.ONE);f++)p=o.sqr(p);let h=o.pow(u,en<<BigInt(c-f-1));u=o.sqr(h),d=o.mul(d,h),l=o.mul(l,u),c=f}return d}}function Nse(t){if(t%wI===Mse){let e=(t+en)/wI;return function(r,n){let s=r.pow(n,e);if(!r.eql(r.sqr(s),n))throw new Error("Cannot find square root");return s}}if(t%jN===CN){let e=(t-CN)/jN;return function(r,n){let s=r.mul(n,vf),a=r.pow(s,e),o=r.mul(n,a),i=r.mul(r.mul(o,vf),a),c=r.mul(o,r.sub(i,r.ONE));if(!r.eql(r.sqr(c),n))throw new Error("Cannot find square root");return c}}return t%Ose,Bse(t)}var Use=(t,e)=>(Ur(t,e)&en)===en,Lse=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Kse(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Lse.reduce((n,s)=>(n[s]="function",n),e);return Df(t,r)}function zse(t,e,r){if(r<Jn)throw new Error("Expected power > 0");if(r===Jn)return t.ONE;if(r===en)return e;let n=t.ONE,s=e;for(;r>Jn;)r&en&&(n=t.mul(n,s)),s=t.sqr(s),r>>=en;return n}function qse(t,e){let r=new Array(e.length),n=e.reduce((a,o,i)=>t.is0(o)?a:(r[i]=a,t.mul(a,o)),t.ONE),s=t.inv(n);return e.reduceRight((a,o,i)=>t.is0(o)?a:(r[i]=t.mul(a,r[i]),t.mul(a,o)),s),r}function mL(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function WI(t,e,r=!1,n={}){if(t<=Jn)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:s,nByteLength:a}=mL(t,e);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");let o=Nse(t),i=Object.freeze({ORDER:t,BITS:s,BYTES:a,MASK:qI(s),ZERO:Jn,ONE:en,create:c=>Ur(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Jn<=c&&c<t},is0:c=>c===Jn,isOdd:c=>(c&en)===en,neg:c=>Ur(-c,t),eql:(c,u)=>c===u,sqr:c=>Ur(c*c,t),add:(c,u)=>Ur(c+u,t),sub:(c,u)=>Ur(c-u,t),mul:(c,u)=>Ur(c*u,t),pow:(c,u)=>zse(i,c,u),div:(c,u)=>Ur(c*vI(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>vI(c,t),sqrt:n.sqrt||(c=>o(i,c)),invertBatch:c=>qse(i,c),cmov:(c,u,d)=>d?u:c,toBytes:c=>r?Fh(c,a):Sc(c,a),fromBytes:c=>{if(c.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${c.length}`);return r?Fu(c):Ef(c)}});return Object.freeze(i)}function Fse(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 yL(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 gL(t){let e=yL(t);return e+Math.ceil(e/2)}function Gse(t,e,r=!1){let n=t.length,s=yL(e),a=gL(e);if(n<16||n<a||n>1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);let o=r?Ef(t):Fu(t),i=Ur(o,e-en)+en;return r?Fh(i,s):Sc(i,s)}var Wse=BigInt(0),cI=BigInt(1);function wL(t,e){let r=(s,a)=>{let o=a.negate();return s?o:a},n=s=>{let a=Math.ceil(e/s)+1,o=2**(s-1);return{windows:a,windowSize:o}};return{constTimeNegate:r,unsafeLadder(s,a){let o=t.ZERO,i=s;for(;a>Wse;)a&cI&&(o=o.add(i)),i=i.double(),a>>=cI;return o},precomputeWindow(s,a){let{windows:o,windowSize:i}=n(a),c=[],u=s,d=u;for(let l=0;l<o;l++){d=u,c.push(d);for(let f=1;f<i;f++)d=d.add(u),c.push(d);u=d.double()}return c},wNAF(s,a,o){let{windows:i,windowSize:c}=n(s),u=t.ZERO,d=t.BASE,l=BigInt(2**s-1),f=2**s,h=BigInt(s);for(let p=0;p<i;p++){let m=p*c,y=Number(o&l);o>>=h,y>c&&(y-=f,o+=cI);let S=m,v=m+Math.abs(y)-1,E=p%2!==0,k=y<0;y===0?d=d.add(r(E,a[S])):u=u.add(r(k,a[v]))}return{p:u,f:d}},wNAFCached(s,a,o,i){let c=s._WINDOW_SIZE||1,u=a.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&a.set(s,i(u))),this.wNAF(c,u,o)}}}function VI(t){return Kse(t.Fp),Df(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...mL(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Vse(t){let e=VI(t);Df(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:s}=e;if(r){if(!n.eql(s,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})}var{bytesToNumberBE:Hse,hexToBytes:Jse}=rL,xf={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(t){let{Err:e}=xf;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:Hse(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=xf,r=typeof t=="string"?Jse(t):t;if(!xc(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:s,l:a}=xf._parseInt(r.subarray(2)),{d:o,l:i}=xf._parseInt(a);if(i.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:o}},hexFromSig(t){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let d=u.toString(16);return d.length&1?`0${d}`:d},n=e(r(t.s)),s=e(r(t.r)),a=n.length/2,o=s.length/2,i=r(a),c=r(o);return`30${r(o+a+4)}02${c}${s}02${i}${n}`}},Pd=BigInt(0),zo=BigInt(1),Xje=BigInt(2),$N=BigInt(3),e$e=BigInt(4);function Zse(t){let e=Vse(t),{Fp:r}=e,n=e.toBytes||((p,m,y)=>{let S=m.toAffine();return If(Uint8Array.from([4]),r.toBytes(S.x),r.toBytes(S.y))}),s=e.fromBytes||(p=>{let m=p.subarray(1),y=r.fromBytes(m.subarray(0,r.BYTES)),S=r.fromBytes(m.subarray(r.BYTES,2*r.BYTES));return{x:y,y:S}});function a(p){let{a:m,b:y}=e,S=r.sqr(p),v=r.mul(S,p);return r.add(r.add(v,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 o(p){return typeof p=="bigint"&&Pd<p&&p<e.n}function i(p){if(!o(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:S,n:v}=e;if(m&&typeof p!="bigint"){if(xc(p)&&(p=Tf(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let E;try{E=typeof p=="bigint"?p:Ef(Rn("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return S&&(E=Ur(E,v)),i(E),E}let u=new Map;function d(p){if(!(p instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(m,y,S){if(this.px=m,this.py=y,this.pz=S,m==null||!r.isValid(m))throw new Error("x required");if(y==null||!r.isValid(y))throw new Error("y required");if(S==null||!r.isValid(S))throw new Error("z required")}static fromAffine(m){let{x:y,y:S}=m||{};if(!m||!r.isValid(y)||!r.isValid(S))throw new Error("invalid affine point");if(m instanceof l)throw new Error("projective point not allowed");let v=E=>r.eql(E,r.ZERO);return v(y)&&v(S)?l.ZERO:new l(y,S,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=r.invertBatch(m.map(S=>S.pz));return m.map((S,v)=>S.toAffine(y[v])).map(l.fromAffine)}static fromHex(m){let y=l.fromAffine(s(Rn("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return l.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,u.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 S=r.sqr(y),v=a(m);if(!r.eql(S,v))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){d(m);let{px:y,py:S,pz:v}=this,{px:E,py:k,pz:A}=m,D=r.eql(r.mul(y,A),r.mul(E,v)),B=r.eql(r.mul(S,A),r.mul(k,v));return D&&B}negate(){return new l(this.px,r.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,S=r.mul(y,$N),{px:v,py:E,pz:k}=this,A=r.ZERO,D=r.ZERO,B=r.ZERO,j=r.mul(v,v),F=r.mul(E,E),q=r.mul(k,k),N=r.mul(v,E);return N=r.add(N,N),B=r.mul(v,k),B=r.add(B,B),A=r.mul(m,B),D=r.mul(S,q),D=r.add(A,D),A=r.sub(F,D),D=r.add(F,D),D=r.mul(A,D),A=r.mul(N,A),B=r.mul(S,B),q=r.mul(m,q),N=r.sub(j,q),N=r.mul(m,N),N=r.add(N,B),B=r.add(j,j),j=r.add(B,j),j=r.add(j,q),j=r.mul(j,N),D=r.add(D,j),q=r.mul(E,k),q=r.add(q,q),j=r.mul(q,N),A=r.sub(A,j),B=r.mul(q,F),B=r.add(B,B),B=r.add(B,B),new l(A,D,B)}add(m){d(m);let{px:y,py:S,pz:v}=this,{px:E,py:k,pz:A}=m,D=r.ZERO,B=r.ZERO,j=r.ZERO,F=e.a,q=r.mul(e.b,$N),N=r.mul(y,E),W=r.mul(S,k),ee=r.mul(v,A),R=r.add(y,S),$=r.add(E,k);R=r.mul(R,$),$=r.add(N,W),R=r.sub(R,$),$=r.add(y,v);let b=r.add(E,A);return $=r.mul($,b),b=r.add(N,ee),$=r.sub($,b),b=r.add(S,v),D=r.add(k,A),b=r.mul(b,D),D=r.add(W,ee),b=r.sub(b,D),j=r.mul(F,$),D=r.mul(q,ee),j=r.add(D,j),D=r.sub(W,j),j=r.add(W,j),B=r.mul(D,j),W=r.add(N,N),W=r.add(W,N),ee=r.mul(F,ee),$=r.mul(q,$),W=r.add(W,ee),ee=r.sub(N,ee),ee=r.mul(F,ee),$=r.add($,ee),N=r.mul(W,$),B=r.add(B,N),N=r.mul(b,$),D=r.mul(R,D),D=r.sub(D,N),N=r.mul(R,W),j=r.mul(b,j),j=r.add(j,N),new l(D,B,j)}subtract(m){return this.add(m.negate())}is0(){return this.equals(l.ZERO)}wNAF(m){return h.wNAFCached(this,u,m,y=>{let S=r.invertBatch(y.map(v=>v.pz));return y.map((v,E)=>v.toAffine(S[E])).map(l.fromAffine)})}multiplyUnsafe(m){let y=l.ZERO;if(m===Pd)return y;if(i(m),m===zo)return this;let{endo:S}=e;if(!S)return h.unsafeLadder(this,m);let{k1neg:v,k1:E,k2neg:k,k2:A}=S.splitScalar(m),D=y,B=y,j=this;for(;E>Pd||A>Pd;)E&zo&&(D=D.add(j)),A&zo&&(B=B.add(j)),j=j.double(),E>>=zo,A>>=zo;return v&&(D=D.negate()),k&&(B=B.negate()),B=new l(r.mul(B.px,S.beta),B.py,B.pz),D.add(B)}multiply(m){i(m);let y=m,S,v,{endo:E}=e;if(E){let{k1neg:k,k1:A,k2neg:D,k2:B}=E.splitScalar(y),{p:j,f:F}=this.wNAF(A),{p:q,f:N}=this.wNAF(B);j=h.constTimeNegate(k,j),q=h.constTimeNegate(D,q),q=new l(r.mul(q.px,E.beta),q.py,q.pz),S=j.add(q),v=F.add(N)}else{let{p:k,f:A}=this.wNAF(y);S=k,v=A}return l.normalizeZ([S,v])[0]}multiplyAndAddUnsafe(m,y,S){let v=l.BASE,E=(A,D)=>D===Pd||D===zo||!A.equals(v)?A.multiplyUnsafe(D):A.multiply(D),k=E(this,y).add(E(m,S));return k.is0()?void 0:k}toAffine(m){let{px:y,py:S,pz:v}=this,E=this.is0();m==null&&(m=E?r.ONE:r.inv(v));let k=r.mul(y,m),A=r.mul(S,m),D=r.mul(v,m);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(D,r.ONE))throw new Error("invZ was invalid");return{x:k,y:A}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===zo)return!0;if(y)return y(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===zo?this:y?y(l,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(l,this,m)}toHex(m=!0){return Tf(this.toRawBytes(m))}}l.BASE=new l(e.Gx,e.Gy,r.ONE),l.ZERO=new l(r.ZERO,r.ONE,r.ZERO);let f=e.nBitLength,h=wL(l,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:o}}function Yse(t){let e=VI(t);return Df(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Qse(t){let e=Yse(t),{Fp:r,n}=e,s=r.BYTES+1,a=2*r.BYTES+1;function o($){return Pd<$&&$<r.ORDER}function i($){return Ur($,n)}function c($){return vI($,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:l,isWithinCurveOrder:f}=Zse({...e,toBytes($,b,x){let P=b.toAffine(),_=r.toBytes(P.x),I=If;return x?I(Uint8Array.from([b.hasEvenY()?2:3]),_):I(Uint8Array.from([4]),_,r.toBytes(P.y))},fromBytes($){let b=$.length,x=$[0],P=$.subarray(1);if(b===s&&(x===2||x===3)){let _=Ef(P);if(!o(_))throw new Error("Point is not on curve");let I=l(_),O=r.sqrt(I),z=(O&zo)===zo;return(x&1)===1!==z&&(O=r.neg(O)),{x:_,y:O}}else if(b===a&&x===4){let _=r.fromBytes(P.subarray(0,r.BYTES)),I=r.fromBytes(P.subarray(r.BYTES,2*r.BYTES));return{x:_,y:I}}else throw new Error(`Point of length ${b} was invalid. Expected ${s} compressed bytes or ${a} uncompressed bytes`)}}),h=$=>Tf(Sc($,e.nByteLength));function p($){let b=n>>zo;return $>b}function m($){return p($)?i(-$):$}let y=($,b,x)=>Ef($.slice(b,x));class S{constructor(b,x,P){this.r=b,this.s=x,this.recovery=P,this.assertValidity()}static fromCompact(b){let x=e.nByteLength;return b=Rn("compactSignature",b,x*2),new S(y(b,0,x),y(b,x,2*x))}static fromDER(b){let{r:x,s:P}=xf.toSig(Rn("DER",b));return new S(x,P)}assertValidity(){if(!f(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!f(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(b){return new S(this.r,this.s,b)}recoverPublicKey(b){let{r:x,s:P,recovery:_}=this,I=B(Rn("msgHash",b));if(_==null||![0,1,2,3].includes(_))throw new Error("recovery id invalid");let O=_===2||_===3?x+e.n:x;if(O>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let z=_&1?"03":"02",G=u.fromHex(z+h(O)),V=c(O),H=i(-I*V),Y=i(P*V),K=u.BASE.multiplyAndAddUnsafe(G,H,Y);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return qh(this.toDERHex())}toDERHex(){return xf.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return qh(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let v={isValidPrivateKey($){try{return d($),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let $=gL(e.n);return Gse(e.randomBytes($),e.n)},precompute($=8,b=u.BASE){return b._setWindowSize($),b.multiply(BigInt(3)),b}};function E($,b=!0){return u.fromPrivateKey($).toRawBytes(b)}function k($){let b=xc($),x=typeof $=="string",P=(b||x)&&$.length;return b?P===s||P===a:x?P===2*s||P===2*a:$ instanceof u}function A($,b,x=!0){if(k($))throw new Error("first arg must be private key");if(!k(b))throw new Error("second arg must be public key");return u.fromHex(b).multiply(d($)).toRawBytes(x)}let D=e.bits2int||function($){let b=Ef($),x=$.length*8-e.nBitLength;return x>0?b>>BigInt(x):b},B=e.bits2int_modN||function($){return i(D($))},j=qI(e.nBitLength);function F($){if(typeof $!="bigint")throw new Error("bigint expected");if(!(Pd<=$&&$<j))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Sc($,e.nByteLength)}function q($,b,x=N){if(["recovered","canonical"].some(se=>se in x))throw new Error("sign() legacy options not supported");let{hash:P,randomBytes:_}=e,{lowS:I,prehash:O,extraEntropy:z}=x;I==null&&(I=!0),$=Rn("msgHash",$),O&&($=Rn("prehashed msgHash",P($)));let G=B($),V=d(b),H=[F(V),F(G)];if(z!=null){let se=z===!0?_(r.BYTES):z;H.push(Rn("extraEntropy",se))}let Y=If(...H),K=G;function Q(se){let re=D(se);if(!f(re))return;let Z=c(re),de=u.BASE.multiply(re).toAffine(),le=i(de.x);if(le===Pd)return;let pe=i(Z*i(K+le*V));if(pe===Pd)return;let ve=(de.x===le?0:2)|Number(de.y&zo),ce=pe;return I&&p(pe)&&(ce=m(pe),ve^=1),new S(le,ce,ve)}return{seed:Y,k2sig:Q}}let N={lowS:e.lowS,prehash:!1},W={lowS:e.lowS,prehash:!1};function ee($,b,x=N){let{seed:P,k2sig:_}=q($,b,x),I=e;return iL(I.hash.outputLen,I.nByteLength,I.hmac)(P,_)}u.BASE._setWindowSize(8);function R($,b,x,P=W){let _=$;if(b=Rn("msgHash",b),x=Rn("publicKey",x),"strict"in P)throw new Error("options.strict was renamed to lowS");let{lowS:I,prehash:O}=P,z,G;try{if(typeof _=="string"||xc(_))try{z=S.fromDER(_)}catch(Z){if(!(Z instanceof xf.Err))throw Z;z=S.fromCompact(_)}else if(typeof _=="object"&&typeof _.r=="bigint"&&typeof _.s=="bigint"){let{r:Z,s:de}=_;z=new S(Z,de)}else throw new Error("PARSE");G=u.fromHex(x)}catch(Z){if(Z.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(I&&z.hasHighS())return!1;O&&(b=e.hash(b));let{r:V,s:H}=z,Y=B(b),K=c(H),Q=i(Y*K),se=i(V*K),re=u.BASE.multiplyAndAddUnsafe(G,Q,se)?.toAffine();return re?i(re.x)===V:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:A,sign:ee,verify:R,ProjectivePoint:u,Signature:S,utils:v}}var vL=class extends uL{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Tse(t);let r=FI(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,s=new Uint8Array(n);s.set(r.length>n?t.create().update(r).digest():r);for(let a=0;a<s.length;a++)s[a]^=54;this.iHash.update(s),this.oHash=t.create();for(let a=0;a<s.length;a++)s[a]^=106;this.oHash.update(s),s.fill(0)}update(t){return q1(this),this.iHash.update(t),this}digestInto(t){q1(this),oL(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:s,blockLen:a,outputLen:o}=this;return t=t,t.finished=n,t.destroyed=s,t.blockLen=a,t.outputLen=o,t.oHash=e._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},bL=(t,e,r)=>new vL(t,e).update(r).digest();bL.create=(t,e)=>new vL(t,e);function Xse(t){return{hash:t,hmac:(e,...r)=>bL(t,e,dL(...r)),randomBytes:GI}}function PL(t,e){let r=n=>Qse({...t,...Xse(n)});return Object.freeze({...r(e),create:r})}var xL=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),MN=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),eie=BigInt(1),bI=BigInt(2),ON=(t,e)=>(t+e/bI)/e;function tie(t){let e=xL,r=BigInt(3),n=BigInt(6),s=BigInt(11),a=BigInt(22),o=BigInt(23),i=BigInt(44),c=BigInt(88),u=t*t*t%e,d=u*u*t%e,l=an(d,r,e)*d%e,f=an(l,r,e)*d%e,h=an(f,bI,e)*u%e,p=an(h,s,e)*h%e,m=an(p,a,e)*p%e,y=an(m,i,e)*m%e,S=an(y,c,e)*y%e,v=an(S,i,e)*m%e,E=an(v,r,e)*d%e,k=an(E,o,e)*p%e,A=an(k,n,e)*u%e,D=an(A,bI,e);if(!PI.eql(PI.sqr(D),t))throw new Error("Cannot find square root");return D}var PI=WI(xL,void 0,void 0,{sqrt:tie}),fo=PL({a:BigInt(0),b:BigInt(7),Fp:PI,n:MN,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=MN,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-eie*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=r,o=BigInt("0x100000000000000000000000000000000"),i=ON(a*t,e),c=ON(-n*t,e),u=Ur(t-i*r-c*s,e),d=Ur(-i*n-c*a,e),l=u>o,f=d>o;if(l&&(u=e-u),f&&(d=e-d),u>o||d>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:l,k1:u,k2neg:f,k2:d}}}},pL),t$e=BigInt(0),r$e=fo.ProjectivePoint;function rie(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function SL(t,...e){if(!rie(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 BN(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 nie(t,e){SL(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var x1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,dI=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),mc=(t,e)=>t<<32-e|t>>>e,n$e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function sie(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function EL(t){return typeof t=="string"&&(t=sie(t)),SL(t),t}var iie=class{clone(){return this._cloneInto()}},s$e={}.toString;function oie(t){let e=n=>t().update(EL(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function aie(t=32){if(x1&&typeof x1.getRandomValues=="function")return x1.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function cie(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let s=BigInt(32),a=BigInt(4294967295),o=Number(r>>s&a),i=Number(r&a),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,i,n)}var die=(t,e,r)=>t&e^~t&r,uie=(t,e,r)=>t&e^t&r^e&r,lie=class extends iie{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=dI(this.buffer)}update(t){BN(this);let{view:e,buffer:r,blockLen:n}=this;t=EL(t);let s=t.length;for(let a=0;a<s;){let o=Math.min(n-this.pos,s-a);if(o===n){let i=dI(t);for(;n<=s-a;a+=n)this.process(i,a);continue}r.set(t.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){BN(this),nie(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:n,isLE:s}=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 d=a;d<n;d++)e[d]=0;cie(r,n-8,BigInt(this.length*8),s),this.process(r,0);let o=dI(t),i=this.outputLen;if(i%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=i/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,u[d],s)}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:s,destroyed:a,pos:o}=this;return t.length=n,t.pos=o,t.finished=s,t.destroyed=a,n%e&&t.buffer.set(r),t}},fie=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]),Cu=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ju=new Uint32Array(64),pie=class extends lie{constructor(){super(64,32,8,!1),this.A=Cu[0]|0,this.B=Cu[1]|0,this.C=Cu[2]|0,this.D=Cu[3]|0,this.E=Cu[4]|0,this.F=Cu[5]|0,this.G=Cu[6]|0,this.H=Cu[7]|0}get(){let{A:t,B:e,C:r,D:n,E:s,F:a,G:o,H:i}=this;return[t,e,r,n,s,a,o,i]}set(t,e,r,n,s,a,o,i){this.A=t|0,this.B=e|0,this.C=r|0,this.D=n|0,this.E=s|0,this.F=a|0,this.G=o|0,this.H=i|0}process(t,e){for(let d=0;d<16;d++,e+=4)ju[d]=t.getUint32(e,!1);for(let d=16;d<64;d++){let l=ju[d-15],f=ju[d-2],h=mc(l,7)^mc(l,18)^l>>>3,p=mc(f,17)^mc(f,19)^f>>>10;ju[d]=p+ju[d-7]+h+ju[d-16]|0}let{A:r,B:n,C:s,D:a,E:o,F:i,G:c,H:u}=this;for(let d=0;d<64;d++){let l=mc(o,6)^mc(o,11)^mc(o,25),f=u+l+die(o,i,c)+fie[d]+ju[d]|0,h=(mc(r,2)^mc(r,13)^mc(r,22))+uie(r,n,s)|0;u=c,c=i,i=o,o=a+f|0,a=s,s=n,n=r,r=f+h|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,i=i+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,s,a,o,i,c,u)}roundClean(){ju.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},vw=oie(()=>new pie);function hie(t){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let s=Object.keys(n).sort(),a={};for(let o of s)a[o]=e(n[o]);return a}return n},r=e(t);return JSON.stringify(r)}var mie=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},_L=class{static digest(t){return mie(this,arguments,void 0,function*({data:e}){return vw(e)})}},yie=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},NN="urn:jwk:";function fr(t){return yie(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}`);tL(n);let s=hie(n),a=Qe.string(s).toUint8Array(),o=yield _L.digest({data:a});return Qe.uint8Array(o).toBase64Url()})}function _f(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 HI(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 Ed(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 JI(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 gie(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}}var As=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},wie=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 s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},js=class gc{static adjustSignatureToLowS(e){return As(this,arguments,void 0,function*({signature:r}){let n=fo.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return As(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield gc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"secp256k1",d:Qe.uint8Array(r).toBase64Url(),x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield fr({jwk:s}),s})}static bytesToPublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield gc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"secp256k1",x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield fr({jwk:s}),s})}static compressPublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){return fo.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return As(this,arguments,void 0,function*({key:r}){let n=yield gc.privateKeyToBytes({privateKey:r}),s=yield gc.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"secp256k1",x:Qe.uint8Array(s.x).toBase64Url(),y:Qe.uint8Array(s.y).toBase64Url()};return a.kid=yield fr({jwk:a}),a})}static convertDerToCompactSignature(e){return As(this,arguments,void 0,function*({derSignature:r}){return fo.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){return fo.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return As(this,void 0,void 0,function*(){let e=fo.utils.randomPrivateKey(),r=yield gc.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield fr({jwk:r}),r})}static getPublicKey(e){return As(this,arguments,void 0,function*({key:r}){var n;if(!(_f(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:s}=r,a=wie(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield fr({jwk:a})),a})}static privateKeyToBytes(e){return As(this,arguments,void 0,function*({privateKey:r}){if(!_f(r))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return As(this,arguments,void 0,function*({publicKey:r}){if(!(HI(r)&&r.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),s=Qe.base64Url(r.x).toUint8Array(),a=Qe.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...s,...a])})}static sharedSecret(e){return As(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 s=yield gc.privateKeyToBytes({privateKey:r}),a=yield gc.publicKeyToBytes({publicKey:n});return fo.getSharedSecret(s,a,!0).slice(1)})}static sign(e){return As(this,arguments,void 0,function*({data:r,key:n}){let s=yield gc.privateKeyToBytes({privateKey:n}),a=vw(r);return fo.sign(a,s).toCompactRawBytes()})}static validatePrivateKey(e){return As(this,arguments,void 0,function*({privateKeyBytes:r}){return fo.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){try{fo.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return As(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield gc.publicKeyToBytes({publicKey:r}),o=vw(s);return fo.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return As(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=fo.getPublicKey(r));let n=fo.ProjectivePoint.fromHex(r),s=Sc(n.x,32),a=Sc(n.y,32);return{x:s,y:a}})}},kL=WI(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),vie=kL.create(BigInt("-3")),bie=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Pie=PL({a:vie,b:bie,Fp:kL,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},pL),Bo=Pie,Rs=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},xie=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 s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},Xs=class wc{static adjustSignatureToLowS(e){return Rs(this,arguments,void 0,function*({signature:r}){let n=Bo.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Rs(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield wc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"P-256",d:Qe.uint8Array(r).toBase64Url(),x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield fr({jwk:s}),s})}static bytesToPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield wc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"P-256",x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield fr({jwk:s}),s})}static compressPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){return Bo.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Rs(this,arguments,void 0,function*({key:r}){let n=yield wc.privateKeyToBytes({privateKey:r}),s=yield wc.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"P-256",x:Qe.uint8Array(s.x).toBase64Url(),y:Qe.uint8Array(s.y).toBase64Url()};return a.kid=yield fr({jwk:a}),a})}static convertDerToCompactSignature(e){return Rs(this,arguments,void 0,function*({derSignature:r}){return Bo.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){return Bo.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Rs(this,void 0,void 0,function*(){let e=Bo.utils.randomPrivateKey(),r=yield wc.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield fr({jwk:r}),r})}static getPublicKey(e){return Rs(this,arguments,void 0,function*({key:r}){var n;if(!(_f(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:s}=r,a=xie(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield fr({jwk:a})),a})}static privateKeyToBytes(e){return Rs(this,arguments,void 0,function*({privateKey:r}){if(!_f(r))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Rs(this,arguments,void 0,function*({publicKey:r}){if(!(HI(r)&&r.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),s=Qe.base64Url(r.x).toUint8Array(),a=Qe.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...s,...a])})}static sharedSecret(e){return Rs(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 s=yield wc.privateKeyToBytes({privateKey:r}),a=yield wc.publicKeyToBytes({publicKey:n});return Bo.getSharedSecret(s,a,!0).slice(1)})}static sign(e){return Rs(this,arguments,void 0,function*({data:r,key:n}){let s=yield wc.privateKeyToBytes({privateKey:n}),a=vw(r);return Bo.sign(a,s).toCompactRawBytes()})}static validatePrivateKey(e){return Rs(this,arguments,void 0,function*({privateKeyBytes:r}){return Bo.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){try{Bo.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Rs(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield wc.publicKeyToBytes({publicKey:r}),o=vw(s);return Bo.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return Rs(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Bo.getPublicKey(r));let n=Bo.ProjectivePoint.fromHex(r),s=Sc(n.x,32),a=Sc(n.y,32);return{x:s,y:a}})}},yd=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},UN=class extends tP{bytesToPrivateKey(t){return yd(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield js.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Xs.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256",n}default:throw new Go(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return yd(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield js.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Xs.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256",n}default:throw new Go(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return yd(this,arguments,void 0,function*({key:e}){if(!_f(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield js.computePublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield Xs.computePublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return yd(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let r=yield js.generateKey();return r.alg="ES256K",r}case"ES256":case"secp256r1":{let r=yield Xs.generateKey();return r.alg="ES256",r}}})}getPublicKey(t){return yd(this,arguments,void 0,function*({key:e}){if(!_f(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield js.getPublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield Xs.getPublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return yd(this,arguments,void 0,function*({key:e,data:r}){if(!_f(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield js.sign({key:e,data:r});case"P-256":return yield Xs.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return yd(this,arguments,void 0,function*({key:e,signature:r,data:n}){if(!HI(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(e.crv){case"secp256k1":return yield js.verify({key:e,signature:r,data:n});case"P-256":return yield Xs.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return yd(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield js.privateKeyToBytes({privateKey:e});case"P-256":return yield Xs.privateKeyToBytes({privateKey:e});default:throw new Go(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return yd(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield js.publicKeyToBytes({publicKey:e});case"P-256":return yield Xs.publicKeyToBytes({publicKey:e});default:throw new Go(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},h1=BigInt(4294967295),xI=BigInt(32);function TL(t,e=!1){return e?{h:Number(t&h1),l:Number(t>>xI&h1)}:{h:Number(t>>xI&h1)|0,l:Number(t&h1)|0}}function Sie(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:a,l:o}=TL(t[s],e);[r[s],n[s]]=[a,o]}return[r,n]}var Eie=(t,e)=>BigInt(t>>>0)<<xI|BigInt(e>>>0),_ie=(t,e,r)=>t>>>r,kie=(t,e,r)=>t<<32-r|e>>>r,Tie=(t,e,r)=>t>>>r|e<<32-r,Iie=(t,e,r)=>t<<32-r|e>>>r,Aie=(t,e,r)=>t<<64-r|e>>>r-32,Rie=(t,e,r)=>t>>>r-32|e<<64-r,Die=(t,e)=>e,Cie=(t,e)=>t,jie=(t,e,r)=>t<<r|e>>>32-r,$ie=(t,e,r)=>e<<r|t>>>32-r,Mie=(t,e,r)=>e<<r-32|t>>>64-r,Oie=(t,e,r)=>t<<r-32|e>>>64-r;function Bie(t,e,r,n){let s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}var Nie=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Uie=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Lie=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Kie=(t,e,r,n,s)=>e+r+n+s+(t/2**32|0)|0,zie=(t,e,r,n,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(s>>>0),qie=(t,e,r,n,s,a)=>e+r+n+s+a+(t/2**32|0)|0,Fie={fromBig:TL,split:Sie,toBig:Eie,shrSH:_ie,shrSL:kie,rotrSH:Tie,rotrSL:Iie,rotrBH:Aie,rotrBL:Rie,rotr32H:Die,rotr32L:Cie,rotlSH:jie,rotlSL:$ie,rotlBH:Mie,rotlBL:Oie,add:Bie,add3L:Nie,add3H:Uie,add4L:Lie,add4H:Kie,add5H:qie,add5L:zie},Rt=Fie,[Gie,Wie]=Rt.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))),$u=new Uint32Array(80),Mu=new Uint32Array(80),Vie=class extends fL{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:s,Cl:a,Dh:o,Dl:i,Eh:c,El:u,Fh:d,Fl:l,Gh:f,Gl:h,Hh:p,Hl:m}=this;return[t,e,r,n,s,a,o,i,c,u,d,l,f,h,p,m]}set(t,e,r,n,s,a,o,i,c,u,d,l,f,h,p,m){this.Ah=t|0,this.Al=e|0,this.Bh=r|0,this.Bl=n|0,this.Ch=s|0,this.Cl=a|0,this.Dh=o|0,this.Dl=i|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=l|0,this.Gh=f|0,this.Gl=h|0,this.Hh=p|0,this.Hl=m|0}process(t,e){for(let v=0;v<16;v++,e+=4)$u[v]=t.getUint32(e),Mu[v]=t.getUint32(e+=4);for(let v=16;v<80;v++){let E=$u[v-15]|0,k=Mu[v-15]|0,A=Rt.rotrSH(E,k,1)^Rt.rotrSH(E,k,8)^Rt.shrSH(E,k,7),D=Rt.rotrSL(E,k,1)^Rt.rotrSL(E,k,8)^Rt.shrSL(E,k,7),B=$u[v-2]|0,j=Mu[v-2]|0,F=Rt.rotrSH(B,j,19)^Rt.rotrBH(B,j,61)^Rt.shrSH(B,j,6),q=Rt.rotrSL(B,j,19)^Rt.rotrBL(B,j,61)^Rt.shrSL(B,j,6),N=Rt.add4L(D,q,Mu[v-7],Mu[v-16]),W=Rt.add4H(N,A,F,$u[v-7],$u[v-16]);$u[v]=W|0,Mu[v]=N|0}let{Ah:r,Al:n,Bh:s,Bl:a,Ch:o,Cl:i,Dh:c,Dl:u,Eh:d,El:l,Fh:f,Fl:h,Gh:p,Gl:m,Hh:y,Hl:S}=this;for(let v=0;v<80;v++){let E=Rt.rotrSH(d,l,14)^Rt.rotrSH(d,l,18)^Rt.rotrBH(d,l,41),k=Rt.rotrSL(d,l,14)^Rt.rotrSL(d,l,18)^Rt.rotrBL(d,l,41),A=d&f^~d&p,D=l&h^~l&m,B=Rt.add5L(S,k,D,Wie[v],Mu[v]),j=Rt.add5H(B,y,E,A,Gie[v],$u[v]),F=B|0,q=Rt.rotrSH(r,n,28)^Rt.rotrBH(r,n,34)^Rt.rotrBH(r,n,39),N=Rt.rotrSL(r,n,28)^Rt.rotrBL(r,n,34)^Rt.rotrBL(r,n,39),W=r&s^r&o^s&o,ee=n&a^n&i^a&i;y=p|0,S=m|0,p=f|0,m=h|0,f=d|0,h=l|0,{h:d,l}=Rt.add(c|0,u|0,j|0,F|0),c=o|0,u=i|0,o=s|0,i=a|0,s=r|0,a=n|0;let R=Rt.add3L(F,N,ee);r=Rt.add3H(R,j,q,W),n=R|0}({h:r,l:n}=Rt.add(this.Ah|0,this.Al|0,r|0,n|0)),{h:s,l:a}=Rt.add(this.Bh|0,this.Bl|0,s|0,a|0),{h:o,l:i}=Rt.add(this.Ch|0,this.Cl|0,o|0,i|0),{h:c,l:u}=Rt.add(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=Rt.add(this.Eh|0,this.El|0,d|0,l|0),{h:f,l:h}=Rt.add(this.Fh|0,this.Fl|0,f|0,h|0),{h:p,l:m}=Rt.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:y,l:S}=Rt.add(this.Hh|0,this.Hl|0,y|0,S|0),this.set(r,n,s,a,o,i,c,u,d,l,f,h,p,m,y,S)}roundClean(){$u.fill(0),Mu.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)}},IL=lL(()=>new Vie),_a=BigInt(0),uo=BigInt(1),m1=BigInt(2),Hie=BigInt(8),Jie={zip215:!0};function Zie(t){let e=VI(t);return Df(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function ZI(t){let e=Zie(t),{Fp:r,n,prehash:s,hash:a,randomBytes:o,nByteLength:i,h:c}=e,u=m1<<BigInt(i*8)-uo,d=r.create,l=e.uvRatio||((x,P)=>{try{return{isValid:!0,value:r.sqrt(x*r.inv(P))}}catch{return{isValid:!1,value:_a}}}),f=e.adjustScalarBytes||(x=>x),h=e.domain||((x,P,_)=>{if(P.length||_)throw new Error("Contexts/pre-hash are not supported");return x}),p=x=>typeof x=="bigint"&&_a<x,m=(x,P)=>p(x)&&p(P)&&x<P,y=x=>x===_a||m(x,u);function S(x,P){if(m(x,P))return x;throw new Error(`Expected valid scalar < ${P}, got ${typeof x} ${x}`)}function v(x){return x===_a?x:S(x,n)}let E=new Map;function k(x){if(!(x instanceof A))throw new Error("ExtendedPoint expected")}class A{constructor(P,_,I,O){if(this.ex=P,this.ey=_,this.ez=I,this.et=O,!y(P))throw new Error("x required");if(!y(_))throw new Error("y required");if(!y(I))throw new Error("z required");if(!y(O))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(P){if(P instanceof A)throw new Error("extended point not allowed");let{x:_,y:I}=P||{};if(!y(_)||!y(I))throw new Error("invalid affine point");return new A(_,I,uo,d(_*I))}static normalizeZ(P){let _=r.invertBatch(P.map(I=>I.ez));return P.map((I,O)=>I.toAffine(_[O])).map(A.fromAffine)}_setWindowSize(P){this._WINDOW_SIZE=P,E.delete(this)}assertValidity(){let{a:P,d:_}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:I,ey:O,ez:z,et:G}=this,V=d(I*I),H=d(O*O),Y=d(z*z),K=d(Y*Y),Q=d(V*P),se=d(Y*d(Q+H)),re=d(K+d(_*d(V*H)));if(se!==re)throw new Error("bad point: equation left != right (1)");let Z=d(I*O),de=d(z*G);if(Z!==de)throw new Error("bad point: equation left != right (2)")}equals(P){k(P);let{ex:_,ey:I,ez:O}=this,{ex:z,ey:G,ez:V}=P,H=d(_*V),Y=d(z*O),K=d(I*V),Q=d(G*O);return H===Y&&K===Q}is0(){return this.equals(A.ZERO)}negate(){return new A(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:P}=e,{ex:_,ey:I,ez:O}=this,z=d(_*_),G=d(I*I),V=d(m1*d(O*O)),H=d(P*z),Y=_+I,K=d(d(Y*Y)-z-G),Q=H+G,se=Q-V,re=H-G,Z=d(K*se),de=d(Q*re),le=d(K*re),pe=d(se*Q);return new A(Z,de,pe,le)}add(P){k(P);let{a:_,d:I}=e,{ex:O,ey:z,ez:G,et:V}=this,{ex:H,ey:Y,ez:K,et:Q}=P;if(_===BigInt(-1)){let Et=d((z-O)*(Y+H)),Se=d((z+O)*(Y-H)),et=d(Se-Et);if(et===_a)return this.double();let wt=d(G*m1*Q),xt=d(V*m1*K),$t=xt+wt,T=Se+Et,M=xt-wt,L=d($t*et),te=d(T*M),ae=d($t*M),he=d(et*T);return new A(L,te,he,ae)}let se=d(O*H),re=d(z*Y),Z=d(V*I*Q),de=d(G*K),le=d((O+z)*(H+Y)-se-re),pe=de-Z,ve=de+Z,ce=d(re-_*se),ge=d(le*pe),Me=d(ve*ce),Le=d(le*ce),qe=d(pe*ve);return new A(ge,Me,qe,Le)}subtract(P){return this.add(P.negate())}wNAF(P){return j.wNAFCached(this,E,P,A.normalizeZ)}multiply(P){let{p:_,f:I}=this.wNAF(S(P,n));return A.normalizeZ([_,I])[0]}multiplyUnsafe(P){let _=v(P);return _===_a?B:this.equals(B)||_===uo?this:this.equals(D)?this.wNAF(_).p:j.unsafeLadder(this,_)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return j.unsafeLadder(this,n).is0()}toAffine(P){let{ex:_,ey:I,ez:O}=this,z=this.is0();P==null&&(P=z?Hie:r.inv(O));let G=d(_*P),V=d(I*P),H=d(O*P);if(z)return{x:_a,y:uo};if(H!==uo)throw new Error("invZ was invalid");return{x:G,y:V}}clearCofactor(){let{h:P}=e;return P===uo?this:this.multiplyUnsafe(P)}static fromHex(P,_=!1){let{d:I,a:O}=e,z=r.BYTES;P=Rn("pointHex",P,z);let G=P.slice(),V=P[z-1];G[z-1]=V&-129;let H=Fu(G);H===_a||(_?S(H,u):S(H,r.ORDER));let Y=d(H*H),K=d(Y-uo),Q=d(I*Y-O),{isValid:se,value:re}=l(K,Q);if(!se)throw new Error("Point.fromHex: invalid y coordinate");let Z=(re&uo)===uo,de=(V&128)!==0;if(!_&&re===_a&&de)throw new Error("Point.fromHex: x=0 and x_0=1");return de!==Z&&(re=d(-re)),A.fromAffine({x:re,y:H})}static fromPrivateKey(P){return N(P).point}toRawBytes(){let{x:P,y:_}=this.toAffine(),I=Fh(_,r.BYTES);return I[I.length-1]|=P&uo?128:0,I}toHex(){return Tf(this.toRawBytes())}}A.BASE=new A(e.Gx,e.Gy,uo,d(e.Gx*e.Gy)),A.ZERO=new A(_a,uo,uo,_a);let{BASE:D,ZERO:B}=A,j=wL(A,i*8);function F(x){return Ur(x,n)}function q(x){return F(Fu(x))}function N(x){let P=i;x=Rn("private key",x,P);let _=Rn("hashed private key",a(x),2*P),I=f(_.slice(0,P)),O=_.slice(P,2*P),z=q(I),G=D.multiply(z),V=G.toRawBytes();return{head:I,prefix:O,scalar:z,point:G,pointBytes:V}}function W(x){return N(x).pointBytes}function ee(x=new Uint8Array,...P){let _=If(...P);return q(a(h(_,Rn("context",x),!!s)))}function R(x,P,_={}){x=Rn("message",x),s&&(x=s(x));let{prefix:I,scalar:O,pointBytes:z}=N(P),G=ee(_.context,I,x),V=D.multiply(G).toRawBytes(),H=ee(_.context,V,z,x),Y=F(G+H*O);v(Y);let K=If(V,Fh(Y,r.BYTES));return Rn("result",K,i*2)}let $=Jie;function b(x,P,_,I=$){let{context:O,zip215:z}=I,G=r.BYTES;x=Rn("signature",x,2*G),P=Rn("message",P),s&&(P=s(P));let V=Fu(x.slice(G,2*G)),H,Y,K;try{H=A.fromHex(_,z),Y=A.fromHex(x.slice(0,G),z),K=D.multiplyUnsafe(V)}catch{return!1}if(!z&&H.isSmallOrder())return!1;let Q=ee(O,Y.toRawBytes(),H.toRawBytes(),P);return Y.add(H.multiplyUnsafe(Q)).subtract(K).clearCofactor().equals(A.ZERO)}return D._setWindowSize(8),{CURVE:e,getPublicKey:W,sign:R,verify:b,ExtendedPoint:A,utils:{getExtendedPublicKey:N,randomPrivateKey:()=>o(r.BYTES),precompute(x=8,P=A.BASE){return P._setWindowSize(x),P.multiply(BigInt(3)),P}}}}var Jg=BigInt(0),uI=BigInt(1);function Yie(t){return Df(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function Qie(t){let e=Yie(t),{P:r}=e,n=E=>Ur(E,r),s=e.montgomeryBits,a=Math.ceil(s/8),o=e.nByteLength,i=e.adjustScalarBytes||(E=>E),c=e.powPminus2||(E=>hL(E,r-BigInt(2),r));function u(E,k,A){let D=n(E*(k-A));return k=n(k-D),A=n(A+D),[k,A]}function d(E){if(typeof E=="bigint"&&Jg<=E&&E<r)return E;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let l=(e.a-BigInt(2))/BigInt(4);function f(E,k){let A=d(E),D=d(k),B=A,j=uI,F=Jg,q=A,N=uI,W=Jg,ee;for(let $=BigInt(s-1);$>=Jg;$--){let b=D>>$&uI;W^=b,ee=u(W,j,q),j=ee[0],q=ee[1],ee=u(W,F,N),F=ee[0],N=ee[1],W=b;let x=j+F,P=n(x*x),_=j-F,I=n(_*_),O=P-I,z=q+N,G=q-N,V=n(G*x),H=n(z*_),Y=V+H,K=V-H;q=n(Y*Y),N=n(B*n(K*K)),j=n(P*I),F=n(O*(P+n(l*O)))}ee=u(W,j,q),j=ee[0],q=ee[1],ee=u(W,F,N),F=ee[0],N=ee[1];let R=c(F);return n(j*R)}function h(E){return Fh(n(E),a)}function p(E){let k=Rn("u coordinate",E,a);return o===32&&(k[31]&=127),Fu(k)}function m(E){let k=Rn("scalar",E),A=k.length;if(A!==a&&A!==o)throw new Error(`Expected ${a} or ${o} bytes, got ${A}`);return Fu(i(k))}function y(E,k){let A=p(k),D=m(E),B=f(A,D);if(B===Jg)throw new Error("Invalid private or public key received");return h(B)}let S=h(e.Gu);function v(E){return y(E,S)}return{scalarMult:y,scalarMultBase:v,getSharedSecret:(E,k)=>y(E,k),getPublicKey:E=>v(E),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var bw=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),LN=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),i$e=BigInt(0),Xie=BigInt(1),SI=BigInt(2),eoe=BigInt(5),KN=BigInt(10),toe=BigInt(20),roe=BigInt(40),zN=BigInt(80);function AL(t){let e=bw,r=t*t%e*t%e,n=an(r,SI,e)*r%e,s=an(n,Xie,e)*t%e,a=an(s,eoe,e)*s%e,o=an(a,KN,e)*a%e,i=an(o,toe,e)*o%e,c=an(i,roe,e)*i%e,u=an(c,zN,e)*c%e,d=an(u,zN,e)*c%e,l=an(d,KN,e)*a%e;return{pow_p_5_8:an(l,SI,e)*t%e,b2:r}}function RL(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function noe(t,e){let r=bw,n=Ur(e*e*e,r),s=Ur(n*n*e,r),a=AL(t*s).pow_p_5_8,o=Ur(t*n*a,r),i=Ur(e*o*o,r),c=o,u=Ur(o*LN,r),d=i===t,l=i===Ur(-t,r),f=i===Ur(-t*LN,r);return d&&(o=c),(l||f)&&(o=u),Use(o,r)&&(o=Ur(-o,r)),{isValid:d||l,value:o}}var Wo=WI(bw,void 0,!0),Pw={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Wo,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:IL,randomBytes:GI,adjustScalarBytes:RL,uvRatio:noe},gf=ZI(Pw);function DL(t,e,r){if(e.length>255)throw new Error("Context is too big");return dL(cL("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var o$e=ZI({...Pw,domain:DL}),a$e=ZI({...Pw,domain:DL,prehash:IL}),tw=Qie({P:bw,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=bw,{pow_p_5_8:r,b2:n}=AL(t);return Ur(an(r,BigInt(3),e)*n,e)},adjustScalarBytes:RL,randomBytes:GI});function soe(t){let{y:e}=gf.ExtendedPoint.fromHex(t),r=BigInt(1);return Wo.toBytes(Wo.create((r+e)*Wo.inv(r-e)))}function ioe(t){let e=Pw.hash(t.subarray(0,32));return Pw.adjustScalarBytes(e).subarray(0,32)}var ooe=(Wo.ORDER+BigInt(3))/BigInt(8),c$e=Wo.pow(SI,ooe),d$e=Wo.sqrt(Wo.neg(Wo.ONE)),u$e=(Wo.ORDER-BigInt(5))/BigInt(8),l$e=BigInt(486662),f$e=Fse(Wo,Wo.neg(BigInt(486664))),p$e=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),h$e=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),m$e=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),y$e=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),g$e=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),No=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},aoe=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 s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},$s=class Lu{static bytesToPrivateKey(e){return No(this,arguments,void 0,function*({privateKeyBytes:r}){let n=gf.getPublicKey(r),s={crv:"Ed25519",d:Qe.uint8Array(r).toBase64Url(),kty:"OKP",x:Qe.uint8Array(n).toBase64Url()};return s.kid=yield fr({jwk:s}),s})}static bytesToPublicKey(e){return No(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:Qe.uint8Array(r).toBase64Url()};return n.kid=yield fr({jwk:n}),n})}static computePublicKey(e){return No(this,arguments,void 0,function*({key:r}){let n=yield Lu.privateKeyToBytes({privateKey:r}),s=gf.getPublicKey(n),a={kty:"OKP",crv:"Ed25519",x:Qe.uint8Array(s).toBase64Url()};return a.kid=yield fr({jwk:a}),a})}static convertPrivateKeyToX25519(e){return No(this,arguments,void 0,function*({privateKey:r}){let n=yield Lu.privateKeyToBytes({privateKey:r}),s=ioe(n),a=tw.getPublicKey(s),o={kty:"OKP",crv:"X25519",d:Qe.uint8Array(s).toBase64Url(),x:Qe.uint8Array(a).toBase64Url()};return o.kid=yield fr({jwk:o}),o})}static convertPublicKeyToX25519(e){return No(this,arguments,void 0,function*({publicKey:r}){let n=yield Lu.publicKeyToBytes({publicKey:r});if(!(yield Lu.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let s=soe(n),a={kty:"OKP",crv:"X25519",x:Qe.uint8Array(s).toBase64Url()};return a.kid=yield fr({jwk:a}),a})}static generateKey(){return No(this,void 0,void 0,function*(){let e=gf.utils.randomPrivateKey(),r=yield Lu.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield fr({jwk:r}),r})}static getPublicKey(e){return No(this,arguments,void 0,function*({key:r}){var n;if(!(Ed(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:s}=r,a=aoe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield fr({jwk:a})),a})}static privateKeyToBytes(e){return No(this,arguments,void 0,function*({privateKey:r}){if(!Ed(r))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return No(this,arguments,void 0,function*({publicKey:r}){if(!JI(r))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return Qe.base64Url(r.x).toUint8Array()})}static sign(e){return No(this,arguments,void 0,function*({key:r,data:n}){let s=yield Lu.privateKeyToBytes({privateKey:r});return gf.sign(n,s)})}static validatePublicKey(e){return No(this,arguments,void 0,function*({publicKeyBytes:r}){try{gf.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return No(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield Lu.publicKeyToBytes({publicKey:r});return gf.verify(n,s,a)})}},gd=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},coe=class extends tP{bytesToPrivateKey(t){return gd(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"Ed25519":{let n=yield $s.bytesToPrivateKey({privateKeyBytes:r});return n.alg="EdDSA",n}default:throw new Go(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return gd(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"Ed25519":{let n=yield $s.bytesToPublicKey({publicKeyBytes:r});return n.alg="EdDSA",n}default:throw new Go(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return gd(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield $s.computePublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return gd(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let r=yield $s.generateKey();return r.alg="EdDSA",r}}})}getPublicKey(t){return gd(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield $s.getPublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return gd(this,arguments,void 0,function*({key:e,data:r}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield $s.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return gd(this,arguments,void 0,function*({key:e,signature:r,data:n}){if(!JI(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield $s.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return gd(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"Ed25519":return yield $s.privateKeyToBytes({privateKey:e});default:throw new Go(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return gd(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield $s.publicKeyToBytes({publicKey:e});default:throw new Go(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},doe=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},uoe=class extends tP{digest(t){return doe(this,arguments,void 0,function*({algorithm:e,data:r}){switch(e){case"SHA-256":return yield _L.digest({data:r})}})}},Ou=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},loe=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 s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},Ch=class rw{static bytesToPrivateKey(e){return Ou(this,arguments,void 0,function*({privateKeyBytes:r}){let n=tw.getPublicKey(r),s={kty:"OKP",crv:"X25519",d:Qe.uint8Array(r).toBase64Url(),x:Qe.uint8Array(n).toBase64Url()};return s.kid=yield fr({jwk:s}),s})}static bytesToPublicKey(e){return Ou(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:Qe.uint8Array(r).toBase64Url()};return n.kid=yield fr({jwk:n}),n})}static computePublicKey(e){return Ou(this,arguments,void 0,function*({key:r}){let n=yield rw.privateKeyToBytes({privateKey:r}),s=tw.getPublicKey(n),a={kty:"OKP",crv:"X25519",x:Qe.uint8Array(s).toBase64Url()};return a.kid=yield fr({jwk:a}),a})}static generateKey(){return Ou(this,void 0,void 0,function*(){let e=tw.utils.randomPrivateKey(),r=yield rw.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield fr({jwk:r}),r})}static getPublicKey(e){return Ou(this,arguments,void 0,function*({key:r}){var n;if(!(Ed(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:s}=r,a=loe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield fr({jwk:a})),a})}static privateKeyToBytes(e){return Ou(this,arguments,void 0,function*({privateKey:r}){if(!Ed(r))throw new Error("X25519: The provided key is not a valid OKP private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Ou(this,arguments,void 0,function*({publicKey:r}){if(!JI(r))throw new Error("X25519: The provided key is not a valid OKP public key.");return Qe.base64Url(r.x).toUint8Array()})}static sharedSecret(e){return Ou(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 s=yield rw.privateKeyToBytes({privateKey:r}),a=yield rw.publicKeyToBytes({publicKey:n});return tw.getSharedSecret(s,a)})}},Zg=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},foe=class extends tP{bytesToPrivateKey(t){return Zg(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"X25519":return Ch.bytesToPrivateKey({privateKeyBytes:r});default:throw new Go(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return Zg(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Ch.computePublicKey({key:e});default:throw new Go(Li.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(t){return Zg(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return Ch.generateKey();default:throw new Go(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(t){return Zg(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Ch.getPublicKey({key:e});default:throw new Go(Li.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return Zg(this,arguments,void 0,function*({privateKey:e}){return Ch.privateKeyToBytes({privateKey:e})})}},wd=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},lI={Ed25519:{implementation:coe,names:["Ed25519"]},secp256k1:{implementation:UN,names:["ES256K","secp256k1"]},secp256r1:{implementation:UN,names:["ES256","secp256r1"]},"SHA-256":{implementation:uoe,names:["SHA-256"]},X25519:{implementation:foe,names:["X25519"]}},Ia=class{constructor(t){var e;this._algorithmInstances=new Map,this._keyStore=(e=t?.keyStore)!==null&&e!==void 0?e:new yse}digest(t){return wd(this,arguments,void 0,function*({algorithm:e,data:r}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:r})})}exportKey(t){return wd(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(t){return wd(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=`${NN}${r.kid}`;return yield this._keyStore.set(n,r),n})}getKeyUri(t){return wd(this,arguments,void 0,function*({key:e}){let r=yield fr({jwk:e});return`${NN}${r}`})}getPublicKey(t){return wd(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 wd(this,arguments,void 0,function*({key:e}){var r;if(!gie(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 fr({jwk:n}));let s=yield this.getKeyUri({key:n});return yield this._keyStore.set(s,n),s})}sign(t){return wd(this,arguments,void 0,function*({keyUri:e,data:r}){let n=yield this.getPrivateKey({keyUri:e}),s=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:s}).sign({data:r,key:n})})}verify(t){return wd(this,arguments,void 0,function*({key:e,signature:r,data:n}){let s=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:s}).verify({key:e,signature:r,data:n})})}getAlgorithm({algorithm:t}){var e;let r=(e=lI[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 lI){let s=lI[n];if(e&&s.names.includes(e)||r&&s.names.includes(r))return n}throw new Error(`Unable to determine algorithm based on provided input: alg=${e}, crv=${r}`)}getPrivateKey(t){return wd(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})}},poe=class EI{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 aie(e)}static randomUuid(){return x1.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 s=Math.pow(10,e);do{let a=EI.randomBytes(Math.ceil(e/2));n=new DataView(a.buffer).getUint16(0,!1)%s}while(n>r)}else{let s=Math.pow(10,10);do{let a=EI.randomBytes(4);n=new DataView(a.buffer).getUint32(0,!1)%s}while(n>r)}return n.toString().padStart(e,"0")}},hoe=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function moe(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":yoe(t)||"Object"}function yoe(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(hoe.includes(e))return e}var Pe=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}};Pe.uint=new Pe(0,"uint",!0);Pe.negint=new Pe(1,"negint",!0);Pe.bytes=new Pe(2,"bytes",!0);Pe.string=new Pe(3,"string",!0);Pe.array=new Pe(4,"array",!1);Pe.map=new Pe(5,"map",!1);Pe.tag=new Pe(6,"tag",!1);Pe.float=new Pe(7,"float",!0);Pe.false=new Pe(7,"false",!0);Pe.true=new Pe(7,"true",!0);Pe.null=new Pe(7,"null",!0);Pe.undefined=new Pe(7,"undefined",!0);Pe.break=new Pe(7,"break",!0);var Je=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}`}},Tw=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",goe=new TextEncoder;function F1(t){return Tw&&globalThis.Buffer.isBuffer(t)}function CL(t){return t instanceof Uint8Array?F1(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var woe=24,voe=200,boe=Tw?t=>t.length>=woe?globalThis.Buffer.from(t):qN(t):t=>t.length>=voe?goe.encode(t):qN(t),vd=t=>Uint8Array.from(t),Poe=Tw?(t,e,r)=>F1(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),xoe=Tw?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),CL(globalThis.Buffer.concat(t,e))):(t,e)=>{let r=new Uint8Array(e),n=0;for(let s of t)n+s.length>r.length&&(s=s.subarray(0,r.length-n)),r.set(s,n),n+=s.length;return r},Soe=Tw?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function jL(t,e){if(F1(t)&&F1(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 qN(t){let e=[],r=0;for(let n=0;n<t.length;n++){let s=t.charCodeAt(n);s<128?e[r++]=s:s<2048?(e[r++]=s>>6|192,e[r++]=s&63|128):(s&64512)===55296&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(s=65536+((s&1023)<<10)+(t.charCodeAt(++n)&1023),e[r++]=s>>18|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128,e[r++]=s&63|128):(s>=55296&&s<=57343&&(s=65533),e[r++]=s>>12|224,e[r++]=s>>6&63|128,e[r++]=s&63|128)}return e}var Eoe=256,$L=class{constructor(t=Eoe){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=Soe(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=Poe(r,0,this.cursor)}else e=xoe(this.chunks,this.cursor);return t&&this.reset(),e}},_oe=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}},cn="CBOR decode error:",ML="CBOR encode error:",Iw=[];Iw[23]=1;Iw[24]=2;Iw[25]=3;Iw[26]=5;Iw[27]=9;function Jh(t,e,r){if(t.length-e<r)throw new Error(`${cn} not enough data for type`)}var Ms=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Cf(t,e,r){Jh(t,e,1);let n=t[e];if(r.strict===!0&&n<Ms[0])throw new Error(`${cn} integer encoded in more bytes than necessary (strict decode)`);return n}function jf(t,e,r){Jh(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<Ms[1])throw new Error(`${cn} integer encoded in more bytes than necessary (strict decode)`);return n}function $f(t,e,r){Jh(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<Ms[2])throw new Error(`${cn} integer encoded in more bytes than necessary (strict decode)`);return n}function Mf(t,e,r){Jh(t,e,8);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],s=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],a=(BigInt(n)<<BigInt(32))+BigInt(s);if(r.strict===!0&&a<Ms[3])throw new Error(`${cn} 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(`${cn} integers outside of the safe integer range are not supported`)}function koe(t,e,r,n){return new Je(Pe.uint,Cf(t,e+1,n),2)}function Toe(t,e,r,n){return new Je(Pe.uint,jf(t,e+1,n),3)}function Ioe(t,e,r,n){return new Je(Pe.uint,$f(t,e+1,n),5)}function Aoe(t,e,r,n){return new Je(Pe.uint,Mf(t,e+1,n),9)}function Of(t,e){return Ho(t,0,e.value)}function Ho(t,e,r){if(r<Ms[0]){let n=Number(r);t.push([e|n])}else if(r<Ms[1]){let n=Number(r);t.push([e|24,n])}else if(r<Ms[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<Ms[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<Ms[4]){let s=[e|27,0,0,0,0,0,0,0],a=Number(n&BigInt(4294967295)),o=Number(n>>BigInt(32)&BigInt(4294967295));s[8]=a&255,a=a>>8,s[7]=a&255,a=a>>8,s[6]=a&255,a=a>>8,s[5]=a&255,s[4]=o&255,o=o>>8,s[3]=o&255,o=o>>8,s[2]=o&255,o=o>>8,s[1]=o&255,t.push(s)}else throw new Error(`${cn} encountered BigInt larger than allowable range`)}}Of.encodedSize=function(t){return Ho.encodedSize(t.value)};Ho.encodedSize=function(t){return t<Ms[0]?1:t<Ms[1]?2:t<Ms[2]?3:t<Ms[3]?5:9};Of.compareTokens=function(t,e){return t.value<e.value?-1:t.value>e.value?1:0};function Roe(t,e,r,n){return new Je(Pe.negint,-1-Cf(t,e+1,n),2)}function Doe(t,e,r,n){return new Je(Pe.negint,-1-jf(t,e+1,n),3)}function Coe(t,e,r,n){return new Je(Pe.negint,-1-$f(t,e+1,n),5)}var YI=BigInt(-1),OL=BigInt(1);function joe(t,e,r,n){let s=Mf(t,e+1,n);if(typeof s!="bigint"){let a=-1-s;if(a>=Number.MIN_SAFE_INTEGER)return new Je(Pe.negint,a,9)}if(n.allowBigInt!==!0)throw new Error(`${cn} integers outside of the safe integer range are not supported`);return new Je(Pe.negint,YI-BigInt(s),9)}function QI(t,e){let r=e.value,n=typeof r=="bigint"?r*YI-OL:r*-1-1;Ho(t,e.type.majorEncoded,n)}QI.encodedSize=function(t){let e=t.value,r=typeof e=="bigint"?e*YI-OL:e*-1-1;return r<Ms[0]?1:r<Ms[1]?2:r<Ms[2]?3:r<Ms[3]?5:9};QI.compareTokens=function(t,e){return t.value<e.value?1:t.value>e.value?-1:0};function Aw(t,e,r,n){Jh(t,e,r+n);let s=t.slice(e+r,e+r+n);return new Je(Pe.bytes,s,r+n)}function $oe(t,e,r,n){return Aw(t,e,1,r)}function Moe(t,e,r,n){return Aw(t,e,2,Cf(t,e+1,n))}function Ooe(t,e,r,n){return Aw(t,e,3,jf(t,e+1,n))}function Boe(t,e,r,n){return Aw(t,e,5,$f(t,e+1,n))}function Noe(t,e,r,n){let s=Mf(t,e+1,n);if(typeof s=="bigint")throw new Error(`${cn} 64-bit integer bytes lengths not supported`);return Aw(t,e,9,s)}function G1(t){return t.encodedBytes===void 0&&(t.encodedBytes=Pe.equals(t.type,Pe.string)?boe(t.value):t.value),t.encodedBytes}function nP(t,e){let r=G1(e);Ho(t,e.type.majorEncoded,r.length),t.push(r)}nP.encodedSize=function(t){let e=G1(t);return Ho.encodedSize(e.length)+e.length};nP.compareTokens=function(t,e){return Uoe(G1(t),G1(e))};function Uoe(t,e){return t.length<e.length?-1:t.length>e.length?1:jL(t,e)}var FN=new TextDecoder,Loe=32;function Koe(t,e,r){if(r-e<Loe){let n="";for(let s=e;s<r;s++){let a=t[s];if(a&128)return FN.decode(t.subarray(e,r));n+=String.fromCharCode(a)}return n}return FN.decode(t.subarray(e,r))}function Rw(t,e,r,n,s){let a=r+n;Jh(t,e,a);let o=new Je(Pe.string,Koe(t,e+r,e+a),a);return s.retainStringBytes===!0&&(o.byteValue=t.slice(e+r,e+a)),o}function zoe(t,e,r,n){return Rw(t,e,1,r,n)}function qoe(t,e,r,n){return Rw(t,e,2,Cf(t,e+1,n),n)}function Foe(t,e,r,n){return Rw(t,e,3,jf(t,e+1,n),n)}function Goe(t,e,r,n){return Rw(t,e,5,$f(t,e+1,n),n)}function Woe(t,e,r,n){let s=Mf(t,e+1,n);if(typeof s=="bigint")throw new Error(`${cn} 64-bit integer string lengths not supported`);return Rw(t,e,9,s,n)}var Voe=nP;function Zh(t,e,r,n){return new Je(Pe.array,n,r)}function Hoe(t,e,r,n){return Zh(t,e,1,r)}function Joe(t,e,r,n){return Zh(t,e,2,Cf(t,e+1,n))}function Zoe(t,e,r,n){return Zh(t,e,3,jf(t,e+1,n))}function Yoe(t,e,r,n){return Zh(t,e,5,$f(t,e+1,n))}function Qoe(t,e,r,n){let s=Mf(t,e+1,n);if(typeof s=="bigint")throw new Error(`${cn} 64-bit integer array lengths not supported`);return Zh(t,e,9,s)}function Xoe(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${cn} indefinite length items not allowed`);return Zh(t,e,1,1/0)}function XI(t,e){Ho(t,Pe.array.majorEncoded,e.value)}XI.compareTokens=Of.compareTokens;XI.encodedSize=function(t){return Ho.encodedSize(t.value)};function Yh(t,e,r,n){return new Je(Pe.map,n,r)}function eae(t,e,r,n){return Yh(t,e,1,r)}function tae(t,e,r,n){return Yh(t,e,2,Cf(t,e+1,n))}function rae(t,e,r,n){return Yh(t,e,3,jf(t,e+1,n))}function nae(t,e,r,n){return Yh(t,e,5,$f(t,e+1,n))}function sae(t,e,r,n){let s=Mf(t,e+1,n);if(typeof s=="bigint")throw new Error(`${cn} 64-bit integer map lengths not supported`);return Yh(t,e,9,s)}function iae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${cn} indefinite length items not allowed`);return Yh(t,e,1,1/0)}function eA(t,e){Ho(t,Pe.map.majorEncoded,e.value)}eA.compareTokens=Of.compareTokens;eA.encodedSize=function(t){return Ho.encodedSize(t.value)};function oae(t,e,r,n){return new Je(Pe.tag,r,1)}function aae(t,e,r,n){return new Je(Pe.tag,Cf(t,e+1,n),2)}function cae(t,e,r,n){return new Je(Pe.tag,jf(t,e+1,n),3)}function dae(t,e,r,n){return new Je(Pe.tag,$f(t,e+1,n),5)}function uae(t,e,r,n){return new Je(Pe.tag,Mf(t,e+1,n),9)}function tA(t,e){Ho(t,Pe.tag.majorEncoded,e.value)}tA.compareTokens=Of.compareTokens;tA.encodedSize=function(t){return Ho.encodedSize(t.value)};var BL=20,NL=21,UL=22,LL=23;function lae(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${cn} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Je(Pe.null,null,1):new Je(Pe.undefined,void 0,1)}function fae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${cn} indefinite length items not allowed`);return new Je(Pe.break,void 0,1)}function rA(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${cn} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${cn} Infinity values are not supported`)}return new Je(Pe.float,t,e)}function pae(t,e,r,n){return rA(sA(t,e+1),3,n)}function hae(t,e,r,n){return rA(iA(t,e+1),5,n)}function mae(t,e,r,n){return rA(FL(t,e+1),9,n)}function nA(t,e,r){let n=e.value;if(n===!1)t.push([Pe.float.majorEncoded|BL]);else if(n===!0)t.push([Pe.float.majorEncoded|NL]);else if(n===null)t.push([Pe.float.majorEncoded|UL]);else if(n===void 0)t.push([Pe.float.majorEncoded|LL]);else{let s,a=!1;(!r||r.float64!==!0)&&(zL(n),s=sA(ka,1),n===s||Number.isNaN(n)?(ka[0]=249,t.push(ka.slice(0,3)),a=!0):(qL(n),s=iA(ka,1),n===s&&(ka[0]=250,t.push(ka.slice(0,5)),a=!0))),a||(yae(n),s=FL(ka,1),ka[0]=251,t.push(ka.slice(0,9)))}}nA.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){zL(r);let n=sA(ka,1);if(r===n||Number.isNaN(r))return 3;if(qL(r),n=iA(ka,1),r===n)return 5}return 9};var KL=new ArrayBuffer(9),Lo=new DataView(KL,1),ka=new Uint8Array(KL,0);function zL(t){if(t===1/0)Lo.setUint16(0,31744,!1);else if(t===-1/0)Lo.setUint16(0,64512,!1);else if(Number.isNaN(t))Lo.setUint16(0,32256,!1);else{Lo.setFloat32(0,t);let e=Lo.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)Lo.setUint16(0,31744,!1);else if(r===0)Lo.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let s=r-127;s<-24?Lo.setUint16(0,0):s<-14?Lo.setUint16(0,(e&2147483648)>>16|1<<24+s,!1):Lo.setUint16(0,(e&2147483648)>>16|s+15<<10|n>>13,!1)}}}function sA(t,e){if(t.length-e<2)throw new Error(`${cn} 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,s=r&1023,a;return n===0?a=s*2**-24:n!==31?a=(s+1024)*2**(n-25):a=s===0?1/0:NaN,r&32768?-a:a}function qL(t){Lo.setFloat32(0,t,!1)}function iA(t,e){if(t.length-e<4)throw new Error(`${cn} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function yae(t){Lo.setFloat64(0,t,!1)}function FL(t,e){if(t.length-e<8)throw new Error(`${cn} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}nA.compareTokens=Of.compareTokens;function nr(t,e,r){throw new Error(`${cn} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function sP(t){return()=>{throw new Error(`${cn} ${t}`)}}var Ce=[];for(let t=0;t<=23;t++)Ce[t]=nr;Ce[24]=koe;Ce[25]=Toe;Ce[26]=Ioe;Ce[27]=Aoe;Ce[28]=nr;Ce[29]=nr;Ce[30]=nr;Ce[31]=nr;for(let t=32;t<=55;t++)Ce[t]=nr;Ce[56]=Roe;Ce[57]=Doe;Ce[58]=Coe;Ce[59]=joe;Ce[60]=nr;Ce[61]=nr;Ce[62]=nr;Ce[63]=nr;for(let t=64;t<=87;t++)Ce[t]=$oe;Ce[88]=Moe;Ce[89]=Ooe;Ce[90]=Boe;Ce[91]=Noe;Ce[92]=nr;Ce[93]=nr;Ce[94]=nr;Ce[95]=sP("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)Ce[t]=zoe;Ce[120]=qoe;Ce[121]=Foe;Ce[122]=Goe;Ce[123]=Woe;Ce[124]=nr;Ce[125]=nr;Ce[126]=nr;Ce[127]=sP("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)Ce[t]=Hoe;Ce[152]=Joe;Ce[153]=Zoe;Ce[154]=Yoe;Ce[155]=Qoe;Ce[156]=nr;Ce[157]=nr;Ce[158]=nr;Ce[159]=Xoe;for(let t=160;t<=183;t++)Ce[t]=eae;Ce[184]=tae;Ce[185]=rae;Ce[186]=nae;Ce[187]=sae;Ce[188]=nr;Ce[189]=nr;Ce[190]=nr;Ce[191]=iae;for(let t=192;t<=215;t++)Ce[t]=oae;Ce[216]=aae;Ce[217]=cae;Ce[218]=dae;Ce[219]=uae;Ce[220]=nr;Ce[221]=nr;Ce[222]=nr;Ce[223]=nr;for(let t=224;t<=243;t++)Ce[t]=sP("simple values are not supported");Ce[244]=nr;Ce[245]=nr;Ce[246]=nr;Ce[247]=lae;Ce[248]=sP("simple values are not supported");Ce[249]=pae;Ce[250]=hae;Ce[251]=mae;Ce[252]=nr;Ce[253]=nr;Ce[254]=nr;Ce[255]=fae;var kd=[];for(let t=0;t<24;t++)kd[t]=new Je(Pe.uint,t,1);for(let t=-1;t>=-24;t--)kd[31-t]=new Je(Pe.negint,t,1);kd[64]=new Je(Pe.bytes,new Uint8Array(0),1);kd[96]=new Je(Pe.string,"",1);kd[128]=new Je(Pe.array,0,1);kd[160]=new Je(Pe.map,0,1);kd[244]=new Je(Pe.false,!1,1);kd[245]=new Je(Pe.true,!0,1);kd[246]=new Je(Pe.null,null,1);function gae(t){switch(t.type){case Pe.false:return vd([244]);case Pe.true:return vd([245]);case Pe.null:return vd([246]);case Pe.bytes:return t.value.length?void 0:vd([64]);case Pe.string:return t.value===""?vd([96]):void 0;case Pe.array:return t.value===0?vd([128]):void 0;case Pe.map:return t.value===0?vd([160]):void 0;case Pe.uint:return t.value<24?vd([Number(t.value)]):void 0;case Pe.negint:if(t.value>=-24)return vd([31-Number(t.value)])}}var wae=Object.freeze({float64:!0,mapSorter:Sae,quickEncodeToken:gae});function vae(){let t=[];return t[Pe.uint.major]=Of,t[Pe.negint.major]=QI,t[Pe.bytes.major]=nP,t[Pe.string.major]=Voe,t[Pe.array.major]=XI,t[Pe.map.major]=eA,t[Pe.tag.major]=tA,t[Pe.float.major]=nA,t}var bae=vae(),Pae=new $L,GN=class GL{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(`${ML} object contains circular references`);return new GL(r,e)}},Bu={null:new Je(Pe.null,null),undefined:new Je(Pe.undefined,void 0),true:new Je(Pe.true,!0),false:new Je(Pe.false,!1),emptyArray:new Je(Pe.array,0),emptyMap:new Je(Pe.map,0)},Wu={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new Je(Pe.float,t):t>=0?new Je(Pe.uint,t):new Je(Pe.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new Je(Pe.uint,t):new Je(Pe.negint,t)},Uint8Array(t,e,r,n){return new Je(Pe.bytes,t)},string(t,e,r,n){return new Je(Pe.string,t)},boolean(t,e,r,n){return t?Bu.true:Bu.false},null(t,e,r,n){return Bu.null},undefined(t,e,r,n){return Bu.undefined},ArrayBuffer(t,e,r,n){return new Je(Pe.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new Je(Pe.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[Bu.emptyArray,new Je(Pe.break)]:Bu.emptyArray;n=GN.createCheck(n,t);let s=[],a=0;for(let o of t)s[a++]=S1(o,r,n);return r.addBreakTokens?[new Je(Pe.array,t.length),s,new Je(Pe.break)]:[new Je(Pe.array,t.length),s]},Object(t,e,r,n){let s=e!=="Object",a=s?t.keys():Object.keys(t),o=s?t.size:a.length,i;if(o){i=new Array(o),n=GN.createCheck(n,t);let c=!s&&r.ignoreUndefinedProperties,u=0;for(let d of a){let l=s?t.get(d):t[d];c&&l===void 0||(i[u++]=[S1(d,r,n),S1(l,r,n)])}u<o&&(i.length=u)}return i?.length?(xae(i,r),r.addBreakTokens?[new Je(Pe.map,i.length),i,new Je(Pe.break)]:[new Je(Pe.map,i.length),i]):r.addBreakTokens===!0?[Bu.emptyMap,new Je(Pe.break)]:Bu.emptyMap}};Wu.Map=Wu.Object;Wu.Buffer=Wu.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Wu[`${t}Array`]=Wu.DataView;function S1(t,e={},r){let n=moe(t),s=e&&e.typeEncoders&&e.typeEncoders[n]||Wu[n];if(typeof s=="function"){let o=s(t,n,e,r);if(o!=null)return o}let a=Wu[n];if(!a)throw new Error(`${ML} unsupported type: ${n}`);return a(t,n,e,r)}function xae(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Sae(t,e){if(t[0]instanceof Je&&e[0]instanceof Je){let r=t[0],n=e[0];return r._keyBytes||(r._keyBytes=WN(r.value)),n._keyBytes||(n._keyBytes=WN(n.value)),jL(r._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function WN(t){return Eae(t,bae,wae)}function WL(t,e,r,n){if(Array.isArray(e))for(let s of e)WL(t,s,r,n);else r[e.type.major](t,e,n)}var w$e=Pe.uint.majorEncoded,v$e=Pe.negint.majorEncoded,b$e=Pe.bytes.majorEncoded,P$e=Pe.string.majorEncoded,x$e=Pe.array.majorEncoded,S$e=Pe.float.majorEncoded|BL,E$e=Pe.float.majorEncoded|NL,_$e=Pe.float.majorEncoded|UL,k$e=Pe.float.majorEncoded|LL,T$e=BigInt(-1),I$e=BigInt(1);function Eae(t,e,r,n){let s=n instanceof Uint8Array,a=s?new _oe(n):Pae,o=S1(t,r);if(!Array.isArray(o)&&r.quickEncodeToken){let i=r.quickEncodeToken(o);if(i)return s?(a.push(i),a.toBytes()):i;let c=e[o.type.major];if(c.encodedSize){let u=c.encodedSize(o,r);if(s||(a=new $L(u)),c(a,o,r),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${o} was wrong`);return s?a.toBytes():CL(a.chunks[0])}}return a.reset(),WL(a,o,e,r),a.toBytes(!0)}var A$e=Symbol.for("DONE"),R$e=Symbol.for("BREAK"),VN;(function(t){t[t.OKP=1]="OKP",t[t.EC2=2]="EC2",t[t.Symmetric=4]="Symmetric"})(VN||(VN={}));var ei;(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"})(ei||(ei={}));var Fo;(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"})(Fo||(Fo={}));var HN;(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"})(HN||(HN={}));var JN;(function(t){t[t.Crv=-1]="Crv",t[t.X=-2]="X",t[t.Y=-3]="Y",t[t.D=-4]="D"})(JN||(JN={}));var D$e={"P-256":ei.P256,"P-384":ei.P384,"P-521":ei.P521,X25519:ei.X25519,Ed25519:ei.Ed25519,Ed448:ei.Ed448,secp256k1:ei.Secp256k1},C$e={[ei.P256]:"P-256",[ei.P384]:"P-384",[ei.P521]:"P-521",[ei.X25519]:"X25519",[ei.Ed25519]:"Ed25519",[ei.Ed448]:"Ed448",[ei.Secp256k1]:"secp256k1"},j$e={EdDSA:Fo.EdDSA,ES256:Fo.ES256,ES384:Fo.ES384,ES512:Fo.ES512,ES256K:Fo.ES256K},$$e={[Fo.EdDSA]:"EdDSA",[Fo.ES256]:"ES256",[Fo.ES384]:"ES384",[Fo.ES512]:"ES512",[Fo.ES256K]:"ES256K"},ZN;(function(t){t[t.Alg=1]="Alg",t[t.Crit=2]="Crit",t[t.ContentType=3]="ContentType",t[t.Kid=4]="Kid"})(ZN||(ZN={}));var YN;(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"})(YN||(YN={}));var QN;(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"})(QN||(QN={}));var XN;(function(t){t[t.Unrestricted=1]="Unrestricted",t[t.Restricted=2]="Restricted",t[t.SecureRestricted=3]="SecureRestricted",t[t.Hardware=4]="Hardware"})(XN||(XN={}));var _ae={};BI(_ae,{extractDidFragment:()=>Ei,getServices:()=>kae,getVerificationMethodByKey:()=>Tae,getVerificationMethodTypes:()=>VL,getVerificationMethods:()=>iP,getVerificationRelationshipsById:()=>HL,isDidService:()=>JL,isDidVerificationMethod:()=>W1,isDwnDidService:()=>Iae,isPortableDid:()=>Aae,keyBytesToMultibaseId:()=>ZL,multibaseIdToKeyBytes:()=>YL});function Ei(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function kae({didDocument:t,id:e,type:r}){return t?.service?.filter(n=>!(e&&n.id!==e||r&&n.type!==r))??[]}async function Tae({didDocument:t,publicKeyJwk:e,publicKeyMultibase:r}){let n=iP({didDocument:t});for(let s of n)if(e&&s.publicKeyJwk){if(await fr({jwk:e})===await fr({jwk:s.publicKeyJwk}))return s}else if(r&&s.publicKeyMultibase&&r===s.publicKeyMultibase)return s;return null}function iP({didDocument:t}){if(!t)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...t.verificationMethod?.filter(W1)??[]),Object.keys(eP).forEach(r=>{e.push(...t[r]?.filter(W1)??[])}),e}function VL({didDocument:t}){let e=iP({didDocument:t}).map(r=>r.type);return[...new Set(e)]}function HL({didDocument:t,methodId:e}){let r=[];return Object.keys(eP).forEach(n=>{if(Array.isArray(t[n])){let s=t[n],a=Ei(e);s.some(o=>{let i=Ei(o)===a,c=W1(o)&&Ei(o.id)===a;return i||c})&&r.push(n)}}),r}function JL(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function Iae(t){return!(!JL(t)||t.type!=="DecentralizedWebNode")}function W1(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 Aae(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 ZL({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Vo.addPrefix({code:e,data:t,name:r}),s=Qe.uint8Array(n).toBase58Btc();return Qe.base58Btc(s).toMultibase()}function YL({multibaseKeyId:t}){try{let e=Qe.multibase(t).toBase58Btc(),r=Qe.base58Btc(e).toUint8Array(),{code:n,data:s,name:a}=Vo.removePrefix({prefixedData:r});return{keyBytes:s,multicodecCode:n,multicodecName:a}}catch{throw new Ze("invalidDid",`Invalid multibase identifier: ${t}`)}}var Ec=class QL{constructor({uri:e,document:r,metadata:n,keyManager:s}){this.uri=e,this.document=r,this.metadata=n,this.keyManager=s}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 s=await this.keyManager.getKeyUri({key:n.publicKeyJwk}),a=await this.keyManager.exportKey({keyUri:s});r.push({...a})}e.privateKeys=r}return e}async getSigner(e){let r=this.document.verificationMethod?.find(o=>Ei(o.id)===(Ei(e?.methodId)??Ei(this.document.assertionMethod?.[0])));if(!(r&&r.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");let n=await this.keyManager.getKeyUri({key:r.publicKeyJwk}),s=await this.keyManager.getPublicKey({keyUri:n}),a=this.keyManager;return{algorithm:poe.getJoseSignatureAlgorithmFromPublicKey(s),keyId:r.id,async sign({data:o}){return await a.sign({data:o,keyUri:n})},async verify({data:o,signature:i}){return await a.verify({data:o,key:s,signature:i})}}}static async import({portableDid:e,keyManager:r=new Ia}){let n=iP({didDocument:e.document});if(n.length===0)throw new Ze("invalidDidDocument","At least one verification method is required but 0 were given");for(let s of e.privateKeys??[]){let a=await r.getKeyUri({key:s});await r.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1)||await r.importKey({key:s})}for(let s of n){if(!s.publicKeyJwk)throw new Error(`Verification method '${s.id}' does not contain a public key in JWK format`);let a=await r.getKeyUri({key:s.publicKeyJwk});await r.getPublicKey({keyUri:a})}return new QL({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:r})}},Dw=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()")}},XL=(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))(XL||{}),oA=(t=>(t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519",t))(oA||{}),eK=(t=>(t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm",t))(eK||{}),eU="0123456789abcdef",tK=[],tU=[];for(let t=0;t<256;t++)tK[t]=eU[t>>4&15]+eU[t&15],t<16&&(t<10?tU[48+t]=t:tU[87+t]=t);var Rae=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=tK[t[n++]];return r},Dae=(t,e=0)=>{let r=t.length||0;if(!e){let o=r;for(;o--;)e+=t[o].length}let n=new Uint8Array(e),s=e,a=r;for(;a--;)s-=t[a].length,n.set(t[a],s);return n},rU="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Cae=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Yg=0;Yg<rU.length;Yg++)Cae[rU.charCodeAt(Yg)]=Yg;var Yg,jae=new TextDecoder,rK=(t,e)=>e?new TextDecoder(e).decode(t):jae.decode(t),$ae=new TextEncoder,_d=t=>$ae.encode(t),nU=typeof window<"u"?window:self,sU=nU.crypto||nU.msCrypto||{},M$e=sU.subtle||sU.webkitSubtle;function Cw(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function nK(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 cr(t,e,r){let n=[],s=null;return cr._encode(n,t),s=Dae(n),cr.bytes=s.length,ArrayBuffer.isView(e)?(e.set(s,r),e):s}cr.bytes=-1;cr._floatConversionDetected=!1;cr._encode=function(t,e){if(e!=null)switch(nK(e)){case"object":cr.dict(t,e);break;case"map":cr.dictMap(t,e);break;case"array":cr.list(t,e);break;case"set":cr.listSet(t,e);break;case"string":cr.string(t,e);break;case"number":cr.number(t,e);break;case"boolean":cr.number(t,e);break;case"arraybufferview":cr.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":cr.buffer(t,new Uint8Array(e));break}};var oP=new Uint8Array([101]),sK=new Uint8Array([100]),iK=new Uint8Array([108]);cr.buffer=function(t,e){t.push(_d(e.length+":"),e)};cr.string=function(t,e){t.push(_d(_d(e).byteLength+":"+e))};cr.number=function(t,e){if(Number.isInteger(e))return t.push(_d("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,s=e%r<<0,a=n*r+s;t.push(_d("i"+a+"e")),a!==e&&!cr._floatConversionDetected&&(cr._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())};cr.dict=function(t,e){t.push(sK);let r=0,n,s=Object.keys(e).sort(),a=s.length;for(;r<a;r++)n=s[r],e[n]!=null&&(cr.string(t,n),cr._encode(t,e[n]));t.push(oP)};cr.dictMap=function(t,e){t.push(sK);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?cr._encode(t,n):cr.string(t,String(n)),cr._encode(t,e.get(n)));t.push(oP)};cr.list=function(t,e){let r=0,n=e.length;for(t.push(iK);r<n;r++)e[r]!=null&&cr._encode(t,e[r]);t.push(oP)};cr.listSet=function(t,e){t.push(iK);for(let r of e)r!=null&&cr._encode(t,r);t.push(oP)};var Mae=cr,Oae=105,Bae=58,Nae=100,Uae=108,aA=101;function oK(t,e,r){let n=0,s=1;for(let a=e;a<r;a++){let o=t[a];if(o<58&&o>=48){n=n*10+(o-48);continue}if(!(a===e&&o===43)){if(a===e&&o===45){s=-1;continue}if(o===46)break;throw new Error("not a number: buffer["+a+"] = "+o)}}return n*s}function lt(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),lt.position=0,lt.encoding=n||null,lt.data=ArrayBuffer.isView(t)?new Uint8Array(t.slice(e,r)):_d(t),lt.bytes=lt.data.length,lt.next())}lt.bytes=0;lt.position=0;lt.data=null;lt.encoding=null;lt.next=function(){switch(lt.data[lt.position]){case Nae:return lt.dictionary();case Uae:return lt.list();case Oae:return lt.integer();default:return lt.buffer()}};lt.find=function(t){let e=lt.position,r=lt.data.length,n=lt.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)+"]")};lt.dictionary=function(){lt.position++;let t={};for(;lt.data[lt.position]!==aA;){let e=lt.buffer(),r=rK(e);r.includes("\uFFFD")&&(r=Rae(e)),t[r]=lt.next()}return lt.position++,t};lt.list=function(){lt.position++;let t=[];for(;lt.data[lt.position]!==aA;)t.push(lt.next());return lt.position++,t};lt.integer=function(){let t=lt.find(aA),e=oK(lt.data,lt.position+1,t);return lt.position+=t+1-lt.position,e};lt.buffer=function(){let t=lt.find(Bae),e=oK(lt.data,lt.position,t),r=++t+e;return lt.position=r,lt.encoding?rK(lt.data.slice(t,r)):lt.data.slice(t,r)};var Lae=lt;function Kae(t){let e=2;for(let r of t)e+=aP(r);return e}function zae(t){let e=2;for(let[r,n]of t){let s=_d(r).byteLength;e+=Cw(s)+1+s,e+=aP(n)}return e}function qae(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let s=_d(r[n]).byteLength;e+=Cw(s)+1+s,e+=aP(t[r[n]])}return e}function Fae(t){let e=_d(t).byteLength;return Cw(e)+1+e}function Gae(t){let e=t.byteLength-t.byteOffset;return Cw(e)+1+e}function aP(t){if(t==null)return 0;let e=nK(t);switch(e){case"arraybufferview":return Gae(t);case"string":return Fae(t);case"array":case"set":return Kae(t);case"number":return 1+Cw(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return qae(t);case"map":return zae(t);default:throw new TypeError(`Unsupported value of type "${e}"`)}}var aK=aP,Wae=aK,cK={encode:Mae,decode:Lae,byteLength:aK,encodingLength:Wae},Vae=/^(\d{1,3}\.){3,3}\d{1,3}$/,Hae=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,Pc={name:"v4",size:4,isFormat:t=>Vae.test(t),encode(t,e,r){r=~~r,e=e||new Uint8Array(r+4);let n=t.length,s=0;for(let a=0;a<n;){let o=t.charCodeAt(a++);o===46?(e[r++]=s,s=0):s=s*10+(o-48)}return e[r]=s,e},decode(t,e){return e=~~e,`${t[e++]}.${t[e++]}.${t[e++]}.${t[e]}`}},Gu={name:"v6",size:16,isFormat:t=>t.length>0&&Hae.test(t),encode(t,e,r){r=~~r;let n=r+16,s=-1,a=0,o=0,i=!0,c=!1;e=e||new Uint8Array(r+16);for(let u=0;u<t.length;u++){let d=t.charCodeAt(u);d===58?(i?s!==-1?(r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2):r<n&&(s=r):(c===!0?(r<n&&(e[r]=o),r++):(r<n&&(e[r]=a>>8),r<n-1&&(e[r+1]=a&255),r+=2),a=0,o=0),i=!0,c=!1):d===46?(r<n&&(e[r]=o),r++,o=0,a=0,i=!1,c=!0):(i=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,o=o*10+d),a=(a<<4)+d)}if(i===!1)c===!0?(r<n&&(e[r]=o),r++):(r<n&&(e[r]=a>>8),r<n-1&&(e[r+1]=a&255),r+=2);else if(s===0)r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2;else if(s!==-1){r+=2;for(let u=Math.min(r-1,n-1);u>=s+2;u--)e[u]=e[u-2];e[s]=0,e[s+1]=0,s=r}if(s!==r&&s!==-1)for(r>n-2&&(r=n-2);n>s;)e[--n]=r<n&&r>s?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}/,"::")}};function dK(t){if(Pc.isFormat(t))return Pc.size;if(Gu.isFormat(t))return Gu.size;throw Error(`Invalid ip address: ${t}`)}function Jae(t){return dK(t)===Pc.size?1:2}function Zae(t,e,r){r=~~r;let n=dK(t);return typeof e=="function"&&(e=e(r+n)),n===Pc.size?Pc.encode(t,e,r):Gu.encode(t,e,r)}function Yae(t,e,r){if(e=~~e,r=r||t.length-e,r===Pc.size)return Pc.decode(t,e,r);if(r===Gu.size)return Gu.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${Pc.size} for v4 or ${Gu.size} for v6.`)}function cP(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 xw(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 Qae(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 Xae(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 uK(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 lK(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 ece(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 iU(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 fK(t){let e=0,r=t.length;for(let n=0;n<r;n+=1){let s=t.charCodeAt(n);if(s<=127)e+=1;else if(s<=2047)e+=2;else if((s&63488)!==55296)e+=3;else{let a=n+1;a===r||s>=56320||(t.charCodeAt(a)&64512)!==56320?e+=3:(n=a,e+=4)}}return e}function Sw(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(fK(t)+r));let s=r;for(let a=0;a<n;a+=1){let o=t.charCodeAt(a);if(o<=127)e[s++]=o;else if(o<=2047)e[s++]=192|(o&1984)>>6,e[s++]=128|o&63;else if((o&63488)!==55296)e[s++]=224|(o&61440)>>12,e[s++]=128|(o&4032)>>6,e[s++]=128|o&63;else{let i=a+1;if(i===n||o>=56320)e[s++]=239,e[s++]=191,e[s++]=189;else{let c=t.charCodeAt(i);(c&64512)!==56320?(e[s++]=239,e[s++]=191,e[s++]=189):(a=i,o=65536|(o&1023)<<10|c&1023,e[s++]=240|(o&1835008)>>18,e[s++]=128|(o&258048)>>12,e[s++]=128|(o&4032)>>6,e[s++]=128|o&63)}}}return Sw.bytes=s-r,e}Sw.bytes=0;function jw(t,e,r){let n="";e==null&&(e=0),r==null&&(r=t.length);for(let s=e;s<r;){let a=t[s++],o;if(a<=128)o=a;else if(a>191&&a<224)o=(a&31)<<6|t[s++]&63;else if(a>239&&a<365){o=((a&7)<<18|(t[s++]&63)<<12|(t[s++]&63)<<6|t[s++]&63)-65536;let i=55296|o>>10&1023;n+=String.fromCharCode(i),o=56320|o&1023}else o=(a&15)<<12|(t[s++]&63)<<6|t[s++]&63;n+=String.fromCharCode(o)}return jw.bytes=r-e,n}jw.bytes=0;var Af=t=>t instanceof Uint8Array;function Vu(t){return typeof t=="string"?fK(t):t.byteLength}function cA(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Sw(t)}function dA(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Sw(e,t,r),Sw.bytes}var nw={},pK=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 s=n.toString(16),a=s.toUpperCase(),o=t<<4|n,i=`${e}${s}`;pK[o]=i,nw[i]=o,nw[`${r}${s}`]=o,nw[`${e}${a}`]=o,nw[`${r}${a}`]=o}}function tce(t,e,r){let n="";for(let s=e;s<r;){let a=t[s++];n+=pK[a]}return n}function oU(t){return t.length>>>1}function rce(t,e,r,n){let s=0;for(;r<n;){let a=e.substr(s,2),o=nw[a];if(o===void 0)return;t[r++]=o,s+=2}return t}var nce=Math.pow(2,24),sce=Math.pow(2,16),ice=Math.pow(2,8),xd=(t,e)=>t[e]*nce+t[e+1]*sce+t[e+2]*ice+t[e+3],Dt=(t,e)=>t[e]<<8|t[e+1],Sd=(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),Xe=(t,e,r)=>(t[r]=e>>8,t[r+1]=e&255,r+2);function mo(t,e,r,n,s){return r<0&&(n-=r,r=0),n<0&&(n=0),s<0?new Uint8Array(0):r>=e.length||n>=s?0:oce(t,e,r,n,s)}function oce(t,e,r,n,s){s-n>e.length-r&&(s=n+e.length-r);let a=s-n,o=t.length-n;return a>o&&(a=o),(n!==0||s<t.length)&&(t=new Uint8Array(t.buffer,t.byteOffset+n,a)),e.set(t,r),a}var ace=0,aU=32768,_I=32768,cce=~_I,hK=32768,dce=~hK;function jr({bytes:t=0,encode:e,decode:r,encodingLength:n}){return e.bytes=t,r.bytes=t,{encode:e,decode:r,encodingLength:n||(()=>t)}}var Fe=jr({encode(t,e,r){e||(e=new Uint8Array(Fe.encodingLength(t))),r||(r=0);let n=r,s=t.replace(/^\.|\.$/gm,"");if(s.length){let a=s.split(".");for(let o=0;o<a.length;o++){let i=dA(e,a[o],r+1);e[r]=i,r+=i+1}}return e[r++]=0,Fe.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=[],n=e,s=0,a=0,o=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let i=t[e++];if(a+=o?0:1,i===0)break;if(i&192)if((i&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let c=Dt(t,e-1)-49152;if(c>=n)throw new Error("Cannot decode name (bad pointer)");e=c,n=c,a+=o?0:1,o=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+i>t.length)throw new Error("Cannot decode name (buffer overflow)");if(s+=i+1,s>254)throw new Error("Cannot decode name (name too long)");r.push(jw(t,e,e+i)),e+=i,a+=o?0:i}}return Fe.decode.bytes=a,r.length===0?".":r.join(".")},encodingLength(t){return t==="."||t===".."?1:Vu(t.replace(/^\.|\.$/gm,""))+2}}),Hn=jr({encode(t,e,r){e||(e=new Uint8Array(Hn.encodingLength(t))),r||(r=0);let n=dA(e,t,r+1);return e[r]=n,Hn.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=jw(t,e+1,e+1+r);return Hn.decode.bytes=r+1,n},encodingLength(t){return Vu(t)+1}}),jh=jr({bytes:12,encode(t,e,r){e||(e=new Uint8Array(jh.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,s=t.type==="response"?aU:ace;return Xe(e,t.id||0,r),Xe(e,n|s,r+2),Xe(e,t.questions.length,r+4),Xe(e,t.answers.length,r+6),Xe(e,t.authorities.length,r+8),Xe(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=Dt(t,e+2);return{id:Dt(t,e),type:r&aU?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:Xae(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:Qae(r&15),questions:new Array(Dt(t,e+4)),answers:new Array(Dt(t,e+6)),authorities:new Array(Dt(t,e+8)),additionals:new Array(Dt(t,e+10))}},encodingLength(){return 12}}),E1=jr({encode(t,e,r){e||(e=new Uint8Array(E1.encodingLength(t))),r||(r=0);let n=t.length;return Xe(e,n,r),mo(t,e,r+2,0,n),E1.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=Dt(t,e),n=t.slice(e+2,e+2+r);return E1.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),_1=jr({encode(t,e,r){return e||(e=new Uint8Array(_1.encodingLength(t))),r||(r=0),Fe.encode(t,e,r+2),Xe(e,Fe.encode.bytes,r),_1.encode.bytes=Fe.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Dt(t,e),n=Fe.decode(t,e+2);return _1.decode.bytes=r+2,n},encodingLength(t){return Fe.encodingLength(t)+2}}),k1=jr({encode(t,e,r){e||(e=new Uint8Array(k1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Fe.encode(t.mname,e,r),r+=Fe.encode.bytes,Fe.encode(t.rname,e,r),r+=Fe.encode.bytes,Sd(e,t.serial||0,r),r+=4,Sd(e,t.refresh||0,r),r+=4,Sd(e,t.retry||0,r),r+=4,Sd(e,t.expire||0,r),r+=4,Sd(e,t.minimum||0,r),r+=4,Xe(e,r-n-2,n),k1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=Fe.decode(t,e),e+=Fe.decode.bytes,n.rname=Fe.decode(t,e),e+=Fe.decode.bytes,n.serial=xd(t,e),e+=4,n.refresh=xd(t,e),e+=4,n.retry=xd(t,e),e+=4,n.expire=xd(t,e),e+=4,n.minimum=xd(t,e),e+=4,k1.decode.bytes=e-r,n},encodingLength(t){return 22+Fe.encodingLength(t.mname)+Fe.encodingLength(t.rname)}}),T1=jr({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let s=0;s<t.length;s++)if(typeof t[s]=="string"&&(t[s]=cA(t[s])),!Af(t[s]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(T1.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(s){e[r++]=s.length,mo(s,e,r,0,s.length),r+=s.length}),Xe(e,r-n-2,n),T1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=Dt(t,e);e+=2;let s=[];for(;n>0;){let a=t[e++];if(--n,n<a)throw new Error("Buffer overflow");s.push(t.slice(e,e+a)),e+=a,n-=a}return T1.decode.bytes=e-r,s},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=Vu(r)+1:e+=r.length+1}),e}}),I1=jr({encode(t,e,r){e||(e=new Uint8Array(I1.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=cA(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let s=t.length;return mo(t,e,r,0,s),r+=s,Xe(e,r-n-2,n),I1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=Dt(t,e);e+=2;let s=t.slice(e,e+n);return e+=n,I1.decode.bytes=e-r,s},encodingLength(t){return t?(Af(t)?t.length:Vu(t))+2:2}}),A1=jr({encode(t,e,r){e||(e=new Uint8Array(A1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Hn.encode(t.cpu,e,r),r+=Hn.encode.bytes,Hn.encode(t.os,e,r),r+=Hn.encode.bytes,Xe(e,r-n-2,n),A1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Hn.decode(t,e),e+=Hn.decode.bytes,n.os=Hn.decode(t,e),e+=Hn.decode.bytes,A1.decode.bytes=e-r,n},encodingLength(t){return Hn.encodingLength(t.cpu)+Hn.encodingLength(t.os)+2}}),Lh=jr({encode(t,e,r){return e||(e=new Uint8Array(Lh.encodingLength(t))),r||(r=0),Fe.encode(t,e,r+2),Xe(e,Fe.encode.bytes,r),Lh.encode.bytes=Fe.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Fe.decode(t,e+2);return Lh.decode.bytes=Fe.decode.bytes+2,r},encodingLength(t){return Fe.encodingLength(t)+2}}),R1=jr({encode(t,e,r){e||(e=new Uint8Array(R1.encodingLength(t))),r||(r=0),Xe(e,t.priority||0,r+2),Xe(e,t.weight||0,r+4),Xe(e,t.port||0,r+6),Fe.encode(t.target,e,r+8);let n=Fe.encode.bytes+6;return Xe(e,n,r),R1.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=Dt(t,e),n={};return n.priority=Dt(t,e+2),n.weight=Dt(t,e+4),n.port=Dt(t,e+6),n.target=Fe.decode(t,e+8),R1.decode.bytes=r+2,n},encodingLength(t){return 8+Fe.encodingLength(t.target)}}),zu=jr({encode(t,e,r){let n=zu.encodingLength(t);return e||(e=new Uint8Array(zu.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=zu.ISSUER_CRITICAL),Xe(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,Hn.encode(t.tag,e,r),r+=Hn.encode.bytes,dA(e,t.value,r),r+=Vu(t.value),zu.encode.bytes=n,e},decode(t,e){e||(e=0);let r=Dt(t,e);e+=2;let n=e,s={};return s.flags=t[e],e+=1,s.tag=Hn.decode(t,e),e+=Hn.decode.bytes,s.value=jw(t,e,n+r),s.issuerCritical=!!(s.flags&zu.ISSUER_CRITICAL),zu.decode.bytes=r+2,s},encodingLength(t){return Hn.encodingLength(t.tag)+Hn.encodingLength(t.value)+2}});zu.ISSUER_CRITICAL=128;var D1=jr({encode(t,e,r){e||(e=new Uint8Array(D1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Xe(e,t.preference||0,r),r+=2,Fe.encode(t.exchange,e,r),r+=Fe.encode.bytes,Xe(e,r-n-2,n),D1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=Dt(t,e),e+=2,n.exchange=Fe.decode(t,e),e+=Fe.decode.bytes,D1.decode.bytes=e-r,n},encodingLength(t){return 4+Fe.encodingLength(t.exchange)}}),mK=jr({encode(t,e,r){return e||(e=new Uint8Array(mK.encodingLength(t))),r||(r=0),Xe(e,4,r),r+=2,Pc.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,Pc.decode(t,e)},bytes:6}),C1=jr({encode(t,e,r){return e||(e=new Uint8Array(C1.encodingLength(t))),r||(r=0),Xe(e,16,r),r+=2,Gu.encode(t,e,r),C1.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=Gu.decode(t,e);return C1.decode.bytes=18,r},bytes:18}),cU=t=>new Uint8Array(t),bd=jr({encode(t,e,r){e||(e=new Uint8Array(bd.encodingLength(t))),r||(r=0);let n=r,s=iU(t.code);if(Xe(e,s,r),r+=2,t.data)Xe(e,t.data.length,r),r+=2,mo(t.data,e,r),r+=t.data.length;else switch(s){case 8:{let a=t.sourcePrefixLength||0,o=t.family||Jae(t.ip,cU),i=Zae(t.ip,cU),c=Math.ceil(a/8);Xe(e,c+4,r),r+=2,Xe(e,o,r),r+=2,e[r++]=a,e[r++]=t.scopePrefixLength||0,mo(i,e,r,0,c),r+=c}break;case 11:t.timeout?(Xe(e,2,r),r+=2,Xe(e,t.timeout,r),r+=2):(Xe(e,0,r),r+=2);break;case 12:{let a=t.length||0;Xe(e,a,r),r+=2,e.fill(0,r,r+a),r+=a}break;case 14:{let a=t.tags.length*2;Xe(e,a,r),r+=2;for(let o of t.tags)Xe(e,o,r),r+=2}break;default:throw new Error(`Unknown roption code: ${t.code}`)}return bd.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=Dt(t,e),r.type=ece(r.code),e+=2;let n=Dt(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=Dt(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let s=new Uint8Array(r.family===1?4:16);mo(t,s,0,e,e+n-4),r.ip=Yae(s)}break;case 11:n>0&&(r.timeout=Dt(t,e),e+=2);break;case 14:r.tags=[];for(let s=0;s<n;s+=2)r.tags.push(Dt(t,e)),e+=2}return bd.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(iU(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}`)}}),qu=jr({encode(t,e,r){e||(e=new Uint8Array(qu.encodingLength(t))),r||(r=0);let n=r,s=Nh(t,bd);return Xe(e,s,r),r=dw(t,bd,e,r+2),qu.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],s=Dt(t,e);e+=2;let a=0;for(;s>0;)n[a++]=bd.decode(t,e),e+=bd.decode.bytes,s-=bd.decode.bytes;return qu.decode.bytes=e-r,n},encodingLength(t){return 2+Nh(t||[],bd)}}),bc=jr({encode(t,e,r){e||(e=new Uint8Array(bc.encodingLength(t))),r||(r=0);let n=r,s=t.key;if(!Af(s))throw new Error("Key must be a Buffer");return r+=2,Xe(e,t.flags,r),r+=2,e[r]=bc.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,mo(s,e,r,0,s.length),r+=s.length,bc.encode.bytes=r-n,Xe(e,bc.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);if(e+=2,n.flags=Dt(t,e),e+=2,t[e]!==bc.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t[e],e+=1,n.key=t.slice(e,r+s+2),e+=n.key.length,bc.decode.bytes=e-r,n},encodingLength(t){return 6+Vu(t.key)}});bc.PROTOCOL_DNSSEC=3;bc.ZONE_KEY=128;bc.SECURE_ENTRYPOINT=32768;var sw=jr({encode(t,e,r){e||(e=new Uint8Array(sw.encodingLength(t))),r||(r=0);let n=r,s=t.signature;if(!Af(s))throw new Error("Signature must be a Buffer");return r+=2,Xe(e,xw(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,Sd(e,t.originalTTL,r),r+=4,Sd(e,t.expiration,r),r+=4,Sd(e,t.inception,r),r+=4,Xe(e,t.keyTag,r),r+=2,Fe.encode(t.signersName,e,r),r+=Fe.encode.bytes,mo(s,e,r,0,s.length),r+=s.length,sw.encode.bytes=r-n,Xe(e,sw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);return e+=2,n.typeCovered=cP(Dt(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=xd(t,e),e+=4,n.expiration=xd(t,e),e+=4,n.inception=xd(t,e),e+=4,n.keyTag=Dt(t,e),e+=2,n.signersName=Fe.decode(t,e),e+=Fe.decode.bytes,n.signature=t.slice(e,r+s+2),e+=n.signature.length,sw.decode.bytes=e-r,n},encodingLength(t){return 20+Fe.encodingLength(t.signersName)+Vu(t.signature)}}),iw=jr({encode(t,e,r){e||(e=new Uint8Array(iw.encodingLength(t))),r||(r=0);let n=r;return r+=2,Fe.encode(t.mbox||".",e,r),r+=Fe.encode.bytes,Fe.encode(t.txt||".",e,r),r+=Fe.encode.bytes,iw.encode.bytes=r-n,Xe(e,iw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=Fe.decode(t,e)||".",e+=Fe.decode.bytes,n.txt=Fe.decode(t,e)||".",e+=Fe.decode.bytes,iw.decode.bytes=e-r,n},encodingLength(t){return 2+Fe.encodingLength(t.mbox||".")+Fe.encodingLength(t.txt||".")}}),ho=jr({encode(t,e,r){e||(e=new Uint8Array(ho.encodingLength(t))),r||(r=0);let n=r,s=[];for(let a=0;a<t.length;a++){let o=xw(t[a]);s[o>>8]===void 0&&(s[o>>8]=[]),s[o>>8][o>>3&31]|=1<<7-(o&7)}for(let a=0;a<s.length;a++)if(s[a]!==void 0){let o=cA(s[a]);e[r]=a,r+=1,e[r]=o.length,r+=1,mo(o,e,r,0,o.length),r+=o.length}return ho.encode.bytes=r-n,e},decode(t,e,r){e||(e=0);let n=e,s=[];for(;e-n<r;){let a=t[e];e+=1;let o=t[e];e+=1;for(let i=0;i<o;i++){let c=t[e+i];for(let u=0;u<8;u++)if(c&1<<7-u){let d=cP(a<<8|i<<3|u);s.push(d)}}e+=o}return ho.decode.bytes=e-n,s},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let s=xw(t[n]);e[s>>8]=Math.max(e[s>>8]||0,s&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}}),ow=jr({encode(t,e,r){e||(e=new Uint8Array(ow.encodingLength(t))),r||(r=0);let n=r;return r+=2,Fe.encode(t.nextDomain,e,r),r+=Fe.encode.bytes,ho.encode(t.rrtypes,e,r),r+=ho.encode.bytes,ow.encode.bytes=r-n,Xe(e,ow.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);return e+=2,n.nextDomain=Fe.decode(t,e),e+=Fe.decode.bytes,n.rrtypes=ho.decode(t,e,s-(e-r)),e+=ho.decode.bytes,ow.decode.bytes=e-r,n},encodingLength(t){return 2+Fe.encodingLength(t.nextDomain)+ho.encodingLength(t.rrtypes)}}),aw=jr({encode(t,e,r){e||(e=new Uint8Array(aw.encodingLength(t))),r||(r=0);let n=r,s=t.salt;if(!Af(s))throw new Error("salt must be a Buffer");let a=t.nextDomain;if(!Af(a))throw new Error("nextDomain must be a Buffer");return r+=2,e[r]=t.algorithm,r+=1,e[r]=t.flags,r+=1,Xe(e,t.iterations,r),r+=2,e[r]=s.length,r+=1,mo(s,e,r,0,s.length),r+=s.length,e[r]=a.length,r+=1,mo(a,e,r,0,a.length),r+=a.length,ho.encode(t.rrtypes,e,r),r+=ho.encode.bytes,aw.encode.bytes=r-n,Xe(e,aw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=Dt(t,e),e+=2;let a=t[e];e+=1,n.salt=t.slice(e,e+a),e+=a;let o=t[e];return e+=1,n.nextDomain=t.slice(e,e+o),e+=o,n.rrtypes=ho.decode(t,e,s-(e-r)),e+=ho.decode.bytes,aw.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+ho.encodingLength(t.rrtypes)}}),cw=jr({encode(t,e,r){e||(e=new Uint8Array(cw.encodingLength(t))),r||(r=0);let n=r,s=t.digest;if(!Af(s))throw new Error("Digest must be a Buffer");return r+=2,Xe(e,t.keyTag,r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.digestType,r+=1,mo(s,e,r,0,s.length),r+=s.length,cw.encode.bytes=r-n,Xe(e,cw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);return e+=2,n.keyTag=Dt(t,e),e+=2,n.algorithm=t[e],e+=1,n.digestType=t[e],e+=1,n.digest=t.slice(e,r+s+2),e+=n.digest.length,cw.decode.bytes=e-r,n},encodingLength(t){return 6+Vu(t.digest)}}),Bh=jr({encode(t,e,r){e||(e=new Uint8Array(Bh.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let s=oU(t.fingerprint),a=kI(t.hash);if(s!==a)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${s} != ${a}`);return rce(e,t.fingerprint,r,r+=s),Bh.encode.bytes=r-n,Xe(e,Bh.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 s=kI(n.hash);return n.fingerprint=tce(t,e,e+s),e+=s,Bh.decode.bytes=e-r,n},encodingLength(t){return 4+oU(t.fingerprint)}});function kI(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}Bh.getFingerprintLengthForHashType=kI;function fI(t){switch(t.toUpperCase()){case"A":return mK;case"PTR":return Lh;case"CNAME":return Lh;case"DNAME":return Lh;case"TXT":return T1;case"NULL":return I1;case"AAAA":return C1;case"SRV":return R1;case"HINFO":return A1;case"CAA":return zu;case"NS":return _1;case"SOA":return k1;case"MX":return D1;case"OPT":return qu;case"DNSKEY":return bc;case"RRSIG":return sw;case"RP":return iw;case"NSEC":return ow;case"NSEC3":return aw;case"SSHFP":return Bh;case"DS":return cw}return E1}var Ko=jr({encode(t,e,r){e||(e=new Uint8Array(Ko.encodingLength(t))),r||(r=0);let n=r;if(Fe.encode(t.name,e,r),r+=Fe.encode.bytes,Xe(e,xw(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");Xe(e,t.udpPayloadSize||4096,r+2),e[r+4]=t.extendedRcode||0,e[r+5]=t.ednsVersion||0,Xe(e,t.flags||0,r+6),r+=8,qu.encode(t.options||[],e,r),r+=qu.encode.bytes}else{let s=lK(t.class===void 0?"IN":t.class);t.flush&&(s|=_I),Xe(e,s,r+2),Sd(e,t.ttl||0,r+4),r+=8;let a=fI(t.type);a.encode(t.data,e,r),r+=a.encode.bytes}return Ko.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={},n=e;if(r.name=Fe.decode(t,e),e+=Fe.decode.bytes,r.type=cP(Dt(t,e)),r.type==="OPT")r.udpPayloadSize=Dt(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=Dt(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=qu.decode(t,e+8),e+=8+qu.decode.bytes;else{let s=Dt(t,e+2);r.ttl=xd(t,e+4),r.class=uK(s&cce),r.flush=!!(s&_I);let a=fI(r.type);r.data=a.decode(t,e+8),e+=8+a.decode.bytes}return Ko.decode.bytes=e-n,r},encodingLength(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Fe.encodingLength(t.name)+8+fI(t.type).encodingLength(e)}}),Kh=jr({encode(t,e,r){e||(e=new Uint8Array(Kh.encodingLength(t))),r||(r=0);let n=r;return Fe.encode(t.name,e,r),r+=Fe.encode.bytes,Xe(e,xw(t.type),r),r+=2,Xe(e,lK(t.class===void 0?"IN":t.class),r),r+=2,Kh.encode.bytes=r-n,t},decode(t,e){e||(e=0);let r=e,n={};return n.name=Fe.decode(t,e),e+=Fe.decode.bytes,n.type=cP(Dt(t,e)),e+=2,n.class=uK(Dt(t,e)),e+=2,n.class&hK&&(n.class&=dce),Kh.decode.bytes=e-r,n},encodingLength(t){return Fe.encodingLength(t.name)+4}}),uce=1024,Os={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(lce(t))),r||(r=0);let s=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),jh.encode(t,e,r),r+=jh.encode.bytes,r=dw(t.questions,Kh,e,r),r=dw(t.answers,Ko,e,r),r=dw(t.authorities,Ko,e,r),r=dw(t.additionals,Ko,e,r),Os.encode.bytes=r-s,n&&Z1.bytes!==e.length?e.slice(0,Z1.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=jh.decode(t,e);return e+=jh.decode.bytes,e=y1(n.questions,Kh,t,e),e=y1(n.answers,Ko,t,e),e=y1(n.authorities,Ko,t,e),e=y1(n.additionals,Ko,t,e),Os.decode.bytes=e-r,n},encodingLength:function(t){return jh.encodingLength(t)+Nh(t.questions||[],Kh)+Nh(t.answers||[],Ko)+Nh(t.authorities||[],Ko)+Nh(t.additionals||[],Ko)}};Os.encode.bytes=0;Os.decode.bytes=0;function V1(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}var H1={encode:function(t,e,r){return e=Os.encode(V1(t,"query"),e,r),H1.encode.bytes=Os.encode.bytes,e},decode:function(t,e){let r=Os.decode(t,e);return H1.decode.bytes=Os.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Os.encodingLength(V1(t,"query"))}};H1.encode.bytes=0;H1.decode.bytes=0;var J1={encode:function(t,e,r){return e=Os.encode(V1(t,"response"),e,r),J1.encode.bytes=Os.encode.bytes,e},decode:function(t,e){let r=Os.decode(t,e);return J1.decode.bytes=Os.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Os.encodingLength(V1(t,"response"))}};J1.encode.bytes=0;J1.decode.bytes=0;var Z1=Os.encode,TI=Os.decode,lce=Os.encodingLength;function yK(t){let e=Z1(t),r=new Uint8Array(2+e.byteLength);return Xe(r,e.byteLength),mo(e,r,2,0,e.length),yK.bytes=r.byteLength,r}yK.bytes=0;function gK(t){let e=Dt(t,0);if(t.byteLength<e+2)return null;let r=TI(t.slice(2));return gK.bytes=TI.bytes,r}gK.bytes=0;function Nh(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function dw(t,e,r,n){for(let s=0;s<t.length;s++)e.encode(t[s],r,n),n+=e.encode.bytes;return n}function y1(t,e,r,n){for(let s=0;s<t.length;s++)t[s]=e.decode(r,n),n+=e.decode.bytes;return n}function wK(t,e){let r=Qe.uint8Array(t).toBase32Z();return new URL(r,e).href}async function fce({gatewayUri:t,publicKeyBytes:e}){let r=Qe.uint8Array(e).toBase32Z(),n=wK(e,t),s;try{if(s=await fetch(n,{method:"GET",signal:AbortSignal.timeout(3e4)}),!s.ok)throw new Ze("notFound",`Pkarr record not found for: ${r}`)}catch(o){throw o instanceof Ze?o:new Ze("internalError",`Failed to fetch Pkarr record: ${o.message}`)}let a=await s.arrayBuffer();if(!a)throw new Ze("notFound",`Pkarr record not found for: ${r}`);if(a.byteLength<72)throw new Ze("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${a.byteLength}`);if(a.byteLength>1072)throw new Ze("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 pce({gatewayUri:t,bep44Message:e}){let r=Qe.uint8Array(e.k).toBase32Z(),n=wK(e.k,t),s=new Uint8Array(e.v.length+72);s.set(e.sig,0),new DataView(s.buffer).setBigUint64(e.sig.length,BigInt(e.seq)),s.set(e.v,e.sig.length+8);let a;try{a=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:s,signal:AbortSignal.timeout(3e4)})}catch(o){throw new Ze("internalError",`Failed to put Pkarr record for identifier ${r}: ${o.message}`)}return a.ok}async function hce({dnsPacket:t,publicKeyBytes:e,signer:r}){let n=Math.ceil(Date.now()/1e3),s=Z1(t),a=cK.encode({seq:n,v:s}).subarray(1,-1);if(a.length>1e3)throw new Ze("invalidDidDocumentLength",`DNS packet exceeds the 1000 byte maximum size: ${a.length} bytes`);let o=await r.sign({data:new Uint8Array(a)});return{k:e,seq:n,sig:o,v:s}}async function mce({bep44Message:t}){let e=await $s.bytesToPublicKey({publicKeyBytes:t.k}),r=cK.encode({seq:t.seq,v:t.v}).subarray(1,-1);if(!await $s.verify({key:e,signature:t.sig,data:new Uint8Array(r)}))throw new Ze("invalidSignature","Invalid signature for DHT BEP44 message");return TI(t.v)}var vK="dht";async function bK({didUri:t}){let e=uA({didUri:t});return await $s.bytesToPublicKey({publicKeyBytes:e})}function uA({didUri:t}){let e=us.parse(t);if(!e)throw new Ze("invalidDid",`Invalid DID URI: ${t}`);if(e.method!==vK)throw new Ze("methodNotSupported",`Method not supported: ${e.method}`);let r;try{r=Qe.base32Z(e.id).toUint8Array()}catch{throw new Ze("invalidPublicKey","Failed to decode method-specific identifier")}if(r.length!==32)throw new Ze("invalidPublicKeyLength",`Invalid public key length: ${r.length}`);return r}async function yce({identityKey:t}){let e=await $s.publicKeyToBytes({publicKey:t}),r=Qe.uint8Array(e).toBase32Z();return`did:${vK}:${r}`}function lA(t){let e={Ed25519:$s,"P-256":{publicKeyToBytes:async({publicKey:r})=>{let n=await Xs.publicKeyToBytes({publicKey:r});return await Xs.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:Xs.bytesToPublicKey,privateKeyToBytes:Xs.privateKeyToBytes,bytesToPrivateKey:Xs.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:r})=>{let n=await js.publicKeyToBytes({publicKey:r});return await js.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:js.bytesToPublicKey,privateKeyToBytes:js.privateKeyToBytes,bytesToPrivateKey:js.bytesToPrivateKey},X25519:Ch}[t];if(!e)throw new Ze("invalidPublicKeyType",`Unsupported curve: ${t}`);return e}async function PK({newDid:t,previousDidProof:e}){let r=await bK({didUri:e.previousDid}),n=uA({didUri:t}),s=Qe.base64Url(e.signature).toUint8Array();if(!await $s.verify({key:r,data:n,signature:s}))throw new Ze("invalidPreviousDidProof","The previous DID proof is invalid.")}var gce=0,Nu=7200,j1=";",Si=",",xK={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},SK={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};function Ew(t){if(typeof t=="string")return t;if(t instanceof Uint8Array)return Qe.uint8Array(t).toString();if(Array.isArray(t))return t.map(e=>Ew(e)).join("");throw new Ze("internalError","Pkarr returned DNS TXT record with invalid data type")}function uw(t){return Ew(t).split(j1).reduce((e,r)=>{let[n,s]=r.split("=");return e[n]=s,e},{})}function EK(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 wce({didUri:t,dnsPacket:e}){let r={id:t},n={published:!0},s=new Map;for(let a of e?.answers??[]){if(a.type!=="TXT")continue;let o=a.name.split(".")[0].substring(1);switch(!0){case o.startsWith("aka"):{let i=Ew(a.data);r.alsoKnownAs=i.split(Si);break}case o.startsWith("cnt"):{let i=Ew(a.data);r.controller=i.includes(Si)?i.split(Si):i;break}case o.startsWith("k"):{let{id:i,t:c,k:u,c:d,a:l}=uw(a.data),f=Qe.base64Url(u).toUint8Array(),h=oA[Number(c)],p=await lA(h).bytesToPublicKey({publicKeyBytes:f});p.alg=l||SK[Number(c)];let m=o==="k0"?"0":i!==void 0?i:await fr({jwk:p});r.verificationMethod??=[];let y=`${t}#${m}`;r.verificationMethod.push({id:y,type:"JsonWebKey",controller:d??t,publicKeyJwk:p}),s.set(o,y);break}case o.startsWith("s"):{let{id:i,t:c,se:u,...d}=uw(a.data),l=u.includes(Si)?u.split(Si):[u],f=Object.fromEntries(Object.entries(d).map(([h,p])=>[h,p.includes(Si)?p.split(Si):p]));r.service??=[],r.service.push({...f,id:`${t}#${i}`,type:c,serviceEndpoint:l});break}case o.startsWith("typ"):{let{id:i}=uw(a.data);n.types=i.split(Si).map(c=>Number(c));break}case o.startsWith("did"):{let i=h=>h.split(Si).map(p=>s.get(p)).filter(p=>typeof p=="string"),{auth:c,asm:u,del:d,inv:l,agm:f}=uw(a.data);c&&(r.authentication=i(c)),u&&(r.assertionMethod=i(u)),d&&(r.capabilityDelegation=i(d)),l&&(r.capabilityInvocation=i(l)),f&&(r.keyAgreement=i(f));break}}}return{didDocument:r,didDocumentMetadata:n,didResolutionMetadata:{}}}async function vce({didDocument:t,didMetadata:e,authoritativeGatewayUris:r,previousDidProof:n}){let s=[],a=[],o=new Map,i=[],c=[];if(n!==void 0){let{signature:d,previousDid:l}=n;await PK({newDid:t.id,previousDidProof:n}),s.push({type:"TXT",name:"_prv._did.",ttl:Nu,data:`id=${l};s=${d}`})}if(t.alsoKnownAs&&s.push({type:"TXT",name:"_aka._did.",ttl:Nu,data:t.alsoKnownAs.join(Si)}),t.controller){let d=Array.isArray(t.controller)?t.controller.join(Si):t.controller;s.push({type:"TXT",name:"_cnt._did.",ttl:Nu,data:d})}for(let[d,l]of t.verificationMethod?.entries()??[]){let f=`k${d}`;c.push(f);let h=l.id.split("#").pop();o.set(h,f);let p=l.publicKeyJwk;if(!(p?.crv&&p.crv in xK))throw new Ze("invalidPublicKeyType",`Verification method '${l.id}' contains an unsupported key type: ${p?.crv??"undefined"}`);let m=oA[p.crv],y=await lA(p.crv).publicKeyToBytes({publicKey:p}),S=Qe.uint8Array(y).toBase64Url(),v=[`t=${m}`,`k=${S}`];h!=="0"&&await fr({jwk:p})!==h&&v.unshift(`id=${h}`),p.alg!==SK[m]&&v.push(`a=${p.alg}`),l.controller!==t.id&&v.push(`c=${l.controller}`),s.push({type:"TXT",name:`_${f}._did.`,ttl:Nu,data:v.join(j1)})}t.service?.forEach((d,l)=>{let f=`s${l}`;i.push(f);let{id:h,type:p,serviceEndpoint:m,...y}=d;h=Ei(h),m=Array.isArray(m)?m.join(","):m;let S=Object.entries({id:h,t:p,se:m,...y}).map(([E,k])=>`${E}=${k}`).join(j1),v=EK(S);s.push({type:"TXT",name:`_${f}._did.`,ttl:Nu,data:v})});let u=[`v=${gce}`];if(c.length&&u.push(`vm=${c.join(Si)}`),Object.keys(eP).forEach(d=>{let l=t[d]?.map(f=>o.get(f.split("#").pop()));if(l){let f=eK[d];u.push(`${f}=${l.join(Si)}`)}}),i.length&&u.push(`svc=${i.join(Si)}`),e.types?.length){let d=e.types.map(l=>typeof l=="string"?XL[l]:l);s.push({type:"TXT",name:"_typ._did.",ttl:Nu,data:`id=${d.join(Si)}`})}s.push({type:"TXT",name:"_did."+dU(t.id)+".",ttl:Nu,data:u.join(j1)});for(let d of r||[])a.push({type:"NS",name:"_did."+dU(t.id)+".",ttl:Nu,data:d+"."});return{id:0,type:"response",flags:uce,answers:[...s,...a]}}function dU(t){return t.split(":")[2]}var uU=U.DID_DHT_GATEWAY_URI||"https://enbox-did-dht.fly.dev",_K=class II extends Dw{static async create({keyManager:e=new Ia,options:r={}}={}){if(r.verificationMethods?.some(d=>!(d.algorithm in xK)))throw new Error("One or more verification method algorithms are not supported");let n=r.verificationMethods?.filter(d=>"id"in d).map(d=>d.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(r.services?.some(d=>!d.id||!d.type||!d.serviceEndpoint))throw new Error("One or more services are missing required properties");let s=await e.generateKey({algorithm:"Ed25519"}),a=await e.getPublicKey({keyUri:s}),o=await Uh.identityKeyToIdentifier({identityKey:a}),i={id:o,...r.alsoKnownAs&&{alsoKnownAs:r.alsoKnownAs},...r.controllers&&{controller:r.controllers}},c=[...r.verificationMethods??[]];c?.some(d=>d.id?.split("#").pop()==="0")||c.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let d of c){let l=d.id&&d.id.split("#").pop()==="0"?s:await e.generateKey({algorithm:d.algorithm}),f=await e.getPublicKey({keyUri:l}),h=d.id??f.kid??await fr({jwk:f});h=`${o}#${Ei(h)}`,i.verificationMethod??=[],i.verificationMethod.push({id:h,type:"JsonWebKey",controller:d.controller??o,publicKeyJwk:f});for(let p of d.purposes??[])i[p]??=[],i[p].push(h)}r.services?.forEach(d=>{i.service??=[],d.id=`${o}#${d.id.split("#").pop()}`,i.service.push(d)});let u=new Ec({uri:o,document:i,metadata:{published:!1,...r.types&&{types:r.types}},keyManager:e});if(r.publish??!0){let d=await II.publish({did:u,gatewayUri:r.gatewayUri});u.metadata=d.didDocumentMetadata}return u}static async import({portableDid:e,keyManager:r=new Ia}){if(us.parse(e.uri)?.method!==II.methodName)throw new Ze("methodNotSupported","Method not supported");let n=await Ec.import({portableDid:e,keyManager:r});if(!n.document.verificationMethod?.some(s=>s.id?.split("#").pop()==="0"))throw new Ze("invalidDidDocument","DID document must contain an Identity Key");return n}static async getSigningMethod({didDocument:e,methodId:r="#0"}){let n=us.parse(e.id);if(n&&n.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${n.method}`);let s=e.verificationMethod?.find(a=>Ei(a.id)===(Ei(r)??Ei(e.assertionMethod?.[0])));if(!(s&&s.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async publish({did:e,gatewayUri:r=uU}){return await lU.put({did:e,gatewayUri:r})}static async resolve(e,r={}){let n=r?.gatewayUri??uU;try{await Uh.identifierToIdentityKey({didUri:e});let{didDocument:s,didDocumentMetadata:a}=await lU.get({didUri:e,gatewayUri:n});return{...ds,didDocument:s,didDocumentMetadata:a}}catch(s){if(!(s instanceof Ze))throw new Error(s);return{...ds,didResolutionMetadata:{error:s.code,...s.message&&{errorMessage:s.message}}}}}};_K.methodName="dht";var kK=_K,lU=class lw{static async get({didUri:e,gatewayUri:r}){let n=Uh.identifierToIdentityKeyBytes({didUri:e}),s=await lw.pkarrGet({gatewayUri:r,publicKeyBytes:n}),a=await Uh.parseBep44GetMessage({bep44Message:s}),o=await lw.fromDnsPacket({didUri:e,dnsPacket:a});return o.didDocumentMetadata.versionId=s.seq.toString(),o}static async put({did:e,gatewayUri:r}){let n=await lw.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[r]}),s=await Uh.createBep44PutMessage({dnsPacket:n,publicKeyBytes:Uh.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),a=await lw.pkarrPut({gatewayUri:r,bep44Message:s});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:a,versionId:s.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return fce(e)}static async pkarrPut(e){return pce(e)}static async fromDnsPacket(e){return wce(e)}static async toDnsPacket(e){return vce(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},Uh=class{static async createBep44PutMessage(t){return hce(t)}static async identifierToIdentityKey(t){return bK(t)}static identifierToIdentityKeyBytes(t){return uA(t)}static async identityKeyToIdentifier(t){return yce(t)}static keyConverter(t){return lA(t)}static async parseBep44GetMessage(t){return mce(t)}static parseTxtDataToObject(t){return uw(t)}static parseTxtDataToString(t){return Ew(t)}static async validatePreviousDidProof(t){return PK(t)}static chunkDataIfNeeded(t){return EK(t)}},In={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"},An=class extends Error{constructor(t,e){super(`${t}: ${e}`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}},O$e=new Uint8Array(0),bce=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")},Pce=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")}},xce=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 TK(this,t)}},Sce=class{constructor(t){this.decoders=t}or(t){return TK(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`)}},TK=(t,e)=>new Sce({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Ece=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new Pce(t,e,r),this.decoder=new xce(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},_ce=({name:t,prefix:e,encode:r,decode:n})=>new Ece(t,e,r,n),kce=(t,e,r,n)=>{let s={};for(let d=0;d<e.length;++d)s[e[d]]=d;let a=t.length;for(;t[a-1]==="=";)--a;let o=new Uint8Array(a*r/8|0),i=0,c=0,u=0;for(let d=0;d<a;++d){let l=s[t[d]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|l,i+=r,i>=8&&(i-=8,o[u++]=255&c>>i)}if(i>=r||255&c<<8-i)throw new SyntaxError("Unexpected end of data");return o},Tce=(t,e,r)=>{let n=e[e.length-1]==="=",s=(1<<r)-1,a="",o=0,i=0;for(let c=0;c<t.length;++c)for(i=i<<8|t[c],o+=8;o>r;)o-=r,a+=e[s&i>>o];if(o&&(a+=e[s&i<<r-o]),n)for(;a.length*r&7;)a+="=";return a},dP=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>_ce({prefix:e,name:t,encode(s){return Tce(s,n,r)},decode(s){return kce(s,n,r,t)}}),B$e=dP({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),N$e=dP({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fU=dP({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),U$e=dP({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Gh=class $1{static encode(e){return fU.baseEncode(e)}static decodeAsBytes(e,r){if(!$1.isBase64UrlString(e))throw new An(In.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return fU.baseDecode(e)}static decodeAsString(e,r){let n=$1.decodeAsBytes(e,r);return $1.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)}},Ice=Rf(_ne(),1),AI;(function(t){t.Public="public",t.Private="private"})(AI||(AI={}));var vc=AI,lo=class{static validateEs256kOperationKey(t,e){let r=new Set(["kty","crv","x","y"]);e===vc.Private&&r.add("d");for(let n in t)if(!r.has(n))throw new An(In.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${n}'.`);if(t.crv!=="secp256k1")throw new An(In.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${t.crv}.'`);if(t.kty!=="EC")throw new An(In.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${t.kty}.'`);if(t.x.length!==43)throw new An(In.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(t.y.length!==43)throw new An(In.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(e===vc.Private&&(t.d===void 0||t.d.length!==43))throw new An(In.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(t){if(t.length>50)throw new An(In.IdTooLong,`Key ID length ${t.length} exceed max allowed length of 50.`);if(!Gh.isBase64UrlString(t))throw new An(In.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 An(In.PublicKeyPurposeDuplicated,`Public key purpose '${r}' already specified.`);e.add(r)}}},fA=class{};fA.hashAlgorithmInMultihashCode=18;fA.maxCanonicalizedDeltaSizeInBytes=1e3;var Ta=fA,Ace=Rf(kne(),1),_w=class RI{static canonicalizeAsBytes(e){let r=RI.removeAllUndefinedProperties(e),n=Ace.default(r);return Gh.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let r in e)typeof e[r]=="object"?RI.removeAllUndefinedProperties(e[r]):e[r]===void 0&&delete e[r];return e}},Rce=IK,pU=128,Dce=127,Cce=~Dce,jce=Math.pow(2,31);function IK(t,e,r){e=e||[],r=r||0;for(var n=r;t>=jce;)e[r++]=t&255|pU,t/=128;for(;t&Cce;)e[r++]=t&255|pU,t>>>=7;return e[r]=t|0,IK.bytes=r-n+1,e}var $ce=DI,Mce=128,hU=127;function DI(t,n){var r=0,n=n||0,s=0,a=n,o,i=t.length;do{if(a>=i)throw DI.bytes=0,new RangeError("Could not decode varint");o=t[a++],r+=s<28?(o&hU)<<s:(o&hU)*Math.pow(2,s),s+=7}while(o>=Mce);return DI.bytes=a-n,r}var Oce=Math.pow(2,7),Bce=Math.pow(2,14),Nce=Math.pow(2,21),Uce=Math.pow(2,28),Lce=Math.pow(2,35),Kce=Math.pow(2,42),zce=Math.pow(2,49),qce=Math.pow(2,56),Fce=Math.pow(2,63),Gce=function(t){return t<Oce?1:t<Bce?2:t<Nce?3:t<Uce?4:t<Lce?5:t<Kce?6:t<zce?7:t<qce?8:t<Fce?9:10},Wce={encode:Rce,decode:$ce,encodingLength:Gce},Vce=Wce,Y1=Vce,mU=(t,e=0)=>[Y1.decode(t,e),Y1.decode.bytes],yU=(t,e,r=0)=>(Y1.encode(t,e,r),e),gU=t=>Y1.encodingLength(t),wU=(t,e)=>{let r=e.byteLength,n=gU(t),s=n+gU(r),a=new Uint8Array(s+r);return yU(t,a,0),yU(r,a,n),a.set(e,s),new AK(t,r,e,a)},Hce=t=>{let e=bce(t),[r,n]=mU(e),[s,a]=mU(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==s)throw new Error("Incorrect length");return new AK(r,s,o,e)},AK=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},RK=({name:t,code:e,encode:r})=>new Jce(t,e,r),Jce=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?wU(this.code,e):e.then(r=>wU(this.code,r))}else throw Error("Unknown type, must be binary type")}},DK=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),vU=RK({name:"sha2-256",code:18,encode:DK("SHA-256")}),L$e=RK({name:"sha2-512",code:19,encode:DK("SHA-512")}),Qg=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},po=class fw{static hash(e,r){return Qg(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield vU.digest(e)).bytes;break;default:throw new An(In.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return Qg(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield vU.encode(e);break;default:throw new An(In.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return Qg(this,void 0,void 0,function*(){let n=_w.canonicalizeAsBytes(e);return yield fw.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return Qg(this,void 0,void 0,function*(){let n=_w.canonicalizeAsBytes(e),s=yield fw.hashAsNonMultihashBytes(n,r);return yield fw.hashThenEncode(s,r)})}static hashThenEncode(e,r){return Qg(this,void 0,void 0,function*(){let n=yield fw.hash(e,r);return Gh.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,s=Gh.decodeAsBytes(e,r);try{n=Hce(s)}catch{throw new An(In.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let a=Ta.hashAlgorithmInMultihashCode;if(a!==n.code)throw new An(In.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${a} or change IonSdkConfig to desired hashing algorithm.`)}},CI;(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(CI||(CI={}));var g1=CI,jI;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})(jI||(jI={}));var Dh=jI,w1=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},CK=class Uo{static createCreateRequest(e){return w1(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,s=e.document.publicKeys,a=e.document.services;lo.validateEs256kOperationKey(r,vc.Public),lo.validateEs256kOperationKey(n,vc.Public),Uo.validateDidDocumentKeys(s),Uo.validateServices(a);let o=Ta.hashAlgorithmInMultihashCode,i=[{action:Dh.Replace,document:e.document}],c={updateCommitment:yield po.canonicalizeThenDoubleHashThenEncode(n,o),patches:i};Uo.validateDeltaSize(c);let u={deltaHash:yield po.canonicalizeThenHashThenEncode(c,o),recoveryCommitment:yield po.canonicalizeThenDoubleHashThenEncode(r,o)};return{type:g1.Create,suffixData:u,delta:c}})}static createDeactivateRequest(e){return w1(this,void 0,void 0,function*(){Uo.validateDidSuffix(e.didSuffix),lo.validateEs256kOperationKey(e.recoveryPublicKey,vc.Public);let r=Ta.hashAlgorithmInMultihashCode,n=yield po.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),s={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},a=yield e.signer.sign({alg:"ES256K"},s);return{type:g1.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:a}})}static createRecoverRequest(e){return w1(this,void 0,void 0,function*(){Uo.validateDidSuffix(e.didSuffix),lo.validateEs256kOperationKey(e.recoveryPublicKey,vc.Public),lo.validateEs256kOperationKey(e.nextRecoveryPublicKey,vc.Public),lo.validateEs256kOperationKey(e.nextUpdatePublicKey,vc.Public),Uo.validateDidDocumentKeys(e.document.publicKeys),Uo.validateServices(e.document.services);let r=Ta.hashAlgorithmInMultihashCode,n=yield po.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),s=[{action:Dh.Replace,document:e.document}],a=yield po.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),o={patches:s,updateCommitment:a},i=yield po.canonicalizeThenHashThenEncode(o,r),c={recoveryCommitment:yield po.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,r),recoveryKey:e.recoveryPublicKey,deltaHash:i},u=yield e.signer.sign({alg:"ES256K"},c);return{type:g1.Recover,didSuffix:e.didSuffix,revealValue:n,delta:o,signedData:u}})}static createUpdateRequest(e){return w1(this,void 0,void 0,function*(){if(Uo.validateDidSuffix(e.didSuffix),lo.validateEs256kOperationKey(e.updatePublicKey,vc.Public),lo.validateEs256kOperationKey(e.nextUpdatePublicKey,vc.Public),Uo.validateServices(e.servicesToAdd),Uo.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let p of e.idsOfServicesToRemove)lo.validateId(p);if(e.idsOfPublicKeysToRemove!==void 0)for(let p of e.idsOfPublicKeysToRemove)lo.validateId(p);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let p={action:Dh.AddServices,services:n};r.push(p)}let s=e.idsOfServicesToRemove;if(s!==void 0&&s.length>0){let p={action:Dh.RemoveServices,ids:s};r.push(p)}let a=e.publicKeysToAdd;if(a!==void 0&&a.length>0){let p={action:Dh.AddPublicKeys,publicKeys:a};r.push(p)}let o=e.idsOfPublicKeysToRemove;if(o!==void 0&&o.length>0){let p={action:Dh.RemovePublicKeys,ids:o};r.push(p)}let i=Ta.hashAlgorithmInMultihashCode,c=yield po.canonicalizeThenHashThenEncode(e.updatePublicKey,i),u=yield po.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,i),d={patches:r,updateCommitment:u},l=yield po.canonicalizeThenHashThenEncode(d,i),f={updateKey:e.updatePublicKey,deltaHash:l},h=yield e.signer.sign({alg:"ES256K"},f);return{type:g1.Update,didSuffix:e.didSuffix,revealValue:c,delta:d,signedData:h}})}static validateDidSuffix(e){po.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 An(In.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(lo.validateId(n.id),r.has(n.id))throw new An(In.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);r.add(n.id),lo.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let r=new Set;for(let n of e){if(Uo.validateService(n),r.has(n.id))throw new An(In.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){lo.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 An(In.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new An(In.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&Ice.parse(e.serviceEndpoint).error!==void 0)throw new An(In.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=_w.canonicalizeAsBytes(e);if(r.length>Ta.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${Ta.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new An(In.DeltaExceedsMaximumSize,n)}}},bU=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},Zce=class jK{static createLongFormDid(e){return bU(this,void 0,void 0,function*(){let r=yield CK.createCreateRequest(e),n=yield jK.computeDidUniqueSuffix(r.suffixData),s;Ta.network===void 0||Ta.network==="mainnet"?s=`did:ion:${n}`:s=`did:ion:${Ta.network}:${n}`;let a={suffixData:r.suffixData,delta:r.delta},o=_w.canonicalizeAsBytes(a),i=Gh.encode(o);return`${s}:${i}`})}static computeDidUniqueSuffix(e){return bU(this,void 0,void 0,function*(){let r=_w.canonicalizeAsBytes(e),n=yield po.hash(r,Ta.hashAlgorithmInMultihashCode);return Gh.encode(n)})}},Cs=2n**255n-19n,M1=2n**252n+27742317777372353535851937790883648493n,$I=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,MI=0x6666666666666666666666666666666666666666666666666666666666666658n,v1={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Cs,n:M1,h:8,Gx:$I,Gy:MI},Ui=(t="")=>{throw new Error(t)},$K=t=>typeof t=="string",pA=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?Ui("Uint8Array expected"):t,Wh=t=>new Uint8Array(t),Yce=(t,e)=>pA($K(t)?mA(t):Wh(t),e),nt=(t,e=Cs)=>{let r=t%e;return r>=0n?r:e+r},PU=t=>t instanceof Vh?t:Ui("Point expected"),xU,Vh=class $h{constructor(e,r,n,s){this.ex=e,this.ey=r,this.ez=n,this.et=s}static fromAffine(e){return new $h(e.x,e.y,1n,nt(e.x*e.y))}static fromHex(e,r=!0){let{d:n}=v1;e=Yce(e,32);let s=e.slice();s[31]=e[31]&-129;let a=Xce(s);a===0n||(r&&!(0n<a&&a<Cs)&&Ui("bad y coord 1"),!r&&!(0n<a&&a<2n**256n)&&Ui("bad y coord 2"));let o=nt(a*a),i=nt(o-1n),c=nt(n*o+1n),{isValid:u,value:d}=tde(i,c);u||Ui("bad y coordinate 3");let l=(d&1n)===1n;return(e[31]&128)!==0!==l&&(d=nt(-d)),new $h(d,a,1n,nt(d*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){let{ex:r,ey:n,ez:s}=this,{ex:a,ey:o,ez:i}=PU(e),c=nt(r*i),u=nt(a*s),d=nt(n*i),l=nt(o*s);return c===u&&d===l}is0(){return this.equals(O1)}negate(){return new $h(nt(-this.ex),this.ey,this.ez,nt(-this.et))}double(){let{ex:e,ey:r,ez:n}=this,{a:s}=v1,a=nt(e*e),o=nt(r*r),i=nt(2n*nt(n*n)),c=nt(s*a),u=e+r,d=nt(nt(u*u)-a-o),l=c+o,f=l-i,h=c-o,p=nt(d*f),m=nt(l*h),y=nt(d*h),S=nt(f*l);return new $h(p,m,S,y)}add(e){let{ex:r,ey:n,ez:s,et:a}=this,{ex:o,ey:i,ez:c,et:u}=PU(e),{a:d,d:l}=v1,f=nt(r*o),h=nt(n*i),p=nt(a*l*u),m=nt(s*c),y=nt((r+n)*(o+i)-f-h),S=nt(m-p),v=nt(m+p),E=nt(h-d*f),k=nt(y*S),A=nt(v*E),D=nt(y*E),B=nt(S*v);return new $h(k,A,B,D)}mul(e,r=!0){if(e===0n)return r===!0?Ui("cannot multiply by 0"):O1;if(typeof e=="bigint"&&0n<e&&e<M1||Ui("invalid scalar, must be < L"),!r&&this.is0()||e===1n)return this;if(this.equals(Q1))return sde(e).p;let n=O1,s=Q1;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):r&&(s=s.add(a));return n}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(v1.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(M1/2n,!1).double();return M1%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 s=OK(n);return nt(n*s)!==1n&&Ui("invalid inverse"),{x:nt(e*s),y:nt(r*s)}}toRawBytes(){let{x:e,y:r}=this.toAffine(),n=Qce(r);return n[31]|=e&1n?128:0,n}toHex(){return hA(this.toRawBytes())}};Vh.BASE=new Vh($I,MI,1n,nt($I*MI));Vh.ZERO=new Vh(0n,1n,1n,0n);var{BASE:Q1,ZERO:O1}=Vh,MK=(t,e)=>t.toString(16).padStart(e,"0"),hA=t=>Array.from(t).map(e=>MK(e,2)).join(""),mA=t=>{let e=t.length;(!$K(t)||e%2)&&Ui("hex invalid 1");let r=Wh(e/2);for(let n=0;n<r.length;n++){let s=n*2,a=t.slice(s,s+2),o=Number.parseInt(a,16);(Number.isNaN(o)||o<0)&&Ui("hex invalid 2"),r[n]=o}return r},Qce=t=>mA(MK(t,32*2)).reverse(),Xce=t=>BigInt("0x"+hA(Wh(pA(t)).reverse())),SU=(...t)=>{let e=Wh(t.reduce((n,s)=>n+pA(s).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},OK=(t,e=Cs)=>{(t===0n||e<=0n)&&Ui("no inverse n="+t+" mod="+e);let r=nt(t,e),n=e,s=0n,a=1n,o=1n,i=0n;for(;r!==0n;){let c=n/r,u=n%r,d=s-o*c,l=a-i*c;n=r,r=u,s=o,a=i,o=d,i=l}return n===1n?nt(s,e):Ui("no inverse")},yc=(t,e)=>{let r=t;for(;e-- >0n;)r*=r,r%=Cs;return r},ede=t=>{let e=t*t%Cs*t%Cs,r=yc(e,2n)*e%Cs,n=yc(r,1n)*t%Cs,s=yc(n,5n)*n%Cs,a=yc(s,10n)*s%Cs,o=yc(a,20n)*a%Cs,i=yc(o,40n)*o%Cs,c=yc(i,80n)*i%Cs,u=yc(c,80n)*i%Cs,d=yc(u,10n)*s%Cs;return{pow_p_5_8:yc(d,2n)*t%Cs,b2:e}},EU=19681161376707505956807079304988542015446066515923890162744021073123829784752n,tde=(t,e)=>{let r=nt(e*e*e),n=nt(r*r*e),s=ede(t*n).pow_p_5_8,a=nt(t*r*s),o=nt(e*a*a),i=a,c=nt(a*EU),u=o===t,d=o===nt(-t),l=o===nt(-t*EU);return u&&(a=i),(d||l)&&(a=c),(nt(a)&1n)===1n&&(a=nt(-a)),{isValid:u||d,value:a}},pI,_U=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,rde={bytesToHex:hA,hexToBytes:mA,concatBytes:SU,mod:nt,invert:OK,randomBytes:t=>{let e=_U();return e||Ui("crypto.getRandomValues must be defined"),e.getRandomValues(Wh(t))},sha512Async:async(...t)=>{let e=_U();e||Ui("crypto.subtle or etc.sha512Async must be defined");let r=SU(...t);return Wh(await e.subtle.digest("SHA-512",r.buffer))},sha512Sync:void 0};Object.defineProperties(rde,{sha512Sync:{configurable:!1,get(){return pI},set(t){pI||(pI=t)}}});var bf=8,nde=()=>{let t=[],e=256/bf+1,r=Q1,n=r;for(let s=0;s<e;s++){n=r,t.push(n);for(let a=1;a<2**(bf-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},sde=t=>{let e=xU||(xU=nde()),r=(d,l)=>{let f=l.negate();return d?f:l},n=O1,s=Q1,a=1+256/bf,o=2**(bf-1),i=BigInt(2**bf-1),c=2**bf,u=BigInt(bf);for(let d=0;d<a;d++){let l=d*o,f=Number(t&i);t>>=u,f>o&&(f-=c,t+=1n);let h=l,p=l+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?s=s.add(r(m,e[h])):n=n.add(r(y,e[p]))}return{p:n,f:s}},yA=2n**256n,kf=yA-0x1000003d1n,gA=yA-0x14551231950b75fc4402da1732fc9bebfn,BK=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,NK=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,UK={p:kf,n:gA,a:0n,b:7n,Gx:BK,Gy:NK},zh=32,kU=t=>He(He(t*t)*t+UK.b),cs=(t="")=>{throw new Error(t)},uP=t=>typeof t=="bigint",LK=t=>typeof t=="string",hI=t=>uP(t)&&0n<t&&t<kf,KK=t=>uP(t)&&0n<t&&t<gA,zK=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?cs("Uint8Array expected"):t,kw=t=>new Uint8Array(t),wA=(t,e)=>zK(LK(t)?lP(t):kw(t),e),He=(t,e=kf)=>{let r=t%e;return r>=0n?r:e+r},TU=t=>t instanceof Hh?t:cs("Point expected"),IU,Hh=class Mh{constructor(e,r,n){this.px=e,this.py=r,this.pz=n}static fromAffine(e){return new Mh(e.x,e.y,1n)}static fromHex(e){e=wA(e);let r,n=e[0],s=e.subarray(1),a=AU(s,0,zh),o=e.length;if(o===33&&[2,3].includes(n)){hI(a)||cs("Point hex invalid: x not FE");let i=ide(kU(a)),c=(i&1n)===1n;(n&1)===1!==c&&(i=He(-i)),r=new Mh(a,i,1n)}return o===65&&n===4&&(r=new Mh(a,AU(s,zh,2*zh),1n)),r?r.ok():cs("Point is not on curve")}static fromPrivateKey(e){return yw.mul(ode(e))}get x(){return this.aff().x}get y(){return this.aff().y}equals(e){let{px:r,py:n,pz:s}=this,{px:a,py:o,pz:i}=TU(e),c=He(r*i),u=He(a*s),d=He(n*i),l=He(o*s);return c===u&&d===l}negate(){return new Mh(this.px,He(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:r,py:n,pz:s}=this,{px:a,py:o,pz:i}=TU(e),{a:c,b:u}=UK,d=0n,l=0n,f=0n,h=He(u*3n),p=He(r*a),m=He(n*o),y=He(s*i),S=He(r+n),v=He(a+o);S=He(S*v),v=He(p+m),S=He(S-v),v=He(r+s);let E=He(a+i);return v=He(v*E),E=He(p+y),v=He(v-E),E=He(n+s),d=He(o+i),E=He(E*d),d=He(m+y),E=He(E-d),f=He(c*v),d=He(h*y),f=He(d+f),d=He(m-f),f=He(m+f),l=He(d*f),m=He(p+p),m=He(m+p),y=He(c*y),v=He(h*v),m=He(m+y),y=He(p-y),y=He(c*y),v=He(v+y),p=He(m*v),l=He(l+p),p=He(E*v),d=He(S*d),d=He(d-p),p=He(S*m),f=He(E*f),f=He(f+p),new Mh(d,l,f)}mul(e,r=!0){if(!r&&e===0n)return B1;if(KK(e)||cs("invalid scalar"),this.equals(yw))return ude(e).p;let n=B1,s=yw;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):r&&(s=s.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(B1))return{x:0n,y:0n};if(n===1n)return{x:e,y:r};let s=FK(n);return He(n*s)!==1n&&cs("invalid inverse"),{x:He(e*s),y:He(r*s)}}assertValidity(){let{x:e,y:r}=this.aff();return(!hI(e)||!hI(r))&&cs("Point invalid: x or y"),He(r*r)===kU(e)?this:cs("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")+RU(r)+(e?"":RU(n))}toRawBytes(e=!0){return lP(this.toHex(e))}};Hh.BASE=new Hh(BK,NK,1n);Hh.ZERO=new Hh(0n,1n,0n);var{BASE:yw,ZERO:B1}=Hh,qK=(t,e)=>t.toString(16).padStart(e,"0"),vA=t=>Array.from(t).map(e=>qK(e,2)).join(""),lP=t=>{let e=t.length;(!LK(t)||e%2)&&cs("hex invalid 1");let r=kw(e/2);for(let n=0;n<r.length;n++){let s=n*2,a=t.slice(s,s+2),o=Number.parseInt(a,16);(Number.isNaN(o)||o<0)&&cs("hex invalid 2"),r[n]=o}return r},fP=t=>BigInt("0x"+(vA(t)||"0")),AU=(t,e,r)=>fP(t.slice(e,r)),bA=t=>uP(t)&&t>=0n&&t<yA?lP(qK(t,2*zh)):cs("bigint expected"),RU=t=>vA(bA(t)),DU=(...t)=>{let e=kw(t.reduce((n,s)=>n+zK(s).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},FK=(t,e=kf)=>{(t===0n||e<=0n)&&cs("no inverse n="+t+" mod="+e);let r=He(t,e),n=e,s=0n,a=1n,o=1n,i=0n;for(;r!==0n;){let c=n/r,u=n%r,d=s-o*c,l=a-i*c;n=r,r=u,s=o,a=i,o=d,i=l}return n===1n?He(s,e):cs("no inverse")},ide=t=>{let e=1n;for(let r=t,n=(kf+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*r%kf),r=r*r%kf;return He(e*e)===t?e:cs("sqrt invalid")},ode=t=>(uP(t)||(t=fP(wA(t,zh))),KK(t)?t:cs("private key out of range")),CU=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,N1;function ade(t){t=wA(t);let e=zh+8;(t.length<e||t.length>1024)&&cs("expected proper params");let r=He(fP(t),gA-1n)+1n;return bA(r)}var cde={hexToBytes:lP,bytesToHex:vA,concatBytes:DU,bytesToNumberBE:fP,numberToBytesBE:bA,mod:He,invert:FK,hmacSha256Async:async(t,...e)=>{let r=CU();if(!r)return cs("etc.hmacSha256Async not set");let n=r.subtle,s=await n.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return kw(await n.sign("HMAC",s,DU(...e)))},hmacSha256Sync:N1,hashToPrivateKey:ade,randomBytes:t=>{let e=CU();return e||cs("crypto.getRandomValues must be defined"),e.getRandomValues(kw(t))}};Object.defineProperties(cde,{hmacSha256Sync:{configurable:!1,get(){return N1},set(t){N1||(N1=t)}}});var Pf=8,dde=()=>{let t=[],e=256/Pf+1,r=yw,n=r;for(let s=0;s<e;s++){n=r,t.push(n);for(let a=1;a<2**(Pf-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},ude=t=>{let e=IU||(IU=dde()),r=(d,l)=>{let f=l.negate();return d?f:l},n=B1,s=yw,a=1+256/Pf,o=2**(Pf-1),i=BigInt(2**Pf-1),c=2**Pf,u=BigInt(Pf);for(let d=0;d<a;d++){let l=d*o,f=Number(t&i);t>>=u,f>o&&(f-=c,t+=1n);let h=l,p=l+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?s=s.add(r(m,e[h])):n=n.add(r(y,e[p]))}return{p:n,f:s}},jU;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(jU||(jU={}));var $U;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})($U||($U={}));var Xg=class wf{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:s}){let a=await wf.createIonDocument({services:n,verificationMethods:s}),o=wf.normalizeJwk(e),i=wf.normalizeJwk(r);return await Zce.createLongFormDid({document:a,recoveryKey:o,updateKey:i})}static async constructCreateRequest({ionDocument:e,recoveryKey:r,updateKey:n}){return await CK.createCreateRequest({document:e,recoveryKey:wf.normalizeJwk(r),updateKey:wf.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:r}){let n=[];for(let a of r){let o=a.id??a.publicKeyJwk.kid??await fr({jwk:a.publicKeyJwk});o=`${o.split("#").pop()}`;let i={id:o,publicKeyJwk:wf.normalizeJwk(a.publicKeyJwk),purposes:a.purposes,type:"JsonWebKey2020"};n.push(i)}let s=e.map(a=>({...a,id:`${a.id.split("#").pop()}`}));return{publicKeys:n,services:s}}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}},lde=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519",t))(lde||{}),fde={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},MU="https://ion.tbd.engineering",pde=class pw extends Dw{static async create({keyManager:e=new Ia,options:r={}}={}){if(r.verificationMethods?.some(p=>!(p.algorithm in fde)))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 s={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},a=[];for(let p of r.verificationMethods??[s]){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 o=await e.generateKey({algorithm:"secp256k1"}),i=await e.getPublicKey({keyUri:o}),c=await e.generateKey({algorithm:"secp256k1"}),u=await e.getPublicKey({keyUri:c}),d=await Xg.computeLongFormDidUri({recoveryKey:i,updateKey:u,services:r.services??[],verificationMethods:a}),{didDocument:l,didResolutionMetadata:f}=await pw.resolve(d,{gatewayUri:r.gatewayUri});if(l===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let h=new Ec({uri:d,document:l,metadata:{published:!1,canonicalId:d.split(":",3).join(":"),recoveryKey:i,updateKey:u},keyManager:e});if(r.publish??!0){let p=await pw.publish({did:h,gatewayUri:r.gatewayUri});h.metadata=p.didDocumentMetadata}return h}static async getSigningMethod({didDocument:e,methodId:r}){let n=us.parse(e.id);if(n&&n.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${n.method}`);let s=e.verificationMethod?.find(a=>a.id===(r??e.assertionMethod?.[0]));if(!(s&&s.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async import({portableDid:e,keyManager:r=new Ia}){if(us.parse(e.uri)?.method!==pw.methodName)throw new Ze("methodNotSupported","Method not supported");return await Ec.import({portableDid:e,keyManager:r})}static async publish({did:e,gatewayUri:r=MU}){let n=e.document.verificationMethod?.map(o=>({id:o.id,publicKeyJwk:o.publicKeyJwk,purposes:HL({didDocument:e.document,methodId:o.id})}))??[],s=await Xg.createIonDocument({services:e.document.service??[],verificationMethods:n}),a=await Xg.constructCreateRequest({ionDocument:s,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let o=Xg.appendPathToUrl({baseUrl:r,path:"/operations"}),i=await fetch(o,{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:i.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=us.parse(e);if(!n)return{...ds,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==pw.methodName)return{...ds,didResolutionMetadata:{error:"methodNotSupported"}};let s=r?.gatewayUri??MU;try{let a=Xg.appendPathToUrl({baseUrl:s,path:`/identifiers/${e}`}),o=await fetch(a,{signal:AbortSignal.timeout(3e4)});if(!o.ok)throw new Ze("notFound",`Unable to find DID document for: ${e}`);let{didDocument:i,didDocumentMetadata:c}=await o.json();return{...ds,...i&&{didDocument:i},didDocumentMetadata:{published:c?.method?.published,...c}}}catch(a){if(!(a instanceof Ze))throw new Error(a);return{...ds,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};pde.methodName="ion";var GK=class hw extends Dw{static async create({keyManager:e=new Ia,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",s=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:s}),o=Qe.object(a).toBase64Url(),i=`did:${hw.methodName}:${o}`,c=(await hw.resolve(i)).didDocument;return new Ec({uri:i,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let r=us.parse(e.id);if(r&&r.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.verificationMethod??[];if(!(n&&n.publicKeyJwk))throw new Ze("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 Ia}){if(us.parse(e.uri)?.method!==hw.methodName)throw new Ze("methodNotSupported","Method not supported");let n=await Ec.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new Ze("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){let n=us.parse(e),s;try{s=n?Qe.base64Url(n.id).toObject():void 0}catch{}if(!n||!s)return{...ds,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==hw.methodName)return{...ds,didResolutionMetadata:{error:"methodNotSupported"}};let a={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},o=`${a.id}#0`;switch(a.verificationMethod=[{id:o,type:"JsonWebKey",controller:a.id,publicKeyJwk:s}],a.authentication=[o],a.assertionMethod=[o],a.capabilityInvocation=[o],a.capabilityDelegation=[o],a.keyAgreement=[o],s.use){case"sig":{delete a.keyAgreement;break}case"enc":{delete a.authentication,delete a.assertionMethod,delete a.capabilityInvocation,delete a.capabilityDelegation;break}}return{...ds,didDocument:a}}};GK.methodName="jwk";var WK=GK,hde={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},U1=class Oh{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(":"),s=Oh.JWK_TO_MULTICODEC[n];if(s===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:Vo.getCodeFromName({name:s}),name:s}}static keyCompressor(e){let r={"P-256":Xs.compressPublicKey,secp256k1:js.compressPublicKey}[e];if(!r)throw new Ze("invalidPublicKeyType",`Unsupported curve: ${e}`);return r}static keyConverter(e){let r={Ed25519:$s,"P-256":Xs,secp256k1:js}[e];if(!r)throw new Ze("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?Vo.getNameFromCode({code:e}):r;let n=r,s=Oh.MULTICODEC_TO_JWK[n];if(s===void 0)throw new Error("Unsupported Multicodec to JWK conversion");return{...s}}static async publicKeyToMultibaseId({publicKey:e}){if(!(e?.crv&&e.crv in hde))throw new Ze("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let r=await Oh.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(r=await Oh.keyCompressor(e.crv)({publicKeyBytes:r}));let{name:n}=await Oh.jwkToMulticodec({jwk:e});return ZL({keyBytes:r,multicodecName:n})}};U1.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},U1.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},U1.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:""}};var b1=U1,mde=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t))(mde||{}),OU={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},VK=class Ku extends Dw{static async create({keyManager:e=new Ia,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",s=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:s}),o=await b1.publicKeyToMultibaseId({publicKey:a}),i=`did:${Ku.methodName}:${o}`,c=(await Ku.resolve(i,r)).didDocument;return new Ec({uri:i,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let r=us.parse(e.id);if(r&&r.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.assertionMethod||[],s=e.verificationMethod?.find(a=>a.id===n);if(!(s&&s.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async import({portableDid:e,keyManager:r=new Ia}){if(us.parse(e.uri)?.method!==Ku.methodName)throw new Ze("methodNotSupported","Method not supported");let n=await Ec.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new Ze("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){try{let n=await Ku.createDocument({didUri:e,options:r});return{...ds,didDocument:n}}catch(n){if(!(n instanceof Ze))throw new Error(n);return{...ds,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:s=!1,publicKeyFormat:a="JsonWebKey2020"}=r,o={id:""},i=us.parse(e);if(!i)throw new Ze("invalidDid",`Invalid DID URI: ${e}`);let c=i.id;if(i.method!==Ku.methodName)throw new Ze("methodNotSupported",`Method not supported: ${i.method}`);if(!Ku.validateIdentifier(i))throw new Ze("invalidDid",`Invalid DID URI: ${e}`);let u=await Ku.createSignatureMethod({didUri:e,multibaseValue:c,options:{enableExperimentalPublicKeyTypes:s,publicKeyFormat:a}});o.id=i.uri,o.verificationMethod=[u],o.authentication=[u.id],o.assertionMethod=[u.id],o.capabilityInvocation=[u.id],o.capabilityDelegation=[u.id];let d=[n];return VL({didDocument:o}).forEach(l=>{let f=OU[l];d.push(f)}),o["@context"]=d,o}static async createSignatureMethod({didUri:e,multibaseValue:r,options:n}){let{enableExperimentalPublicKeyTypes:s,publicKeyFormat:a}=n,o={id:"",type:"",controller:""},{keyBytes:i,multicodecCode:c,multicodecName:u}=YL({multibaseKeyId:r}),d=i.byteLength,l=b1.MULTICODEC_PUBLIC_KEY_LENGTH[c];if(d!==l)throw new Ze("invalidPublicKeyLength",`Expected ${d} bytes. Actual: ${l}`);let f=!1;switch(u){case"secp256k1-pub":f=await js.validatePublicKey({publicKeyBytes:i});break;case"ed25519-pub":f=await $s.validatePublicKey({publicKeyBytes:i});break}if(!f)throw new Ze("invalidPublicKey","Invalid public key detected.");o.id=`${e}#${r}`;try{new URL(o.id)}catch{throw new Ze("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(a in OU))throw new Ze("unsupportedPublicKeyType",`Unsupported format: ${a}`);if(s===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(a))throw new Ze("invalidPublicKeyType",`Specified '${a}' without setting enableExperimentalPublicKeyTypes to true.`);if(o.type=a,o.controller=e,a==="Ed25519VerificationKey2020"&&(o.publicKeyMultibase=r),a==="JsonWebKey2020"){let{crv:h}=await b1.multicodecToJwk({code:c});o.publicKeyJwk=await b1.keyConverter(h).bytesToPublicKey({publicKeyBytes:i})}return o}static validateIdentifier(e){let{method:r,id:n}=e,[s]=e.uri.split(":",1);return s==="did"&&r==="key"&&!0&&mI(n)==="String"&&n.startsWith("z")}};VK.methodName="key";var $w=VK,yde=3e4;function gde(t){let e=t.toLowerCase();if(e==="localhost"||e==="localhost.")return!0;let r=e.split(".");if(r.length===4){let s=r.map(Number);if(s.every(a=>!Number.isNaN(a)&&a>=0&&a<=255)){let[a,o]=s;if(a===10||a===172&&o>=16&&o<=31||a===192&&o===168||a===127||a===169&&o===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 HK=class L1 extends Dw{static async create({keyManager:e=new Ia,options:r}){if(!r.domain)throw new Ze("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,s=`did:${L1.methodName}:${n}`;if(!us.parse(s))throw new Ze("invalidDid",`The constructed DID URI is invalid: ${s}`);let a=r.verificationMethods??[{algorithm:r.algorithm??"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]}],o={"@context":["https://www.w3.org/ns/did/v1"],id:s};for(let i=0;i<a.length;i++){let c=a[i],u=await e.generateKey({algorithm:c.algorithm}),d=await e.getPublicKey({keyUri:u}),l=c.id?.split("#").pop()??`key-${i}`,f=`${s}#${l}`;o.verificationMethod??=[],o.verificationMethod.push({id:f,type:"JsonWebKey",controller:c.controller??s,publicKeyJwk:d});for(let h of c.purposes??[])o[h]??=[],o[h].push(f)}return r.services&&(o.service=r.services.map(i=>({...i,id:`${s}#${i.id.split("#").pop()}`}))),new Ec({uri:s,document:o,metadata:{published:!1},keyManager:e})}static async getSigningMethod({didDocument:e,methodId:r}){let n=us.parse(e.id);if(n&&n.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${n.method}`);let s=Ei(r)??Ei(e.assertionMethod?.[0]),a=s?e.verificationMethod?.find(o=>Ei(o.id)===s):e.verificationMethod?.[0];if(!(a&&a.publicKeyJwk))throw new Ze("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 Ia}){if(us.parse(e.uri)?.method!==L1.methodName)throw new Ze("methodNotSupported","Method not supported");return await Ec.import({portableDid:e,keyManager:r})}static async resolve(e,r){let n=us.parse(e);if(!n)return{...ds,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==L1.methodName)return{...ds,didResolutionMetadata:{error:"methodNotSupported"}};let s=`https://${n.id.replace(/:/g,"/")}`;s=decodeURIComponent(s);let a=n.id.includes(":")?`${s}/did.json`:`${s}/.well-known/did.json`;try{let o=new URL(a);if(gde(o.hostname))return{...ds,didResolutionMetadata:{error:"notFound"}};let i=await fetch(a,{signal:AbortSignal.timeout(yde)});if(!i.ok)throw new Error("HTTP error status code returned");let c=await i.json();return{...ds,didDocument:c}}catch{return{...ds,didResolutionMetadata:{error:"notFound"}}}}};HK.methodName="web";var JK=HK,K$e=Rf(WU(),1),z$e=Rf(VU(),1);var wde=Rf(VU(),1),ZK=class{constructor({ttl:t="15m"}={}){this.cache=new Ine.default({ttl:(0,wde.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(){}},vde={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()}},YK=class{constructor({cache:t,didResolvers:e}){this.didResolvers=new Map,this.cache=t||vde;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=us.parse(t);if(!r)return{...ds,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${t}`}};let n=this.didResolvers.get(r.method);if(!n)return{...ds,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${r.method}`}};let s=await this.cache.get(r.uri);if(s)return s;{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=us.parse(t);if(!r)return{dereferencingMetadata:{error:"invalidDidUrl"},contentStream:null,contentMetadata:{}};let{didDocument:n,didResolutionMetadata:s,didDocumentMetadata:a}=await this.resolve(r.uri);if(!n)return{dereferencingMetadata:{error:s.error},contentStream:null,contentMetadata:{}};if(!r.fragment||r.query)return{dereferencingMetadata:{contentType:"application/did+json"},contentStream:n,contentMetadata:a};let{service:o=[],verificationMethod:i=[]}=n,c=new Set([t,r.fragment,`#${r.fragment}`]),u;for(let d of i)if(c.has(d.id)){u=d;break}for(let d of o)if(c.has(d.id)){u=d;break}return u?{dereferencingMetadata:{contentType:"application/did+json"},contentStream:u,contentMetadata:s}:{dereferencingMetadata:{error:"notFound"},contentStream:null,contentMetadata:{}}}};Qt();var PA=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 Rh({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new a1(e.resumableTaskStore,this.storageController),this._coreProtocols=new ag,this._coreProtocols.register(new Tr);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={["MessagesRead"]:new vb(r),["MessagesSubscribe"]:new Pb(r),["MessagesSync"]:new xb(r),["ProtocolsConfigure"]:new s1(r),["ProtocolsQuery"]:new i1(r),["RecordsCount"]:new o1(r),["RecordsDelete"]:new c1(r),["RecordsQuery"]:new d1(r),["RecordsRead"]:new u1(r),["RecordsSubscribe"]:new l1(r),["RecordsWrite"]:new f1(r)}}static async create(e){e.didResolver||(e.didResolver=new YK({didResolvers:[kK,WK,$w,JK],cache:new ZK}),e.ownsResolver=!0),e.tenantGate??=new cg;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 s=await this.validateTenant(e)??await this.validateMessageIntegrity(r);if(s!==void 0)return s;let{dataStream:a,subscriptionHandler:o}=n,i=r.descriptor.interface+r.descriptor.method;return await this.methodHandlers[i].handle({tenant:e,message:r,dataStream:a,subscriptionHandler:o})}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(s){return ut(s,400)}}};ht();Qt();ln();Dy();vi();w();function bde(t){return new Promise((e,r)=>{if(t.aborted){r(t.reason);return}t.addEventListener("abort",()=>{r(t.reason)})})}async function On(t,e){return e?Promise.race([t,bde(e)]):t}Oa();ir();la();k0();$n();c0();e2();Ja();Vs();zE();Il();w();Xm();w();import{Level as Pde}from"level";async function Ki(t,e){return new Pde(t,{...e,keyEncoding:"utf8"})}var Aa=class t{config;db;constructor(e,r){this.config={createLevelDatabase:Ki,...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 On(this.createLevelDatabase(),r?.signal);try{return await On(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 On(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 On(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 On(this.createLevelDatabase(),n?.signal),On(this.db.put(String(e),r),n?.signal)}async delete(e,r){return r?.signal?.throwIfAborted(),await On(this.createLevelDatabase(),r?.signal),On(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 On(this.createLevelDatabase(),r?.signal),On(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 On(this.createLevelDatabase(),e?.signal);let r=this.sublevelRange;if(!r)return;let n=this.root;if(n.db.supports.additionalMethods.compactRange)return On(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 Bf=class t{config;db;constructor(e,r){this.config={createLevelDatabase:Ki,...e},this.db=r??new Aa({...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),zt.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,s]of r)yield{cid:zt.decode(n),block:s}}async*deleteMany(e,r){for await(let n of e)await this.delete(n,r),yield n}async clear(){return this.db.clear()}};w();Vd();w();var kP=Nn(ko(),1);w();function xde(t){return t[Symbol.asyncIterator]!=null}function Sde(t){if(xde(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 QK=Sde;Fc();w();Tp();To();var $9=Nn(ko(),1);fy();w();Qu();rp();var XK=0,Ede="identity",e9=Zo,_de=t=>sl(XK,e9(t)),t9={code:XK,name:Ede,encode:e9,digest:_de};w();Tp();var r9=Nn(ko(),1);Fc();var kde=async(t,e,r,n,s,a,o,i)=>{let c=await o.get(t,i),u=q2(c),d=u,l=r;for(;n.length>0;){let f=n[0];if(f in d){n.shift(),l=`${l}/${f}`;let h=zt.asCID(d[f]);if(h!=null)return{entry:{type:"object",name:e,path:r,cid:t,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield u}},next:{cid:h,name:f,path:l,toResolve:n}};d=d[f]}else throw(0,r9.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:c,depth:a,size:BigInt(c.length),content:async function*(){yield u}}}},n9=kde;w();var s9=Nn(ko(),1);rp();Wc();w();function Tde(t,e,r,n){let s=BigInt(t.length),a=BigInt(e+s);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 Nf=Tde;w();var Mw=Nn(ko(),1),Ide=(t,e=0,r=t)=>{let n=BigInt(t),s=BigInt(e??0),a=BigInt(r);if(a!==n&&(a=s+a),a>n&&(a=n),s<0n)throw(0,Mw.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(s>n)throw(0,Mw.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(a<0n)throw(0,Mw.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(a>n)throw(0,Mw.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:s,end:a}},Qh=Ide;var Ade=t=>{async function*e(r={}){let{start:n,end:s}=Qh(t.length,r.offset,r.length),a=Nf(t,0n,n,s);r.onProgress?.(new mn("unixfs:exporter:progress:identity",{bytesRead:BigInt(a.byteLength),totalBytes:s-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Rde=async(t,e,r,n,s,a,o,i)=>{if(n.length>0)throw(0,s9.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let c=a0(t.multihash.bytes);return{entry:{type:"identity",name:e,path:r,cid:t,content:Ade(c.digest),depth:a,size:BigInt(c.digest.length),node:c.digest}}},i9=Rde;w();var o9=Nn(ko(),1);Wc();var Dde=t=>{async function*e(r={}){let{start:n,end:s}=Qh(t.length,r.offset,r.length),a=Nf(t,0n,n,s);r.onProgress?.(new mn("unixfs:exporter:progress:raw",{bytesRead:BigInt(a.byteLength),totalBytes:s-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Cde=async(t,e,r,n,s,a,o,i)=>{if(n.length>0)throw(0,o9.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let c=await o.get(t,i);return{entry:{type:"raw",name:e,path:r,cid:t,content:Dde(c),depth:a,size:BigInt(c.length),node:c}}},a9=Cde;w();To();var qw=Nn(ko(),1);Zd();w();To();qS();FS();var jde=async function(t){return(await dv.encode(t)).slice(0,8).reverse()},$de=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 s=parseInt(n.Name,16);e._putObjectAt(s,new Fa({hash:r._options.hash,bits:r._options.bits},e,s));return}await r.put(n.Name.substring(2),!0)}))},c9=t=>t.toString(16).toUpperCase().padStart(2,"0").substring(0,2),Mde=t=>{let e=t.bucket,r=[];for(;e._parent!=null;)r.push(e),e=e._parent;return r.push(e),r.reverse()},d9=async(t,e,r,n,s)=>{if(n==null){let d=fv({hashFn:jde});n={rootBucket:d,hamtDepth:1,lastBucket:d}}await $de(t.Links,n.lastBucket,n.rootBucket);let a=await n.rootBucket._findNewBucketAndPos(e),o=c9(a.pos),i=Mde(a);i.length>n.hamtDepth&&(n.lastBucket=i[n.hamtDepth],o=c9(n.lastBucket._posAtParent));let c=t.Links.find(d=>{if(d.Name==null)return!1;let l=d.Name.substring(0,2),f=d.Name.substring(2);return!(l!==o||f!==""&&f!==e)});if(c==null)return;if(c.Name!=null&&c.Name.substring(2)===e)return c.Hash;n.hamtDepth++;let u=await r.get(c.Hash,s);return t=Gc(u),d9(t,e,r,n,s)},u9=d9;w();w();w();function Ode(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[r](){return this}}}var pP=Ode;function Bde(t){return t[Symbol.asyncIterator]!=null}function Nde(t,e){let r=0;if(Bde(t))return async function*(){for await(let c of t)await e(c,r++)&&(yield c)}();let n=pP(t),{value:s,done:a}=n.next();if(a===!0)return function*(){}();let o=e(s,r++);if(typeof o.then=="function")return async function*(){await o&&(yield s);for(let c of n)await e(c,r++)&&(yield c)}();let i=e;return function*(){o===!0&&(yield s);for(let c of n)i(c,r++)&&(yield c)}()}var l9=Nde;w();function Ude(t){return t[Symbol.asyncIterator]!=null}function Lde(t,e){let r=0;if(Ude(t))return async function*(){for await(let c of t)yield e(c,r++)}();let n=pP(t),{value:s,done:a}=n.next();if(a===!0)return function*(){}();let o=e(s,r++);if(typeof o.then=="function")return async function*(){yield await o;for(let c of n)yield e(c,r++)}();let i=e;return function*(){yield o;for(let c of n)yield i(c,r++)}()}var Xh=Lde;w();w();function zi(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var hP=globalThis.CustomEvent??Event;async function*Uf(t,e={}){let r=e.concurrency??1/0;r<1&&(r=1/0);let n=e.ordered??!1,s=new EventTarget,a=[],o=zi(),i=zi(),c=!1,u,d=!1;s.addEventListener("task-complete",()=>{i.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of t){if(a.length===r&&(o=zi(),await o.promise),d)break;let m={done:!1};a.push(m),p().then(y=>{m.done=!0,m.ok=!0,m.value=y,s.dispatchEvent(new hP("task-complete"))},y=>{m.done=!0,m.err=y,s.dispatchEvent(new hP("task-complete"))})}c=!0,s.dispatchEvent(new hP("task-complete"))}catch(p){u=p,s.dispatchEvent(new hP("task-complete"))}});function l(){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 d=!0,o.resolve(),p.err;o.resolve()}}function*h(){for(;l();)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 d=!0,o.resolve(),m.err;o.resolve()}}for(;;){if(l()||(i=zi(),await i.promise),u!=null||(n?yield*f():yield*h(),u!=null))throw u;if(c&&a.length===0)break}}w();w();w();var mP=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}},em=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new mP(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 mP(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()}};var xA=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function yP(t={}){return Kde(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 Kde(t,e){e=e??{};let r=e.onEnd,n=new em,s,a,o,i=zi(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,S)=>{a=v=>{a=null,n.push(v);try{y(t(n))}catch(E){S(E)}return s}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{i.resolve(),i=zi()})}},u=y=>a!=null?a(y):(n.push(y),s),d=y=>(n=new em,a!=null?a({error:y}):(n.push({error:y}),s)),l=y=>{if(o)return s;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},f=y=>o?s:(o=!0,y!=null?d(y):u({done:!0})),h=()=>(n=new em,f(),{done:!0}),p=y=>(f(y),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:f,get readableLength(){return n.size},onEmpty:async y=>{let S=y?.signal;if(S?.throwIfAborted(),n.isEmpty())return;let v,E;S!=null&&(v=new Promise((k,A)=>{E=()=>{A(new xA)},S.addEventListener("abort",E)}));try{await Promise.race([i.promise,v])}finally{E!=null&&S!=null&&S?.removeEventListener("abort",E)}}},r==null)return s;let m=s;return s={[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:l,end(y){return m.end(y),r!=null&&(r(y),r=void 0),s},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},s}w();w();w();function zde(t){return t.reason}async function f9(t,e,r){if(e==null)return t;let n=r?.translateError??zde;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([t,new Promise((a,o)=>{s=()=>{o(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var SA=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=zi(),this.haveNext=zi()}[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=zi(),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=zi(),await f9(this.readNext.promise,r?.signal,r)}};function p9(){return new SA}function qde(t){return t[Symbol.asyncIterator]!=null}async function Fde(t,e,r){try{await Promise.all(t.map(async n=>{for await(let s of n)await e.push(s,{signal:r}),r.throwIfAborted()})),await e.end(void 0,{signal:r})}catch(n){await e.end(n,{signal:r}).catch(()=>{})}}async function*Gde(t){let e=new AbortController,r=p9();Fde(t,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort()}}function*Wde(t){for(let e of t)yield*e}function Vde(...t){let e=[];for(let r of t)qde(r)||e.push(r);return e.length===t.length?Wde(e):Gde(t)}var h9=Vde;function tm(t,...e){if(t==null)throw new Error("Empty pipeline");if(EA(t)){let n=t;t=()=>n.source}else if(y9(t)||m9(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&EA(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++)EA(r[n])&&(r[n]=Jde(r[n]));return Hde(...r)}var Hde=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},m9=t=>t?.[Symbol.asyncIterator]!=null,y9=t=>t?.[Symbol.iterator]!=null,EA=t=>t==null?!1:t.sink!=null&&t.source!=null,Jde=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=yP({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let s,a=t.source;if(m9(a))s=async function*(){yield*a,n.end()};else if(y9(a))s=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return h9(n,s())}return t.source};Wc();var Zde=(t,e,r,n,s,a,o)=>{async function*i(c={}){let u=c.offset??0,d=c.length??e.Links.length,l=e.Links.slice(u,d);c.onProgress?.(new mn("unixfs:exporter:walk:directory",{cid:t})),yield*tm(l,f=>Xh(f,h=>async()=>{let p=h.Name??"",m=`${n}/${p}`;return(await s(h.Hash,p,m,[],a+1,o,c)).entry}),f=>Uf(f,{ordered:!0}),f=>l9(f,h=>h!=null))}return i},g9=Zde;w();To();var Kf=Nn(ko(),1);Zd();fy();w();w();var kA=Nn(v9(),1);w();var Bw=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},TA=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},b9=t=>globalThis.DOMException===void 0?new TA(t):new DOMException(t),P9=t=>{let e=t.reason===void 0?b9("This operation was aborted."):t.reason;return e instanceof Error?e:b9(e)};function IA(t,e,r,n){let s,a=new Promise((o,i)=>{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){o(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&i(P9(c)),c.addEventListener("abort",()=>{i(P9(c))})}s=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{o(r())}catch(d){i(d)}return}let c=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new Bw(c);typeof t.cancel=="function"&&t.cancel(),i(u)},e),(async()=>{try{o(await t)}catch(c){i(c)}finally{n.customTimers.clearTimeout.call(void 0,s)}})()});return a.clear=()=>{clearTimeout(s),s=void 0},a}w();w();function AA(t,e,r){let n=0,s=t.length;for(;s>0;){let a=Math.trunc(s/2),o=n+a;r(t[o],e)<=0?(n=++o,s-=a+1):s=a}return n}var Lf=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)},Td,RA=class{constructor(){Td.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&Lf(this,Td,"f")[this.size-1].priority>=r.priority){Lf(this,Td,"f").push(n);return}let s=AA(Lf(this,Td,"f"),n,(a,o)=>o.priority-a.priority);Lf(this,Td,"f").splice(s,0,n)}dequeue(){let e=Lf(this,Td,"f").shift();return e?.run}filter(e){return Lf(this,Td,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return Lf(this,Td,"f").length}};Td=new WeakMap;var x9=RA;var dn=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},Ge=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)},Dn,Uw,Lw,Ju,SP,Kw,wP,Ra,Nw,go,vP,wo,zw,Hu,bP,S9,E9,T9,_9,k9,PP,DA,CA,EP,I9,xP,_P=class extends Error{},jA=class extends kA.default{constructor(e){var r,n,s,a;if(super(),Dn.add(this),Uw.set(this,void 0),Lw.set(this,void 0),Ju.set(this,0),SP.set(this,void 0),Kw.set(this,void 0),wP.set(this,0),Ra.set(this,void 0),Nw.set(this,void 0),go.set(this,void 0),vP.set(this,void 0),wo.set(this,0),zw.set(this,void 0),Hu.set(this,void 0),bP.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:x9,...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=(s=e.interval)===null||s===void 0?void 0:s.toString())!==null&&a!==void 0?a:""}\` (${typeof e.interval})`);dn(this,Uw,e.carryoverConcurrencyCount,"f"),dn(this,Lw,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),dn(this,SP,e.intervalCap,"f"),dn(this,Kw,e.interval,"f"),dn(this,go,new e.queueClass,"f"),dn(this,vP,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,dn(this,bP,e.throwOnTimeout===!0,"f"),dn(this,Hu,e.autoStart===!1,"f")}get concurrency(){return Ge(this,zw,"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})`);dn(this,zw,e,"f"),Ge(this,Dn,"m",EP).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:Ge(this,bP,"f"),...r},new Promise((n,s)=>{Ge(this,go,"f").enqueue(async()=>{var a,o,i;dn(this,wo,(o=Ge(this,wo,"f"),o++,o),"f"),dn(this,Ju,(i=Ge(this,Ju,"f"),i++,i),"f");try{if(!((a=r.signal)===null||a===void 0)&&a.aborted)throw new _P("The task was aborted.");let c=e({signal:r.signal});r.timeout&&(c=IA(Promise.resolve(c),r.timeout)),r.signal&&(c=Promise.race([c,Ge(this,Dn,"m",I9).call(this,r.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Bw&&!r.throwOnTimeout){n();return}s(c),this.emit("error",c)}finally{Ge(this,Dn,"m",T9).call(this)}},r),this.emit("add"),Ge(this,Dn,"m",PP).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return Ge(this,Hu,"f")?(dn(this,Hu,!1,"f"),Ge(this,Dn,"m",EP).call(this),this):this}pause(){dn(this,Hu,!0,"f")}clear(){dn(this,go,new(Ge(this,vP,"f")),"f")}async onEmpty(){Ge(this,go,"f").size!==0&&await Ge(this,Dn,"m",xP).call(this,"empty")}async onSizeLessThan(e){Ge(this,go,"f").size<e||await Ge(this,Dn,"m",xP).call(this,"next",()=>Ge(this,go,"f").size<e)}async onIdle(){Ge(this,wo,"f")===0&&Ge(this,go,"f").size===0||await Ge(this,Dn,"m",xP).call(this,"idle")}get size(){return Ge(this,go,"f").size}sizeBy(e){return Ge(this,go,"f").filter(e).length}get pending(){return Ge(this,wo,"f")}get isPaused(){return Ge(this,Hu,"f")}};Uw=new WeakMap,Lw=new WeakMap,Ju=new WeakMap,SP=new WeakMap,Kw=new WeakMap,wP=new WeakMap,Ra=new WeakMap,Nw=new WeakMap,go=new WeakMap,vP=new WeakMap,wo=new WeakMap,zw=new WeakMap,Hu=new WeakMap,bP=new WeakMap,Dn=new WeakSet,S9=function(){return Ge(this,Lw,"f")||Ge(this,Ju,"f")<Ge(this,SP,"f")},E9=function(){return Ge(this,wo,"f")<Ge(this,zw,"f")},T9=function(){var e;dn(this,wo,(e=Ge(this,wo,"f"),e--,e),"f"),Ge(this,Dn,"m",PP).call(this),this.emit("next")},_9=function(){Ge(this,Dn,"m",CA).call(this),Ge(this,Dn,"m",DA).call(this),dn(this,Nw,void 0,"f")},k9=function(){let e=Date.now();if(Ge(this,Ra,"f")===void 0){let r=Ge(this,wP,"f")-e;if(r<0)dn(this,Ju,Ge(this,Uw,"f")?Ge(this,wo,"f"):0,"f");else return Ge(this,Nw,"f")===void 0&&dn(this,Nw,setTimeout(()=>{Ge(this,Dn,"m",_9).call(this)},r),"f"),!0}return!1},PP=function(){if(Ge(this,go,"f").size===0)return Ge(this,Ra,"f")&&clearInterval(Ge(this,Ra,"f")),dn(this,Ra,void 0,"f"),this.emit("empty"),Ge(this,wo,"f")===0&&this.emit("idle"),!1;if(!Ge(this,Hu,"f")){let e=!Ge(this,Dn,"a",k9);if(Ge(this,Dn,"a",S9)&&Ge(this,Dn,"a",E9)){let r=Ge(this,go,"f").dequeue();return r?(this.emit("active"),r(),e&&Ge(this,Dn,"m",DA).call(this),!0):!1}}return!1},DA=function(){Ge(this,Lw,"f")||Ge(this,Ra,"f")!==void 0||(dn(this,Ra,setInterval(()=>{Ge(this,Dn,"m",CA).call(this)},Ge(this,Kw,"f")),"f"),dn(this,wP,Date.now()+Ge(this,Kw,"f"),"f"))},CA=function(){Ge(this,Ju,"f")===0&&Ge(this,wo,"f")===0&&Ge(this,Ra,"f")&&(clearInterval(Ge(this,Ra,"f")),dn(this,Ra,void 0,"f")),dn(this,Ju,Ge(this,Uw,"f")?Ge(this,wo,"f"):0,"f"),Ge(this,Dn,"m",EP).call(this)},EP=function(){for(;Ge(this,Dn,"m",PP).call(this););},I9=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new _P("The task was aborted."))},{once:!0})})},xP=async function(e,r){return new Promise(n=>{let s=()=>{r&&!r()||(this.off(e,s),n())};this.on(e,s)})};var A9=jA;Wc();async function R9(t,e,r,n,s,a,o){if(e instanceof Uint8Array){let u=Nf(e,n,s,a);r.push(u);return}if(e.Data==null)throw(0,Kf.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let i;try{i=rs.unmarshal(e.Data)}catch(u){throw(0,Kf.default)(u,"ERR_NOT_UNIXFS")}if(i.data!=null){let u=i.data,d=Nf(u,n,s,a);r.push(d),n+=BigInt(d.byteLength)}let c=[];if(e.Links.length!==i.blockSizes.length)throw(0,Kf.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let u=0;u<e.Links.length;u++){let d=e.Links[u],l=n,f=l+i.blockSizes[u];if((s>=l&&s<f||a>=l&&a<=f||s<l&&a>f)&&c.push({link:d,blockStart:n}),n=f,n>a)break}await tm(c,u=>Xh(u,d=>async()=>{let l=await t.get(d.link.Hash,o);return{...d,block:l}}),u=>Uf(u,{ordered:!0}),async u=>{for await(let{link:d,block:l,blockStart:f}of u){let h;switch(d.Hash.code){case sy:h=Gc(l);break;case Yd:h=l;break;default:r.end((0,Kf.default)(new Error(`Unsupported codec: ${d.Hash.code}`),"ERR_NOT_UNIXFS"));return}let p=new A9({concurrency:1});p.on("error",m=>{r.end(m)}),p.add(async()=>{o.onProgress?.(new mn("unixfs:exporter:walk:file",{cid:d.Hash})),await R9(t,h,r,f,s,a,o)}),await p.onIdle()}}),n>=a&&r.end()}var Xde=(t,e,r,n,s,a,o)=>{async function*i(c={}){let u=r.fileSize();if(u===void 0)throw new Error("File was a directory");let{start:d,end:l}=Qh(u,c.offset,c.length);if(l===0n)return;let f=0n,h=l-d,p=yP();c.onProgress?.(new mn("unixfs:exporter:walk:file",{cid:t})),R9(o,e,p,0n,d,l,c).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,Kf.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(),c.onProgress?.(new mn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:h,fileSize:u})),yield m}if(f<h)throw(0,Kf.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return i},$A=Xde;w();To();Wc();var eue=(t,e,r,n,s,a,o)=>{function i(c={}){return c.onProgress?.(new mn("unixfs:exporter:walk:hamt-sharded-directory",{cid:t})),D9(e,n,s,a,o,c)}return i};async function*D9(t,e,r,n,s,a){let o=t.Links,i=tm(o,c=>Xh(c,u=>async()=>{let d=u.Name!=null?u.Name.substring(2):null;if(d!=null&&d!==""){let l=await r(u.Hash,d,`${e}/${d}`,[],n+1,s,a);return{entries:l.entry==null?[]:[l.entry]}}else{let l=await s.get(u.Hash,a);return t=Gc(l),a.onProgress?.(new mn("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:D9(t,e,r,n,s,a)}}}),c=>Uf(c,{ordered:!0}));for await(let{entries:c}of i)yield*c}var C9=eue;var tue=(t,e)=>t.Links.find(n=>n.Name===e)?.Hash,rue={raw:$A,file:$A,directory:g9,"hamt-sharded-directory":C9,metadata:(t,e,r,n,s,a,o)=>()=>[],symlink:(t,e,r,n,s,a,o)=>()=>[]},nue=async(t,e,r,n,s,a,o,i)=>{let c=await o.get(t,i),u=Gc(c),d,l;if(e==null&&(e=t.toString()),u.Data==null)throw(0,qw.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{d=rs.unmarshal(u.Data)}catch(h){throw(0,qw.default)(h,"ERR_NOT_UNIXFS")}if(r==null&&(r=e),n.length>0){let h;if(d?.type==="hamt-sharded-directory"?h=await u9(u,n[0],o):h=tue(u,n[0]),h==null)throw(0,qw.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let p=n.shift(),m=`${r}/${p}`;l={cid:h,toResolve:n,name:p??"",path:m}}let f=rue[d.type](t,u,d,r,s,a,o);if(f==null)throw(0,qw.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return d.isDirectory()?{entry:{type:"directory",name:e,path:r,cid:t,content:f,unixfs:d,depth:a,node:u,size:d.fileSize()},next:l}:{entry:{type:"file",name:e,path:r,cid:t,content:f,unixfs:d,depth:a,node:u,size:d.fileSize()},next:l}},j9=nue;var sue={[sy]:j9,[Yd]:a9,[Wd]:n9,[t9.code]:i9},M9=async(t,e,r,n,s,a,o)=>{let i=sue[t.code];if(i==null)throw(0,$9.default)(new Error(`No resolver for code ${t.code}`),"ERR_NO_RESOLVER");return i(t,e,r,n,M9,s,a,o)},O9=M9;var iue=(t="")=>(t.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),oue=t=>{if(t instanceof Uint8Array)return{cid:zt.decode(t),toResolve:[]};let e=zt.asCID(t);if(e!=null)return{cid:e,toResolve:[]};if(typeof t=="string"){t.indexOf("/ipfs/")===0&&(t=t.substring(6));let r=iue(t);return{cid:zt.parse(r[0]),toResolve:r.slice(1)}}throw(0,kP.default)(new Error(`Unknown path type ${t}`),"ERR_BAD_PATH")};async function*aue(t,e,r={}){let{cid:n,toResolve:s}=oue(t),a=n.toString(),o=a,i=s.length;for(;;){let c=await O9(n,a,o,s,i,e,r);if(c.entry==null&&c.next==null)throw(0,kP.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");if(c.entry!=null&&(yield c.entry),c.next==null)return;s=c.next.toResolve,n=c.next.cid,a=c.next.name,o=c.next.path}}async function B9(t,e,r={}){let n=await QK(aue(t,e,r));if(n==null)throw(0,kP.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");return n}VS();var MA=new TextEncoder,TP=new TextDecoder,OA=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:Ki,...e},this.blockstore=new Bf({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,s){let a=await this.getRefsPartition(e,r),o=await a.get(n);if(o){await s.cancel();let{dataSize:l}=JSON.parse(TP.decode(o));return{dataSize:l}}let i=await this.getRefcountsPartition(),c=await i.get(n),u=c?JSON.parse(TP.decode(c)):{count:0,dataSize:0},d;if(u.count>0)await s.cancel(),d=u.dataSize;else{let l=await this.getBlocksPartition(n),f=my([{content:ts.asAsyncIterable(s)}],l,{cidVersion:1}),h;for await(h of f);d=Number(h.unixfs?.fileSize()??h.size)}return await a.put(n,MA.encode(JSON.stringify({dataSize:d}))),await i.put(n,MA.encode(JSON.stringify({count:u.count+1,dataSize:d}))),{dataSize:d}}async get(e,r,n){let a=await(await this.getRefsPartition(e,r)).get(n);if(!a)return;let{dataSize:o}=JSON.parse(TP.decode(a)),i=await this.getBlocksPartition(n);if(!await i.has(n))return;let d=(await B9(n,i)).content(),l=new ReadableStream({async pull(f){let h=await d.next();h.done?f.close():f.enqueue(h.value)}});return{dataSize:o,dataStream:l}}async delete(e,r,n){let s=await this.getRefsPartition(e,r);if(!await s.get(n))return;await s.delete(n);let o=await this.getRefcountsPartition(),i=await o.get(n);if(!i)return;let c=JSON.parse(TP.decode(i)),u=c.count-1;u<=0?(await(await this.getBlocksPartition(n)).clear(),await o.delete(n)):await o.put(n,MA.encode(JSON.stringify({count:u,dataSize:c.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")}};w();hs();JS();Ja();w();ya();Ja();var IP="";async function N9(t,e,r){let n=`__compound:${r.name}__`;return(await t.partition(e)).partition(n)}function U9(t,e,r,n,s){let a=[];for(let u of r.properties){let d=e[u];if(d===void 0||Array.isArray(d))return;a.push(n(d))}let o=e[r.sortProperty];if(o===void 0||Array.isArray(o))return;let i=a.join(IP),c=n(o);return i+IP+c+s+t}function L9(t,e,r){let n=[];for(let s of e.properties){let a=t[s];if(a===void 0||typeof a=="object")return;n.push(r(a))}return n.join(IP)+IP}function K9(t,e,r,n,s,a){let o=U9(r.messageCid,r.indexes,n,s,a);if(o!==void 0)return q9(t,e,`__compound:${n.name}__`,{type:"put",key:o,value:JSON.stringify(r)})}function z9(t,e,r,n,s,a,o){let i=U9(r,n,s,a,o);if(i!==void 0)return q9(t,e,`__compound:${s.name}__`,{type:"del",key:i})}async function q9(t,e,r,n){return(await t.partition(e)).createPartitionOperation(r,n)}function BA(t,e,r){let n,s=0;for(let a of r){if(a.sortProperty!==e.sortProperty)continue;let o=!0;for(let i of a.properties){let c=t[i];if(c===void 0||typeof c=="object"){o=!1;break}}o&&a.properties.length>s&&(n=a,s=a.properties.length)}return n}async function F9(t,e,r,n,s,a,o,i,c){let{sortDirection:u=1,cursor:d,limit:l}=n,f=L9(r,s,a);if(f===void 0)return i(e,[r],n,c);let h=await N9(t,e,s),p={};if(d!==void 0){let E=a(d.value),k=f+E+o+d.messageCid;u===1?(p.gt=k,p.lt=f+"\xFF"):(p.lt=k,p.gt=f,p.reverse=!0)}else u===1?(p.gt=f,p.lt=f+"\xFF"):(p.gt=f,p.lt=f+"\xFF",p.reverse=!0);let m=new Set(s.properties),y={},S=!1;for(let E in r)m.has(E)||(y[E]=r[E],S=!0);let v=[];for await(let[E,k]of h.iterator(p,c)){if(l!==void 0&&v.length===l)break;let A=JSON.parse(k);S&&!Wt.matchFilter(A.indexes,y)||v.push(A)}return v}async function G9(t,e,r,n,s,a,o){let i=L9(r,n,s);if(i===void 0)return(await a(e,[r],{sortProperty:n.sortProperty},o)).length;let c=await N9(t,e,n),u=new Set(n.properties),d=!1,l={};for(let p in r)u.has(p)||(l[p]=r[p],d=!0);let f={gt:i,lt:i+"\xFF"},h=0;if(d)for await(let[p,m]of c.iterator(f,o)){let y=JSON.parse(m);Wt.matchFilter(y.indexes,l)&&h++}else for await(let[p,m]of c.iterator(f,o))h++;return h}ht();ya();var W9="index",rm=class t{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:Ki,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new Aa({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,s){if(Tl(n))throw new ne("IndexMissingIndexableProperty","Index must include at least one valid indexable property");let a={messageCid:r,indexes:n},o=[];for(let d in n){let l=n[d];if(Array.isArray(l))for(let f of l){let h=this.createPutIndexedItemOperation(e,a,d,f);o.push(h)}else{let f=this.createPutIndexedItemOperation(e,a,d,l);o.push(f)}}for(let d of this._compoundIndexes){let l=K9(this.db,e,a,d,t.encodeValue,t.delimiter);l!==void 0&&o.push(l)}let i=this.createOperationForIndexesLookupPartition(e,{type:"put",key:r,value:JSON.stringify(n)});o.push(i);let c=await Promise.all(o);await(await this.db.partition(e)).batch(c,s)}async delete(e,r,n){let s=[],a=await this.getIndexes(e,r);if(a===void 0)return;let o=this.createOperationForIndexesLookupPartition(e,{type:"del",key:r});s.push(o);for(let u in a){let d=a[u];if(Array.isArray(d))for(let l of d){let f=this.createDeleteIndexedItemOperation(e,r,u,l);s.push(f)}else{let l=this.createDeleteIndexedItemOperation(e,r,u,d);s.push(l)}}for(let u of this._compoundIndexes){let d=z9(this.db,e,r,a,u,t.encodeValue,t.delimiter);d!==void 0&&s.push(d)}let i=await Promise.all(s);await(await this.db.partition(e)).batch(i,n)}async createPutIndexedItemOperation(e,r,n,s){let{messageCid:a}=r,o=t.keySegmentJoin(t.encodeValue(s),a);return this.createOperationForIndexPartition(e,n,{type:"put",key:o,value:JSON.stringify(r)})}async createDeleteIndexedItemOperation(e,r,n,s){let a=t.keySegmentJoin(t.encodeValue(s),r);return this.createOperationForIndexPartition(e,n,{type:"del",key:a})}async createOperationForIndexPartition(e,r,n){let s=await this.db.partition(e),a=t.getIndexPartitionName(r);return s.createPartitionOperation(a,n)}async createOperationForIndexesLookupPartition(e,r){return(await this.db.partition(e)).createPartitionOperation(W9,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(W9)}async query(e,r,n,s){if(r.length===1&&!Tl(r[0])){let a=BA(r[0],n,this._compoundIndexes);if(a!==void 0)return F9(this.db,e,r[0],n,a,t.encodeValue,t.delimiter,this.queryWithIteratorPaging.bind(this),s)}return t.shouldQueryWithInMemoryPaging(r,n)?this.queryWithInMemoryPaging(e,r,n,s):this.queryWithIteratorPaging(e,r,n,s)}async count(e,r,n,s){if(r.length===1&&!Tl(r[0])){let o=BA(r[0],{...n},this._compoundIndexes);if(o!==void 0)return G9(this.db,e,r[0],o,t.encodeValue,this.query.bind(this),s)}return(await this.query(e,r,{...n},s)).length}async queryWithIteratorPaging(e,r,n,s){let{cursor:a,limit:o}=n,i=a?this.createStartingKeyFromCursor(a):"",c=[];for await(let u of this.getIndexIterator(e,i,n,s)){if(o!==void 0&&o===c.length)break;let{indexes:d}=u;Wt.matchAnyFilter(d,r)&&c.push(u)}return c}async*getIndexIterator(e,r,n,s){let{sortProperty:a,sortDirection:o=1,cursor:i}=n,c={gt:r};o===-1&&(c.reverse=!0,i!==void 0&&(c.lt=r,delete c.gt));let u=await this.getIndexPartition(e,a);for await(let[d,l]of u.iterator(c,s)){let{indexes:f,messageCid:h}=JSON.parse(l);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:s}=e,a=s[r];if(a===void 0)throw new ne("IndexInvalidCursorSortProperty",`the sort property '${r}' is not defined within the given item.`);if(typeof a=="boolean"||Array.isArray(a))throw new 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,s){let{sortProperty:a,sortDirection:o=1,cursor:i,limit:c}=n,u=i?this.createStartingKeyFromCursor(i):void 0,d=new Map;r.length===0&&(r=[{}]);try{for(let p of r)await this.executeSingleFilterQuery(e,p,a,d,s)}catch(p){if(p.code==="IndexInvalidSortPropertyInMemory")return[]}let l=[...d.values()].sort((p,m)=>this.sortItems(p,m,a,o)),f=u!==void 0?this.findCursorStartingIndex(l,o,a,u):0;if(f<0)return[];let h=c!==void 0?f+c:void 0;return l.slice(f,h)}async executeSingleFilterQuery(e,r,n,s,a){let o=c=>{for(let u of c)if(!(s.has(u.messageCid)||!Wt.matchFilter(u.indexes,r))){if(u.indexes[n]===void 0)throw new ne("IndexInvalidSortPropertyInMemory",`invalid sort property ${n}`);s.set(u.messageCid,u)}};if(Tl(r)){let c=await this.getAllItems(e,n);o(c);return}let i=jv.reduceFilter(r);for(let c in i){let u=i[c];if(Wt.isEqualFilter(u)){let d=await this.filterExactMatches(e,c,u,a);o(d)}else if(Wt.isOneOfFilter(u))for(let d of new Set(u)){let l=await this.filterExactMatches(e,c,d,a);o(l)}else if(Wt.isRangeFilter(u)){let d=await this.filterRangeMatches(e,c,u,a);o(d)}}}async getAllItems(e,r){let n=await this.getIndexPartition(e,r),s=[];for await(let[a,o]of n.iterator())s.push(JSON.parse(o));return s}async filterExactMatches(e,r,n,s){let a=t.keySegmentJoin(t.encodeValue(n)),o={gt:a},i=await this.getIndexPartition(e,r),c=[];for await(let[u,d]of i.iterator(o,s)){if(!u.startsWith(a))break;c.push(JSON.parse(d))}return c}async filterRangeMatches(e,r,n,s){let a={};for(let c in n){let u=c,d=t.encodeValue(n[u]);u==="lte"?a[u]=d+"\xFF":a[u]=d}a.gt===void 0&&a.gte===void 0&&(a.reverse=!0);let o=[],i=await this.getIndexPartition(e,r);for await(let[c,u]of i.iterator(a,s))"gt"in n&&this.extractIndexValueFromKey(c)===t.encodeValue(n.gt)||o.push(JSON.parse(u));return o}sortItems(e,r,n,s){let a=e.indexes[n],o=r.indexes[n],i=t.encodeValue(a)+e.messageCid,c=t.encodeValue(o)+r.messageCid;return s===1?yy(i,c):yy(c,i)}findCursorStartingIndex(e,r,n,s){let a=c=>{let{messageCid:u,indexes:d}=c,l=d[n],f=t.keySegmentJoin(t.encodeValue(l),u);return r===1?f>s:f<s},o=0,i=e.length;for(;o<i;){let c=o+i>>>1;a(e[c])?i=c:o=c+1}return o<e.length?o:-1}async getIndexes(e,r){let s=await(await this.getIndexesLookupPartition(e)).get(r);if(s!==void 0)return JSON.parse(s)}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="!",s=String(Number.MAX_SAFE_INTEGER).length,a=e<0?n:"",o=e<0?r:0;return a+String(e+o).padStart(s,"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}};w();w();Xm();J2();function AP({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*cue(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let s=[...t,r],a=zt.asCID(n);a?yield[s.join("/"),a]:typeof n=="object"&&(yield*NA(n,s))}else{let r=zt.asCID(e);r?yield[t.join("/"),r]:yield*NA(e,t)}}function*NA(t,e){if(t==null||t instanceof Uint8Array)return;let r=zt.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,s]of Object.entries(t)){let a=[...e,n];yield*cue(a,s)}}function*due(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let s=[...t,r];yield s.join("/"),typeof n=="object"&&!zt.asCID(n)&&(yield*UA(n,s))}else yield*UA(e,t)}function*UA(t,e){if(!(t==null||typeof t!="object"))for(let[r,n]of Object.entries(t)){let s=[...e,r];yield s.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!zt.asCID(n)&&(yield*due(s,n))}}function uue(t,e){let r=t;for(let[n,s]of e.entries()){if(r=r[s],r==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(o=>`[${JSON.stringify(o)}]`).join("")}`);let a=zt.asCID(r);if(a)return{value:a,remaining:e.slice(n+1).join("/")}}return{value:r}}var RP=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:AP(),bytes:AP(),value:AP(),asBlock:AP()})}links(){return NA(this.value,[])}tree(){return UA(this.value,[])}get(e="/"){return uue(this.value,e.split("/").filter(Boolean))}};async function V9({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),s=await r.digest(n),a=zt.create(1,e.code,s);return new RP({value:t,bytes:n,cid:a})}async function H9({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),s=await r.digest(t),a=zt.create(1,e.code,s);return new RP({value:n,bytes:t,cid:a})}Tp();Vc();Fc();ir();Rd();Ja();var fue=[{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"}],LA=class t{config;blockstore;index;constructor(e={}){this.config={blockstoreLocation:"MESSAGESTORE",indexLocation:"INDEX",createLevelDatabase:Ki,...e},this.blockstore=new Bf({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new rm({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??fue})}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 s=await On(this.blockstore.partition(e),n?.signal),a=zt.parse(r),o=await s.get(a,n);return o?(await On(H9({bytes:o,codec:qc,hasher:Pn}),n?.signal)).value:void 0}async query(e,r,n,s,a){a?.signal?.throwIfAborted();let o=t.buildQueryOptions(n,s),i=await this.index.query(e,r,o,a),c;s?.limit!==void 0&&s.limit<i.length&&(i.splice(-1),c=rm.createCursorFromLastArrayItem(i,o.sortProperty));let u=[];for(let d=0;d<i.length;d++){let{messageCid:l}=i[d],f=await this.get(e,l,a);f&&u.push(f)}return{messages:u,cursor:c}}async count(e,r,n,s){s?.signal?.throwIfAborted();let a=t.buildQueryOptions(n);return this.index.count(e,r,a,s)}static buildQueryOptions(e={},r={}){let{limit:n,cursor:s}=r,{dateCreated:a,datePublished:o,messageTimestamp:i}=e,c=1,u="messageTimestamp";return a!==void 0?u="dateCreated":o!==void 0?u="datePublished":i!==void 0&&(u="messageTimestamp"),e[u]!==void 0&&(c=e[u]),n!==void 0&&n>0&&(n=n+1),{sortDirection:c,sortProperty:u,limit:n,cursor:s}}async delete(e,r,n){n?.signal?.throwIfAborted();let s=await On(this.blockstore.partition(e),n?.signal),a=zt.parse(r);await s.delete(a,n),await this.index.delete(e,r,n)}async put(e,r,n,s){s?.signal?.throwIfAborted();let a=await On(this.blockstore.partition(e),s?.signal),o=await On(V9({value:r,codec:qc,hasher:Pn}),s?.signal),i=Ar.parseCid(await we.getCid(r));await a.put(i,o.bytes,s);let c=i.toString();await this.index.put(e,c,n,s)}async clear(){await this.blockstore.clear(),await this.index.clear()}};w();Vc();var KA=class t{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:Ki,...e},this.db=new Aa({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 Ar.computeCid(e),s={id:n,timeout:Date.now()+r*1e3,retryCount:0,task:e};return await this.db.put(n,JSON.stringify(s)),s}async grab(e){let r=[];for await(let[n,s]of this.db.iterator()){let a=JSON.parse(s);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 s=JSON.parse(n);s.timeout=Date.now()+r*1e3,await this.db.put(s.id,JSON.stringify(s))}}async delete(e){return this.db.delete(e)}async clear(){await this.db.clear()}};w();w();function J9(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(s){s(r)}),(n=t.get("*"))&&n.slice().map(function(s){s(e,r)})}}}ya();ht();var Z9="events",zA=class t{emitter=J9();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 ne("EventLogNotOpenError","a message emitted when EventLog is closed")),"";let a=(this.tenantSeqs.get(e)??0)+1;this.tenantSeqs.set(e,a);let o=this.tenantLogs.get(e);if(o===void 0&&(o=new Map,this.tenantLogs.set(e,o)),o.set(a,{event:r,indexes:n}),o.size>this.maxEventsPerTenant){let c=o.size-this.maxEventsPerTenant,u=0;for(let d of o.keys()){if(u>=c)break;o.delete(d),u++}}let i=`${e}_${Z9}`;return this.emitter.emit(i,{tenant:e,event:r,indexes:n,seq:a}),String(a)}async read(e,r={}){let{cursor:n,limit:s,filters:a}=r,o=n!==void 0?t.parseCursor(n):void 0,i=this.tenantLogs.get(e);if(i===void 0||i.size===0)return{events:[],cursor:n};let c=[],u=s??Number.MAX_SAFE_INTEGER;for(let[l,f]of i)if(!(o!==void 0&&l<=o)&&!(a!==void 0&&a.length>0&&!Wt.matchAnyFilter(f.indexes,a))&&(c.push({seq:l,event:f.event,indexes:f.indexes}),c.length>=u))break;let d=c.length>0?c[c.length-1].seq:void 0;return{events:c,cursor:d!==void 0?String(d):n}}static parseCursor(e){let r=Number(e);if(Number.isNaN(r)||r<0)throw new ne("EventLogNotOpenError",`invalid cursor: '${e}'`);return r}async subscribe(e,r,n,s){let a=`${e}_${Z9}`,{cursor:o,filters:i}=s??{};if(o!==void 0){let u=t.parseCursor(o),d=[],l=!1,f=y=>{i!==void 0&&i.length>0&&!Wt.matchAnyFilter(y.indexes,i)||(l?n({type:"event",cursor:String(y.seq),event:y.event}):d.push({event:y.event,seq:y.seq}))};this.emitter.on(a,f);let h=await this.read(e,{cursor:o,filters:i}),p=h.cursor??o,m=h.cursor!==void 0?Number(h.cursor):u;for(let y of h.events)n({type:"event",cursor:String(y.seq),event:y.event});l=!0;for(let y of d)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 c=u=>{i!==void 0&&i.length>0&&!Wt.matchAnyFilter(u.indexes,i)||n({type:"event",cursor:String(u.seq),event:u.event})};return this.emitter.on(a,c),{id:r,close:async()=>{this.emitter.off(a,c)}}}async trim(e,r){let n=this.tenantLogs.get(e);if(n!==void 0)if(typeof r=="number")for(let s of n.keys())if(s<r)n.delete(s);else break;else for(let[s,a]of n)(a.indexes.messageTimestamp??"")<r&&n.delete(s)}};w();vu();w();vu();var Fw=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=Vn(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=Vn(e),s=this.serializeNode(r);await this.nodesPartition.put(n,JSON.stringify(s))}async deleteNode(e){this.ensureInitialized();let r=Vn(e);await this.nodesPartition.delete(r)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return ef(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",Vn(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:Vn(e.leftHash),rightHash:Vn(e.rightHash)}:{type:"leaf",keyHash:Vn(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:ef(e.leftHash),rightHash:ef(e.rightHash)}:{type:"leaf",keyHash:ef(e.keyHash),valueCid:e.valueCid}}};w();vu();var Gw=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await ph()}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 Xl(e),n=await ug(r,e),s={type:"leaf",keyHash:r,valueCid:e};await this.store.putNode(n,s);let a=await this.getRoot(),o=await this.insertAtNode(a,r,n,s,0);return await this.store.setRoot(o),o}async delete(e){let r=await Xl(e),n=await this.getRoot(),s=await this.deleteAtNode(n,r,0);return await this.store.setRoot(s),s}async has(e){let r=await Xl(e),n=await this.getRoot();return this.existsAtNode(n,r,0)}async getProof(e){let r=await Xl(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(Xr(r,this.defaultHashes[n]))return this.defaultHashes[e.length];let s=await this.store.getNode(r);if(s===void 0||s.type==="leaf")return s!==void 0&&s.type==="leaf"?this.computeSubtreeHashForLeaf(s,n,e):this.defaultHashes[e.length];let a=s;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(Xr(r,this.defaultHashes[n]))return[];let s=await this.store.getNode(r);if(s===void 0)return[];if(s.type==="leaf")return this.leafMatchesPrefix(s.keyHash,e)?[s.valueCid]:[];let a=s;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(Xr(r,n))return{onlyLocal:[],onlyRemote:[]};let s=[],a=[];return await this.diffAtNode(r,n,0,this,e,s,a),{onlyLocal:s,onlyRemote:a}}async insertAtNode(e,r,n,s,a){if(a>=bi||Xr(e,this.defaultHashes[a]))return n;let o=await this.store.getNode(e);if(o===void 0)return n;if(o.type==="leaf")return Xr(o.keyHash,r)?(await this.store.deleteNode(e),n):this.splitLeaves(o,e,s,n,a);let i=o,c=co(r,a),u,d;c?(u=i.leftHash,d=await this.insertAtNode(i.rightHash,r,n,s,a+1)):(u=await this.insertAtNode(i.leftHash,r,n,s,a+1),d=i.rightHash);let l=await wu(u,d);if(!Xr(l,e)){let f={type:"internal",leftHash:u,rightHash:d};await this.store.putNode(l,f),await this.store.deleteNode(e)}return l}async splitLeaves(e,r,n,s,a){let o=a;for(;o<bi&&co(e.keyHash,o)===co(n.keyHash,o);)o++;if(o>=bi)return s;let i=co(e.keyHash,o),c,u;i?(c=s,u=r):(c=r,u=s);let d=await wu(c,u);await this.store.putNode(d,{type:"internal",leftHash:c,rightHash:u});for(let l=o-1;l>=a;l--){let f=co(e.keyHash,l),h=this.defaultHashes[l+1],p,m;f?(p=h,m=d):(p=d,m=h),d=await wu(p,m),await this.store.putNode(d,{type:"internal",leftHash:p,rightHash:m})}return d}async deleteAtNode(e,r,n){if(n>=bi)return this.defaultHashes[bi];if(Xr(e,this.defaultHashes[n]))return e;let s=await this.store.getNode(e);if(s===void 0)return this.defaultHashes[n];if(s.type==="leaf")return Xr(s.keyHash,r)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let a=s,o=co(r,n),i,c;if(o?(i=a.leftHash,c=await this.deleteAtNode(a.rightHash,r,n+1)):(i=await this.deleteAtNode(a.leftHash,r,n+1),c=a.rightHash),Xr(i,this.defaultHashes[n+1])&&Xr(c,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let u=Xr(i,this.defaultHashes[n+1]),d=Xr(c,this.defaultHashes[n+1]);if(u||d){let f=u?c:i,h=await this.store.getNode(f);if(h!==void 0&&h.type==="leaf")return await this.store.deleteNode(e),f}let l=await wu(i,c);if(!Xr(l,e)){let f={type:"internal",leftHash:i,rightHash:c};await this.store.putNode(l,f),await this.store.deleteNode(e)}return l}async existsAtNode(e,r,n){if(n>=bi||Xr(e,this.defaultHashes[n]))return!1;let s=await this.store.getNode(e);if(s===void 0)return!1;if(s.type==="leaf")return Xr(s.keyHash,r);let a=s;return co(r,n)?this.existsAtNode(a.rightHash,r,n+1):this.existsAtNode(a.leftHash,r,n+1)}async generateProof(e,r,n){if(n>=bi)return{siblings:[],leafNode:void 0,depth:n};if(Xr(e,this.defaultHashes[n]))return{siblings:[],leafNode:void 0,depth:n};let s=await this.store.getNode(e);if(s===void 0)return{siblings:[],leafNode:void 0,depth:n};if(s.type==="leaf")return{siblings:[],leafNode:s,depth:n};let a=s,o=co(r,n),i,c;o?(i=a.rightHash,c=a.leftHash):(i=a.leftHash,c=a.rightHash);let u=await this.generateProof(i,r,n+1);return u.siblings.unshift(c),u}async computeSubtreeHashForLeaf(e,r,n){for(let s=r;s<n.length;s++)if(co(e.keyHash,s)!==n[s])return this.defaultHashes[n.length];return await ug(e.keyHash,e.valueCid)}leafMatchesPrefix(e,r){for(let n=0;n<r.length;n++)if(co(e,n)!==r[n])return!1;return!0}async collectLeaves(e,r){if(r>=bi||Xr(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 s=n,a=await this.collectLeaves(s.leftHash,r+1),o=await this.collectLeaves(s.rightHash,r+1);return[...a,...o]}async diffAtNode(e,r,n,s,a,o,i){if(Xr(e,r)||n>=bi)return;let c=Xr(e,this.defaultHashes[n]),u=Xr(r,this.defaultHashes[n]);if(c&&!u){let f=await a.collectLeaves(r,n);i.push(...f);return}if(!c&&u){let f=await s.collectLeaves(e,n);o.push(...f);return}let d=await s.store.getNode(e),l=await a.store.getNode(r);if(d?.type==="leaf"&&l?.type==="leaf"){Xr(d.keyHash,l.keyHash)?d.valueCid!==l.valueCid&&(o.push(d.valueCid),i.push(l.valueCid)):(o.push(d.valueCid),i.push(l.valueCid));return}if(d?.type==="leaf"){let f=await a.collectLeaves(r,n),h=d.valueCid;new Set(f).has(h)||o.push(h);for(let m of f)m!==h&&i.push(m);return}if(l?.type==="leaf"){let f=await s.collectLeaves(e,n),h=l.valueCid;new Set(f).has(h)||i.push(h);for(let m of f)m!==h&&o.push(m);return}if(d?.type==="internal"&&l?.type==="internal"){await this.diffAtNode(d.leftHash,l.leftHash,n+1,s,a,o,i),await this.diffAtNode(d.rightHash,l.rightHash,n+1,s,a,o,i);return}if(d===void 0){let f=await a.collectLeaves(r,n);i.push(...f)}if(l===void 0){let f=await s.collectLeaves(e,n);o.push(...f)}}};var qA=class{config;db;globalTrees=new Map;protocolTrees=new Map;constructor(e){this.config={location:"STATEINDEX",createLevelDatabase:Ki,...e}}async open(){this.db=new Aa({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await ph()}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 s of r){let a=await this.getStoredIndexes(e,s);if(await n.delete(s),a!==void 0){let o=a.protocol;o!==void 0&&await(await this.getProtocolTree(e,o)).delete(s)}await this.deleteStoredIndexes(e,s)}}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}`,s=this.protocolTrees.get(n);return s!==void 0||(s=this.createTree(this.db,[e,"proto",r]),this.protocolTrees.set(n,s)),s}async createTree(e,r){let n=e;for(let o of r)n=await n.partition(o);let s=new Fw(n),a=new Gw(s);return await a.initialize(),a}async storeIndexes(e,r,n){let s=await this.getMetaPartition(e),a={protocol:n.protocol};await s.put(r,JSON.stringify(a))}async getStoredIndexes(e,r){let s=await(await this.getMetaPartition(e)).get(r);if(s!==void 0)return JSON.parse(s)}async deleteStoredIndexes(e,r){await(await this.getMetaPartition(e)).delete(r)}async getMetaPartition(e){return(await this.db.partition(e)).partition("meta")}};w();vu();var FA=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(Vn(e))}async putNode(e,r){this.nodes.set(Vn(e),r)}async deleteNode(e){this.nodes.delete(Vn(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}};vu();w();Tp();Fc();Vd();ZP();ln();Oa();k0();$n();vi();hs();c0();Rd();Vs();Up();Dy();Qt();Kp();var pue={protocol:"http://test-protocol.xyz",published:!1,types:{testRecord:{}},structure:{testRecord:{}}},GA=class t{static async generatePersona(e){let r=e?.did;r||(r=`did:example:${t.randomString(32)}`);let n=t.randomString(10),s=e?.keyId??`${r}#${n}`,a=e?.keyPair??await $a.generateKeyPair(),o=e?.encryptionKeyPair;if(!o){let c=await gn.generateKey();o={publicJwk:await gn.getPublicKey({key:c}),privateJwk:c}}return{did:r,keyId:s,keyPair:a,encryptionKeyPair:o,signer:new Ud({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:`${r}#${s}`})}}static async installDefaultTestProtocol(e,r){let n=await fd.create({definition:pue,signer:vt.createSigner(r)}),s=await e.processMessage(r.did,n.message);if(s.status.code!==202)throw new Error(`Failed to install default test protocol: ${s.status.code} ${s.status.detail}`)}static async generateProtocolsConfigure(e){let r=e?.author??await t.generatePersona(),n=e?.protocolDefinition;if(!n){let i="record"+t.randomString(10);n={protocol:t.randomString(20),published:e?.published??!1,types:{},structure:{}},n.types[i]={schema:"test-object",dataFormats:["text/plain"]},n.structure[i]={}}let s=vt.createSigner(r),a={messageTimestamp:e?.messageTimestamp,definition:n,signer:s,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},o=await fd.create(a);return{author:r,message:o.message,protocolsConfigure:o}}static async generateProtocolsQuery(e){let r=e?.author??await t.generatePersona(),n=vt.createSigner(r),s={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};qt(s);let a=await hf.create(s);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(),s=e?.dateExpires??yt.createOffsetTimestamp({seconds:10}),a=e?.scope??{interface:"Messages",method:"Read"},o=vt.createSigner(r),i=n.did,c={signer:o,grantedTo:i,dateExpires:s,scope:a,description:e?.description??t.randomString(10),delegated:e?.delegated??!1,requestId:e?.requestId,conditions:e?.conditions},u=await Tr.createGrant(c);return{dataStream:ts.fromBytes(u.permissionGrantBytes),recordsWrite:u.recordsWrite,dataBytes:u.permissionGrantBytes,message:u.recordsWrite.message,dataEncodedMessage:u.dataEncodedMessage}}static async generateRecordsWrite(e){let r=e?.author??await t.generatePersona(),n=vt.createSigner(r),s=vt.createSigners(e?.attesters??[]),a=e?.dataCid,o=e?.dataSize,i,c;a===void 0&&o===void 0&&(i=e?.data??t.randomBytes(32),c=ts.fromBytes(i));let u={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:i,dataCid:a,dataSize:o,signer:n,attestationSigners:s,encryptionInput:e?.encryptionInput,permissionGrantId:e?.permissionGrantId,squash:e?.squash},d=await St.create(u),l=d.message;return{author:r,message:l,dataCid:a,dataSize:o,dataBytes:i,dataStream:c,recordsWrite:d}}static async generateProtocolEncryptedRecordsWrite(e){let{plaintextBytes:r,author:n,recipient:s,protocolDefinition:a,protocolPath:o,protocolParentContextId:i,protocolContextDerivingRootKeyId:c,protocolContextDerivedPublicKeyJwk:u}=e,d=t.randomBytes(12),l=t.randomBytes(32),{ciphertext:f,tag:h}=await ma.aeadEncrypt("A256GCM",l,d,r),p=o.split("/"),m=p[p.length-1],{message:y,dataStream:S,recordsWrite:v}=await t.generateRecordsWrite({author:n,recipient:s,protocol:a.protocol,protocolPath:o,parentContextId:i,schema:a.types[m].schema,dataFormat:a.types[m].dataFormats?.[0],data:f}),E={initializationVector:d,key:l,authenticationTag:h,keyEncryptionInputs:[]};if(e.encryptSymmetricKeyWithProtocolPathDerivedKey){let k=a.structure;for(let j of p)k=k[j];let A=k.$encryption?.publicKeyJwk,B={publicKeyId:k.$encryption?.rootKeyId,publicKey:A,derivationScheme:"protocolPath"};E.keyEncryptionInputs.push(B)}if(e.encryptSymmetricKeyWithProtocolContextDerivedKey){let k;if(i===void 0){let A={rootKeyId:n.keyId,derivationScheme:"protocolContext",derivedPrivateKey:n.encryptionKeyPair.privateJwk},D=await St.getEntryId(n.did,y.descriptor),B=ke.constructKeyDerivationPathUsingProtocolContextScheme(D),j=await Va.derivePublicKey(A,B);k={publicKeyId:n.keyId,publicKey:j,derivationScheme:"protocolContext"}}else{if(c===void 0||u===void 0)throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicKeyJwk` must both be defined if `protocolContextId` is given");k={publicKeyId:c,publicKey:u,derivationScheme:"protocolContext"}}E.keyEncryptionInputs.push(k)}return await v.encryptSymmetricEncryptionKey(E),await v.sign({signer:vt.createSigner(n)}),{message:y,dataStream:S,recordsWrite:v,encryptedDataBytes:f,encryptionInput:E}}static async generateFromRecordsWrite(e){let r=e.existingWrite.message,n=yt.getCurrentTimestamp(),s=!(e.published??r.descriptor.published),a=e.datePublished??(s?n:void 0),o=e.data??t.randomBytes(32),i=ts.fromBytes(o),c={recordsWriteMessage:e.existingWrite.message,data:o,published:s,datePublished:a,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:vt.createSigner(e.author)},u=await St.createFrom(c);return{message:u.message,recordsWrite:u,dataBytes:o,dataStream:i}}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 s;r!==void 0&&(s=vt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole};qt(a);let i=(await Jl.create(a)).message;return{author:r,message:i}}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 s;r!==void 0&&(s=vt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole,cursor:e?.cursor};qt(a);let i=(await mf.create(a)).message;return{author:r,message:i}}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 s;r!==void 0&&(s=vt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},protocolRole:e?.protocolRole};qt(a);let i=(await Hl.create(a)).message;return{author:r,message:i}}static async generateRecordsDelete(e){let r=e?.author??await t.generateDidKeyPersona(),n=await pd.create({recordId:e?.recordId??await t.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:vt.createSigner(r)});return{author:r,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let r=e?.author??await t.generatePersona(),n=vt.createSigner(r),s={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};qt(s);let a=await Yl.create(s),o=a.message;return{author:r,messagesSubscribe:a,message:o}}static async generateMessagesRead(e){let r=e?.author??await t.generatePersona(),s={signer:vt.createSigner(r),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},a=await Zl.create(s);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 fm.generateKeyPair(),r=await fm.sign(t.randomBytes(32),e.privateJwk);return Te.bytesToBase64Url(r)}static randomString(e){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="";for(let s=0;s<e;s++)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 Pn.digest(e);return(await zt.createV1(Wd,r)).toString()}static randomInt(e,r){return Math.floor(Math.random()*(r-e)+e)}static randomTimestamp(e){let{year:r,month:n,day:s,hour:a,minute:o,second:i,millisecond:c,microsecond:u}=e||{};return yt.createTimestamp({year:r||this.randomInt(2e3,2022),month:n||this.randomInt(1,12),day:s||this.randomInt(1,28),hour:a||this.randomInt(0,23),minute:o||this.randomInt(0,59),second:i||this.randomInt(0,59),millisecond:c||this.randomInt(0,1e3),microsecond:u||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 $w.create(),r=await $w.getSigningMethod({didDocument:e.document}),n=r.id,s=await e.export(),a={publicJwk:r.publicKeyJwk,privateJwk:s.privateKeys[0]},o=await gn.generateKey(),c={publicJwk:await gn.getPublicKey({key:o}),privateJwk:o};return{did:e.uri,keyId:n,keyPair:a,encryptionKeyPair:c,signer:new Ud({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:n})}}};w();Vs();var WA=class t{static pollRetrySleep=20;static pollTimeout=2e3;static async pollUntilSuccessOrTimeout(e,r=t.pollRetrySleep,n=t.pollTimeout){let s=Date.now();for(;;)try{return await e()}catch{if(Date.now()-s>=n)throw new Error("Operation timed out");await yt.sleep(r)}}};export{cg as AllowAllTenantGate,Bf as BlockstoreLevel,Ar as Cid,UE as ContentEncryptionAlgorithm,ag as CoreProtocolRegistry,OA as DataStoreLevel,ts as DataStream,$p as DateSort,PA as Dwn,dc as DwnConstant,ne as DwnError,pt as DwnErrorCode,Yt as DwnInterfaceName,ar as DwnMethodName,Te as Encoder,ma as Encryption,zA as EventEmitterEventLog,Va as HdKey,rm as IndexLevel,vt as Jws,y3 as KeyAgreementAlgorithm,Lp as KeyDerivationScheme,Aa as LevelWrapper,we as Message,LA as MessageStoreLevel,Zl as MessagesRead,Yl as MessagesSubscribe,lg as MessagesSync,LE as PERMISSIONS_REVOCATION_PATH,w3 as PermissionConditionPublication,Zr as PermissionGrant,dg as PermissionRequest,Tr as PermissionsProtocol,WA as Poller,Ud as PrivateKeySigner,cm as ProtocolRecordLimitStrategy,nI as Protocols,fd as ProtocolsConfigure,hf as ProtocolsQuery,ke as Records,Hl as RecordsCount,pd as RecordsDelete,Jl as RecordsQuery,Wg as RecordsRead,mf as RecordsSubscribe,St as RecordsWrite,KA as ResumableTaskStoreLevel,Fw as SMTStoreLevel,FA as SMTStoreMemory,bi as SMT_DEPTH,$a as Secp256k1,Nd as Secp256r1,Ha as SortDirection,Gw as SparseMerkleTree,qA as StateIndexLevel,GA as TestDataGenerator,yt as Time,nk as ZERO_HASH,on as authenticate,Ki as createLevelDatabase,On as executeUnlessAborted,co as getBit,yO as getDefaultHashes,ld as getRuleSetAtPath,wu as hashChildren,Xr as hashEquals,Xl as hashKey,ug as hashLeaf,Vn as hashToHex,ef as hexToHash,ph as initDefaultHashes,pf as isCrossProtocolRef,Bi as parseCrossProtocolRef};
10
+ deps: ${r}}`};var Uee={keyword:"dependencies",type:"object",schemaType:"object",error:pc.error,code(t){let[e,r]=Lee(t);dB(t,e),uB(t,r)}};function Lee({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function dB(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let a=r.let("missing");for(let o in e){let i=e[o];if(i.length===0)continue;let c=(0,Lg.propertyInData)(r,n,o,s.opts.ownProperties);t.setParams({property:o,depsCount:i.length,deps:i.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of i)(0,Lg.checkReportMissingProp)(t,u)}):(r.if((0,PT._)`${c} && (${(0,Lg.checkMissingProp)(t,i,a)})`),(0,Lg.reportMissingProp)(t,a),r.else())}}pc.validatePropertyDeps=dB;function uB(t,e=t.schema){let{gen:r,data:n,keyword:s,it:a}=t,o=r.name("valid");for(let i in e)(0,Nee.alwaysValidSchema)(a,e[i])||(r.if((0,Lg.propertyInData)(r,n,i,a.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:i},o);t.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),t.ok(o))}pc.validateSchemaDeps=uB;pc.default=Uee});var fB=Ee(xT=>{"use strict";w();Object.defineProperty(xT,"__esModule",{value:!0});var lB=kt(),Kee=Ut(),zee={message:"property name must be valid",params:({params:t})=>(0,lB._)`{propertyName: ${t.propertyName}}`},qee={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:zee,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,Kee.alwaysValidSchema)(s,r))return;let a=e.name("valid");e.forIn("key",n,o=>{t.setParams({propertyName:o}),t.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},a),e.if((0,lB.not)(a),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(a)}};xT.default=qee});var ET=Ee(ST=>{"use strict";w();Object.defineProperty(ST,"__esModule",{value:!0});var Yb=$o(),Ea=kt(),Fee=jo(),Qb=Ut(),Gee={message:"must NOT have additional properties",params:({params:t})=>(0,Ea._)`{additionalProperty: ${t.additionalProperty}}`},Wee={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Gee,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:a,it:o}=t;if(!a)throw new Error("ajv implementation error");let{allErrors:i,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Qb.alwaysValidSchema)(o,r))return;let u=(0,Yb.allSchemaProperties)(n.properties),d=(0,Yb.allSchemaProperties)(n.patternProperties);l(),t.ok((0,Ea._)`${a} === ${Fee.default.errors}`);function l(){e.forIn("key",s,y=>{!u.length&&!d.length?p(y):e.if(f(y),()=>p(y))})}function f(y){let S;if(u.length>8){let v=(0,Qb.schemaRefOrVal)(o,n.properties,"properties");S=(0,Yb.isOwnProperty)(e,v,y)}else u.length?S=(0,Ea.or)(...u.map(v=>(0,Ea._)`${y} === ${v}`)):S=Ea.nil;return d.length&&(S=(0,Ea.or)(S,...d.map(v=>(0,Ea._)`${(0,Yb.usePattern)(t,v)}.test(${y})`))),(0,Ea.not)(S)}function h(y){e.code((0,Ea._)`delete ${s}[${y}]`)}function p(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),i||e.break();return}if(typeof r=="object"&&!(0,Qb.alwaysValidSchema)(o,r)){let S=e.name("valid");c.removeAdditional==="failing"?(m(y,S,!1),e.if((0,Ea.not)(S),()=>{t.reset(),h(y)})):(m(y,S),i||e.if((0,Ea.not)(S),()=>e.break()))}}function m(y,S,v){let E={keyword:"additionalProperties",dataProp:y,dataPropType:Qb.Type.Str};v===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(E,S)}}};ST.default=Wee});var mB=Ee(kT=>{"use strict";w();Object.defineProperty(kT,"__esModule",{value:!0});var Vee=_g(),pB=$o(),_T=Ut(),hB=ET(),Hee={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:a}=t;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&hB.default.code(new Vee.KeywordCxt(a,hB.default,"additionalProperties"));let o=(0,pB.allSchemaProperties)(r);for(let l of o)a.definedProperties.add(l);a.opts.unevaluated&&o.length&&a.props!==!0&&(a.props=_T.mergeEvaluated.props(e,(0,_T.toHash)(o),a.props));let i=o.filter(l=>!(0,_T.alwaysValidSchema)(a,r[l]));if(i.length===0)return;let c=e.name("valid");for(let l of i)u(l)?d(l):(e.if((0,pB.propertyInData)(e,s,l,a.opts.ownProperties)),d(l),a.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return a.opts.useDefaults&&!a.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};kT.default=Hee});var vB=Ee(TT=>{"use strict";w();Object.defineProperty(TT,"__esModule",{value:!0});var yB=$o(),Xb=kt(),gB=Ut(),wB=Ut(),Jee={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:a}=t,{opts:o}=a,i=(0,yB.allSchemaProperties)(r),c=i.filter(m=>(0,gB.alwaysValidSchema)(a,r[m]));if(i.length===0||c.length===i.length&&(!a.opts.unevaluated||a.props===!0))return;let u=o.strictSchema&&!o.allowMatchingProperties&&s.properties,d=e.name("valid");a.props!==!0&&!(a.props instanceof Xb.Name)&&(a.props=(0,wB.evaluatedPropsToName)(e,a.props));let{props:l}=a;f();function f(){for(let m of i)u&&h(m),a.allErrors?p(m):(e.var(d,!0),p(m),e.if(d))}function h(m){for(let y in u)new RegExp(m).test(y)&&(0,gB.checkStrictMode)(a,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,y=>{e.if((0,Xb._)`${(0,yB.usePattern)(t,m)}.test(${y})`,()=>{let S=c.includes(m);S||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:wB.Type.Str},d),a.opts.unevaluated&&l!==!0?e.assign((0,Xb._)`${l}[${y}]`,!0):!S&&!a.allErrors&&e.if((0,Xb.not)(d),()=>e.break())})})}}};TT.default=Jee});var bB=Ee(IT=>{"use strict";w();Object.defineProperty(IT,"__esModule",{value:!0});var Zee=Ut(),Yee={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Zee.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};IT.default=Yee});var PB=Ee(AT=>{"use strict";w();Object.defineProperty(AT,"__esModule",{value:!0});var Qee=$o(),Xee={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Qee.validateUnion,error:{message:"must match a schema in anyOf"}};AT.default=Xee});var xB=Ee(RT=>{"use strict";w();Object.defineProperty(RT,"__esModule",{value:!0});var e1=kt(),ete=Ut(),tte={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,e1._)`{passingSchemas: ${t.passing}}`},rte={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:tte,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let a=r,o=e.let("valid",!1),i=e.let("passing",null),c=e.name("_valid");t.setParams({passing:i}),e.block(u),t.result(o,()=>t.reset(),()=>t.error(!0));function u(){a.forEach((d,l)=>{let f;(0,ete.alwaysValidSchema)(s,d)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,e1._)`${c} && ${o}`).assign(o,!1).assign(i,(0,e1._)`[${i}, ${l}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(i,l),f&&t.mergeEvaluated(f,e1.Name)})})}}};RT.default=rte});var SB=Ee(DT=>{"use strict";w();Object.defineProperty(DT,"__esModule",{value:!0});var nte=Ut(),ste={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 s=e.name("valid");r.forEach((a,o)=>{if((0,nte.alwaysValidSchema)(n,a))return;let i=t.subschema({keyword:"allOf",schemaProp:o},s);t.ok(s),t.mergeEvaluated(i)})}};DT.default=ste});var kB=Ee(CT=>{"use strict";w();Object.defineProperty(CT,"__esModule",{value:!0});var t1=kt(),_B=Ut(),ite={message:({params:t})=>(0,t1.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,t1._)`{failingKeyword: ${t.ifClause}}`},ote={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ite,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,_B.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=EB(n,"then"),a=EB(n,"else");if(!s&&!a)return;let o=e.let("valid",!0),i=e.name("_valid");if(c(),t.reset(),s&&a){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(i,u("then",d),u("else",d))}else s?e.if(i,u("then")):e.if((0,t1.not)(i),u("else"));t.pass(o,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);t.mergeEvaluated(d)}function u(d,l){return()=>{let f=t.subschema({keyword:d},i);e.assign(o,i),t.mergeValidEvaluated(f,o),l?e.assign(l,(0,t1._)`${d}`):t.setParams({ifClause:d})}}}};function EB(t,e){let r=t.schema[e];return r!==void 0&&!(0,_B.alwaysValidSchema)(t,r)}CT.default=ote});var TB=Ee(jT=>{"use strict";w();Object.defineProperty(jT,"__esModule",{value:!0});var ate=Ut(),cte={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,ate.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};jT.default=cte});var IB=Ee($T=>{"use strict";w();Object.defineProperty($T,"__esModule",{value:!0});var dte=yT(),ute=iB(),lte=gT(),fte=aB(),pte=cB(),hte=Zb(),mte=fB(),yte=ET(),gte=mB(),wte=vB(),vte=bB(),bte=PB(),Pte=xB(),xte=SB(),Ste=kB(),Ete=TB();function _te(t=!1){let e=[vte.default,bte.default,Pte.default,xte.default,Ste.default,Ete.default,mte.default,yte.default,hte.default,gte.default,wte.default];return t?e.push(ute.default,fte.default):e.push(dte.default,lte.default),e.push(pte.default),e}$T.default=_te});var OT=Ee(Kg=>{"use strict";w();Object.defineProperty(Kg,"__esModule",{value:!0});Kg.dynamicAnchor=void 0;var MT=kt(),kte=jo(),AB=Tg(),Tte=Fb(),Ite={keyword:"$dynamicAnchor",schemaType:"string",code:t=>RB(t,t.schema)};function RB(t,e){let{gen:r,it:n}=t;n.schemaEnv.root.dynamicAnchors[e]=!0;let s=(0,MT._)`${kte.default.dynamicAnchors}${(0,MT.getProperty)(e)}`,a=n.errSchemaPath==="#"?n.validateName:Ate(t);r.if((0,MT._)`!${s}`,()=>r.assign(s,a))}Kg.dynamicAnchor=RB;function Ate(t){let{schemaEnv:e,schema:r,self:n}=t.it,{root:s,baseId:a,localRefs:o,meta:i}=e.root,{schemaId:c}=n.opts,u=new AB.SchemaEnv({schema:r,schemaId:c,root:s,baseId:a,localRefs:o,meta:i});return AB.compileSchema.call(n,u),(0,Tte.getValidate)(t,u)}Kg.default=Ite});var BT=Ee(zg=>{"use strict";w();Object.defineProperty(zg,"__esModule",{value:!0});zg.dynamicRef=void 0;var DB=kt(),Rte=jo(),CB=Fb(),Dte={keyword:"$dynamicRef",schemaType:"string",code:t=>jB(t,t.schema)};function jB(t,e){let{gen:r,keyword:n,it:s}=t;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let a=e.slice(1);if(s.allErrors)o();else{let c=r.let("valid",!1);o(c),t.ok(c)}function o(c){if(s.schemaEnv.root.dynamicAnchors[a]){let u=r.let("_v",(0,DB._)`${Rte.default.dynamicAnchors}${(0,DB.getProperty)(a)}`);r.if(u,i(u,c),i(s.validateName,c))}else i(s.validateName,c)()}function i(c,u){return u?()=>r.block(()=>{(0,CB.callRef)(t,c),r.let(u,!0)}):()=>(0,CB.callRef)(t,c)}}zg.dynamicRef=jB;zg.default=Dte});var $B=Ee(NT=>{"use strict";w();Object.defineProperty(NT,"__esModule",{value:!0});var Cte=OT(),jte=Ut(),$te={keyword:"$recursiveAnchor",schemaType:"boolean",code(t){t.schema?(0,Cte.dynamicAnchor)(t,""):(0,jte.checkStrictMode)(t.it,"$recursiveAnchor: false is ignored")}};NT.default=$te});var MB=Ee(UT=>{"use strict";w();Object.defineProperty(UT,"__esModule",{value:!0});var Mte=BT(),Ote={keyword:"$recursiveRef",schemaType:"string",code:t=>(0,Mte.dynamicRef)(t,t.schema)};UT.default=Ote});var OB=Ee(LT=>{"use strict";w();Object.defineProperty(LT,"__esModule",{value:!0});var Bte=OT(),Nte=BT(),Ute=$B(),Lte=MB(),Kte=[Bte.default,Nte.default,Ute.default,Lte.default];LT.default=Kte});var NB=Ee(KT=>{"use strict";w();Object.defineProperty(KT,"__esModule",{value:!0});var BB=Zb(),zte={keyword:"dependentRequired",type:"object",schemaType:"object",error:BB.error,code:t=>(0,BB.validatePropertyDeps)(t)};KT.default=zte});var UB=Ee(zT=>{"use strict";w();Object.defineProperty(zT,"__esModule",{value:!0});var qte=Zb(),Fte={keyword:"dependentSchemas",type:"object",schemaType:"object",code:t=>(0,qte.validateSchemaDeps)(t)};zT.default=Fte});var LB=Ee(qT=>{"use strict";w();Object.defineProperty(qT,"__esModule",{value:!0});var Gte=Ut(),Wte={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:e,it:r}){e.contains===void 0&&(0,Gte.checkStrictMode)(r,`"${t}" without "contains" is ignored`)}};qT.default=Wte});var KB=Ee(FT=>{"use strict";w();Object.defineProperty(FT,"__esModule",{value:!0});var Vte=NB(),Hte=UB(),Jte=LB(),Zte=[Vte.default,Hte.default,Jte.default];FT.default=Zte});var qB=Ee(GT=>{"use strict";w();Object.defineProperty(GT,"__esModule",{value:!0});var Tu=kt(),zB=Ut(),Yte=jo(),Qte={message:"must NOT have unevaluated properties",params:({params:t})=>(0,Tu._)`{unevaluatedProperty: ${t.unevaluatedProperty}}`},Xte={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Qte,code(t){let{gen:e,schema:r,data:n,errsCount:s,it:a}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:o,props:i}=a;i instanceof Tu.Name?e.if((0,Tu._)`${i} !== true`,()=>e.forIn("key",n,l=>e.if(u(i,l),()=>c(l)))):i!==!0&&e.forIn("key",n,l=>i===void 0?c(l):e.if(d(i,l),()=>c(l))),a.props=!0,t.ok((0,Tu._)`${s} === ${Yte.default.errors}`);function c(l){if(r===!1){t.setParams({unevaluatedProperty:l}),t.error(),o||e.break();return}if(!(0,zB.alwaysValidSchema)(a,r)){let f=e.name("valid");t.subschema({keyword:"unevaluatedProperties",dataProp:l,dataPropType:zB.Type.Str},f),o||e.if((0,Tu.not)(f),()=>e.break())}}function u(l,f){return(0,Tu._)`!${l} || !${l}[${f}]`}function d(l,f){let h=[];for(let p in l)l[p]===!0&&h.push((0,Tu._)`${f} !== ${p}`);return(0,Tu.and)(...h)}}};GT.default=Xte});var GB=Ee(WT=>{"use strict";w();Object.defineProperty(WT,"__esModule",{value:!0});var ff=kt(),FB=Ut(),ere={message:({params:{len:t}})=>(0,ff.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ff._)`{limit: ${t}}`},tre={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:ere,code(t){let{gen:e,schema:r,data:n,it:s}=t,a=s.items||0;if(a===!0)return;let o=e.const("len",(0,ff._)`${n}.length`);if(r===!1)t.setParams({len:a}),t.fail((0,ff._)`${o} > ${a}`);else if(typeof r=="object"&&!(0,FB.alwaysValidSchema)(s,r)){let c=e.var("valid",(0,ff._)`${o} <= ${a}`);e.if((0,ff.not)(c),()=>i(c,a)),t.ok(c)}s.items=!0;function i(c,u){e.forRange("i",u,o,d=>{t.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:FB.Type.Num},c),s.allErrors||e.if((0,ff.not)(c),()=>e.break())})}}};WT.default=tre});var WB=Ee(VT=>{"use strict";w();Object.defineProperty(VT,"__esModule",{value:!0});var rre=qB(),nre=GB(),sre=[rre.default,nre.default];VT.default=sre});var VB=Ee(HT=>{"use strict";w();Object.defineProperty(HT,"__esModule",{value:!0});var Tn=kt(),ire={message:({schemaCode:t})=>(0,Tn.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Tn._)`{format: ${t}}`},ore={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:ire,code(t,e){let{gen:r,data:n,$data:s,schema:a,schemaCode:o,it:i}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=i;if(!c.validateFormats)return;s?f():h();function f(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,Tn._)`${p}[${o}]`),y=r.let("fType"),S=r.let("format");r.if((0,Tn._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,Tn._)`${m}.type || "string"`).assign(S,(0,Tn._)`${m}.validate`),()=>r.assign(y,(0,Tn._)`"string"`).assign(S,m)),t.fail$data((0,Tn.or)(v(),E()));function v(){return c.strictSchema===!1?Tn.nil:(0,Tn._)`${o} && !${S}`}function E(){let k=d.$async?(0,Tn._)`(${m}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,Tn._)`${S}(${n})`,A=(0,Tn._)`(typeof ${S} == "function" ? ${k} : ${S}.test(${n}))`;return(0,Tn._)`${S} && ${S} !== true && ${y} === ${e} && !${A}`}}function h(){let p=l.formats[a];if(!p){v();return}if(p===!0)return;let[m,y,S]=E(p);m===e&&t.pass(k());function v(){if(c.strictSchema===!1){l.logger.warn(A());return}throw new Error(A());function A(){return`unknown format "${a}" ignored in schema at path "${u}"`}}function E(A){let D=A instanceof RegExp?(0,Tn.regexpCode)(A):c.code.formats?(0,Tn._)`${c.code.formats}${(0,Tn.getProperty)(a)}`:void 0,B=r.scopeValue("formats",{key:a,ref:A,code:D});return typeof A=="object"&&!(A instanceof RegExp)?[A.type||"string",A.validate,(0,Tn._)`${B}.validate`]:["string",A,B]}function k(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Tn._)`await ${S}(${n})`}return typeof y=="function"?(0,Tn._)`${S}(${n})`:(0,Tn._)`${S}.test(${n})`}}}};HT.default=ore});var HB=Ee(JT=>{"use strict";w();Object.defineProperty(JT,"__esModule",{value:!0});var are=VB(),cre=[are.default];JT.default=cre});var JB=Ee(_h=>{"use strict";w();Object.defineProperty(_h,"__esModule",{value:!0});_h.contentVocabulary=_h.metadataVocabulary=void 0;_h.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];_h.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var YB=Ee(ZT=>{"use strict";w();Object.defineProperty(ZT,"__esModule",{value:!0});var dre=q4(),ure=tB(),lre=IB(),fre=OB(),pre=KB(),hre=WB(),mre=HB(),ZB=JB(),yre=[fre.default,dre.default,ure.default,(0,lre.default)(!0),mre.default,ZB.metadataVocabulary,ZB.contentVocabulary,pre.default,hre.default];ZT.default=yre});var XB=Ee(r1=>{"use strict";w();Object.defineProperty(r1,"__esModule",{value:!0});r1.DiscrError=void 0;var QB;(function(t){t.Tag="tag",t.Mapping="mapping"})(QB||(r1.DiscrError=QB={}))});var tN=Ee(QT=>{"use strict";w();Object.defineProperty(QT,"__esModule",{value:!0});var kh=kt(),YT=XB(),eN=Tg(),gre=kg(),wre=Ut(),vre={message:({params:{discrError:t,tagName:e}})=>t===YT.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,kh._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},bre={keyword:"discriminator",type:"object",schemaType:"object",error:vre,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:a}=t,{oneOf:o}=s;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let i=n.propertyName;if(typeof i!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,kh._)`${r}${(0,kh.getProperty)(i)}`);e.if((0,kh._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:YT.DiscrError.Tag,tag:u,tagName:i})),t.ok(c);function d(){let h=f();e.if(!1);for(let p in h)e.elseIf((0,kh._)`${u} === ${p}`),e.assign(c,l(h[p]));e.else(),t.error(!1,{discrError:YT.DiscrError.Mapping,tag:u,tagName:i}),e.endIf()}function l(h){let p=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:h},p);return t.mergeEvaluated(m,kh.Name),p}function f(){var h;let p={},m=S(s),y=!0;for(let k=0;k<o.length;k++){let A=o[k];if(A?.$ref&&!(0,wre.schemaHasRulesButRef)(A,a.self.RULES)){let B=A.$ref;if(A=eN.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,B),A instanceof eN.SchemaEnv&&(A=A.schema),A===void 0)throw new gre.default(a.opts.uriResolver,a.baseId,B)}let D=(h=A?.properties)===null||h===void 0?void 0:h[i];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);y=y&&(m||S(A)),v(D,k)}if(!y)throw new Error(`discriminator: "${i}" must be required`);return p;function S({required:k}){return Array.isArray(k)&&k.includes(i)}function v(k,A){if(k.const)E(k.const,A);else if(k.enum)for(let D of k.enum)E(D,A);else throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`)}function E(k,A){if(typeof k!="string"||k in p)throw new Error(`discriminator: "${i}" values must be unique strings`);p[k]=A}}}};QT.default=bre});var rN=Ee((MDe,Pre)=>{Pre.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 nN=Ee((ODe,xre)=>{xre.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 sN=Ee((BDe,Sre)=>{Sre.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 iN=Ee((NDe,Ere)=>{Ere.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 oN=Ee((UDe,_re)=>{_re.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 aN=Ee((LDe,kre)=>{kre.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 cN=Ee((KDe,Tre)=>{Tre.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 dN=Ee((zDe,Ire)=>{Ire.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 uN=Ee(XT=>{"use strict";w();Object.defineProperty(XT,"__esModule",{value:!0});var Are=rN(),Rre=nN(),Dre=sN(),Cre=iN(),jre=oN(),$re=aN(),Mre=cN(),Ore=dN(),Bre=["/properties"];function Nre(t){return[Are,Rre,Dre,Cre,jre,e(this,$re),Mre,e(this,Ore)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function e(r,n){return t?r.$dataMetaSchema(n,Bre):n}}XT.default=Nre});var rI=Ee((Wr,tI)=>{"use strict";w();Object.defineProperty(Wr,"__esModule",{value:!0});Wr.MissingRefError=Wr.ValidationError=Wr.CodeGen=Wr.Name=Wr.nil=Wr.stringify=Wr.str=Wr._=Wr.KeywordCxt=Wr.Ajv2020=void 0;var Ure=N4(),Lre=YB(),Kre=tN(),zre=uN(),eI="https://json-schema.org/draft/2020-12/schema",Th=class extends Ure.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Lre.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Kre.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:r}=this.opts;r&&(zre.default.call(this,e),this.refs["http://json-schema.org/schema"]=eI)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(eI)?eI:void 0)}};Wr.Ajv2020=Th;tI.exports=Wr=Th;tI.exports.Ajv2020=Th;Object.defineProperty(Wr,"__esModule",{value:!0});Wr.default=Th;var qre=_g();Object.defineProperty(Wr,"KeywordCxt",{enumerable:!0,get:function(){return qre.KeywordCxt}});var Ih=kt();Object.defineProperty(Wr,"_",{enumerable:!0,get:function(){return Ih._}});Object.defineProperty(Wr,"str",{enumerable:!0,get:function(){return Ih.str}});Object.defineProperty(Wr,"stringify",{enumerable:!0,get:function(){return Ih.stringify}});Object.defineProperty(Wr,"nil",{enumerable:!0,get:function(){return Ih.nil}});Object.defineProperty(Wr,"Name",{enumerable:!0,get:function(){return Ih.Name}});Object.defineProperty(Wr,"CodeGen",{enumerable:!0,get:function(){return Ih.CodeGen}});var Fre=Mb();Object.defineProperty(Wr,"ValidationError",{enumerable:!0,get:function(){return Fre.default}});var Gre=kg();Object.defineProperty(Wr,"MissingRefError",{enumerable:!0,get:function(){return Gre.default}})});var v9=Ee((HOe,_A)=>{"use strict";w();var Yde=Object.prototype.hasOwnProperty,_i="~";function Ow(){}Object.create&&(Ow.prototype=Object.create(null),new Ow().__proto__||(_i=!1));function Qde(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function w9(t,e,r,n,s){if(typeof r!="function")throw new TypeError("The listener must be a function");var a=new Qde(r,n||t,s),o=_i?_i+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],a]:t._events[o].push(a):(t._events[o]=a,t._eventsCount++),t}function gP(t,e){--t._eventsCount===0?t._events=new Ow:delete t._events[e]}function ti(){this._events=new Ow,this._eventsCount=0}ti.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)Yde.call(r,n)&&e.push(_i?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};ti.prototype.listeners=function(e){var r=_i?_i+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,a=n.length,o=new Array(a);s<a;s++)o[s]=n[s].fn;return o};ti.prototype.listenerCount=function(e){var r=_i?_i+e:e,n=this._events[r];return n?n.fn?1:n.length:0};ti.prototype.emit=function(e,r,n,s,a,o){var i=_i?_i+e:e;if(!this._events[i])return!1;var c=this._events[i],u=arguments.length,d,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,s),!0;case 5:return c.fn.call(c.context,r,n,s,a),!0;case 6:return c.fn.call(c.context,r,n,s,a,o),!0}for(l=1,d=new Array(u-1);l<u;l++)d[l-1]=arguments[l];c.fn.apply(c.context,d)}else{var f=c.length,h;for(l=0;l<f;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,r);break;case 3:c[l].fn.call(c[l].context,r,n);break;case 4:c[l].fn.call(c[l].context,r,n,s);break;default:if(!d)for(h=1,d=new Array(u-1);h<u;h++)d[h-1]=arguments[h];c[l].fn.apply(c[l].context,d)}}return!0};ti.prototype.on=function(e,r,n){return w9(this,e,r,n,!1)};ti.prototype.once=function(e,r,n){return w9(this,e,r,n,!0)};ti.prototype.removeListener=function(e,r,n,s){var a=_i?_i+e:e;if(!this._events[a])return this;if(!r)return gP(this,a),this;var o=this._events[a];if(o.fn)o.fn===r&&(!s||o.once)&&(!n||o.context===n)&&gP(this,a);else{for(var i=0,c=[],u=o.length;i<u;i++)(o[i].fn!==r||s&&!o[i].once||n&&o[i].context!==n)&&c.push(o[i]);c.length?this._events[a]=c.length===1?c[0]:c:gP(this,a)}return this};ti.prototype.removeAllListeners=function(e){var r;return e?(r=_i?_i+e:e,this._events[r]&&gP(this,r)):(this._events=new Ow,this._eventsCount=0),this};ti.prototype.off=ti.prototype.removeListener;ti.prototype.addListener=ti.prototype.on;ti.prefixed=_i;ti.EventEmitter=ti;typeof _A<"u"&&(_A.exports=ti)});w();w();var cm=(r=>(r.Reject="reject",r.PurgeOldest="purgeOldest",r))(cm||{});w();w();ln();Oa();w();w();var Cm=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,UD=new Set,r2=typeof process=="object"&&process?process:{},LD=(t,e,r,n)=>{typeof r2.emitWarning=="function"?r2.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},T0=globalThis.AbortController,ND=globalThis.AbortSignal;if(typeof T0>"u"){ND=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,s){this._onabort.push(s)}},T0=class{constructor(){e()}signal=new ND;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let s of this.signal._onabort)s(n);this.signal.onabort?.(n)}}};let t=r2.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,LD("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var IF=t=>!UD.has(t),Hhe=Symbol("type"),Ld=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),KD=t=>Ld(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?hp:null:null,hp=class extends Array{constructor(e){super(e),this.fill(0)}},n2=class t{heap;length;static#c=!1;static create(e){let r=KD(e);if(!r)return[];t.#c=!0;let n=new t(e,r);return t.#c=!1,n}constructor(e,r){if(!t.#c)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},I0=class t{#c;#l;#w;#h;#A;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#m;#s;#r;#e;#d;#f;#a;#i;#y;#o;#x;#S;#g;#v;#_;#u;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#g,sizes:e.#x,keyMap:e.#s,keyList:e.#r,valList:e.#e,next:e.#d,prev:e.#f,get head(){return e.#a},get tail(){return e.#i},free:e.#y,isBackgroundFetch:r=>e.#t(r),backgroundFetch:(r,n,s,a)=>e.#C(r,n,s,a),moveToTail:r=>e.#I(r),indexes:r=>e.#b(r),rindexes:r=>e.#P(r),isStale:r=>e.#p(r)}}get max(){return this.#c}get maxSize(){return this.#l}get calculatedSize(){return this.#m}get size(){return this.#n}get fetchMethod(){return this.#A}get dispose(){return this.#w}get disposeAfter(){return this.#h}constructor(e){let{max:r=0,ttl:n,ttlResolution:s=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:i,allowStale:c,dispose:u,disposeAfter:d,noDisposeOnSet:l,noUpdateTTL:f,maxSize:h=0,maxEntrySize:p=0,sizeCalculation:m,fetchMethod:y,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:k,ignoreFetchAbort:A}=e;if(r!==0&&!Ld(r))throw new TypeError("max option must be a nonnegative integer");let D=r?KD(r):Array;if(!D)throw new Error("invalid max value: "+r);if(this.#c=r,this.#l=h,this.maxEntrySize=p||this.#l,this.sizeCalculation=m,this.sizeCalculation){if(!this.#l&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#A=y,this.#_=!!y,this.#s=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#d=new D(r),this.#f=new D(r),this.#a=0,this.#i=0,this.#y=n2.create(r),this.#n=0,this.#m=0,typeof u=="function"&&(this.#w=u),typeof d=="function"?(this.#h=d,this.#o=[]):(this.#h=void 0,this.#o=void 0),this.#v=!!this.#w,this.#u=!!this.#h,this.noDisposeOnSet=!!l,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!k,this.ignoreFetchAbort=!!A,this.maxEntrySize!==0){if(this.#l!==0&&!Ld(this.#l))throw new TypeError("maxSize must be a positive integer if specified");if(!Ld(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#N()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!i,this.ttlResolution=Ld(s)||s===0?s:1,this.ttlAutopurge=!!a,this.ttl=n||0,this.ttl){if(!Ld(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#j()}if(this.#c===0&&this.ttl===0&&this.#l===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#c&&!this.#l){let B="LRU_CACHE_UNBOUNDED";IF(B)&&(UD.add(B),LD("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",B,t))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#j(){let e=new hp(this.#c),r=new hp(this.#c);this.#g=e,this.#S=r,this.#$=(a,o,i=Cm.now())=>{if(r[a]=o!==0?i:0,e[a]=o,o!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#p(a)&&this.delete(this.#r[a])},o+1);c.unref&&c.unref()}},this.#k=a=>{r[a]=e[a]!==0?Cm.now():0},this.#E=(a,o)=>{if(e[o]){let i=e[o],c=r[o];a.ttl=i,a.start=c,a.now=n||s();let u=a.now-c;a.remainingTTL=i-u}};let n=0,s=()=>{let a=Cm.now();if(this.ttlResolution>0){n=a;let o=setTimeout(()=>n=0,this.ttlResolution);o.unref&&o.unref()}return a};this.getRemainingTTL=a=>{let o=this.#s.get(a);if(o===void 0)return 0;let i=e[o],c=r[o];if(i===0||c===0)return 1/0;let u=(n||s())-c;return i-u},this.#p=a=>e[a]!==0&&r[a]!==0&&(n||s())-r[a]>e[a]}#k=()=>{};#E=()=>{};#$=()=>{};#p=()=>!1;#N(){let e=new hp(this.#c);this.#m=0,this.#x=e,this.#T=r=>{this.#m-=e[r],e[r]=0},this.#M=(r,n,s,a)=>{if(this.#t(n))return 0;if(!Ld(s))if(a){if(typeof a!="function")throw new TypeError("sizeCalculation must be a function");if(s=a(n,r),!Ld(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return s},this.#R=(r,n,s)=>{if(e[r]=n,this.#l){let a=this.#l-e[r];for(;this.#m>a;)this.#D(!0)}this.#m+=e[r],s&&(s.entrySize=n,s.totalCalculatedSize=this.#m)}}#T=e=>{};#R=(e,r,n)=>{};#M=(e,r,n,s)=>{if(n||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#b({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#i;!(!this.#O(r)||((e||!this.#p(r))&&(yield r),r===this.#a));)r=this.#f[r]}*#P({allowStale:e=this.allowStale}={}){if(this.#n)for(let r=this.#a;!(!this.#O(r)||((e||!this.#p(r))&&(yield r),r===this.#i));)r=this.#d[r]}#O(e){return e!==void 0&&this.#s.get(this.#r[e])===e}*entries(){for(let e of this.#b())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*rentries(){for(let e of this.#P())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*keys(){for(let e of this.#b()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*rkeys(){for(let e of this.#P()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*values(){for(let e of this.#b())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#P())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}find(e,r={}){for(let n of this.#b()){let s=this.#e[n],a=this.#t(s)?s.__staleWhileFetching:s;if(a!==void 0&&e(a,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(e,r=this){for(let n of this.#b()){let s=this.#e[n],a=this.#t(s)?s.__staleWhileFetching:s;a!==void 0&&e.call(r,a,this.#r[n],this)}}rforEach(e,r=this){for(let n of this.#P()){let s=this.#e[n],a=this.#t(s)?s.__staleWhileFetching:s;a!==void 0&&e.call(r,a,this.#r[n],this)}}purgeStale(){let e=!1;for(let r of this.#P({allowStale:!0}))this.#p(r)&&(this.delete(this.#r[r]),e=!0);return e}dump(){let e=[];for(let r of this.#b({allowStale:!0})){let n=this.#r[r],s=this.#e[r],a=this.#t(s)?s.__staleWhileFetching:s;if(a===void 0||n===void 0)continue;let o={value:a};if(this.#g&&this.#S){o.ttl=this.#g[r];let i=Cm.now()-this.#S[r];o.start=Math.floor(Date.now()-i)}this.#x&&(o.size=this.#x[r]),e.unshift([n,o])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let s=Date.now()-n.start;n.start=Cm.now()-s}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:s=this.ttl,start:a,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:i=this.sizeCalculation,status:c}=n,{noUpdateTTL:u=this.noUpdateTTL}=n,d=this.#M(e,r,n.size||0,i);if(this.maxEntrySize&&d>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.delete(e),this;let l=this.#n===0?void 0:this.#s.get(e);if(l===void 0)l=this.#n===0?this.#i:this.#y.length!==0?this.#y.pop():this.#n===this.#c?this.#D(!1):this.#n,this.#r[l]=e,this.#e[l]=r,this.#s.set(e,l),this.#d[this.#i]=l,this.#f[l]=this.#i,this.#i=l,this.#n++,this.#R(l,d,c),c&&(c.set="add"),u=!1;else{this.#I(l);let f=this.#e[l];if(r!==f){if(this.#_&&this.#t(f)?f.__abortController.abort(new Error("replaced")):o||(this.#v&&this.#w?.(f,e,"set"),this.#u&&this.#o?.push([f,e,"set"])),this.#T(l),this.#R(l,d,c),this.#e[l]=r,c){c.set="replace";let h=f&&this.#t(f)?f.__staleWhileFetching:f;h!==void 0&&(c.oldValue=h)}}else c&&(c.set="update")}if(s!==0&&!this.#g&&this.#j(),this.#g&&(u||this.#$(l,s,a),c&&this.#E(c,l)),!o&&this.#u&&this.#o){let f=this.#o,h;for(;h=f?.shift();)this.#h?.(...h)}return this}pop(){try{for(;this.#n;){let e=this.#e[this.#a];if(this.#D(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#u&&this.#o){let e=this.#o,r;for(;r=e?.shift();)this.#h?.(...r)}}}#D(e){let r=this.#a,n=this.#r[r],s=this.#e[r];return this.#_&&this.#t(s)?s.__abortController.abort(new Error("evicted")):(this.#v||this.#u)&&(this.#v&&this.#w?.(s,n,"evict"),this.#u&&this.#o?.push([s,n,"evict"])),this.#T(r),e&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#y.push(r)),this.#n===1?(this.#a=this.#i=0,this.#y.length=0):this.#a=this.#d[r],this.#s.delete(n),this.#n--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:s}=r,a=this.#s.get(e);if(a!==void 0){let o=this.#e[a];if(this.#t(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#p(a))s&&(s.has="stale",this.#E(s,a));else return n&&this.#k(a),s&&(s.has="hit",this.#E(s,a)),!0}else s&&(s.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,s=this.#s.get(e);if(s!==void 0&&(n||!this.#p(s))){let a=this.#e[s];return this.#t(a)?a.__staleWhileFetching:a}}#C(e,r,n,s){let a=r===void 0?void 0:this.#e[r];if(this.#t(a))return a;let o=new T0,{signal:i}=n;i?.addEventListener("abort",()=>o.abort(i.reason),{signal:o.signal});let c={signal:o.signal,options:n,context:s},u=(m,y=!1)=>{let{aborted:S}=o.signal,v=n.ignoreFetchAbort&&m!==void 0;if(n.status&&(S&&!y?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,v&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),S&&!v&&!y)return l(o.signal.reason);let E=h;return this.#e[r]===h&&(m===void 0?E.__staleWhileFetching?this.#e[r]=E.__staleWhileFetching:this.delete(e):(n.status&&(n.status.fetchUpdated=!0),this.set(e,m,c.options))),m},d=m=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=m),l(m)),l=m=>{let{aborted:y}=o.signal,S=y&&n.allowStaleOnFetchAbort,v=S||n.allowStaleOnFetchRejection,E=v||n.noDeleteOnFetchRejection,k=h;if(this.#e[r]===h&&(!E||k.__staleWhileFetching===void 0?this.delete(e):S||(this.#e[r]=k.__staleWhileFetching)),v)return n.status&&k.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),k.__staleWhileFetching;if(k.__returned===k)throw m},f=(m,y)=>{let S=this.#A?.(e,a,c);S&&S instanceof Promise&&S.then(v=>m(v),y),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(m(),n.allowStaleOnFetchAbort&&(m=v=>u(v,!0)))})};n.status&&(n.status.fetchDispatched=!0);let h=new Promise(f).then(u,d),p=Object.assign(h,{__abortController:o,__staleWhileFetching:a,__returned:void 0});return r===void 0?(this.set(e,p,{...c.options,status:void 0}),r=this.#s.get(e)):this.#e[r]=p,p}#t(e){if(!this.#_)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof T0}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:i=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:l=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:y=!1,status:S,signal:v}=r;if(!this.#_)return S&&(S.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:a,status:S});let E={allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:a,ttl:o,noDisposeOnSet:i,size:c,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:l,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:p,ignoreFetchAbort:h,status:S,signal:v},k=this.#s.get(e);if(k===void 0){S&&(S.fetch="miss");let A=this.#C(e,k,E,m);return A.__returned=A}else{let A=this.#e[k];if(this.#t(A)){let q=n&&A.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",q&&(S.returnedStale=!0)),q?A.__staleWhileFetching:A.__returned=A}let D=this.#p(k);if(!y&&!D)return S&&(S.fetch="hit"),this.#I(k),s&&this.#k(k),S&&this.#E(S,k),A;let B=this.#C(e,k,E,m),F=B.__staleWhileFetching!==void 0&&n;return S&&(S.fetch=D?"stale":"refresh",F&&D&&(S.returnedStale=!0)),F?B.__staleWhileFetching:B.__returned=B}}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:a=this.noDeleteOnStaleGet,status:o}=r,i=this.#s.get(e);if(i!==void 0){let c=this.#e[i],u=this.#t(c);return o&&this.#E(o,i),this.#p(i)?(o&&(o.get="stale"),u?(o&&n&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),n?c.__staleWhileFetching:void 0):(a||this.delete(e),o&&n&&(o.returnedStale=!0),n?c:void 0)):(o&&(o.get="hit"),u?c.__staleWhileFetching:(this.#I(i),s&&this.#k(i),c))}else o&&(o.get="miss")}#B(e,r){this.#f[r]=e,this.#d[e]=r}#I(e){e!==this.#i&&(e===this.#a?this.#a=this.#d[e]:this.#B(this.#f[e],this.#d[e]),this.#B(this.#i,e),this.#i=e)}delete(e){let r=!1;if(this.#n!==0){let n=this.#s.get(e);if(n!==void 0)if(r=!0,this.#n===1)this.clear();else{this.#T(n);let s=this.#e[n];this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#v||this.#u)&&(this.#v&&this.#w?.(s,e,"delete"),this.#u&&this.#o?.push([s,e,"delete"])),this.#s.delete(e),this.#r[n]=void 0,this.#e[n]=void 0,n===this.#i?this.#i=this.#f[n]:n===this.#a?this.#a=this.#d[n]:(this.#d[this.#f[n]]=this.#d[n],this.#f[this.#d[n]]=this.#f[n]),this.#n--,this.#y.push(n)}}if(this.#u&&this.#o?.length){let n=this.#o,s;for(;s=n?.shift();)this.#h?.(...s)}return r}clear(){for(let e of this.#P({allowStale:!0})){let r=this.#e[e];if(this.#t(r))r.__abortController.abort(new Error("deleted"));else{let n=this.#r[e];this.#v&&this.#w?.(r,n,"delete"),this.#u&&this.#o?.push([r,n,"delete"])}}if(this.#s.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#g&&this.#S&&(this.#g.fill(0),this.#S.fill(0)),this.#x&&this.#x.fill(0),this.#a=0,this.#i=0,this.#y.length=0,this.#m=0,this.#n=0,this.#u&&this.#o){let e=this.#o,r;for(;r=e?.shift();)this.#h?.(...r)}}};var A0=class{constructor(e){this.timeToLiveInSeconds=e;this.cache=new I0({max:1e5,ttl:e*1e3})}cache;async set(e,r){try{this.cache.set(e,r)}catch{}}async get(e){return this.cache.get(e)}};C0();ht();var zd=class t{static _singleton;cache;constructor(e){this.cache=e||new A0(600)}static get singleton(){return t._singleton===void 0&&(t._singleton=new t),t._singleton}static async verifySignatures(e,r){return await t.singleton.verifySignatures(e,r)}async verifySignatures(e,r){let n=[];for(let s of e.signatures){let a,o=Te.base64UrlToObject(s.protected),{kid:i,alg:c}=o;if(i===void 0||typeof i!="string")throw new ne("GeneralJwsVerifierMissingKid","JWS protected header is missing required 'kid' property");if(c===void 0||typeof c!="string")throw new ne("GeneralJwsVerifierMissingAlg","JWS protected header is missing required 'alg' property");let u=`${s.protected}.${e.payload}.${s.signature}`,d=await this.cache.get(u);if(d===void 0){let f=await t.getPublicKey(i,r);a=await vt.verifySignature(e.payload,s,f),await this.cache.set(u,a)}else a=d;let l=vt.extractDid(i);if(a)n.push(l);else throw new ne("GeneralJwsVerifierInvalidSignature",`Signature verification failed for ${l}`)}return{signers:n}}static async getPublicKey(e,r){let n=vt.extractDid(e),{didDocument:s}=await r.resolve(n),{verificationMethod:a=[]}=s||{},o;for(let c of a)if(e.endsWith(c.id)){o=c;break}if(!o)throw new ne("GeneralJwsVerifierGetPublicKeyNotFound","public key needed to verify signature not found in DID Document");Lc("JwkVerificationMethod",o);let{publicKeyJwk:i}=o;return i}};vi();ht();async function on(t,e,r){if(t===void 0)throw new ne("AuthenticateJwsMissing","Missing JWS.");if(await zd.verifySignatures(t.signature,e),t.ownerSignature!==void 0&&await zd.verifySignatures(t.ownerSignature,e),t.authorDelegatedGrant!==void 0){let n=await St.parse(t.authorDelegatedGrant);await zd.verifySignatures(n.message.authorization.signature,e)}if(t.ownerDelegatedGrant!==void 0){let n=await St.parse(t.ownerDelegatedGrant);await zd.verifySignatures(n.message.authorization.signature,e)}r!==void 0&&await zd.verifySignatures(r,e)}w();var ag=class{_protocols=new Map;register(e){this._protocols.set(e.uri,e)}get(e){return this._protocols.get(e)}getDefinition(e){return this._protocols.get(e)?.definition}has(e){return this._protocols.has(e)}all(){return[...this._protocols.values()]}mapErrorToStatusCode(e){for(let r of this._protocols.values()){let n=r.mapErrorToStatusCode?.(e);if(n!==void 0)return n}}};KE();w();var cg=class{async isActiveTenant(e){return{isActiveTenant:!0}}};Vc();w();w();Oa();ir();var bn=class{_message;get message(){return this._message}_signer;get signer(){return this._signer}_author;get author(){return this._author}_signaturePayload;get signaturePayload(){return this._signaturePayload}get isSignedByAuthorDelegate(){return we.isSignedByAuthorDelegate(this._message)}constructor(e){this._message=e,e.authorization!==void 0&&(this._signer=we.getSigner(e),e.authorization.authorDelegatedGrant!==void 0?this._author=we.getSigner(e.authorization.authorDelegatedGrant):this._author=this._signer,this._signaturePayload=vt.decodePlainObjectPayload(e.authorization.signature))}toJSON(){return this.message}};ir();la();$n();Ya();hs();Vs();ht();Qt();Ao();var Hl=class t extends bn{static async parse(e){let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne("RecordsCountFilterMissingRequiredProperties","Role-authorized counts must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&zn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Za(e.descriptor.filter.schema),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Records",method:"Count",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:ke.normalizeFilter(e.filter)};qt(r);let n=e.signer,s;n&&(s=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Zr.parse(this.message.authorization.authorDelegatedGrant);await Sn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}};w();Il();ir();la();$n();Ya();hs();Vs();ht();Qt();Ao();var Jl=class t extends bn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort==="publishedAscending"||e.descriptor.dateSort==="publishedDescending"))throw new ne("RecordsQueryParseFilterPublishedSortInvalid",`queries must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne("RecordsQueryFilterMissingRequiredProperties","Role-authorized queries must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&zn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Za(e.descriptor.filter.schema),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Records",method:"Query",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:ke.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination};if(e.filter.published===!1&&(e.dateSort==="publishedAscending"||e.dateSort==="publishedDescending"))throw new ne("RecordsQueryCreateFilterPublishedSortInvalid",`queries must not filter for \`published:false\` and sort by ${e.dateSort}`);qt(r);let n=e.signer,s;n&&(s=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Zr.parse(this.message.authorization.authorDelegatedGrant);await Sn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantee:this.signer,expectedGrantor:this.author,permissionGrant:r,messageStore:e})}};Vd();Kp();w();ir();w();function ut(t,e){let r=t instanceof Error?t.message:"Error";return{status:{code:e,detail:r}}}w();Vd();ln();w();Qt();$v();w();w();var dc=class{static maxDataSizeAllowedToBeEncoded=3e4};ln();ya();ir();la();w();ln();ir();ht();var dg=class t{id;requester;description;delegated;scope;conditions;static parse(e){return t.validateMessage(e),new t(e)}static validateMessage(e){if(e.encodedData===void 0||e.encodedData===null)throw new ne("PermissionRequestParseMissingEncodedData","permission request message is missing encodedData");if(we.getSigner(e)===void 0)throw new ne("PermissionRequestParseMissingAuthorization","permission request message is missing authorization (unable to extract requester)");if(Te.base64UrlToObject(e.encodedData).scope===void 0)throw new ne("PermissionRequestParseMissingScope","permission request data is missing required property `scope`")}constructor(e){this.id=e.recordId,this.requester=we.getSigner(e);let r=e.encodedData,n=Te.base64UrlToObject(r);this.delegated=n.delegated,this.description=n.description,this.scope=n.scope,this.conditions=n.conditions}};$n();vi();Vs();C0();ht();Qt();Ao();var Tr=class t{static uri="https://identity.foundation/dwn/permissions";static requestPath="request";static grantPath="grant";static revocationPath="grant/revocation";static definition={published:!0,protocol:t.uri,types:{request:{dataFormats:["application/json"]},grant:{dataFormats:["application/json"]},revocation:{dataFormats:["application/json"]}},structure:{request:{$size:{max:1e4},$actions:[{who:"anyone",can:["create"]}]},grant:{$size:{max:1e4},$actions:[{who:"recipient",of:"grant",can:["read"]}],revocation:{$size:{max:1e4},$actions:[{who:"anyone",can:["read"]}]}}}};get uri(){return t.uri}get definition(){return t.definition}validateRecord(e,r){t.validateSchema(e,r)}async preProcessWrite(e,r,n){if(r.descriptor.protocolPath!==t.revocationPath)return;let s=r.descriptor.parentId,a=await t.fetchGrant(e,n,s),o=r.descriptor.tags?.protocol,i="protocol"in a.scope?a.scope.protocol:void 0;if(i!==o)throw new ne("PermissionsProtocolValidateRevocationProtocolTagMismatch",`Revocation protocol ${o} does not match grant protocol ${i}`)}async postProcessWrite(e,r,n){if(r.message.descriptor.protocolPath!==t.revocationPath)return;let a={permissionGrantId:r.message.descriptor.parentId,dateCreated:{gte:r.message.descriptor.messageTimestamp}},{messages:o}=await n.messageStore.query(e,[a]);if(o.length===0)return;for(let c of o)if(c.descriptor.method==="Write"){let u=c;u.descriptor.dataSize>dc.maxDataSizeAllowedToBeEncoded&&await n.dataStore.delete(e,u.recordId,u.descriptor.dataCid)}let i=await Promise.all(o.map(c=>we.getCid(c)));await n.stateIndex.delete(e,i),await Promise.all(i.map(c=>n.messageStore.delete(e,c)))}mapErrorToStatusCode(e){if(e.startsWith("PermissionsProtocolValidate"))return 400}constructAdditionalMessageFilter(e){let{protocol:r,messageTimestamp:n}=e;if(r===void 0)return;let s={protocol:t.uri,...ke.convertTagsFilter({protocol:r})};if(n!==void 0){let a=Wt.convertRangeCriterion(n);a&&(s.messageTimestamp=a)}return s}static parseRequest(e){return Te.base64UrlToObject(e)}static async createRequest(e){if(this.isRecordPermissionScope(e.scope)&&e.scope.protocol===void 0)throw new ne("PermissionsProtocolCreateRequestRecordsScopeMissingProtocol","Permission request for Records must have a scope with a `protocol` property");let r=t.normalizePermissionScope(e.scope),n={description:e.description,delegated:e.delegated,scope:r,conditions:e.conditions},s;this.hasProtocolScope(r)&&(s={protocol:r.protocol});let a=Te.objectToBytes(n),o=await St.create({signer:e.signer,messageTimestamp:e.dateRequested,protocol:t.uri,protocolPath:t.requestPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:Te.bytesToBase64Url(a)};return{recordsWrite:o,permissionRequestData:n,permissionRequestBytes:a,dataEncodedMessage:i}}static async createGrant(e){if(this.isRecordPermissionScope(e.scope)&&e.scope.protocol===void 0)throw new ne("PermissionsProtocolCreateGrantRecordsScopeMissingProtocol","Permission grants for Records must have a scope with a `protocol` property");let r=t.normalizePermissionScope(e.scope),n={dateExpires:e.dateExpires,requestId:e.requestId,description:e.description,delegated:e.delegated,scope:r,conditions:e.conditions},s;this.hasProtocolScope(r)&&(s={protocol:r.protocol});let a=Te.objectToBytes(n),o=await St.create({signer:e.signer,messageTimestamp:e.dateGranted,dateCreated:e.dateGranted,recipient:e.grantedTo,protocol:t.uri,protocolPath:t.grantPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:Te.bytesToBase64Url(a)};return{recordsWrite:o,permissionGrantData:n,permissionGrantBytes:a,dataEncodedMessage:i}}static async createRevocation(e){let r={description:e.description},n=e.grant.id,s;this.hasProtocolScope(e.grant.scope)&&(s={protocol:pi(e.grant.scope.protocol)});let a=Te.objectToBytes(r),o=await St.create({signer:e.signer,parentContextId:n,protocol:t.uri,protocolPath:t.revocationPath,dataFormat:"application/json",data:a,tags:s}),i={...o.message,encodedData:Te.bytesToBase64Url(a)};return{recordsWrite:o,permissionRevocationData:r,permissionRevocationBytes:a,dataEncodedMessage:i}}static validateSchema(e,r){let n=Te.bytesToString(r),s=JSON.parse(n);if(e.descriptor.protocolPath===t.requestPath){let a=s;Lc("PermissionRequestData",a),t.validateScopeAndTags(a.scope,e)}else if(e.descriptor.protocolPath===t.grantPath){Lc("PermissionGrantData",s);let a=s;t.validateScopeAndTags(a.scope,e),yt.validateTimestamp(a.dateExpires)}else if(e.descriptor.protocolPath===t.revocationPath)Lc("PermissionRevocationData",s);else throw new ne("PermissionsProtocolValidateSchemaUnexpectedRecord",`Unexpected permission record: ${e.descriptor.protocolPath}`)}static async fetchGrant(e,r,n){let s={recordId:n,isLatestBaseState:!0},{messages:a}=await r.query(e,[s]),o=a[0],i=o?.descriptor.interface,c=o?.descriptor.method;if(i!=="Records"||c!=="Write"||o.descriptor.protocolPath!==t.grantPath)throw new ne("GrantAuthorizationGrantMissing",`Could not find permission grant with record ID ${n}.`);let u=o;return Zr.parse(u)}static async getScopeFromPermissionRecord(e,r,n){if(n.descriptor.protocol!==t.uri)throw new ne("PermissionsProtocolGetScopeInvalidProtocol",`Unexpected protocol for permission record: ${n.descriptor.protocol}`);return n.descriptor.protocolPath===t.revocationPath?(await t.fetchGrant(e,r,n.descriptor.parentId)).scope:n.descriptor.protocolPath===t.grantPath?Zr.parse(n).scope:dg.parse(n).scope}static normalizePermissionScope(e){let r={...e};return t.hasProtocolScope(r)&&(r.protocol=pi(r.protocol)),r}static isRecordPermissionScope(e){return e.interface==="Records"}static hasProtocolScope(e){return"protocol"in e&&e.protocol!==void 0}static validateTags(e,r){if(e.descriptor.tags===void 0||e.descriptor.tags.protocol===void 0)throw new ne("PermissionsProtocolValidateScopeMissingProtocolTag","Permission grants must have a `tags` property that contains a protocol tag");let n=e.descriptor.tags.protocol;if(n!==r)throw new ne("PermissionsProtocolValidateScopeProtocolMismatch",`Permission grants must have a scope with a protocol that matches the tagged protocol: ${n}`)}static validateScopeAndTags(e,r){if(this.hasProtocolScope(e)&&(zn(e.protocol),this.validateTags(r,e.protocol)),!!this.isRecordPermissionScope(e)&&e.contextId!==void 0&&e.protocolPath!==void 0)throw new ne("PermissionsProtocolValidateScopeContextIdProhibitedProperties","Permission grants cannot have both `contextId` and `protocolPath` present")}};$n();vi();ht();var gu=class t{static async authorizeMessagesRead(e){let{messagesReadMessage:r,messageToRead:n,expectedGrantor:s,expectedGrantee:a,permissionGrant:o,messageStore:i}=e;await ro.performBaseValidation({incomingMessage:r,expectedGrantor:s,expectedGrantee:a,permissionGrant:o,messageStore:i});let c=o.scope;await t.verifyScope(s,n,c,i)}static async authorizeSubscribeOrSync(e){let{incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}=e;if(await ro.performBaseValidation({incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}),Tr.hasProtocolScope(a.scope)){let i=a.scope.protocol;if("action"in r.descriptor){let c=r;if(c.descriptor.protocol!==i)throw new ne("EventsGrantAuthorizationMismatchedProtocol",`The protocol ${c.descriptor.protocol} does not match the scoped protocol ${i}`)}else{let c=r;for(let u of c.descriptor.filters)if(u.protocol!==i)throw new ne("EventsGrantAuthorizationMismatchedProtocol",`The protocol ${u.protocol} does not match the scoped protocol ${i}`)}}}static async verifyScope(e,r,n,s){if(n.protocol!==void 0){if(r.descriptor.interface==="Records"){let a=r,o=ke.isRecordsWrite(a)?a:await St.fetchNewestRecordsWrite(s,e,a.descriptor.recordId);if(o.descriptor.protocol===n.protocol)return;if(o.descriptor.protocol===Tr.uri){let i=await Tr.getScopeFromPermissionRecord(e,s,o);if(Tr.hasProtocolScope(i)&&i.protocol===n.protocol)return}}else if(r.descriptor.interface==="Protocols"&&r.descriptor.definition.protocol===n.protocol)return;throw new ne("MessagesReadVerifyScopeFailed","record message failed scope authorization")}}};w();Vc();ir();Vs();ht();Qt();var Zl=class t extends bn{static async parse(e){return we.validateJsonSchema(e),this.validateMessageCid(e.descriptor.messageCid),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let{signer:r,permissionGrantId:n}=e,s={interface:"Messages",method:"Read",messageCid:e.messageCid,messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),...n!==void 0&&{permissionGrantId:n}},a=await we.createAuthorization({descriptor:s,signer:r,permissionGrantId:n}),o={descriptor:s,authorization:a};return we.validateJsonSchema(o),t.validateMessageCid(e.messageCid),new t(o)}static validateMessageCid(e){try{Ar.parseCid(e)}catch{throw new ne("MessagesReadInvalidCid",`${e} is not a valid CID`)}}};$n();ht();var vb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Zl.parse(r)}catch(o){return ut(o,400)}try{await on(r.authorization,this.deps.didResolver)}catch(o){return ut(o,401)}let s=await this.deps.messageStore.get(e,r.descriptor.messageCid);if(s===void 0)return{status:{code:404,detail:"Not Found"}};try{await t.authorizeMessagesRead(e,n,s,this.deps.messageStore)}catch(o){return ut(o,401)}let a={message:s,messageCid:r.descriptor.messageCid};if(ke.isRecordsWrite(s)){let o=a.message;if(o.encodedData!==void 0){let i=Te.base64UrlToBytes(o.encodedData);a.data=ts.fromBytes(i),delete o.encodedData}else{let i=await this.deps.dataStore.get(e,o.recordId,o.descriptor.dataCid);i?.dataStream!==void 0&&(a.data=i.dataStream)}}return{status:{code:200,detail:"OK"},entry:a}}static async authorizeMessagesRead(e,r,n,s){if(r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let a=await Tr.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await gu.authorizeMessagesRead({messagesReadMessage:r.message,messageToRead:n,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:a,messageStore:s})}else throw new ne("MessagesReadAuthorizationFailed","protocol message failed authorization")}};w();ir();w();ya();Ao();hs();var bb=class{static normalizeFilters(e){let r=[];for(let n of e){let s=n.protocol!==void 0?pi(n.protocol):void 0,a={...n,protocol:s};qt(a),Tl(a)||r.push(a)}return r}static convertFilters(e,r){let n=[];for(let s of e){if(r!==void 0)for(let a of r.all()){let o=a.constructAdditionalMessageFilter?.(s);o!==void 0&&n.push(o)}n.push(this.convertFilter(s))}return n}static convertFilter(e){let r={...e},{messageTimestamp:n}=e,s=n?Wt.convertRangeCriterion(n):void 0;return s&&(r.messageTimestamp=s,delete r.dateUpdated),r}};w();ir();hs();Vs();Ao();Qt();var Yl=class t extends bn{static async parse(e){we.validateJsonSchema(e),await we.validateSignatureStructure(e.authorization.signature,e.descriptor);for(let r of e.descriptor.filters)"protocol"in r&&r.protocol!==void 0&&zn(r.protocol);return yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r=yt.getCurrentTimestamp(),n={interface:"Messages",method:"Subscribe",filters:e.filters??[],messageTimestamp:e.messageTimestamp??r,permissionGrantId:e.permissionGrantId,cursor:e.cursor};qt(n);let{permissionGrantId:s,signer:a}=e,o=await we.createAuthorization({descriptor:n,signer:a,permissionGrantId:s}),i={descriptor:n,authorization:o};return we.validateJsonSchema(i),new t(i)}};ht();var Pb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return ut(new ne("MessagesSubscribeEventLogUnimplemented","Subscriptions are not supported"),501);let s;try{s=await Yl.parse(r)}catch(u){return ut(u,400)}try{await on(r.authorization,this.deps.didResolver),await t.authorizeMessagesSubscribe(e,s,this.deps.messageStore)}catch(u){return ut(u,401)}let{filters:a,cursor:o}=r.descriptor,i=bb.convertFilters(a,this.deps.coreProtocols),c=await we.getCid(r);try{let u=await this.deps.eventLog.subscribe(e,c,n,{cursor:o,filters:i});return{status:{code:200,detail:"OK"},subscription:u}}catch(u){return ut(u,500)}}static async authorizeMessagesSubscribe(e,r,n){if(r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await Tr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await gu.authorizeSubscribeOrSync({incomingMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new ne("MessagesSubscribeAuthorizationFailed","message failed authorization")}};w();ln();vu();w();ir();hs();Vs();Ao();Qt();var lg=class t extends bn{static async parse(e){return we.validateJsonSchema(e),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.protocol!==void 0&&zn(e.descriptor.protocol),new t(e)}static async create(e){let r={interface:"Messages",method:"Sync",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),action:e.action,protocol:e.protocol,prefix:e.prefix,permissionGrantId:e.permissionGrantId,hashes:e.hashes,depth:e.depth};qt(r);let{permissionGrantId:n,signer:s}=e,a=await we.createAuthorization({descriptor:r,signer:s,permissionGrantId:n}),o={descriptor:r,authorization:a};return we.validateJsonSchema(o),new t(o)}};ht();var bZ=262144,xb=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await lg.parse(r)}catch(i){return ut(i,400)}try{await on(r.authorization,this.deps.didResolver),await t.authorizeMessagesSync(e,n,this.deps.messageStore)}catch(i){return ut(i,401)}let{action:s,protocol:a,prefix:o}=r.descriptor;try{switch(s){case"root":{let i=a!==void 0?await this.deps.stateIndex.getProtocolRoot(e,a):await this.deps.stateIndex.getRoot(e);return{status:{code:200,detail:"OK"},root:Vn(i)}}case"subtree":{let i=t.parseBitPrefix(o),c=a!==void 0?await this.deps.stateIndex.getProtocolSubtreeHash(e,a,i):await this.deps.stateIndex.getSubtreeHash(e,i);return{status:{code:200,detail:"OK"},hash:Vn(c)}}case"leaves":{let i=t.parseBitPrefix(o),c=a!==void 0?await this.deps.stateIndex.getProtocolLeaves(e,a,i):await this.deps.stateIndex.getLeaves(e,i);return{status:{code:200,detail:"OK"},entries:c}}case"diff":return this.handleDiff(e,r);default:return{status:{code:400,detail:`Unknown action: ${s}`}}}}catch(i){return ut(i,500)}}async handleDiff(e,r){let{protocol:n,hashes:s,depth:a}=r.descriptor;if(!s||a===void 0)return{status:{code:400,detail:"diff action requires hashes and depth"}};let o=this.deps.stateIndex,i=[],c=[],u=await this.getDefaultHashHex(a),d=new Set;for(let[h,p]of Object.entries(s))p!==u&&d.add(h);let l=await this.collectSubtreeHashes(e,n,a);for(let h of Object.keys(l))d.add(h);for(let h of d){let p=s[h],m=l[h];if(p===m)continue;if(m===void 0){c.push(h);continue}if(p===void 0){let v=t.parseBitPrefix(h),E=n!==void 0?await o.getProtocolLeaves(e,n,v):await o.getLeaves(e,v);i.push(...E);continue}let y=t.parseBitPrefix(h),S=n!==void 0?await o.getProtocolLeaves(e,n,y):await o.getLeaves(e,y);i.push(...S),c.push(h)}let f=await this.buildDiffEntries(e,i);return{status:{code:200,detail:"OK"},onlyRemote:f,onlyLocal:c}}async collectSubtreeHashes(e,r,n){let s=this.deps.stateIndex,a={},o=await this.getDefaultHashHex(n),i=async(c,u)=>{let d=t.parseBitPrefix(c),l=r!==void 0?await s.getProtocolSubtreeHash(e,r,d):await s.getSubtreeHash(e,d),f=Vn(l);if(f!==o){if(u>=n){a[c]=f;return}await Promise.all([i(c+"0",u+1),i(c+"1",u+1)])}};return await i("",0),a}_defaultHashHexCache;async getDefaultHashHex(e){if(this._defaultHashHexCache===void 0){let{initDefaultHashes:r}=await Promise.resolve().then(()=>(vu(),gO)),n=await r();this._defaultHashHexCache=new Map;for(let s=0;s<=256;s++)this._defaultHashHexCache.set(s,Vn(n[s]))}return this._defaultHashHexCache.get(e)??""}async buildDiffEntries(e,r){let n=[];for(let s of r){let{message:a,encodedData:o,data:i}=await this.readMessageByCid(e,s);if(!a)continue;let c={messageCid:s,message:a};if(o)c.encodedData=o;else if(i){let u=await t.streamToBytes(i);u.byteLength<=bZ&&(c.encodedData=Te.bytesToBase64Url(u))}n.push(c)}return n}async readMessageByCid(e,r){let n=await this.deps.messageStore.get(e,r);if(!n)return{};let s;"encodedData"in n&&(s=n.encodedData,delete n.encodedData);let a;if(n.descriptor.interface==="Records"&&n.descriptor.method==="Write"){let o=n.descriptor?.dataCid;if(o&&this.deps.dataStore){let i=n.descriptor?.recordId;if(i){let c=await this.deps.dataStore.get(e,i,o);c?.dataStream&&(a=c.dataStream)}}}return{message:n,encodedData:s,data:a}}static async streamToBytes(e){let r=e.getReader(),n=[],s=0;for(;;){let{done:i,value:c}=await r.read();if(i)break;n.push(c),s+=c.byteLength}let a=new Uint8Array(s),o=0;for(let i of n)a.set(i,o),o+=i.byteLength;return a}static parseBitPrefix(e){if(!/^[01]*$/.test(e))throw new ne("MessagesSyncInvalidPrefix",`Invalid prefix: must contain only '0' and '1' characters, got: ${e}`);if(e.length>256)throw new ne("MessagesSyncInvalidPrefix",`Invalid prefix: length must be <= 256, got: ${e.length}`);return Array.from(e,r=>r==="1")}static async authorizeMessagesSync(e,r,n){if(r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await Tr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await gu.authorizeSubscribeOrSync({incomingMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new ne("MessagesSyncAuthorizationFailed","message failed authorization")}};w();ir();w();var lN=Nn(rI(),1);ir();la();w();$v();ht();var Iu=class t{static async authorizeConfigure(e){let{protocolsConfigureMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}=e;await ro.performBaseValidation({incomingMessage:r,expectedGrantor:n,expectedGrantee:s,permissionGrant:a,messageStore:o}),t.verifyScope(r,a.scope)}static async authorizeQuery(e){let{expectedGrantee:r,expectedGrantor:n,incomingMessage:s,permissionGrant:a,messageStore:o}=e;await ro.performBaseValidation({incomingMessage:s,expectedGrantor:n,expectedGrantee:r,permissionGrant:a,messageStore:o});let c=a.scope.protocol,u=s.descriptor.filter?.protocol;if(c!==void 0&&u!==c)throw new ne("ProtocolsGrantAuthorizationQueryProtocolScopeMismatch",`Grant protocol scope ${c} does not match protocol in message ${u}`)}static verifyScope(e,r){if(r.protocol!==void 0&&r.protocol!==e.descriptor.definition.protocol)throw new ne("ProtocolsGrantAuthorizationScopeProtocolMismatch","Grant scope specifies different protocol than what appears in the configure message.")}};Vs();ht();Qt();w();Up();Kp();function Bi(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 pf(t){return t.includes(":")}function n1(t){return t.split("/").slice(-1)[0]}function ld(t,e){let r=t.split("/"),n,s=e;for(let a of r){if(!Object.hasOwn(s,a))return;n=s[a],s=n}return n}var nI=class{static async deriveAndInjectPublicEncryptionKeys(e,r,n){let s=JSON.parse(JSON.stringify(e));if(typeof r!="string"){let u=r,d=["protocolPath",e.protocol];async function l(f,h){for(let p in f)if(!p.startsWith("$")){let m=[...h,p],y=f[p];if(y.$ref!==void 0){await l(y,m);continue}let S=await u.derivePublicKey(m);y.$encryption={rootKeyId:u.rootKeyId,publicKeyJwk:S},await l(y,m)}}return await l(s.structure,d),s}let a=r;async function o(u,d){for(let l in u)if(!l.startsWith("$")){let f=await Va.derivePrivateKey(d,[l]),h=u[l];if(h.$ref!==void 0){await o(h,f);continue}let p=await gn.getPublicKey({key:f.derivedPrivateKey});h.$encryption={rootKeyId:a,publicKeyJwk:p},await o(h,f)}}let i={derivationScheme:"protocolPath",derivedPrivateKey:n,rootKeyId:a},c=await Va.derivePrivateKey(i,["protocolPath",e.protocol]);return await o(s.structure,c),s}};Ao();var fd=class t extends bn{static async parse(e){return we.validateJsonSchema(e),t.validateProtocolDefinition(e.descriptor.definition),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Protocols",method:"Configure",messageTimestamp:e.messageTimestamp??yt.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}),s={descriptor:r,authorization:n};return we.validateJsonSchema(s),t.validateProtocolDefinition(s.descriptor.definition),new t(s)}async authorizeAuthorDelegate(e){let r=Zr.parse(this.message.authorization.authorDelegatedGrant);await Iu.authorizeConfigure({protocolsConfigureMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}static validateProtocolDefinition(e){let{protocol:r,types:n,uses:s}=e;zn(r);for(let a in n){let o=n[a].schema;o!==void 0&&Za(o)}s!==void 0&&t.validateUses(s,r),t.validateStructure(e)}static validateUses(e,r){let n=/^[a-zA-Z][a-zA-Z0-9_-]*$/;for(let s in e){if(!n.test(s))throw new ne("ProtocolsConfigureInvalidUsesAlias",`invalid 'uses' alias '${s}': must match pattern ${n.toString()}.`);try{zn(e[s])}catch{throw new ne("ProtocolsConfigureInvalidUsesProtocolUrl",`invalid 'uses' protocol URL for alias '${s}': '${e[s]}' is not a valid normalized protocol URL.`)}if(e[s]===r)throw new ne("ProtocolsConfigureInvalidUsesSelfReference",`'uses' alias '${s}' references the protocol's own URI '${r}'. a protocol cannot compose itself.`)}}static validateStructure(e){let{uses:r}=e,n=Object.keys(e.types),s=t.fetchAllRolePathsRecursively("",e.structure,[]);t.validateRuleSetRecursively({ruleSet:e.structure,ruleSetProtocolPath:"",recordTypes:n,roles:s,uses:r,types:e.types})}static fetchAllRolePathsRecursively(e,r,n){if(e.split("/").length>10)throw new ne("ProtocolsConfigureRecordNestingDepthExceeded","Record nesting depth exceeded 10 levels.");for(let s in r){if(s.startsWith("$"))continue;let a=r[s],o;e===""?o=s:o=`${e}/${s}`,a.$role?n.push(o):t.fetchAllRolePathsRecursively(o,a,n)}return n}static validateRuleSetRecursively(e){let{ruleSet:r,ruleSetProtocolPath:n,recordTypes:s,roles:a,uses:o,types:i}=e;if(r.$ref!==void 0){if(n.includes("/"))throw new 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,o)}if(r.$size!==void 0){let{min:u=0,max:d}=r.$size;if(d!==void 0&&d<u)throw new ne("ProtocolsConfigureInvalidSize",`Invalid size range found: max limit ${d} less than min limit ${u} at protocol path '${n}'`)}if(r.$recordLimit!==void 0){let{max:u,strategy:d}=r.$recordLimit;if(!Number.isInteger(u)||u<1)throw new ne("ProtocolsConfigureInvalidRecordLimit",`Invalid $recordLimit.max value ${u} at protocol path '${n}': must be an integer >= 1.`);let l=Object.values(cm);if(!l.includes(d))throw new ne("ProtocolsConfigureInvalidRecordLimit",`Invalid $recordLimit.strategy '${d}' at protocol path '${n}': must be one of ${l.join(", ")}.`)}if(r.$tags){let u=new lN.default.default,{$allowUndefinedTags:d,$requiredTags:l,...f}=r.$tags;for(let h in f){let p=f[h];if(!u.validateSchema(p)){let m=u.errorsText(u.errors,{dataVar:`${n}/$tags/${h}`});throw new ne("ProtocolsConfigureInvalidTagSchema",`tags schema validation error: ${m}`)}}}let c=r.$actions??[];for(let u=0;u<c.length;u++){let d=c[u];if(d.role!==void 0){if(pf(d.role))t.validateCrossProtocolAlias(d.role,o,n,"role");else if(!a.includes(d.role))throw new ne("ProtocolsConfigureRoleDoesNotExistAtGivenPath",`Role in action ${JSON.stringify(d)} for rule set ${n} does not exist.`)}if(d.who==="anyone"&&d.of)throw new ne("ProtocolsConfigureInvalidActionOfNotAllowed",`'of' is not allowed at rule set protocol path (${n})`);if(d.who==="recipient"&&d.of===void 0&&d.can.some(f=>!["co-update","co-delete","co-prune"].includes(f)))throw new ne("ProtocolsConfigureInvalidRecipientOfAction","Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`.");if(d.who==="author"&&!d.of)throw new ne("ProtocolsConfigureInvalidActionMissingOf","'of' is required when 'author' is specified as 'who'");if(d.of!==void 0&&n!==""){if(pf(d.of))t.validateCrossProtocolAlias(d.of,o,n,"of");else if(!(n===d.of||n.startsWith(d.of+"/")))throw new ne("ProtocolsConfigureInvalidActionOfNotAnAncestor",`'of' value '${d.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(d)}.`)}if(d.can!==void 0){if(d.can.includes("update")&&!d.can.includes("create"))throw new ne("ProtocolsConfigureInvalidActionUpdateWithoutCreate",`Action rule ${JSON.stringify(d)} contains 'update' action but missing the required 'create' action.`);if(d.can.includes("delete")&&!d.can.includes("create"))throw new ne("ProtocolsConfigureInvalidActionDeleteWithoutCreate",`Action rule ${JSON.stringify(d)} contains 'delete' action but missing the required 'create' action.`);if(d.can.includes("prune")&&!d.can.includes("create"))throw new ne("ProtocolsConfigureInvalidActionPruneWithoutCreate",`Action rule ${JSON.stringify(d)} contains 'prune' action but missing the required 'create' action.`)}for(let l=u+1;l<c.length;l++){let f=c[l];if(d.who!==void 0){if(d.who===f.who&&d.of===f.of)throw new ne("ProtocolsConfigureDuplicateActorInRuleSet",`More than one action rule per actor ${d.who} of ${d.of} not allowed within a rule set: ${JSON.stringify(d)}`)}else if(d.role===f.role)throw new ne("ProtocolsConfigureDuplicateRoleInRuleSet",`More than one action rule per role ${d.role} not allowed within a rule set: ${JSON.stringify(d)}`)}}if(n!==""){let u=n.split("/").pop();i[u]?.encryptionRequired===!0&&c.some(f=>f.who==="anyone"&&f.can.includes("read"))&&console.warn(`ProtocolsConfigure: type '${u}' 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&&c.length>0&&c.some(d=>d.can.includes("update")||d.can.includes("co-update"))&&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 u in r){if(u.startsWith("$"))continue;let d=r[u];if(d.$ref===void 0&&!s.includes(u))throw new ne("ProtocolsConfigureInvalidRuleSetRecordType",`Rule set ${u} is not declared as an allowed type in the protocol definition.`);let l;n===""?l=u:l=`${n}/${u}`,t.validateRuleSetRecursively({ruleSet:d,ruleSetProtocolPath:l,recordTypes:s,roles:a,uses:o,types:i})}}static validateRefNode(e,r,n){let s=e.$ref,a=Bi(s);if(a===void 0)throw new ne("ProtocolsConfigureInvalidRefAlias",`'$ref' value '${s}' at protocol path '${r}' must be in 'alias:typePath' format.`);if(n===void 0||n[a.alias]===void 0)throw new ne("ProtocolsConfigureInvalidRefAlias",`'$ref' alias '${a.alias}' at protocol path '${r}' does not exist in the 'uses' map.`);let o=["$actions","$role","$size","$tags","$encryption","$recordLimit","$immutable","$delivery","$squash"];for(let i of o)if(e[i]!==void 0)throw new ne("ProtocolsConfigureInvalidRefNodeHasDirectives",`'$ref' node at protocol path '${r}' must not have '${i}'. $ref nodes are pure attachment points \u2014 directives belong on child rule sets.`)}static validateCrossProtocolAlias(e,r,n,s){let a=Bi(e);if(a===void 0){let o=s==="role"?"ProtocolsConfigureInvalidCrossProtocolRole":"ProtocolsConfigureInvalidCrossProtocolOf";throw new ne(o,`cross-protocol '${s}' 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 o=s==="role"?"ProtocolsConfigureInvalidCrossProtocolRole":"ProtocolsConfigureInvalidCrossProtocolOf";throw new ne(o,`cross-protocol '${s}' alias '${a.alias}' in '${e}' at protocol path '${n}' does not exist in the 'uses' map.`)}}static normalizeDefinition(e){let r={};for(let s in e.types)r[s]={...e.types[s]};for(let s in r){let a=r[s].schema;a!==void 0&&(r[s].schema=Dl(a))}let n;if(e.uses!==void 0){n={};for(let s in e.uses)try{n[s]=pi(e.uses[s])}catch{n[s]=e.uses[s]}}return{...e,protocol:pi(e.protocol),types:r,...n!==void 0&&{uses:n}}}};ht();Qt();var s1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await fd.parse(r)}catch(d){return ut(d,400)}try{await on(r.authorization,this.deps.didResolver),await t.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(d){return ut(d,401)}try{await t.validateCompositionDependencies(e,r.descriptor.definition,this.deps.messageStore)}catch(d){return ut(d,400)}let s={interface:"Protocols",method:"Configure",protocol:r.descriptor.definition.protocol},{messages:a}=await this.deps.messageStore.query(e,[s]),o=await we.getCid(r);for(let d of a)if(await we.getCid(d)===o)return{status:{code:409,detail:"Conflict"}};let i=await we.getNewestMessage(a),c=!1;(i===void 0||await we.isNewer(r,i))&&(c=!0,i=r);let u;if(c){let d=t.constructIndexes(n,!0);await this.deps.messageStore.put(e,r,d);let l=await we.getCid(r);await this.deps.stateIndex.insert(e,l,d),this.deps.eventLog!==void 0&&await this.deps.eventLog.emit(e,{message:r},d),u={status:{code:202,detail:"Accepted"}}}else{let d=t.constructIndexes(n,!1);await this.deps.messageStore.put(e,r,d);let l=await we.getCid(r);await this.deps.stateIndex.insert(e,l,d),u={status:{code:202,detail:"Accepted"}}}for(let d of a)if(d!==i){let l=await fd.parse(d),f=t.constructIndexes(l,!1),h=await we.getCid(d);await this.deps.messageStore.delete(e,h),await this.deps.messageStore.put(e,d,f)}return u}static constructIndexes(e,r){let{definition:n,...s}=e.message.descriptor,{author:a}=e;return{...s,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 s=await Tr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await Iu.authorizeConfigure({protocolsConfigureMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else throw new ne("ProtocolsConfigureAuthorizationFailed","message failed authorization")}static async validateCompositionDependencies(e,r,n){let{uses:s}=r;if(s===void 0)return;let a=new Map;for(let o in s){let i=s[o],c=await t.fetchInstalledProtocolDefinition(e,i,n);if(c===void 0)throw new ne("ProtocolsConfigureComposedProtocolNotInstalled",`composed protocol '${i}' (alias '${o}') is not installed for tenant '${e}'.`);a.set(o,c)}t.validateRefsAndRolesRecursively(r.structure,"",a)}static async fetchInstalledProtocolDefinition(e,r,n){let s={interface:"Protocols",method:"Configure",protocol:r,isLatestBaseState:!0},{messages:a}=await n.query(e,[s]);if(a.length!==0)return a[0].descriptor.definition}static validateRefsAndRolesRecursively(e,r,n){for(let s in e){if(s.startsWith("$"))continue;let a=e[s],o=r===""?s:`${r}/${s}`;if(a.$ref!==void 0){let c=Bi(a.$ref);if(c!==void 0){let u=n.get(c.alias);if(u===void 0)throw new ne("ProtocolsConfigureInvalidRefAlias",`'$ref' alias '${c.alias}' at protocol path '${o}' was not found in the referenced definitions map.`);let d=c.protocolPath.split("/"),l=u.structure;for(let f=0;f<d.length;f++){let h=d[f],p=l[h];if(p===void 0)throw new ne("ProtocolsConfigureInvalidRefProtocolPath",`'$ref' at protocol path '${o}' references type path '${c.protocolPath}' which does not exist in protocol '${u.protocol}'.`);if(p.$ref!==void 0){let m=d.slice(0,f+1).join("/");throw new ne("ProtocolsConfigureInvalidRefTargetThroughRef",`'$ref' at protocol path '${o}' references type path '${c.protocolPath}' in protocol '${u.protocol}', but the node '${m}' is itself a '$ref' composition point. multi-level composition (chaining through '$ref' nodes) is not supported.`)}l=p}}}let i=a.$actions??[];for(let c of i){if(c.role!==void 0){let u=Bi(c.role);if(u!==void 0){let d=n.get(u.alias);if(d===void 0)throw new ne("ProtocolsConfigureInvalidCrossProtocolRole",`cross-protocol role alias '${u.alias}' in '${c.role}' at protocol path '${o}' was not found in the referenced definitions map.`);let l=ld(u.protocolPath,d.structure);if(l===void 0||!l.$role)throw new ne("ProtocolsConfigureInvalidCrossProtocolRole",`cross-protocol role '${c.role}' at protocol path '${o}' does not point to a valid role ($role: true) in protocol '${d.protocol}'.`)}}if(c.of!==void 0){let u=Bi(c.of);if(u!==void 0){let d=n.get(u.alias);if(d===void 0)throw new ne("ProtocolsConfigureInvalidCrossProtocolOf",`cross-protocol 'of' alias '${u.alias}' in '${c.of}' at protocol path '${o}' was not found in the referenced definitions map.`);if(ld(u.protocolPath,d.structure)===void 0)throw new ne("ProtocolsConfigureInvalidCrossProtocolOf",`cross-protocol 'of' reference '${c.of}' at protocol path '${o}' does not point to a valid type path in protocol '${d.protocol}'.`)}}}t.validateRefsAndRolesRecursively(a,o,n)}}};w();ht();w();ir();hs();Vs();ht();Qt();Ao();var hf=class t extends bn{static async parse(e){return e.authorization!==void 0&&await we.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&zn(e.descriptor.filter.protocol),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Protocols",method:"Query",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:e.filter?t.normalizeFilter(e.filter):void 0,permissionGrantId:e.permissionGrantId};qt(r);let n;e.signer!==void 0&&(n=await we.createAuthorization({descriptor:r,signer:e.signer,permissionGrantId:e.permissionGrantId}));let s={descriptor:r,authorization:n};return we.validateJsonSchema(s),new t(s)}static normalizeFilter(e){return{...e,protocol:pi(e.protocol)}}async authorize(e,r){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await Tr.fetchGrant(e,r,this.signaturePayload.permissionGrantId);await Iu.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:r})}else throw new ne("ProtocolsQueryUnauthorized","The ProtocolsQuery failed authorization")}};hs();Qt();var i1=class{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await hf.parse(r)}catch(o){return ut(o,400)}try{await on(r.authorization,this.deps.didResolver),await n.authorize(e,this.deps.messageStore)}catch(o){if(o.code==="AuthenticateJwsMissing"||o.code==="ProtocolsQueryUnauthorized"||o.code==="ProtocolsGrantAuthorizationQueryProtocolScopeMismatch"){let i=await this.fetchPublishedProtocolsConfigure(e,n);return{status:{code:200,detail:"OK"},entries:i}}else return ut(o,401)}let s={...r.descriptor.filter,interface:"Protocols",method:"Configure",isLatestBaseState:!0};qt(s);let{messages:a}=await this.deps.messageStore.query(e,[s]);return{status:{code:200,detail:"OK"},entries:a}}async fetchPublishedProtocolsConfigure(e,r){let n={...r.message.descriptor.filter,interface:"Protocols",method:"Configure",published:!0,isLatestBaseState:!0},{messages:s}=await this.deps.messageStore.query(e,[n]);return s}};w();ir();w();Ja();ht();Qt();w();ya();vi();ht();Qt();async function qg(t,e,r,n,s,a,o,i){let c=e.signaturePayload?.protocolRole;if(c===void 0)return;let u=r,d=c;if(pf(c)){let p=Bi(c);if(p===void 0)throw new ne("ProtocolAuthorizationNotARole",`Cross-protocol role '${c}' could not be parsed as a valid 'alias:path' format.`);if(s.uses===void 0||s.uses[p.alias]===void 0)throw new ne("ProtocolAuthorizationNotARole",`Cross-protocol role alias '${p.alias}' in '${c}' does not exist in the protocol's 'uses' map.`);u=s.uses[p.alias],d=p.protocolPath;let m=await o(t,u,a,i),y=ld(d,m.structure);if(y===void 0||!y.$role)throw new ne("ProtocolAuthorizationNotARole",`Cross-protocol role path ${c} does not match role record type.`)}else{let p=ld(c,s.structure);if(p===void 0||!p.$role)throw new ne("ProtocolAuthorizationNotARole",`Protocol path ${c} does not match role record type.`)}let l={interface:"Records",method:"Write",protocol:u,protocolPath:d,recipient:e.author,isLatestBaseState:!0},f=d.split("/").length-1;if(n===void 0&&f>0)throw new ne("ProtocolAuthorizationMissingContextId","Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=Wt.constructPrefixFilterAsRangeFilter(m);l.contextId=y}let{messages:h}=await a.query(t,[l]);if(h.length===0)throw new ne("ProtocolAuthorizationMatchingRoleRecordNotFound",`No matching role record found for protocol path ${d}`)}async function Hre(t,e,r){switch(e.message.descriptor.method){case"Delete":let n=e,s=n.message.descriptor.recordId,a=await St.fetchInitialRecordsWrite(r,t,s);if(a===void 0)return[];let o=[];return n.message.descriptor.prune?(o.push("co-prune"),e.author===a.author&&o.push("prune")):(o.push("co-delete"),e.author===a.author&&o.push("delete")),o;case"Count":return["read"];case"Query":return["read"];case"Read":return["read"];case"Subscribe":return["read"];case"Write":let c=e;if(await c.isInitialWrite())return c.message.descriptor.squash===!0?["squash","create"]:["create"];{let u=e.message.recordId,d=await St.fetchInitialRecordsWrite(r,t,u);return d===void 0?[]:e.author===d.author?["co-update","update"]:["co-update"]}}return[]}async function Fg(t,e,r,n,s,a){let o=e.message.descriptor.method,i=await Hre(t,e,s),c=e.author,u=r.$actions;if(u===void 0)throw new ne("ProtocolAuthorizationActionRulesNotFound",`no action rule defined for Records${o}, ${c} is unauthorized`);let d=e.signaturePayload?.protocolRole;for(let l of u){if(!l.can.some(p=>i.includes(p)))continue;if(l.who==="anyone")return;if(c===void 0)continue;if(d!==void 0){if(l.role===d)return;continue}if(l.who==="recipient"&&l.of===void 0){let p;if(e.message.descriptor.method==="Write"?p=e.message:p=n[n.length-1],p.descriptor.recipient===c)return;continue}if(await Jre(c,l,n,a))return}throw new ne("ProtocolAuthorizationActionNotAllowed",`Inbound message action Records${o} by author ${e.author} not allowed.`)}async function Jre(t,e,r,n){let s=e.of;if(s===void 0)return!1;let a;if(pf(s)&&n?.uses!==void 0){let o=Bi(s);if(o!==void 0){let i=n.uses[o.alias];i!==void 0&&(a=r.find(c=>c.descriptor.protocol===i&&c.descriptor.protocolPath===o.protocolPath))}}else a=r.find(o=>o.descriptor.protocolPath===s);if(a===void 0)return!1;if(e.who==="recipient")return t===a.descriptor.recipient;{let o=(await St.parse(a)).author;return t===o}}w();vi();ht();Qt();async function Ah(t,e,r){let n={interface:"Records",method:"Write",recordId:e},{messages:s}=await r.query(t,[n]);return s.length===0?void 0:await St.getInitialWrite(s)}async function Gg(t,e,r){if(e===void 0)return[];let n=[],s=e;for(;s!==void 0;){let a=await Ah(t,s,r);if(a===void 0)throw new ne("ProtocolAuthorizationParentNotFoundConstructingRecordChain",`Unexpected error that should never trigger: no parent found with ID ${s} when constructing record chain.`);n.push(a),s=a.descriptor.parentId}return n.reverse()}async function sI(t,e,r){let n=await Ah(t,e.message.recordId,r);if(n!==void 0)return n.descriptor.messageTimestamp}w();var fN=Nn(rI(),1);ya();$n();ht();Qt();async function pN(t,e,r,n,s){let a=e.message.descriptor.protocolPath,o=n1(a),i=e.message.descriptor.parentId;if(i===void 0){if(a!==o)throw new ne("ProtocolAuthorizationParentlessIncorrectProtocolPath",`Declared protocol path '${a}' is not valid for records with no parent'.`);return}let c=e.message.descriptor.protocol,u=await Zre(t,c,a,r,n,s),d={isLatestBaseState:!0,interface:"Records",method:"Write",protocol:u,recordId:i},{messages:l}=await r.query(t,[d]),f=l[0];if(f===void 0)throw u!==c?new ne("ProtocolAuthorizationCrossProtocolParentNotFound",`Could not find parent record '${i}' in protocol '${u}' for cross-protocol child at path '${a}'.`):new ne("ProtocolAuthorizationIncorrectProtocolPath",`Could not find matching parent record to verify declared protocol path '${a}'.`);if(`${f.descriptor.protocolPath}/${o}`!==a)throw new 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 ne("ProtocolAuthorizationIncorrectContextId",`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function Zre(t,e,r,n,s,a){let o=r.split("/");if(o.length<=1)return e;let i=await s(t,e,n,a),c=i.structure[o[0]];if(c?.$ref!==void 0){let u=Bi(c.$ref);if(u!==void 0&&i.uses!==void 0){let d=i.uses[u.alias];if(d!==void 0)return o.length===2?d:e}}return e}async function hN(t,e,r,n,s,a){let o=e.descriptor.protocolPath,i=n1(o),c=await Yre(t,o,r,n,s,a);Qre(e,c,i)}async function Yre(t,e,r,n,s,a){let o=e.split("/"),i=r.structure[o[0]];if(i?.$ref!==void 0&&o.length===1){let c=Bi(i.$ref);if(c!==void 0&&r.uses!==void 0){let u=r.uses[c.alias];if(u!==void 0)return(await s(t,u,n,a)).types}}return r.types}function Qre(t,e,r){let n=r??n1(t.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new ne("ProtocolAuthorizationInvalidType",`record with type ${n} not allowed in protocol`);let a=e[n],{schema:o}=t.descriptor;if(a.schema!==void 0&&a.schema!==o)throw new ne("ProtocolAuthorizationInvalidSchema",`type '${n}' must have schema '${a.schema}', instead has '${o}'`);let{dataFormat:i}=t.descriptor;if(a.dataFormats!==void 0&&!a.dataFormats.includes(i))throw new ne("ProtocolAuthorizationIncorrectDataFormat",`type '${n}' must have data format in (${a.dataFormats}), instead has '${i}'`);if(a.encryptionRequired===!0&&t.encryption===void 0)throw new ne("ProtocolAuthorizationEncryptionRequired",`type '${n}' requires encryption but message has no encryption metadata`)}function mN(t,e){let{min:r=0,max:n}=e.$size||{},s=t.message.descriptor.dataSize;if(s<r)throw new ne("ProtocolAuthorizationMinSizeInvalid",`data size ${s} is less than allowed ${r}`);if(n!==void 0&&s>n)throw new ne("ProtocolAuthorizationMaxSizeInvalid",`data size ${s} is more than allowed ${n}`)}function yN(t,e){if(e.$tags!==void 0){let{tags:r={},protocol:n,protocolPath:s}=t.message.descriptor,{$allowUndefinedTags:a,$requiredTags:o,...i}=e.$tags,c=a||!1,u=o||[],d=new fN.default.default,l=d.compile({type:"object",properties:i,required:u,additionalProperties:c});if(!l(r)){let h=d.errorsText(l.errors,{dataVar:`${n}/${s}/$tags`});throw new ne("ProtocolAuthorizationTagsInvalidSchema",`tags schema validation error: ${h}`)}}}async function gN(t,e,r,n){if(!r.$role)return;let s=e,a=s.message.descriptor.recipient;if(a===void 0)throw new ne("ProtocolAuthorizationRoleMissingRecipient","Role records must have a recipient");let o=s.message.descriptor.protocolPath,i={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:s.message.descriptor.protocol,protocolPath:o,recipient:a},c=ke.getParentContextFromOfContextId(s.message.contextId);if(c!==""){let f=Wt.constructPrefixFilterAsRangeFilter(c);i.contextId=f}let{messages:u}=await n.query(t,[i]);if(u.filter(f=>f.recordId!==s.message.recordId).length>0)throw new ne("ProtocolAuthorizationDuplicateRoleRecipient",`DID '${a}' is already recipient of a role record at protocol path '${o} under the parent context ${c}.`)}async function wN(t,e,r,n){if(r.$recordLimit===void 0||!await e.isInitialWrite())return;let{max:a,strategy:o}=r.$recordLimit,i=e.message.descriptor.protocolPath,c={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:e.message.descriptor.protocol,protocolPath:i},u=ke.getParentContextFromOfContextId(e.message.contextId);if(u!==""){let l=Wt.constructPrefixFilterAsRangeFilter(u);c.contextId=l}if(await n.count(t,[c])>=a)throw o==="reject"?new ne("ProtocolAuthorizationRecordLimitExceeded",`record limit of ${a} reached at protocol path '${i}'${u!==""?` under parent context '${u}'`:""}: new records are rejected until existing records are deleted.`):new ne("ProtocolAuthorizationRecordLimitStrategyNotImplemented",`record limit strategy '${o}' is not yet implemented.`)}async function vN(t,e){if(t.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new 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 ne("ProtocolAuthorizationSquashNotInitialWrite","squash write must be an initial write (a new record): updates cannot be squash writes.")}async function bN(t,e){if(!(e.$immutable!==!0||await t.isInitialWrite()))throw new ne("ProtocolAuthorizationImmutableRecord",`record at protocol path '${t.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var Ys=class t{static async validateReferentialIntegrity(e,r,n,s){let a=await sI(e,r,n),o=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,a,s),i=t.createBoundFetchDefinition(s);await hN(e,r.message,o,n,i,a),await pN(e,r,n,i,a);let c=t.getRuleSet(r.message.descriptor.protocolPath,o);await gN(e,r,c,n),mN(r,c),yN(r,c),await bN(r,c),await vN(r,c),await wN(e,r,c,n)}static async authorizeWrite(e,r,n,s){let a=await Ah(e,r.message.recordId,n),o;a===void 0?o=await Gg(e,r.message.descriptor.parentId,n):o=await Gg(e,r.message.recordId,n);let i=await sI(e,r,n),c=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,i,s),u=t.getRuleSet(r.message.descriptor.protocolPath,c),d=t.createBoundFetchDefinition(s);await qg(e,r,r.message.descriptor.protocol,r.message.contextId,c,n,d,i),await Fg(e,r,u,o,n,c)}static async authorizeRead(e,r,n,s,a){let o=await Gg(e,n.message.recordId,s),i=await Ah(e,n.message.recordId,s),c=i!==void 0?i.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,u=await t.fetchProtocolDefinition(e,n.message.descriptor.protocol,s,c,a),d=t.getRuleSet(n.message.descriptor.protocolPath,u),l=t.createBoundFetchDefinition(a);await qg(e,r,n.message.descriptor.protocol,n.message.contextId,u,s,l,c),await Fg(e,r,d,o,s,u)}static async authorizeQueryOrSubscribe(e,r,n,s){let{protocol:a,protocolPath:o,contextId:i}=r.message.descriptor.filter,c=await t.fetchProtocolDefinition(e,a,n,void 0,s),u=t.getRuleSet(o,c),d=t.createBoundFetchDefinition(s);await qg(e,r,a,i,c,n,d),await Fg(e,r,u,[],n,c)}static async authorizeDelete(e,r,n,s,a){let o=await Gg(e,r.message.descriptor.recordId,s),i=await Ah(e,r.message.descriptor.recordId,s),c=i!==void 0?i.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,u=await t.fetchProtocolDefinition(e,n.message.descriptor.protocol,s,c,a),d=t.getRuleSet(n.message.descriptor.protocolPath,u),l=t.createBoundFetchDefinition(a);await qg(e,r,n.message.descriptor.protocol,n.message.contextId,u,s,l,c),await Fg(e,r,d,o,s,u)}static async fetchProtocolDefinition(e,r,n,s,a){if(a!==void 0){let u=a.getDefinition(r);if(u!==void 0)return u}let o={interface:"Protocols",method:"Configure",protocol:r};s!==void 0?o.messageTimestamp={lte:s}:o.isLatestBaseState=!0;let{messages:i}=await n.query(e,[o],{messageTimestamp:-1},{limit:1});if(i.length===0)throw new ne("ProtocolAuthorizationProtocolNotFound",`unable to find protocol definition for ${r}`);return i[0].descriptor.definition}static createBoundFetchDefinition(e){return(r,n,s,a)=>t.fetchProtocolDefinition(r,n,s,a,e)}static getRuleSet(e,r){let n=ld(e,r.structure);if(n===void 0)throw new ne("ProtocolAuthorizationMissingRuleSet",`No rule set defined for protocolPath ${e}`);return n}};$n();Qt();var o1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Hl.parse(r)}catch(a){return ut(a,400)}let s;if(ke.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)s=await this.countPublishedRecords(e,n);else{try{await on(r.authorization,this.deps.didResolver),await t.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(a){return ut(a,401)}n.author===e?s=await this.countRecordsAsOwner(e,n):s=await this.countRecordsAsNonOwner(e,n)}return{status:{code:200,detail:"OK"},count:s}}async countRecordsAsOwner(e,r){let{filter:n}=r.message.descriptor,s={...ke.convertFilter(n),interface:"Records",method:"Write",isLatestBaseState:!0};return this.deps.messageStore.count(e,[s])}async countRecordsAsNonOwner(e,r){let{filter:n}=r.message.descriptor,s=[];return ke.filterIncludesPublishedRecords(n)&&s.push(t.buildPublishedRecordsFilter(r)),ke.filterIncludesUnpublishedRecords(n)&&(ke.shouldBuildUnpublishedAuthorFilter(n,r.author)&&s.push(t.buildUnpublishedRecordsByCountAuthorFilter(r)),ke.shouldProtocolAuthorize(r.signaturePayload)&&s.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),ke.shouldBuildUnpublishedRecipientFilter(n,r.author)&&s.push(t.buildUnpublishedRecordsForCountAuthorFilter(r))),this.deps.messageStore.count(e,s)}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{...ke.convertFilter(r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{...ke.convertFilter(r),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:r}=e.message.descriptor;return{...ke.convertFilter(r),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{...ke.convertFilter(r),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,r,n,s){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),ke.shouldProtocolAuthorize(r.signaturePayload)&&await Ys.authorizeQueryOrSubscribe(e,r,n,s)}};w();Qt();ir();$n();w();ir();la();$n();Ya();hs();Vs();Qt();var pd=class t extends bn{static async parse(e){let r;return e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r=e.recordId,n=yt.getCurrentTimestamp(),s={interface:"Records",method:"Delete",messageTimestamp:e.messageTimestamp??n,recordId:r,prune:e.prune??!1},a=await we.createAuthorization({descriptor:s,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),o={descriptor:s,authorization:a};return we.validateJsonSchema(o),new t(o)}constructIndexes(e){let n={...this.message.descriptor},{protocol:s,protocolPath:a,recipient:o,schema:i,parentId:c,dateCreated:u}=e.descriptor,d={isLatestBaseState:!0,protocol:s,protocolPath:a,recipient:o,schema:i,parentId:c,dateCreated:u,contextId:e.contextId,author:this.author,...n};return qt(d),d}async authorizeDelegate(e,r){let n=Zr.parse(this.message.authorization.authorDelegatedGrant);await Sn.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}};Ya();vi();w();var a1=class t{constructor(e,r){this.resumableTaskStore=e;this.resumableTaskHandlers={RecordsDelete:async n=>await r.performRecordsDelete(n),RecordsSquash:async n=>await r.performRecordsSquash(n)}}static timeoutExtensionFrequencyInSeconds=30;resumableTaskBatchSize=100;resumableTaskHandlers;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 s=this.resumableTaskHandlers[e.task.name];await s(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 s of n)try{await this.runWithAutomaticTimeoutExtension(s)}catch(a){console.error("Error while running resumable task:",a),console.error("Resumable task:",s),r.push(s)}}}};var c1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await pd.parse(r)}catch(u){return ut(u,400)}try{await on(r.authorization,this.deps.didResolver)}catch(u){return ut(u,401)}let s={interface:"Records",recordId:r.descriptor.recordId},{messages:a}=await this.deps.messageStore.query(e,[s]),o=await we.getNewestMessage(a);if(!ke.canPerformDeleteAgainstRecord(r,o))return{status:{code:404,detail:"Not Found"}};if(!await we.isNewer(r,o))return{status:{code:409,detail:"Conflict"}};try{let u=await St.fetchInitialRecordsWrite(this.deps.messageStore,e,r.descriptor.recordId);await t.authorizeRecordsDelete(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return ut(u,401)}return await this.deps.resumableTaskManager.run({name:"RecordsDelete",data:{tenant:e,message:r}}),{status:{code:202,detail:"Accepted"}}}static async authorizeRecordsDelete(e,r,n,s,a){if(we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n.message,s),r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let o=await Tr.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await Sn.authorizeDelete({recordsDeleteMessage:r.message,recordsWriteToDelete:n.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:o,messageStore:s})}else await Ys.authorizeDelete(e,r,n,s,a)}};w();Il();ir();$n();vi();Ja();Qt();var d1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Jl.parse(r)}catch(o){return ut(o,400)}let s,a;if(ke.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0){let o=await this.fetchPublishedRecords(e,n);s=o.messages,a=o.cursor}else{try{await on(r.authorization,this.deps.didResolver),await t.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(o){return ut(o,401)}if(n.author===e){let o=await this.fetchRecordsAsOwner(e,n);s=o.messages,a=o.cursor}else{let o=await this.fetchRecordsAsNonOwner(e,n);s=o.messages,a=o.cursor}}for(let o of s)if(!await St.isInitialWrite(o)){let c=(await this.deps.messageStore.query(e,[{recordId:o.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete c.encodedData,o.initialWrite=c}return{status:{code:200,detail:"OK"},entries:s,cursor:a}}convertDateSort(e){switch(e){case"createdAscending":return{dateCreated:1};case"createdDescending":return{dateCreated:-1};case"publishedAscending":return{datePublished:1};case"publishedDescending":return{datePublished:-1};case"updatedAscending":return{messageTimestamp:1};case"updatedDescending":return{messageTimestamp:-1};default:return{dateCreated:1}}}async fetchRecordsAsOwner(e,r){let{dateSort:n,filter:s,pagination:a}=r.message.descriptor,o={...ke.convertFilter(s,n),interface:"Records",method:"Write",isLatestBaseState:!0},i=this.convertDateSort(n);return this.deps.messageStore.query(e,[o],i,a)}async fetchRecordsAsNonOwner(e,r){let{dateSort:n,pagination:s,filter:a}=r.message.descriptor,o=[];ke.filterIncludesPublishedRecords(a)&&o.push(t.buildPublishedRecordsFilter(r)),ke.filterIncludesUnpublishedRecords(a)&&(ke.shouldBuildUnpublishedAuthorFilter(a,r.author)&&o.push(t.buildUnpublishedRecordsByQueryAuthorFilter(r)),ke.shouldProtocolAuthorize(r.signaturePayload)&&o.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),ke.shouldBuildUnpublishedRecipientFilter(a,r.author)&&o.push(t.buildUnpublishedRecordsForQueryAuthorFilter(r)));let i=this.convertDateSort(n);return this.deps.messageStore.query(e,o,i,s)}async fetchPublishedRecords(e,r){let{dateSort:n,pagination:s}=r.message.descriptor,a=t.buildPublishedRecordsFilter(r),o=this.convertDateSort(n);return this.deps.messageStore.query(e,[a],o,s)}static buildPublishedRecordsFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,r),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,r),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,r),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,r,n,s){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),ke.shouldProtocolAuthorize(r.signaturePayload)&&await Ys.authorizeQueryOrSubscribe(e,r,n,s)}};w();Vd();ln();ir();$n();Ya();w();Il();ir();la();$n();Ya();hs();Vs();ht();Qt();var Wg=class t extends bn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort==="publishedAscending"||e.descriptor.dateSort==="publishedDescending"))throw new 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 ke.validateDelegatedGrantReferentialIntegrity(e,r),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let{filter:r,signer:n,permissionGrantId:s,protocolRole:a,dateSort:o}=e,i=yt.getCurrentTimestamp();if(e.filter.published===!1&&(o==="publishedAscending"||o==="publishedDescending"))throw new ne("RecordsReadCreateFilterPublishedSortInvalid",`reads must not filter for \`published:false\` and sort by ${o}`);let c={interface:"Records",method:"Read",filter:ke.normalizeFilter(r),messageTimestamp:e.messageTimestamp??i,permissionGrantId:s,dateSort:o};qt(c);let u;n!==void 0&&(u=await we.createAuthorization({descriptor:c,signer:n,permissionGrantId:s,protocolRole:a,delegatedGrant:e.delegatedGrant}));let d={descriptor:c,authorization:u};return we.validateJsonSchema(d),new t(d)}async authorizeDelegate(e,r){let n=Zr.parse(this.message.authorization.authorDelegatedGrant);await Sn.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}};vi();ht();Qt();var u1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Wg.parse(r)}catch(l){return ut(l,400)}try{n.author!==void 0&&await on(r.authorization,this.deps.didResolver)}catch(l){return ut(l,401)}let s={interface:"Records",isLatestBaseState:!0,...ke.convertFilter(r.descriptor.filter)},a=ke.convertDateSort(r.descriptor.dateSort),{messages:o}=await this.deps.messageStore.query(e,[s],a,{limit:1});if(o.length===0)return{status:{code:404,detail:"Not Found"}};let i=o[0];if(i.descriptor.method==="Delete"){let l=i,f=l.descriptor.recordId,h=await St.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(h===void 0)return ut(new ne("RecordsReadInitialWriteNotFound","initial write for deleted record not found"),400);let p;try{p=await St.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{p=h}let m=await St.parse(p);try{await t.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return ut(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:l,initialWrite:h}}}let c=i;try{let l=await St.parse(c);await t.authorizeRecordsRead(e,n,l,this.deps.messageStore,this.deps.coreProtocols)}catch(l){return ut(l,401)}let u;if(c.encodedData!==void 0){let l=Te.base64UrlToBytes(c.encodedData);u=ts.fromBytes(l),delete c.encodedData}else{let l=await this.deps.dataStore.get(e,c.recordId,c.descriptor.dataCid);if(l?.dataStream===void 0)return{status:{code:410,detail:"Record data not available"},entry:{recordsWrite:c}};u=l.dataStream}let d={status:{code:200,detail:"OK"},entry:{recordsWrite:c,data:u}};if(!await St.isInitialWrite(c)){let f=(await this.deps.messageStore.query(e,[{recordId:c.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete f.encodedData,d.entry.initialWrite=f}return d}static async authorizeRecordsRead(e,r,n,s,a){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n.message,s);let{descriptor:o}=n.message;if(r.author!==e){if(o.published===!0)return;if(r.author!==void 0&&(r.author===o.recipient||r.author===n.author))return;if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let i=await Tr.fetchGrant(e,s,r.signaturePayload.permissionGrantId);await Sn.authorizeRead({recordsReadMessage:r.message,recordsWriteMessageToBeRead:n.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:i,messageStore:s})}else await Ys.authorizeRead(e,r,n,s,a)}}};w();Il();ir();$n();w();ir();la();$n();Ya();hs();Vs();ht();Qt();Ao();var mf=class t extends bn{static async parse(e){let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await ke.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne("RecordsSubscribeFilterMissingRequiredProperties","Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&zn(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Za(e.descriptor.filter.schema),yt.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:"Records",method:"Subscribe",messageTimestamp:e.messageTimestamp??yt.getCurrentTimestamp(),filter:ke.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};qt(r);let n=e.signer,s;n&&(s=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:s};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Zr.parse(this.message.authorization.authorDelegatedGrant);await Sn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}};vi();Ja();ht();Qt();var l1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return ut(new ne("RecordsSubscribeEventLogUnimplemented","Subscriptions are not supported"),501);let s;try{s=await mf.parse(r)}catch(f){return ut(f,400)}let a=[],o=[];if(ke.filterIncludesPublishedRecords(s.message.descriptor.filter)&&s.author===void 0)a=[t.buildPublishedEventFilter(s)],o=[t.buildPublishedQueryFilter(s)],delete r.authorization;else{try{await on(r.authorization,this.deps.didResolver),await t.authorizeRecordsSubscribe(e,s,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return ut(f,401)}s.author===e?(a=t.buildOwnerEventFilters(s),o=t.buildOwnerQueryFilters(s)):(a=t.buildNonOwnerEventFilters(s),o=t.buildNonOwnerQueryFilters(s))}let i=await we.getCid(r),{cursor:c}=s.message.descriptor;if(c!==void 0)try{let f=await this.deps.eventLog.subscribe(e,i,n,{cursor:c,filters:a});return{status:{code:200,detail:"OK"},subscription:f}}catch(f){return ut(f,500)}let u=await this.deps.eventLog.subscribe(e,i,n,{filters:a}),d,l;try{let{dateSort:f,pagination:h}=s.message.descriptor,p=t.convertDateSort(f),m=await this.deps.messageStore.query(e,o,p,h);d=m.messages,l=m.cursor;for(let y of d)if(!await St.isInitialWrite(y)){let v=(await this.deps.messageStore.query(e,[{recordId:y.recordId,isLatestBaseState:!1,method:"Write"}])).messages[0];delete v.encodedData,y.initialWrite=v}}catch(f){return await u.close(),ut(f,500)}return{status:{code:200,detail:"OK"},subscription:u,entries:d,cursor:l}}static convertDateSort(e){switch(e){case"createdAscending":return{dateCreated:1};case"createdDescending":return{dateCreated:-1};case"publishedAscending":return{datePublished:1};case"publishedDescending":return{datePublished:-1};case"updatedAscending":return{messageTimestamp:1};case"updatedDescending":return{messageTimestamp:-1};default:return{dateCreated:1}}}static buildOwnerEventFilters(e){let{filter:r}=e.message.descriptor;return[{...ke.convertFilter(r),interface:"Records",method:["Write","Delete"]}]}static buildNonOwnerEventFilters(e){let r=[],{filter:n}=e.message.descriptor;return ke.filterIncludesPublishedRecords(n)&&r.push(t.buildPublishedEventFilter(e)),ke.filterIncludesUnpublishedRecords(n)&&(ke.shouldBuildUnpublishedAuthorFilter(n,e.author)&&r.push({...ke.convertFilter(n),author:e.author,interface:"Records",method:["Write","Delete"],published:!1}),ke.shouldProtocolAuthorize(e.signaturePayload)&&r.push({...ke.convertFilter(n),interface:"Records",method:["Write","Delete"],published:!1}),ke.shouldBuildUnpublishedRecipientFilter(n,e.author)&&r.push({...ke.convertFilter(n),interface:"Records",method:["Write","Delete"],recipient:e.author,published:!1})),r}static buildPublishedEventFilter(e){return{...ke.convertFilter(e.message.descriptor.filter),interface:"Records",method:["Write","Delete"],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:r,filter:n}=e.message.descriptor;return[{...ke.convertFilter(n,r),interface:"Records",method:"Write",isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let r=[],{dateSort:n,filter:s}=e.message.descriptor;return ke.filterIncludesPublishedRecords(s)&&r.push(t.buildPublishedQueryFilter(e)),ke.filterIncludesUnpublishedRecords(s)&&(ke.shouldBuildUnpublishedAuthorFilter(s,e.author)&&r.push({...ke.convertFilter(s,n),author:e.author,interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}),ke.shouldProtocolAuthorize(e.signaturePayload)&&r.push({...ke.convertFilter(s,n),interface:"Records",method:"Write",isLatestBaseState:!0,published:!1}),ke.shouldBuildUnpublishedRecipientFilter(s,e.author)&&r.push({...ke.convertFilter(s,n),interface:"Records",method:"Write",recipient:e.author,isLatestBaseState:!0,published:!1})),r}static buildPublishedQueryFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...ke.convertFilter(n,r),interface:"Records",method:"Write",published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,r,n,s){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),ke.shouldProtocolAuthorize(r.signaturePayload)&&await Ys.authorizeQueryOrSubscribe(e,r,n,s)}};w();Vc();Vd();ln();ya();ir();$n();Ya();vi();Ja();w();ya();ir();$n();vi();Qt();var Rh=class t{messageStore;dataStore;stateIndex;eventLog;constructor({messageStore:e,dataStore:r,stateIndex:n,eventLog:s}){this.messageStore=e,this.dataStore=r,this.stateIndex=n,this.eventLog=s}async performRecordsDelete({tenant:e,message:r}){let n={interface:"Records",recordId:r.descriptor.recordId},{messages:s}=await this.messageStore.query(e,[n]),a=await we.getNewestMessage(s);if(!ke.canPerformDeleteAgainstRecord(r,a))return;let o=await pd.parse(r),i=await St.getInitialWrite(s),c=o.constructIndexes(i),u=await we.getCid(r);await this.messageStore.put(e,r,c),await this.stateIndex.insert(e,u,c),this.eventLog!==void 0&&await this.eventLog.emit(e,{message:r,initialWrite:i},c),r.descriptor.prune&&await t.purgeRecordDescendants(e,r.descriptor.recordId,this.messageStore,this.dataStore,this.stateIndex),await t.deleteAllOlderMessagesButKeepInitialWrite(e,s,r,this.messageStore,this.dataStore,this.stateIndex)}async performRecordsSquash({tenant:e,message:r}){let{protocol:n,protocolPath:s,messageTimestamp:a}=r.descriptor,o={interface:"Records",protocol:n,protocolPath:s},i=ke.getParentContextFromOfContextId(r.contextId);if(i!==void 0&&i!==""){let d=Wt.constructPrefixFilterAsRangeFilter(i);o.contextId=d}let{messages:c}=await this.messageStore.query(e,[o]),u=new Map;for(let d of c){let l;ke.isRecordsWrite(d)?l=d.recordId:l=d.descriptor.recordId;let f=u.get(l);f!==void 0?f.push(d):u.set(l,[d])}for(let[d,l]of u){if(d===r.recordId)continue;let f=await we.getNewestMessage(l);if(f===void 0)continue;f.descriptor.messageTimestamp<a&&await t.purgeRecordMessages(e,l,this.messageStore,this.dataStore,this.stateIndex)}}static async deleteFromDataStoreIfNeeded(e,r,n,s){if(n.descriptor.method!=="Write")return;let a=n;a.descriptor.dataSize<=dc.maxDataSizeAllowedToBeEncoded||a.descriptor.dataCid!==s.descriptor.dataCid&&await e.delete(r,a.recordId,a.descriptor.dataCid)}static async purgeRecordDescendants(e,r,n,s,a){let o={interface:"Records",parentId:r},{messages:i}=await n.query(e,[o]),c=new Map;for(let u of i){let d;ke.isRecordsWrite(u)?d=u.recordId:d=u.descriptor.recordId;let l=c.get(d);l?l.push(u):c.set(d,[u])}for(let u of c.keys())await t.purgeRecordDescendants(e,u,n,s,a);for(let u of c.keys())await t.purgeRecordMessages(e,c.get(u),n,s,a)}static async purgeRecordMessages(e,r,n,s,a){let o=r.filter(u=>u.descriptor.method==="Write"),i=await we.getNewestMessage(o);await s.delete(e,i.recordId,i.descriptor.dataCid);let c=await Promise.all(r.map(u=>we.getCid(u)));await a.delete(e,c),await Promise.all(c.map(u=>n.delete(e,u)))}static async deleteAllOlderMessagesButKeepInitialWrite(e,r,n,s,a,o){let i=[];for(let c of r){if(await we.isOlder(c,n)){await t.deleteFromDataStoreIfNeeded(a,e,c,n);let d=await we.getCid(c);if(await s.delete(e,d),await St.isInitialWrite(c)){let p=await(await St.parse(c)).constructIndexes(!1),m=c;delete m.encodedData,await s.put(e,m,p)}else{let f=await we.getCid(c);i.push(f)}}await o.delete(e,i)}}};ht();Qt();var f1=class t{constructor(e){this.deps=e}async handle({tenant:e,message:r,dataStream:n}){let s;try{s=await St.parse(r),await Ys.validateReferentialIntegrity(e,s,this.deps.messageStore,this.deps.coreProtocols)}catch(p){return ut(p,400)}try{await on(r.authorization,this.deps.didResolver,r.attestation),await this.authorizeRecordsWrite(e,s,this.deps.messageStore)}catch(p){return ut(p,401)}let a={interface:"Records",recordId:r.recordId},{messages:o}=await this.deps.messageStore.query(e,[a]),i=await s.isInitialWrite(),c;if(!i)try{c=await St.getInitialWrite(o),St.verifyEqualityOfImmutableProperties(c,r)}catch(p){return ut(p,400)}try{await this.enforceSquashBackstop(e,r)}catch(p){return ut(p,409)}let u=await we.getNewestMessage(o),d=!1,l;if(u===void 0||await we.isNewer(r,u)?(d=!0,l=r):l=u,!d)return{status:{code:409,detail:"Conflict"}};let f=r.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(r.descriptor.protocol):void 0;try{if(u?.descriptor.method==="Delete")throw new 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(!i){let S=u;m=await this.processMessageWithoutDataStream(e,r,S),p=!0}let y=await s.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:c},y)}catch(p){if(p instanceof ne&&(p.code==="RecordsWriteMissingEncodedDataInPrevious"||p.code==="RecordsWriteMissingDataInPrevious"||p.code==="RecordsWriteNotAllowedAfterDelete"||p.code==="RecordsWriteDataCidMismatch"||p.code==="RecordsWriteDataSizeMismatch"||p.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(p.code)!==void 0))return ut(p,400);throw p}let h={status:i&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await Rh.deleteAllOlderMessagesButKeepInitialWrite(e,o,l,this.deps.messageStore,this.deps.dataStore,this.deps.stateIndex),r.descriptor.squash===!0&&await this.deps.resumableTaskManager.run({name:"RecordsSquash",data:{tenant:e,message:r}}),f?.postProcessWrite!==void 0&&await f.postProcessWrite(e,s,{messageStore:this.deps.messageStore,dataStore:this.deps.dataStore,stateIndex:this.deps.stateIndex}),h}async cloneAndAddEncodedData(e,r){let n={...e};return n.encodedData=Te.bytesToBase64Url(r),n}async processMessageWithDataStream(e,r,n){let s=r;if(r.descriptor.dataSize<=dc.maxDataSizeAllowedToBeEncoded){let a=await ts.toBytes(n),o=await Ar.computeDagPbCidFromBytes(a);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,o,a.length);let i=r.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(r.descriptor.protocol):void 0;i?.validateRecord!==void 0&&i.validateRecord(r,a),s=await this.cloneAndAddEncodedData(r,a)}else{let[a,o]=ts.duplicateDataStream(n,2);try{let[i,c]=await Promise.all([Ar.computeDagPbCidFromStream(a),this.deps.dataStore.put(e,r.recordId,r.descriptor.dataCid,o)]);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,i,c.dataSize)}catch(i){throw await this.deps.dataStore.delete(e,r.recordId,r.descriptor.dataCid),i}}return s}async processMessageWithoutDataStream(e,r,n){let s={...r},{dataCid:a,dataSize:o}=r.descriptor;if(t.validateDataIntegrity(a,o,n.descriptor.dataCid,n.descriptor.dataSize),o<=dc.maxDataSizeAllowedToBeEncoded)if(n.encodedData!==void 0)s.encodedData=n.encodedData;else throw new 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 ne("RecordsWriteMissingDataInPrevious","No dataStream was provided and unable to get data from previous message");return s}static validateDataIntegrity(e,r,n,s){if(e!==n)throw new ne("RecordsWriteDataCidMismatch",`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(r!==s)throw new ne("RecordsWriteDataSizeMismatch",`actual data size ${s} 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(d){console.warn(`enforceSquashBackstop: failed to fetch protocol definition for '${r.descriptor.protocol}':`,d);return}let s=r.descriptor.protocolPath.split("/"),a=n.structure[s[0]];for(let d=1;d<s.length&&a!==void 0;d++)a=a[s[d]];if(a===void 0||a.$squash!==!0)return;let o={interface:"Records",method:"Write",isLatestBaseState:!0,protocol:r.descriptor.protocol,protocolPath:r.descriptor.protocolPath,squash:!0},i=ke.getParentContextFromOfContextId(r.contextId);if(i!==void 0&&i!==""){let d=Wt.constructPrefixFilterAsRangeFilter(i);o.contextId=d}let{messages:c}=await this.deps.messageStore.query(e,[o],{messageTimestamp:-1},{limit:1});if(c.length===0)return;let u=c[0];if(r.descriptor.messageTimestamp<=u.descriptor.messageTimestamp)throw new ne("ProtocolAuthorizationSquashBackstop",`incoming message timestamp '${r.descriptor.messageTimestamp}' is not newer than the most recent squash record timestamp '${u.descriptor.messageTimestamp}' at protocol path '${r.descriptor.protocolPath}'.`)}async authorizeRecordsWrite(e,r,n){if(r.owner!==void 0&&r.owner!==e)throw new 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 s=await Tr.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await Sn.authorizeWrite({recordsWriteMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:n})}else await Ys.authorizeWrite(e,r,n,this.deps.coreProtocols)}}};w();var ene=Object.create,OI=Object.defineProperty,tne=Object.getOwnPropertyDescriptor,rne=Object.getOwnPropertyNames,nne=Object.getPrototypeOf,sne=Object.prototype.hasOwnProperty,Kt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),BI=(t,e)=>{for(var r in e)OI(t,r,{get:e[r],enumerable:!0})},ine=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of rne(e))!sne.call(t,s)&&s!==r&&OI(t,s,{get:()=>e[s],enumerable:!(n=tne(e,s))||n.enumerable});return t},Rf=(t,e,r)=>(r=t!=null?ene(nne(t)):{},ine(e||!t||!t.__esModule?OI(r,"default",{value:t,enumerable:!0}):r,t)),one=Kt((t,e)=>{var r=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,n=()=>r.now(),s=i=>i&&i===Math.floor(i)&&i>0&&isFinite(i),a=i=>i===1/0||s(i),o=class BU{constructor({max:c=1/0,ttl:u,updateAgeOnGet:d=!1,checkAgeOnGet:l=!1,noUpdateTTL:f=!1,dispose:h,noDisposeOnSet:p=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,u!==void 0&&!a(u))throw new TypeError("ttl must be positive integer or Infinity if set");if(!a(c))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=u,this.max=c,this.updateAgeOnGet=!!d,this.checkAgeOnGet=!!l,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(c,u){if(this.timerExpiration<c)return;this.timer&&clearTimeout(this.timer);let d=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let l in this.expirations){this.setTimer(l,l-n());break}},u);d.unref&&d.unref(),this.timerExpiration=c,this.timer=d}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return process.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){let c=this.dispose!==BU.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[u,d]of c)this.dispose(d,u,"delete")}setTTL(c,u=this.ttl){let d=this.expirationMap.get(c);if(d!==void 0){let l=this.expirations[d];!l||l.length<=1?delete this.expirations[d]:this.expirations[d]=l.filter(f=>f!==c)}if(u!==1/0){let l=Math.floor(n()+u);this.expirationMap.set(c,l),this.expirations[l]||(this.expirations[l]=[],this.setTimer(l,u)),this.expirations[l].push(c)}else this.expirationMap.set(c,1/0)}set(c,u,{ttl:d=this.ttl,noUpdateTTL:l=this.noUpdateTTL,noDisposeOnSet:f=this.noDisposeOnSet}={}){if(!a(d))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(c)){l||this.setTTL(c,d);let h=this.data.get(c);h!==u&&(this.data.set(c,u),f||this.dispose(h,c,"set"))}else this.setTTL(c,d),this.data.set(c,u);for(;this.size>this.max;)this.purgeToCapacity();return this}has(c){return this.data.has(c)}getRemainingTTL(c){let u=this.expirationMap.get(c);return u===1/0?u:u!==void 0?Math.max(0,Math.ceil(u-n())):0}get(c,{updateAgeOnGet:u=this.updateAgeOnGet,ttl:d=this.ttl,checkAgeOnGet:l=this.checkAgeOnGet}={}){let f=this.data.get(c);if(l&&this.getRemainingTTL(c)===0){this.delete(c);return}return u&&this.setTTL(c,d),f}dispose(c,u){}delete(c){let u=this.expirationMap.get(c);if(u!==void 0){let d=this.data.get(c);this.data.delete(c),this.expirationMap.delete(c);let l=this.expirations[u];return l&&(l.length<=1?delete this.expirations[u]:this.expirations[u]=l.filter(f=>f!==c)),this.dispose(d,c,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let c in this.expirations){let u=this.expirations[c];if(this.size-u.length>=this.max){delete this.expirations[c];let d=[];for(let l of u)d.push([l,this.data.get(l)]),this.data.delete(l),this.expirationMap.delete(l);for(let[l,f]of d)this.dispose(f,l,"evict")}else{let d=this.size-this.max,l=[];for(let f of u.splice(0,d))l.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of l)this.dispose(h,f,"evict");return}}}get size(){return this.data.size}purgeStale(){let c=Math.ceil(n());for(let u in this.expirations){if(u==="Infinity"||u>c)return;let d=[...this.expirations[u]||[]],l=[];delete this.expirations[u];for(let f of d)l.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of l)this.dispose(h,f,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let c in this.expirations)for(let u of this.expirations[c])yield[u,this.data.get(u)]}*keys(){for(let c in this.expirations)for(let u of this.expirations[c])yield u}*values(){for(let c in this.expirations)for(let u of this.expirations[c])yield this.data.get(u)}[Symbol.iterator](){return this.entries()}};e.exports=o}),ane=Kt(t=>{"use strict";t.supports=function(...e){let r=e.reduce((n,s)=>Object.assign(n,s),{});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)})}}),_c=Kt((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)}}}),cne=Kt(t=>{"use strict";t.byteLength=c,t.toByteArray=d,t.fromByteArray=h;var e=[],r=[],n=typeof Uint8Array<"u"?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(a=0,o=s.length;a<o;++a)e[a]=s[a],r[s.charCodeAt(a)]=a;var a,o;r[45]=62,r[95]=63;function i(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 S=y===m?0:4-y%4;return[y,S]}function c(p){var m=i(p),y=m[0],S=m[1];return(y+S)*3/4-S}function u(p,m,y){return(m+y)*3/4-y}function d(p){var m,y=i(p),S=y[0],v=y[1],E=new n(u(p,S,v)),k=0,A=v>0?S-4:S,D;for(D=0;D<A;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)],E[k++]=m>>16&255,E[k++]=m>>8&255,E[k++]=m&255;return v===2&&(m=r[p.charCodeAt(D)]<<2|r[p.charCodeAt(D+1)]>>4,E[k++]=m&255),v===1&&(m=r[p.charCodeAt(D)]<<10|r[p.charCodeAt(D+1)]<<4|r[p.charCodeAt(D+2)]>>2,E[k++]=m>>8&255,E[k++]=m&255),E}function l(p){return e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63]}function f(p,m,y){for(var S,v=[],E=m;E<y;E+=3)S=(p[E]<<16&16711680)+(p[E+1]<<8&65280)+(p[E+2]&255),v.push(l(S));return v.join("")}function h(p){for(var m,y=p.length,S=y%3,v=[],E=16383,k=0,A=y-S;k<A;k+=E)v.push(f(p,k,k+E>A?A:k+E));return S===1?(m=p[y-1],v.push(e[m>>2]+e[m<<4&63]+"==")):S===2&&(m=(p[y-2]<<8)+p[y-1],v.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),v.join("")}}),dne=Kt(t=>{t.read=function(e,r,n,s,a){var o,i,c=a*8-s-1,u=(1<<c)-1,d=u>>1,l=-7,f=n?a-1:0,h=n?-1:1,p=e[r+f];for(f+=h,o=p&(1<<-l)-1,p>>=-l,l+=c;l>0;o=o*256+e[r+f],f+=h,l-=8);for(i=o&(1<<-l)-1,o>>=-l,l+=s;l>0;i=i*256+e[r+f],f+=h,l-=8);if(o===0)o=1-d;else{if(o===u)return i?NaN:(p?-1:1)*(1/0);i=i+Math.pow(2,s),o=o-d}return(p?-1:1)*i*Math.pow(2,o-s)},t.write=function(e,r,n,s,a,o){var i,c,u,d=o*8-a-1,l=(1<<d)-1,f=l>>1,h=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:o-1,m=s?1:-1,y=r<0||r===0&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(c=isNaN(r)?1:0,i=l):(i=Math.floor(Math.log(r)/Math.LN2),r*(u=Math.pow(2,-i))<1&&(i--,u*=2),i+f>=1?r+=h/u:r+=h*Math.pow(2,1-f),r*u>=2&&(i++,u/=2),i+f>=l?(c=0,i=l):i+f>=1?(c=(r*u-1)*Math.pow(2,a),i=i+f):(c=r*Math.pow(2,f-1)*Math.pow(2,a),i=0));a>=8;e[n+p]=c&255,p+=m,c/=256,a-=8);for(i=i<<a|c,d+=a;d>0;e[n+p]=i&255,p+=m,i/=256,d-=8);e[n+p-m]|=y*128}}),NI=Kt(t=>{"use strict";var e=cne(),r=dne(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=i,t.SlowBuffer=v,t.INSPECT_MAX_BYTES=50;var s=2147483647;t.kMaxLength=s,i.TYPED_ARRAY_SUPPORT=a(),!i.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let T=new Uint8Array(1),M={foo:function(){return 42}};return Object.setPrototypeOf(M,Uint8Array.prototype),Object.setPrototypeOf(T,M),T.foo()===42}catch{return!1}}Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}});function o(T){if(T>s)throw new RangeError('The value "'+T+'" is invalid for option "size"');let M=new Uint8Array(T);return Object.setPrototypeOf(M,i.prototype),M}function i(T,M,L){if(typeof T=="number"){if(typeof M=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return l(T)}return c(T,M,L)}i.poolSize=8192;function c(T,M,L){if(typeof T=="string")return f(T,M);if(ArrayBuffer.isView(T))return p(T);if(T==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T);if(Se(T,ArrayBuffer)||T&&Se(T.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Se(T,SharedArrayBuffer)||T&&Se(T.buffer,SharedArrayBuffer)))return m(T,M,L);if(typeof T=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let te=T.valueOf&&T.valueOf();if(te!=null&&te!==T)return i.from(te,M,L);let ae=y(T);if(ae)return ae;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof T[Symbol.toPrimitive]=="function")return i.from(T[Symbol.toPrimitive]("string"),M,L);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T)}i.from=function(T,M,L){return c(T,M,L)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function u(T){if(typeof T!="number")throw new TypeError('"size" argument must be of type number');if(T<0)throw new RangeError('The value "'+T+'" is invalid for option "size"')}function d(T,M,L){return u(T),T<=0?o(T):M!==void 0?typeof L=="string"?o(T).fill(M,L):o(T).fill(M):o(T)}i.alloc=function(T,M,L){return d(T,M,L)};function l(T){return u(T),o(T<0?0:S(T)|0)}i.allocUnsafe=function(T){return l(T)},i.allocUnsafeSlow=function(T){return l(T)};function f(T,M){if((typeof M!="string"||M==="")&&(M="utf8"),!i.isEncoding(M))throw new TypeError("Unknown encoding: "+M);let L=E(T,M)|0,te=o(L),ae=te.write(T,M);return ae!==L&&(te=te.slice(0,ae)),te}function h(T){let M=T.length<0?0:S(T.length)|0,L=o(M);for(let te=0;te<M;te+=1)L[te]=T[te]&255;return L}function p(T){if(Se(T,Uint8Array)){let M=new Uint8Array(T);return m(M.buffer,M.byteOffset,M.byteLength)}return h(T)}function m(T,M,L){if(M<0||T.byteLength<M)throw new RangeError('"offset" is outside of buffer bounds');if(T.byteLength<M+(L||0))throw new RangeError('"length" is outside of buffer bounds');let te;return M===void 0&&L===void 0?te=new Uint8Array(T):L===void 0?te=new Uint8Array(T,M):te=new Uint8Array(T,M,L),Object.setPrototypeOf(te,i.prototype),te}function y(T){if(i.isBuffer(T)){let M=S(T.length)|0,L=o(M);return L.length===0||T.copy(L,0,0,M),L}if(T.length!==void 0)return typeof T.length!="number"||et(T.length)?o(0):h(T);if(T.type==="Buffer"&&Array.isArray(T.data))return h(T.data)}function S(T){if(T>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return T|0}function v(T){return+T!=T&&(T=0),i.alloc(+T)}i.isBuffer=function(T){return T!=null&&T._isBuffer===!0&&T!==i.prototype},i.compare=function(T,M){if(Se(T,Uint8Array)&&(T=i.from(T,T.offset,T.byteLength)),Se(M,Uint8Array)&&(M=i.from(M,M.offset,M.byteLength)),!i.isBuffer(T)||!i.isBuffer(M))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(T===M)return 0;let L=T.length,te=M.length;for(let ae=0,he=Math.min(L,te);ae<he;++ae)if(T[ae]!==M[ae]){L=T[ae],te=M[ae];break}return L<te?-1:te<L?1:0},i.isEncoding=function(T){switch(String(T).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(T,M){if(!Array.isArray(T))throw new TypeError('"list" argument must be an Array of Buffers');if(T.length===0)return i.alloc(0);let L;if(M===void 0)for(M=0,L=0;L<T.length;++L)M+=T[L].length;let te=i.allocUnsafe(M),ae=0;for(L=0;L<T.length;++L){let he=T[L];if(Se(he,Uint8Array))ae+he.length>te.length?(i.isBuffer(he)||(he=i.from(he)),he.copy(te,ae)):Uint8Array.prototype.set.call(te,he,ae);else if(i.isBuffer(he))he.copy(te,ae);else throw new TypeError('"list" argument must be an Array of Buffers');ae+=he.length}return te};function E(T,M){if(i.isBuffer(T))return T.length;if(ArrayBuffer.isView(T)||Se(T,ArrayBuffer))return T.byteLength;if(typeof T!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof T);let L=T.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&L===0)return 0;let ae=!1;for(;;)switch(M){case"ascii":case"latin1":case"binary":return L;case"utf8":case"utf-8":return ge(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L*2;case"hex":return L>>>1;case"base64":return qe(T).length;default:if(ae)return te?-1:ge(T).length;M=(""+M).toLowerCase(),ae=!0}}i.byteLength=E;function k(T,M,L){let te=!1;if((M===void 0||M<0)&&(M=0),M>this.length||((L===void 0||L>this.length)&&(L=this.length),L<=0)||(L>>>=0,M>>>=0,L<=M))return"";for(T||(T="utf8");;)switch(T){case"hex":return _(this,M,L);case"utf8":case"utf-8":return R(this,M,L);case"ascii":return x(this,M,L);case"latin1":case"binary":return P(this,M,L);case"base64":return ee(this,M,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,M,L);default:if(te)throw new TypeError("Unknown encoding: "+T);T=(T+"").toLowerCase(),te=!0}}i.prototype._isBuffer=!0;function A(T,M,L){let te=T[M];T[M]=T[L],T[L]=te}i.prototype.swap16=function(){let T=this.length;if(T%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let M=0;M<T;M+=2)A(this,M,M+1);return this},i.prototype.swap32=function(){let T=this.length;if(T%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let M=0;M<T;M+=4)A(this,M,M+3),A(this,M+1,M+2);return this},i.prototype.swap64=function(){let T=this.length;if(T%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let M=0;M<T;M+=8)A(this,M,M+7),A(this,M+1,M+6),A(this,M+2,M+5),A(this,M+3,M+4);return this},i.prototype.toString=function(){let T=this.length;return T===0?"":arguments.length===0?R(this,0,T):k.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(T){if(!i.isBuffer(T))throw new TypeError("Argument must be a Buffer");return this===T?!0:i.compare(this,T)===0},i.prototype.inspect=function(){let T="",M=t.INSPECT_MAX_BYTES;return T=this.toString("hex",0,M).replace(/(.{2})/g,"$1 ").trim(),this.length>M&&(T+=" ... "),"<Buffer "+T+">"},n&&(i.prototype[n]=i.prototype.inspect),i.prototype.compare=function(T,M,L,te,ae){if(Se(T,Uint8Array)&&(T=i.from(T,T.offset,T.byteLength)),!i.isBuffer(T))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof T);if(M===void 0&&(M=0),L===void 0&&(L=T?T.length:0),te===void 0&&(te=0),ae===void 0&&(ae=this.length),M<0||L>T.length||te<0||ae>this.length)throw new RangeError("out of range index");if(te>=ae&&M>=L)return 0;if(te>=ae)return-1;if(M>=L)return 1;if(M>>>=0,L>>>=0,te>>>=0,ae>>>=0,this===T)return 0;let he=ae-te,xe=L-M,Mt=Math.min(he,xe),Bn=this.slice(te,ae),$r=T.slice(M,L);for(let pr=0;pr<Mt;++pr)if(Bn[pr]!==$r[pr]){he=Bn[pr],xe=$r[pr];break}return he<xe?-1:xe<he?1:0};function D(T,M,L,te,ae){if(T.length===0)return-1;if(typeof L=="string"?(te=L,L=0):L>2147483647?L=2147483647:L<-2147483648&&(L=-2147483648),L=+L,et(L)&&(L=ae?0:T.length-1),L<0&&(L=T.length+L),L>=T.length){if(ae)return-1;L=T.length-1}else if(L<0)if(ae)L=0;else return-1;if(typeof M=="string"&&(M=i.from(M,te)),i.isBuffer(M))return M.length===0?-1:B(T,M,L,te,ae);if(typeof M=="number")return M=M&255,typeof Uint8Array.prototype.indexOf=="function"?ae?Uint8Array.prototype.indexOf.call(T,M,L):Uint8Array.prototype.lastIndexOf.call(T,M,L):B(T,[M],L,te,ae);throw new TypeError("val must be string, number or Buffer")}function B(T,M,L,te,ae){let he=1,xe=T.length,Mt=M.length;if(te!==void 0&&(te=String(te).toLowerCase(),te==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(T.length<2||M.length<2)return-1;he=2,xe/=2,Mt/=2,L/=2}function Bn(pr,sr){return he===1?pr[sr]:pr.readUInt16BE(sr*he)}let $r;if(ae){let pr=-1;for($r=L;$r<xe;$r++)if(Bn(T,$r)===Bn(M,pr===-1?0:$r-pr)){if(pr===-1&&(pr=$r),$r-pr+1===Mt)return pr*he}else pr!==-1&&($r-=$r-pr),pr=-1}else for(L+Mt>xe&&(L=xe-Mt),$r=L;$r>=0;$r--){let pr=!0;for(let sr=0;sr<Mt;sr++)if(Bn(T,$r+sr)!==Bn(M,sr)){pr=!1;break}if(pr)return $r}return-1}i.prototype.includes=function(T,M,L){return this.indexOf(T,M,L)!==-1},i.prototype.indexOf=function(T,M,L){return D(this,T,M,L,!0)},i.prototype.lastIndexOf=function(T,M,L){return D(this,T,M,L,!1)};function j(T,M,L,te){L=Number(L)||0;let ae=T.length-L;te?(te=Number(te),te>ae&&(te=ae)):te=ae;let he=M.length;te>he/2&&(te=he/2);let xe;for(xe=0;xe<te;++xe){let Mt=parseInt(M.substr(xe*2,2),16);if(et(Mt))return xe;T[L+xe]=Mt}return xe}function F(T,M,L,te){return Et(ge(M,T.length-L),T,L,te)}function q(T,M,L,te){return Et(Me(M),T,L,te)}function N(T,M,L,te){return Et(qe(M),T,L,te)}function W(T,M,L,te){return Et(Le(M,T.length-L),T,L,te)}i.prototype.write=function(T,M,L,te){if(M===void 0)te="utf8",L=this.length,M=0;else if(L===void 0&&typeof M=="string")te=M,L=this.length,M=0;else if(isFinite(M))M=M>>>0,isFinite(L)?(L=L>>>0,te===void 0&&(te="utf8")):(te=L,L=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let ae=this.length-M;if((L===void 0||L>ae)&&(L=ae),T.length>0&&(L<0||M<0)||M>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");let he=!1;for(;;)switch(te){case"hex":return j(this,T,M,L);case"utf8":case"utf-8":return F(this,T,M,L);case"ascii":case"latin1":case"binary":return q(this,T,M,L);case"base64":return N(this,T,M,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,T,M,L);default:if(he)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),he=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ee(T,M,L){return M===0&&L===T.length?e.fromByteArray(T):e.fromByteArray(T.slice(M,L))}function R(T,M,L){L=Math.min(T.length,L);let te=[],ae=M;for(;ae<L;){let he=T[ae],xe=null,Mt=he>239?4:he>223?3:he>191?2:1;if(ae+Mt<=L){let Bn,$r,pr,sr;switch(Mt){case 1:he<128&&(xe=he);break;case 2:Bn=T[ae+1],(Bn&192)===128&&(sr=(he&31)<<6|Bn&63,sr>127&&(xe=sr));break;case 3:Bn=T[ae+1],$r=T[ae+2],(Bn&192)===128&&($r&192)===128&&(sr=(he&15)<<12|(Bn&63)<<6|$r&63,sr>2047&&(sr<55296||sr>57343)&&(xe=sr));break;case 4:Bn=T[ae+1],$r=T[ae+2],pr=T[ae+3],(Bn&192)===128&&($r&192)===128&&(pr&192)===128&&(sr=(he&15)<<18|(Bn&63)<<12|($r&63)<<6|pr&63,sr>65535&&sr<1114112&&(xe=sr))}}xe===null?(xe=65533,Mt=1):xe>65535&&(xe-=65536,te.push(xe>>>10&1023|55296),xe=56320|xe&1023),te.push(xe),ae+=Mt}return b(te)}var $=4096;function b(T){let M=T.length;if(M<=$)return String.fromCharCode.apply(String,T);let L="",te=0;for(;te<M;)L+=String.fromCharCode.apply(String,T.slice(te,te+=$));return L}function x(T,M,L){let te="";L=Math.min(T.length,L);for(let ae=M;ae<L;++ae)te+=String.fromCharCode(T[ae]&127);return te}function P(T,M,L){let te="";L=Math.min(T.length,L);for(let ae=M;ae<L;++ae)te+=String.fromCharCode(T[ae]);return te}function _(T,M,L){let te=T.length;(!M||M<0)&&(M=0),(!L||L<0||L>te)&&(L=te);let ae="";for(let he=M;he<L;++he)ae+=wt[T[he]];return ae}function I(T,M,L){let te=T.slice(M,L),ae="";for(let he=0;he<te.length-1;he+=2)ae+=String.fromCharCode(te[he]+te[he+1]*256);return ae}i.prototype.slice=function(T,M){let L=this.length;T=~~T,M=M===void 0?L:~~M,T<0?(T+=L,T<0&&(T=0)):T>L&&(T=L),M<0?(M+=L,M<0&&(M=0)):M>L&&(M=L),M<T&&(M=T);let te=this.subarray(T,M);return Object.setPrototypeOf(te,i.prototype),te};function O(T,M,L){if(T%1!==0||T<0)throw new RangeError("offset is not uint");if(T+M>L)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=this[T],ae=1,he=0;for(;++he<M&&(ae*=256);)te+=this[T+he]*ae;return te},i.prototype.readUintBE=i.prototype.readUIntBE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=this[T+--M],ae=1;for(;M>0&&(ae*=256);)te+=this[T+--M]*ae;return te},i.prototype.readUint8=i.prototype.readUInt8=function(T,M){return T=T>>>0,M||O(T,1,this.length),this[T]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(T,M){return T=T>>>0,M||O(T,2,this.length),this[T]|this[T+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(T,M){return T=T>>>0,M||O(T,2,this.length),this[T]<<8|this[T+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(T,M){return T=T>>>0,M||O(T,4,this.length),(this[T]|this[T+1]<<8|this[T+2]<<16)+this[T+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(T,M){return T=T>>>0,M||O(T,4,this.length),this[T]*16777216+(this[T+1]<<16|this[T+2]<<8|this[T+3])},i.prototype.readBigUInt64LE=xt(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=M+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24,ae=this[++T]+this[++T]*2**8+this[++T]*2**16+L*2**24;return BigInt(te)+(BigInt(ae)<<BigInt(32))}),i.prototype.readBigUInt64BE=xt(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=M*2**24+this[++T]*2**16+this[++T]*2**8+this[++T],ae=this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+L;return(BigInt(te)<<BigInt(32))+BigInt(ae)}),i.prototype.readIntLE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=this[T],ae=1,he=0;for(;++he<M&&(ae*=256);)te+=this[T+he]*ae;return ae*=128,te>=ae&&(te-=Math.pow(2,8*M)),te},i.prototype.readIntBE=function(T,M,L){T=T>>>0,M=M>>>0,L||O(T,M,this.length);let te=M,ae=1,he=this[T+--te];for(;te>0&&(ae*=256);)he+=this[T+--te]*ae;return ae*=128,he>=ae&&(he-=Math.pow(2,8*M)),he},i.prototype.readInt8=function(T,M){return T=T>>>0,M||O(T,1,this.length),this[T]&128?(255-this[T]+1)*-1:this[T]},i.prototype.readInt16LE=function(T,M){T=T>>>0,M||O(T,2,this.length);let L=this[T]|this[T+1]<<8;return L&32768?L|4294901760:L},i.prototype.readInt16BE=function(T,M){T=T>>>0,M||O(T,2,this.length);let L=this[T+1]|this[T]<<8;return L&32768?L|4294901760:L},i.prototype.readInt32LE=function(T,M){return T=T>>>0,M||O(T,4,this.length),this[T]|this[T+1]<<8|this[T+2]<<16|this[T+3]<<24},i.prototype.readInt32BE=function(T,M){return T=T>>>0,M||O(T,4,this.length),this[T]<<24|this[T+1]<<16|this[T+2]<<8|this[T+3]},i.prototype.readBigInt64LE=xt(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=this[T+4]+this[T+5]*2**8+this[T+6]*2**16+(L<<24);return(BigInt(te)<<BigInt(32))+BigInt(M+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24)}),i.prototype.readBigInt64BE=xt(function(T){T=T>>>0,le(T,"offset");let M=this[T],L=this[T+7];(M===void 0||L===void 0)&&pe(T,this.length-8);let te=(M<<24)+this[++T]*2**16+this[++T]*2**8+this[++T];return(BigInt(te)<<BigInt(32))+BigInt(this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+L)}),i.prototype.readFloatLE=function(T,M){return T=T>>>0,M||O(T,4,this.length),r.read(this,T,!0,23,4)},i.prototype.readFloatBE=function(T,M){return T=T>>>0,M||O(T,4,this.length),r.read(this,T,!1,23,4)},i.prototype.readDoubleLE=function(T,M){return T=T>>>0,M||O(T,8,this.length),r.read(this,T,!0,52,8)},i.prototype.readDoubleBE=function(T,M){return T=T>>>0,M||O(T,8,this.length),r.read(this,T,!1,52,8)};function z(T,M,L,te,ae,he){if(!i.isBuffer(T))throw new TypeError('"buffer" argument must be a Buffer instance');if(M>ae||M<he)throw new RangeError('"value" argument is out of bounds');if(L+te>T.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(T,M,L,te){if(T=+T,M=M>>>0,L=L>>>0,!te){let xe=Math.pow(2,8*L)-1;z(this,T,M,L,xe,0)}let ae=1,he=0;for(this[M]=T&255;++he<L&&(ae*=256);)this[M+he]=T/ae&255;return M+L},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(T,M,L,te){if(T=+T,M=M>>>0,L=L>>>0,!te){let xe=Math.pow(2,8*L)-1;z(this,T,M,L,xe,0)}let ae=L-1,he=1;for(this[M+ae]=T&255;--ae>=0&&(he*=256);)this[M+ae]=T/he&255;return M+L},i.prototype.writeUint8=i.prototype.writeUInt8=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,1,255,0),this[M]=T&255,M+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,2,65535,0),this[M]=T&255,this[M+1]=T>>>8,M+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,2,65535,0),this[M]=T>>>8,this[M+1]=T&255,M+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,4,4294967295,0),this[M+3]=T>>>24,this[M+2]=T>>>16,this[M+1]=T>>>8,this[M]=T&255,M+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,4,4294967295,0),this[M]=T>>>24,this[M+1]=T>>>16,this[M+2]=T>>>8,this[M+3]=T&255,M+4};function G(T,M,L,te,ae){de(M,te,ae,T,L,7);let he=Number(M&BigInt(4294967295));T[L++]=he,he=he>>8,T[L++]=he,he=he>>8,T[L++]=he,he=he>>8,T[L++]=he;let xe=Number(M>>BigInt(32)&BigInt(4294967295));return T[L++]=xe,xe=xe>>8,T[L++]=xe,xe=xe>>8,T[L++]=xe,xe=xe>>8,T[L++]=xe,L}function V(T,M,L,te,ae){de(M,te,ae,T,L,7);let he=Number(M&BigInt(4294967295));T[L+7]=he,he=he>>8,T[L+6]=he,he=he>>8,T[L+5]=he,he=he>>8,T[L+4]=he;let xe=Number(M>>BigInt(32)&BigInt(4294967295));return T[L+3]=xe,xe=xe>>8,T[L+2]=xe,xe=xe>>8,T[L+1]=xe,xe=xe>>8,T[L]=xe,L+8}i.prototype.writeBigUInt64LE=xt(function(T,M=0){return G(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=xt(function(T,M=0){return V(this,T,M,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(T,M,L,te){if(T=+T,M=M>>>0,!te){let Mt=Math.pow(2,8*L-1);z(this,T,M,L,Mt-1,-Mt)}let ae=0,he=1,xe=0;for(this[M]=T&255;++ae<L&&(he*=256);)T<0&&xe===0&&this[M+ae-1]!==0&&(xe=1),this[M+ae]=(T/he>>0)-xe&255;return M+L},i.prototype.writeIntBE=function(T,M,L,te){if(T=+T,M=M>>>0,!te){let Mt=Math.pow(2,8*L-1);z(this,T,M,L,Mt-1,-Mt)}let ae=L-1,he=1,xe=0;for(this[M+ae]=T&255;--ae>=0&&(he*=256);)T<0&&xe===0&&this[M+ae+1]!==0&&(xe=1),this[M+ae]=(T/he>>0)-xe&255;return M+L},i.prototype.writeInt8=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,1,127,-128),T<0&&(T=255+T+1),this[M]=T&255,M+1},i.prototype.writeInt16LE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,2,32767,-32768),this[M]=T&255,this[M+1]=T>>>8,M+2},i.prototype.writeInt16BE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,2,32767,-32768),this[M]=T>>>8,this[M+1]=T&255,M+2},i.prototype.writeInt32LE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,4,2147483647,-2147483648),this[M]=T&255,this[M+1]=T>>>8,this[M+2]=T>>>16,this[M+3]=T>>>24,M+4},i.prototype.writeInt32BE=function(T,M,L){return T=+T,M=M>>>0,L||z(this,T,M,4,2147483647,-2147483648),T<0&&(T=4294967295+T+1),this[M]=T>>>24,this[M+1]=T>>>16,this[M+2]=T>>>8,this[M+3]=T&255,M+4},i.prototype.writeBigInt64LE=xt(function(T,M=0){return G(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=xt(function(T,M=0){return V(this,T,M,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function H(T,M,L,te,ae,he){if(L+te>T.length)throw new RangeError("Index out of range");if(L<0)throw new RangeError("Index out of range")}function Y(T,M,L,te,ae){return M=+M,L=L>>>0,ae||H(T,M,L,4,34028234663852886e22,-34028234663852886e22),r.write(T,M,L,te,23,4),L+4}i.prototype.writeFloatLE=function(T,M,L){return Y(this,T,M,!0,L)},i.prototype.writeFloatBE=function(T,M,L){return Y(this,T,M,!1,L)};function K(T,M,L,te,ae){return M=+M,L=L>>>0,ae||H(T,M,L,8,17976931348623157e292,-17976931348623157e292),r.write(T,M,L,te,52,8),L+8}i.prototype.writeDoubleLE=function(T,M,L){return K(this,T,M,!0,L)},i.prototype.writeDoubleBE=function(T,M,L){return K(this,T,M,!1,L)},i.prototype.copy=function(T,M,L,te){if(!i.isBuffer(T))throw new TypeError("argument should be a Buffer");if(L||(L=0),!te&&te!==0&&(te=this.length),M>=T.length&&(M=T.length),M||(M=0),te>0&&te<L&&(te=L),te===L||T.length===0||this.length===0)return 0;if(M<0)throw new RangeError("targetStart out of bounds");if(L<0||L>=this.length)throw new RangeError("Index out of range");if(te<0)throw new RangeError("sourceEnd out of bounds");te>this.length&&(te=this.length),T.length-M<te-L&&(te=T.length-M+L);let ae=te-L;return this===T&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(M,L,te):Uint8Array.prototype.set.call(T,this.subarray(L,te),M),ae},i.prototype.fill=function(T,M,L,te){if(typeof T=="string"){if(typeof M=="string"?(te=M,M=0,L=this.length):typeof L=="string"&&(te=L,L=this.length),te!==void 0&&typeof te!="string")throw new TypeError("encoding must be a string");if(typeof te=="string"&&!i.isEncoding(te))throw new TypeError("Unknown encoding: "+te);if(T.length===1){let he=T.charCodeAt(0);(te==="utf8"&&he<128||te==="latin1")&&(T=he)}}else typeof T=="number"?T=T&255:typeof T=="boolean"&&(T=Number(T));if(M<0||this.length<M||this.length<L)throw new RangeError("Out of range index");if(L<=M)return this;M=M>>>0,L=L===void 0?this.length:L>>>0,T||(T=0);let ae;if(typeof T=="number")for(ae=M;ae<L;++ae)this[ae]=T;else{let he=i.isBuffer(T)?T:i.from(T,te),xe=he.length;if(xe===0)throw new TypeError('The value "'+T+'" is invalid for argument "value"');for(ae=0;ae<L-M;++ae)this[ae+M]=he[ae%xe]}return this};var Q={};function se(T,M,L){Q[T]=class extends L{constructor(){super(),Object.defineProperty(this,"message",{value:M.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${T}]`,this.stack,delete this.name}get code(){return T}set code(te){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:te,writable:!0})}toString(){return`${this.name} [${T}]: ${this.message}`}}}se("ERR_BUFFER_OUT_OF_BOUNDS",function(T){return T?`${T} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),se("ERR_INVALID_ARG_TYPE",function(T,M){return`The "${T}" argument must be of type number. Received type ${typeof M}`},TypeError),se("ERR_OUT_OF_RANGE",function(T,M,L){let te=`The value of "${T}" is out of range.`,ae=L;return Number.isInteger(L)&&Math.abs(L)>2**32?ae=re(String(L)):typeof L=="bigint"&&(ae=String(L),(L>BigInt(2)**BigInt(32)||L<-(BigInt(2)**BigInt(32)))&&(ae=re(ae)),ae+="n"),te+=` It must be ${M}. Received ${ae}`,te},RangeError);function re(T){let M="",L=T.length,te=T[0]==="-"?1:0;for(;L>=te+4;L-=3)M=`_${T.slice(L-3,L)}${M}`;return`${T.slice(0,L)}${M}`}function Z(T,M,L){le(M,"offset"),(T[M]===void 0||T[M+L]===void 0)&&pe(M,T.length-(L+1))}function de(T,M,L,te,ae,he){if(T>L||T<M){let xe=typeof M=="bigint"?"n":"",Mt;throw he>3?M===0||M===BigInt(0)?Mt=`>= 0${xe} and < 2${xe} ** ${(he+1)*8}${xe}`:Mt=`>= -(2${xe} ** ${(he+1)*8-1}${xe}) and < 2 ** ${(he+1)*8-1}${xe}`:Mt=`>= ${M}${xe} and <= ${L}${xe}`,new Q.ERR_OUT_OF_RANGE("value",Mt,T)}Z(te,ae,he)}function le(T,M){if(typeof T!="number")throw new Q.ERR_INVALID_ARG_TYPE(M,"number",T)}function pe(T,M,L){throw Math.floor(T)!==T?(le(T,L),new Q.ERR_OUT_OF_RANGE(L||"offset","an integer",T)):M<0?new Q.ERR_BUFFER_OUT_OF_BOUNDS:new Q.ERR_OUT_OF_RANGE(L||"offset",`>= ${L?1:0} and <= ${M}`,T)}var ve=/[^+/0-9A-Za-z-_]/g;function ce(T){if(T=T.split("=")[0],T=T.trim().replace(ve,""),T.length<2)return"";for(;T.length%4!==0;)T=T+"=";return T}function ge(T,M){M=M||1/0;let L,te=T.length,ae=null,he=[];for(let xe=0;xe<te;++xe){if(L=T.charCodeAt(xe),L>55295&&L<57344){if(!ae){if(L>56319){(M-=3)>-1&&he.push(239,191,189);continue}else if(xe+1===te){(M-=3)>-1&&he.push(239,191,189);continue}ae=L;continue}if(L<56320){(M-=3)>-1&&he.push(239,191,189),ae=L;continue}L=(ae-55296<<10|L-56320)+65536}else ae&&(M-=3)>-1&&he.push(239,191,189);if(ae=null,L<128){if((M-=1)<0)break;he.push(L)}else if(L<2048){if((M-=2)<0)break;he.push(L>>6|192,L&63|128)}else if(L<65536){if((M-=3)<0)break;he.push(L>>12|224,L>>6&63|128,L&63|128)}else if(L<1114112){if((M-=4)<0)break;he.push(L>>18|240,L>>12&63|128,L>>6&63|128,L&63|128)}else throw new Error("Invalid code point")}return he}function Me(T){let M=[];for(let L=0;L<T.length;++L)M.push(T.charCodeAt(L)&255);return M}function Le(T,M){let L,te,ae,he=[];for(let xe=0;xe<T.length&&!((M-=2)<0);++xe)L=T.charCodeAt(xe),te=L>>8,ae=L%256,he.push(ae),he.push(te);return he}function qe(T){return e.toByteArray(ce(T))}function Et(T,M,L,te){let ae;for(ae=0;ae<te&&!(ae+L>=M.length||ae>=T.length);++ae)M[ae+L]=T[ae];return ae}function Se(T,M){return T instanceof M||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===M.name}function et(T){return T!==T}var wt=function(){let T="0123456789abcdef",M=new Array(256);for(let L=0;L<16;++L){let te=L*16;for(let ae=0;ae<16;++ae)M[te+ae]=T[L]+T[ae]}return M}();function xt(T){return typeof BigInt>"u"?$t:T}function $t(){throw new Error("BigInt not supported")}}),NU=Kt((t,e)=>{"use strict";var r=null;e.exports=function(){return r===null&&(r={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),r}}),UU=Kt(t=>{"use strict";var e=_c(),r=new Set(["buffer","view","utf8"]),n=class{constructor(s){if(this.encode=s.encode||this.encode,this.decode=s.decode||this.decode,this.name=s.name||this.name,this.format=s.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'");s.createViewTranscoder&&(this.createViewTranscoder=s.createViewTranscoder),s.createBufferTranscoder&&(this.createBufferTranscoder=s.createBufferTranscoder),s.createUTF8Transcoder&&(this.createUTF8Transcoder=s.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}),LU=Kt(t=>{"use strict";var{Buffer:e}=NI()||{},{Encoding:r}=UU(),n=NU(),s=class extends r{constructor(i){super({...i,format:"buffer"})}createViewTranscoder(){return new a({encode:this.encode,decode:i=>this.decode(e.from(i.buffer,i.byteOffset,i.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},a=class extends r{constructor(i){super({...i,format:"view"})}createBufferTranscoder(){return new s({encode:i=>{let c=this.encode(i);return e.from(c.buffer,c.byteOffset,c.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},o=class extends r{constructor(i){super({...i,format:"utf8"})}createBufferTranscoder(){return new s({encode:i=>e.from(this.encode(i),"utf8"),decode:i=>this.decode(i.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:i,textDecoder:c}=n();return new a({encode:u=>i.encode(this.encode(u)),decode:u=>this.decode(c.decode(u)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};t.BufferFormat=s,t.ViewFormat=a,t.UTF8Format=o}),une=Kt(t=>{"use strict";var{Buffer:e}=NI()||{Buffer:{isBuffer:()=>!1}},{textEncoder:r,textDecoder:n}=NU()(),{BufferFormat:s,ViewFormat:a,UTF8Format:o}=LU(),i=c=>c;t.utf8=new o({encode:function(c){return e.isBuffer(c)?c.toString("utf8"):ArrayBuffer.isView(c)?n.decode(c):String(c)},decode:i,name:"utf8",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:r.encode(c)},decode:function(c){return n.decode(c)},name:`${this.name}+view`})},createBufferTranscoder(){return new s({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:function(c){return c.toString("utf8")},name:`${this.name}+buffer`})}}),t.json=new o({encode:JSON.stringify,decode:JSON.parse,name:"json"}),t.buffer=new s({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:i,name:"buffer",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:e.from(String(c),"utf8")},decode:function(c){return e.from(c.buffer,c.byteOffset,c.byteLength)},name:`${this.name}+view`})}}),t.view=new a({encode:function(c){return ArrayBuffer.isView(c)?c:r.encode(c)},decode:i,name:"view",createBufferTranscoder(){return new s({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:i,name:`${this.name}+buffer`})}}),t.hex=new s({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"hex")},decode:function(c){return c.toString("hex")},name:"hex"}),t.base64=new s({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"base64")},decode:function(c){return c.toString("base64")},name:"base64"})}),lne=Kt(t=>{"use strict";var e=_c(),r=une(),{Encoding:n}=UU(),{BufferFormat:s,ViewFormat:a,UTF8Format:o}=LU(),i=Symbol("formats"),c=Symbol("encodings"),u=new Set(["buffer","view","utf8"]),d=class{constructor(y){if(Array.isArray(y)){if(!y.every(S=>u.has(S)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[c]=new Map,this[i]=new Set(y);for(let S in r)try{this.encoding(S)}catch(v){if(v.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw v}}encodings(){return Array.from(new Set(this[c].values()))}encoding(y){let S=this[c].get(y);if(S===void 0){if(typeof y=="string"&&y!==""){if(S=p[y],!S)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");S=l(y)}let{name:v,format:E}=S;if(!this[i].has(E))if(this[i].has("view"))S=S.createViewTranscoder();else if(this[i].has("buffer"))S=S.createBufferTranscoder();else if(this[i].has("utf8"))S=S.createUTF8Transcoder();else throw new e(`Encoding '${v}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let k of[y,v,S.name,S.commonName])this[c].set(k,S)}return S}};t.Transcoder=d;function l(y){if(y instanceof n)return y;let S="type"in y&&typeof y.type=="string"?y.type:void 0,v=y.name||S||`anonymous-${m++}`;switch(f(y)){case"view":return new a({...y,name:v});case"utf8":return new o({...y,name:v});case"buffer":return new s({...y,name:v});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}),fne=Kt((t,e)=>{"use strict";var r=Object.prototype.hasOwnProperty,n="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(n=!1));function a(u,d,l){this.fn=u,this.context=d,this.once=l||!1}function o(u,d,l,f,h){if(typeof l!="function")throw new TypeError("The listener must be a function");var p=new a(l,f||u,h),m=n?n+d:d;return u._events[m]?u._events[m].fn?u._events[m]=[u._events[m],p]:u._events[m].push(p):(u._events[m]=p,u._eventsCount++),u}function i(u,d){--u._eventsCount===0?u._events=new s:delete u._events[d]}function c(){this._events=new s,this._eventsCount=0}c.prototype.eventNames=function(){var u=[],d,l;if(this._eventsCount===0)return u;for(l in d=this._events)r.call(d,l)&&u.push(n?l.slice(1):l);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},c.prototype.listeners=function(u){var d=n?n+u:u,l=this._events[d];if(!l)return[];if(l.fn)return[l.fn];for(var f=0,h=l.length,p=new Array(h);f<h;f++)p[f]=l[f].fn;return p},c.prototype.listenerCount=function(u){var d=n?n+u:u,l=this._events[d];return l?l.fn?1:l.length:0},c.prototype.emit=function(u,d,l,f,h,p){var m=n?n+u:u;if(!this._events[m])return!1;var y=this._events[m],S=arguments.length,v,E;if(y.fn){switch(y.once&&this.removeListener(u,y.fn,void 0,!0),S){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,l),!0;case 4:return y.fn.call(y.context,d,l,f),!0;case 5:return y.fn.call(y.context,d,l,f,h),!0;case 6:return y.fn.call(y.context,d,l,f,h,p),!0}for(E=1,v=new Array(S-1);E<S;E++)v[E-1]=arguments[E];y.fn.apply(y.context,v)}else{var k=y.length,A;for(E=0;E<k;E++)switch(y[E].once&&this.removeListener(u,y[E].fn,void 0,!0),S){case 1:y[E].fn.call(y[E].context);break;case 2:y[E].fn.call(y[E].context,d);break;case 3:y[E].fn.call(y[E].context,d,l);break;case 4:y[E].fn.call(y[E].context,d,l,f);break;default:if(!v)for(A=1,v=new Array(S-1);A<S;A++)v[A-1]=arguments[A];y[E].fn.apply(y[E].context,v)}}return!0},c.prototype.on=function(u,d,l){return o(this,u,d,l,!1)},c.prototype.once=function(u,d,l){return o(this,u,d,l,!0)},c.prototype.removeListener=function(u,d,l,f){var h=n?n+u:u;if(!this._events[h])return this;if(!d)return i(this,h),this;var p=this._events[h];if(p.fn)p.fn===d&&(!f||p.once)&&(!l||p.context===l)&&i(this,h);else{for(var m=0,y=[],S=p.length;m<S;m++)(p[m].fn!==d||f&&!p[m].once||l&&p[m].context!==l)&&y.push(p[m]);y.length?this._events[h]=y.length===1?y[0]:y:i(this,h)}return this},c.prototype.removeAllListeners=function(u){var d;return u?(d=n?n+u:u,this._events[d]&&i(this,d)):(this._events=new s,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,typeof e<"u"&&(e.exports=c)}),pne=Kt((t,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:r=>Promise.resolve().then(r)}),X1=Kt(t=>{"use strict";var e=pne();t.fromCallback=function(r,n){if(r===void 0){var s=new Promise(function(a,o){r=function(i,c){i?o(i):a(c)}});r[n!==void 0?n:"promise"]=s}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(s){e(()=>n(null,s))}).catch(function(s){e(()=>n(s))})}}),UI=Kt(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:{}}}),Sf=Kt(t=>{"use strict";var{fromCallback:e}=X1(),r=_c(),{getOptions:n,getCallback:s}=UI(),a=Symbol("promise"),o=Symbol("callback"),i=Symbol("working"),c=Symbol("handleOne"),u=Symbol("handleMany"),d=Symbol("autoClose"),l=Symbol("finishWork"),f=Symbol("returnMany"),h=Symbol("closing"),p=Symbol("handleClose"),m=Symbol("closed"),y=Symbol("closeCallbacks"),S=Symbol("keyEncoding"),v=Symbol("valueEncoding"),E=Symbol("abortOnClose"),k=Symbol("legacy"),A=Symbol("keys"),D=Symbol("values"),B=Symbol("limit"),j=Symbol("count"),F=Object.freeze({}),q=()=>{},N=!1,W=class{constructor(x,P,_){if(typeof x!="object"||x===null){let I=x===null?"null":typeof x;throw new TypeError(`The first argument must be an abstract-level database, received ${I}`)}if(typeof P!="object"||P===null)throw new TypeError("The second argument must be an options object");this[m]=!1,this[y]=[],this[i]=!1,this[h]=!1,this[d]=!1,this[o]=null,this[c]=this[c].bind(this),this[u]=this[u].bind(this),this[p]=this[p].bind(this),this[S]=P[S],this[v]=P[v],this[k]=_,this[B]=Number.isInteger(P.limit)&&P.limit>=0?P.limit:1/0,this[j]=0,this[E]=!!P.abortOnClose,this.db=x,this.db.attachResource(this),this.nextTick=x.nextTick}get count(){return this[j]}get limit(){return this[B]}next(x){let P;if(x===void 0)P=new Promise((_,I)=>{x=(O,z,G)=>{O?I(O):this[k]?z===void 0&&G===void 0?_():_([z,G]):_(z)}});else if(typeof x!="function")throw new TypeError("Callback must be a function");return this[h]?this.nextTick(x,new r("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(x,new r("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[i]=!0,this[o]=x,this[j]>=this[B]?this.nextTick(this[c],null):this._next(this[c])),P}_next(x){this.nextTick(x)}nextv(x,P,_){return _=s(P,_),_=e(_,a),P=n(P,F),Number.isInteger(x)?(this[h]?this.nextTick(_,new r("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(_,new r("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(x<1&&(x=1),this[B]<1/0&&(x=Math.min(x,this[B]-this[j])),this[i]=!0,this[o]=_,x<=0?this.nextTick(this[u],null,[]):this._nextv(x,P,this[u])),_[a]):(this.nextTick(_,new TypeError("The first argument 'size' must be an integer")),_[a])}_nextv(x,P,_){let I=[],O=(z,G,V)=>{if(z)return _(z);if(this[k]?G===void 0&&V===void 0:G===void 0)return _(null,I);I.push(this[k]?[G,V]:G),I.length===x?_(null,I):this._next(O)};this._next(O)}all(x,P){return P=s(x,P),P=e(P,a),x=n(x,F),this[h]?this.nextTick(P,new r("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[i]?this.nextTick(P,new r("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[i]=!0,this[o]=P,this[d]=!0,this[j]>=this[B]?this.nextTick(this[u],null,[]):this._all(x,this[u])),P[a]}_all(x,P){let _=this[j],I=[],O=()=>{let G=this[B]<1/0?Math.min(1e3,this[B]-_):1e3;G<=0?this.nextTick(P,null,I):this._nextv(G,F,z)},z=(G,V)=>{G?P(G):V.length===0?P(null,I):(I.push.apply(I,V),_+=V.length,O())};O()}[l](){let x=this[o];return this[E]&&x===null?q:(this[i]=!1,this[o]=null,this[h]&&this._close(this[p]),x)}[f](x,P,_){this[d]?this.close(x.bind(null,P,_)):x(P,_)}seek(x,P){if(P=n(P,F),!this[h]){if(this[i])throw new r("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let _=this.db.keyEncoding(P.keyEncoding||this[S]),I=_.format;P.keyEncoding!==I&&(P={...P,keyEncoding:I});let O=this.db.prefixKey(_.encode(x),I);this._seek(O,P)}}}_seek(x,P){throw new r("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(x){return x=e(x,a),this[m]?this.nextTick(x):this[h]?this[y].push(x):(this[h]=!0,this[y].push(x),this[i]?this[E]&&this[l]()(new r("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[p])),x[a]}_close(x){this.nextTick(x)}[p](){this[m]=!0,this.db.detachResource(this);let x=this[y];this[y]=[];for(let P of x)P()}async*[Symbol.asyncIterator](){try{let x;for(;(x=await this.next())!==void 0;)yield x}finally{this[m]||await this.close()}}},ee=class extends W{constructor(x,P){super(x,P,!0),this[A]=P.keys!==!1,this[D]=P.values!==!1}[c](x,P,_){let I=this[l]();if(x)return I(x);try{P=this[A]&&P!==void 0?this[S].decode(P):void 0,_=this[D]&&_!==void 0?this[v].decode(_):void 0}catch(O){return I(new b("entry",O))}P===void 0&&_===void 0||this[j]++,I(null,P,_)}[u](x,P){let _=this[l]();if(x)return this[f](_,x);try{for(let I of P){let O=I[0],z=I[1];I[0]=this[A]&&O!==void 0?this[S].decode(O):void 0,I[1]=this[D]&&z!==void 0?this[v].decode(z):void 0}}catch(I){return this[f](_,new b("entries",I))}this[j]+=P.length,this[f](_,null,P)}end(x){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(x)}},R=class extends W{constructor(x,P){super(x,P,!1)}[c](x,P){let _=this[l]();if(x)return _(x);try{P=P!==void 0?this[S].decode(P):void 0}catch(I){return _(new b("key",I))}P!==void 0&&this[j]++,_(null,P)}[u](x,P){let _=this[l]();if(x)return this[f](_,x);try{for(let I=0;I<P.length;I++){let O=P[I];P[I]=O!==void 0?this[S].decode(O):void 0}}catch(I){return this[f](_,new b("keys",I))}this[j]+=P.length,this[f](_,null,P)}},$=class extends W{constructor(x,P){super(x,P,!1)}[c](x,P){let _=this[l]();if(x)return _(x);try{P=P!==void 0?this[v].decode(P):void 0}catch(I){return _(new b("value",I))}P!==void 0&&this[j]++,_(null,P)}[u](x,P){let _=this[l]();if(x)return this[f](_,x);try{for(let I=0;I<P.length;I++){let O=P[I];P[I]=O!==void 0?this[v].decode(O):void 0}}catch(I){return this[f](_,new b("values",I))}this[j]+=P.length,this[f](_,null,P)}},b=class extends r{constructor(x,P){super(`Iterator could not decode ${x}`,{code:"LEVEL_DECODE_ERROR",cause:P})}};for(let x of["_ended property","_nexting property","_end method"])Object.defineProperty(ee.prototype,x.split(" ")[0],{get(){throw new r(`The ${x} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new r(`The ${x} has been removed`,{code:"LEVEL_LEGACY"})}});ee.keyEncoding=S,ee.valueEncoding=v,t.AbstractIterator=ee,t.AbstractKeyIterator=R,t.AbstractValueIterator=$}),hne=Kt(t=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:r}=Sf(),n=Symbol("iterator"),s=Symbol("callback"),a=Symbol("handleOne"),o=Symbol("handleMany"),i=class extends e{constructor(u,d){super(u,d),this[n]=u.iterator({...d,keys:!0,values:!1}),this[a]=this[a].bind(this),this[o]=this[o].bind(this)}},c=class extends r{constructor(u,d){super(u,d),this[n]=u.iterator({...d,keys:!1,values:!0}),this[a]=this[a].bind(this),this[o]=this[o].bind(this)}};for(let u of[i,c]){let d=u===i,l=d?f=>f[0]:f=>f[1];u.prototype._next=function(f){this[s]=f,this[n].next(this[a])},u.prototype[a]=function(f,h,p){let m=this[s];f?m(f):m(null,d?h:p)},u.prototype._nextv=function(f,h,p){this[s]=p,this[n].nextv(f,h,this[o])},u.prototype._all=function(f,h){this[s]=h,this[n].all(f,this[o])},u.prototype[o]=function(f,h){let p=this[s];f?p(f):p(null,h.map(l))},u.prototype._seek=function(f,h){this[n].seek(f,h)},u.prototype._close=function(f){this[n].close(f)}}t.DefaultKeyIterator=i,t.DefaultValueIterator=c}),mne=Kt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=Sf(),s=_c(),a=Symbol("nut"),o=Symbol("undefer"),i=Symbol("factory"),c=class extends e{constructor(l,f){super(l,f),this[a]=null,this[i]=()=>l.iterator(f),this.db.defer(()=>this[o]())}},u=class extends r{constructor(l,f){super(l,f),this[a]=null,this[i]=()=>l.keys(f),this.db.defer(()=>this[o]())}},d=class extends n{constructor(l,f){super(l,f),this[a]=null,this[i]=()=>l.values(f),this.db.defer(()=>this[o]())}};for(let l of[c,u,d])l.prototype[o]=function(){this.db.status==="open"&&(this[a]=this[i]())},l.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 s("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},l.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 s("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},l.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 s("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},l.prototype._seek=function(f,h){this[a]!==null?this[a]._seek(f,h):this.db.status==="opening"&&this.db.defer(()=>this._seek(f,h))},l.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=c,t.DeferredKeyIterator=u,t.DeferredValueIterator=d}),KU=Kt(t=>{"use strict";var{fromCallback:e}=X1(),r=_c(),{getCallback:n,getOptions:s}=UI(),a=Symbol("promise"),o=Symbol("status"),i=Symbol("operations"),c=Symbol("finishClose"),u=Symbol("closeCallbacks"),d=class{constructor(l){if(typeof l!="object"||l===null){let f=l===null?"null":typeof l;throw new TypeError(`The first argument must be an abstract-level database, received ${f}`)}this[i]=[],this[u]=[],this[o]="open",this[c]=this[c].bind(this),this.db=l,this.db.attachResource(this),this.nextTick=l.nextTick}get length(){return this[i].length}put(l,f,h){if(this[o]!=="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(l)||this.db._checkValue(f);if(p)throw p;let m=h&&h.sublevel!=null?h.sublevel:this.db,y=h,S=m.keyEncoding(h&&h.keyEncoding),v=m.valueEncoding(h&&h.valueEncoding),E=S.format;h={...h,keyEncoding:E,valueEncoding:v.format},m!==this.db&&(h.sublevel=null);let k=m.prefixKey(S.encode(l),E),A=v.encode(f);return this._put(k,A,h),this[i].push({...y,type:"put",key:l,value:f}),this}_put(l,f,h){}del(l,f){if(this[o]!=="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(l);if(h)throw h;let p=f&&f.sublevel!=null?f.sublevel:this.db,m=f,y=p.keyEncoding(f&&f.keyEncoding),S=y.format;return f={...f,keyEncoding:S},p!==this.db&&(f.sublevel=null),this._del(p.prefixKey(y.encode(l),S),f),this[i].push({...m,type:"del",key:l}),this}_del(l,f){}clear(){if(this[o]!=="open")throw new r("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[i]=[],this}_clear(){}write(l,f){return f=n(l,f),f=e(f,a),l=s(l),this[o]!=="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[o]="writing",this._write(l,h=>{this[o]="closing",this[u].push(()=>f(h)),h||this.db.emit("batch",this[i]),this._close(this[c])})),f[a]}_write(l,f){}close(l){return l=e(l,a),this[o]==="closing"?this[u].push(l):this[o]==="closed"?this.nextTick(l):(this[u].push(l),this[o]!=="writing"&&(this[o]="closing",this._close(this[c]))),l[a]}_close(l){this.nextTick(l)}[c](){this[o]="closed",this.db.detachResource(this);let l=this[u];this[u]=[];for(let f of l)f()}};t.AbstractChainedBatch=d}),yne=Kt(t=>{"use strict";var{AbstractChainedBatch:e}=KU(),r=_c(),n=Symbol("encoded"),s=class extends e{constructor(a){super(a),this[n]=[]}_put(a,o,i){this[n].push({...i,type:"put",key:a,value:o})}_del(a,o){this[n].push({...o,type:"del",key:a})}_clear(){this[n]=[]}_write(a,o){this.db.status==="opening"?this.db.defer(()=>this._write(a,o)):this.db.status==="open"?this[n].length===0?this.nextTick(o):this.db._batch(this[n],a,o):this.nextTick(o,new r("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};t.DefaultChainedBatch=s}),gne=Kt((t,e)=>{"use strict";var r=_c(),n=Object.prototype.hasOwnProperty,s=new Set(["lt","lte","gt","gte"]);e.exports=function(a,o){let i={};for(let c in a)if(n.call(a,c)&&!(c==="keyEncoding"||c==="valueEncoding")){if(c==="start"||c==="end")throw new r(`The legacy range option '${c}' has been removed`,{code:"LEVEL_LEGACY"});if(c==="encoding")throw new r("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});s.has(c)?i[c]=o.encode(a[c]):i[c]=a[c]}return i.reverse=!!i.reverse,i.limit=Number.isInteger(i.limit)&&i.limit>=0?i.limit:-1,i}}),zU=Kt((t,e)=>{var r;e.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):n=>(r||(r=Promise.resolve())).then(n).catch(s=>setTimeout(()=>{throw s},0))}),wne=Kt((t,e)=>{"use strict";var r=zU();e.exports=function(n,...s){s.length===0?r(n):r(()=>n(...s))}}),vne=Kt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=Sf(),s=Symbol("unfix"),a=Symbol("iterator"),o=Symbol("handleOne"),i=Symbol("handleMany"),c=Symbol("callback"),u=class extends e{constructor(f,h,p,m){super(f,h),this[a]=p,this[s]=m,this[o]=this[o].bind(this),this[i]=this[i].bind(this),this[c]=null}[o](f,h,p){let m=this[c];if(f)return m(f);h!==void 0&&(h=this[s](h)),m(f,h,p)}[i](f,h){let p=this[c];if(f)return p(f);for(let m of h){let y=m[0];y!==void 0&&(m[0]=this[s](y))}p(f,h)}},d=class extends r{constructor(f,h,p,m){super(f,h),this[a]=p,this[s]=m,this[o]=this[o].bind(this),this[i]=this[i].bind(this),this[c]=null}[o](f,h){let p=this[c];if(f)return p(f);h!==void 0&&(h=this[s](h)),p(f,h)}[i](f,h){let p=this[c];if(f)return p(f);for(let m=0;m<h.length;m++){let y=h[m];y!==void 0&&(h[m]=this[s](y))}p(f,h)}},l=class extends n{constructor(f,h,p){super(f,h),this[a]=p}};for(let f of[u,d])f.prototype._next=function(h){this[c]=h,this[a].next(this[o])},f.prototype._nextv=function(h,p,m){this[c]=m,this[a].nextv(h,p,this[i])},f.prototype._all=function(h,p){this[c]=p,this[a].all(h,this[i])};for(let f of[l])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[u,d,l])f.prototype._seek=function(h,p){this[a].seek(h,p)},f.prototype._close=function(h){this[a].close(h)};t.AbstractSublevelIterator=u,t.AbstractSublevelKeyIterator=d,t.AbstractSublevelValueIterator=l}),bne=Kt((t,e)=>{"use strict";var r=_c(),{Buffer:n}=NI()||{},{AbstractSublevelIterator:s,AbstractSublevelKeyIterator:a,AbstractSublevelValueIterator:o}=vne(),i=Symbol("prefix"),c=Symbol("upperBound"),u=Symbol("prefixRange"),d=Symbol("parent"),l=Symbol("unfix"),f=new TextEncoder,h={separator:"!"};e.exports=function({AbstractLevel:E}){class k extends E{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,B,j){let{separator:F,manifest:q,...N}=k.defaults(j);B=v(B,F);let W=F.charCodeAt(0)+1,ee=D[d]||D;if(!f.encode(B).every(b=>b>W&&b<127))throw new r(`Prefix must use bytes > ${W} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(p(ee,q),N);let R=(D.prefix||"")+F+B+F,$=R.slice(0,-1)+String.fromCharCode(W);this[d]=ee,this[i]=new y(R),this[c]=new y($),this[l]=new S,this.nextTick=ee.nextTick}prefixKey(D,B){if(B==="utf8")return this[i].utf8+D;if(D.byteLength===0)return this[i][B];if(B==="view"){let j=this[i].view,F=new Uint8Array(j.byteLength+D.byteLength);return F.set(j,0),F.set(D,j.byteLength),F}else{let j=this[i].buffer;return n.concat([j,D],j.byteLength+D.byteLength)}}[u](D,B){D.gte!==void 0?D.gte=this.prefixKey(D.gte,B):D.gt!==void 0?D.gt=this.prefixKey(D.gt,B):D.gte=this[i][B],D.lte!==void 0?D.lte=this.prefixKey(D.lte,B):D.lt!==void 0?D.lt=this.prefixKey(D.lt,B):D.lte=this[c][B]}get prefix(){return this[i].utf8}get db(){return this[d]}_open(D,B){this[d].open({passive:!0},B)}_put(D,B,j,F){this[d].put(D,B,j,F)}_get(D,B,j){this[d].get(D,B,j)}_getMany(D,B,j){this[d].getMany(D,B,j)}_del(D,B,j){this[d].del(D,B,j)}_batch(D,B,j){this[d].batch(D,B,j)}_clear(D,B){this[u](D,D.keyEncoding),this[d].clear(D,B)}_iterator(D){this[u](D,D.keyEncoding);let B=this[d].iterator(D),j=this[l].get(this[i].utf8.length,D.keyEncoding);return new s(this,D,B,j)}_keys(D){this[u](D,D.keyEncoding);let B=this[d].keys(D),j=this[l].get(this[i].utf8.length,D.keyEncoding);return new a(this,D,B,j)}_values(D){this[u](D,D.keyEncoding);let B=this[d].values(D);return new o(this,D,B)}}return{AbstractSublevel:k}};var p=function(E,k){return{...E.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...k,encodings:{utf8:m(E,"utf8"),buffer:m(E,"buffer"),view:m(E,"view")}}},m=function(E,k){return E.supports.encodings[k]?E.keyEncoding(k).name===k:!1},y=class{constructor(E){this.utf8=E,this.view=f.encode(E),this.buffer=n?n.from(this.view.buffer,0,this.view.byteLength):{}}},S=class{constructor(){this.cache=new Map}get(E,k){let A=this.cache.get(k);return A===void 0&&(k==="view"?A=(function(D,B){return B.subarray(D)}).bind(null,E):A=(function(D,B){return B.slice(D)}).bind(null,E),this.cache.set(k,A)),A}},v=function(E,k){let A=0,D=E.length;for(;A<D&&E[A]===k;)A++;for(;D>A&&E[D-1]===k;)D--;return E.slice(A,D)}}),PN=Kt(t=>{"use strict";var{supports:e}=ane(),{Transcoder:r}=lne(),{EventEmitter:n}=fne(),{fromCallback:s}=X1(),a=_c(),{AbstractIterator:o}=Sf(),{DefaultKeyIterator:i,DefaultValueIterator:c}=hne(),{DeferredIterator:u,DeferredKeyIterator:d,DeferredValueIterator:l}=mne(),{DefaultChainedBatch:f}=yne(),{getCallback:h,getOptions:p}=UI(),m=gne(),y=Symbol("promise"),S=Symbol("landed"),v=Symbol("resources"),E=Symbol("closeResources"),k=Symbol("operations"),A=Symbol("undefer"),D=Symbol("deferOpen"),B=Symbol("options"),j=Symbol("status"),F=Symbol("defaultOptions"),q=Symbol("transcoder"),N=Symbol("keyEncoding"),W=Symbol("valueEncoding"),ee=()=>{},R=class extends n{constructor(P,_){if(super(),typeof P!="object"||P===null)throw new TypeError("The first argument 'manifest' must be an object");_=p(_);let{keyEncoding:I,valueEncoding:O,passive:z,...G}=_;this[v]=new Set,this[k]=[],this[D]=!0,this[B]=G,this[j]="opening",this.supports=e(P,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:P.snapshots!==!1,permanence:P.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:P.encodings||{},events:Object.assign({},P.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[q]=new r(x(this)),this[N]=this[q].encoding(I||"utf8"),this[W]=this[q].encoding(O||"utf8");for(let V of this[q].encodings())this.supports.encodings[V.commonName]||(this.supports.encodings[V.commonName]=!0);this[F]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[N].commonName,valueEncoding:this[W].commonName}),key:Object.freeze({keyEncoding:this[N].commonName})},this.nextTick(()=>{this[D]&&this.open({passive:!1},ee)})}get status(){return this[j]}keyEncoding(P){return this[q].encoding(P??this[N])}valueEncoding(P){return this[q].encoding(P??this[W])}open(P,_){_=h(P,_),_=s(_,y),P={...this[B],...p(P)},P.createIfMissing=P.createIfMissing!==!1,P.errorIfExists=!!P.errorIfExists;let I=O=>{this[j]==="closing"||this[j]==="opening"?this.once(S,O?()=>I(O):I):this[j]!=="open"?_(new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:O})):_()};return P.passive?this[j]==="opening"?this.once(S,I):this.nextTick(I):this[j]==="closed"||this[D]?(this[D]=!1,this[j]="opening",this.emit("opening"),this._open(P,O=>{if(O){this[j]="closed",this[E](()=>{this.emit(S),I(O)}),this[A]();return}this[j]="open",this[A](),this.emit(S),this[j]==="open"&&this.emit("open"),this[j]==="open"&&this.emit("ready"),I()})):this[j]==="open"?this.nextTick(I):this.once(S,()=>this.open(P,_)),_[y]}_open(P,_){this.nextTick(_)}close(P){P=s(P,y);let _=I=>{this[j]==="opening"||this[j]==="closing"?this.once(S,I?_(I):_):this[j]!=="closed"?P(new a("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:I})):P()};if(this[j]==="open"){this[j]="closing",this.emit("closing");let I=O=>{this[j]="open",this[A](),this.emit(S),_(O)};this[E](()=>{this._close(O=>{if(O)return I(O);this[j]="closed",this[A](),this.emit(S),this[j]==="closed"&&this.emit("closed"),_()})})}else this[j]==="closed"?this.nextTick(_):this.once(S,()=>this.close(P));return P[y]}[E](P){if(this[v].size===0)return this.nextTick(P);let _=this[v].size,I=!0,O=()=>{--_===0&&(I?this.nextTick(P):P())};for(let z of this[v])z.close(O);I=!1,this[v].clear()}_close(P){this.nextTick(P)}get(P,_,I){if(I=h(_,I),I=s(I,y),_=p(_,this[F].entry),this[j]==="opening")return this.defer(()=>this.get(P,_,I)),I[y];if(b(this,I))return I[y];let O=this._checkKey(P);if(O)return this.nextTick(I,O),I[y];let z=this.keyEncoding(_.keyEncoding),G=this.valueEncoding(_.valueEncoding),V=z.format,H=G.format;return(_.keyEncoding!==V||_.valueEncoding!==H)&&(_=Object.assign({},_,{keyEncoding:V,valueEncoding:H})),this._get(this.prefixKey(z.encode(P),V),_,(Y,K)=>{if(Y)return(Y.code==="LEVEL_NOT_FOUND"||Y.notFound||/NotFound/i.test(Y))&&(Y.code||(Y.code="LEVEL_NOT_FOUND"),Y.notFound||(Y.notFound=!0),Y.status||(Y.status=404)),I(Y);try{K=G.decode(K)}catch(Q){return I(new a("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:Q}))}I(null,K)}),I[y]}_get(P,_,I){this.nextTick(I,new Error("NotFound"))}getMany(P,_,I){if(I=h(_,I),I=s(I,y),_=p(_,this[F].entry),this[j]==="opening")return this.defer(()=>this.getMany(P,_,I)),I[y];if(b(this,I))return I[y];if(!Array.isArray(P))return this.nextTick(I,new TypeError("The first argument 'keys' must be an array")),I[y];if(P.length===0)return this.nextTick(I,null,[]),I[y];let O=this.keyEncoding(_.keyEncoding),z=this.valueEncoding(_.valueEncoding),G=O.format,V=z.format;(_.keyEncoding!==G||_.valueEncoding!==V)&&(_=Object.assign({},_,{keyEncoding:G,valueEncoding:V}));let H=new Array(P.length);for(let Y=0;Y<P.length;Y++){let K=P[Y],Q=this._checkKey(K);if(Q)return this.nextTick(I,Q),I[y];H[Y]=this.prefixKey(O.encode(K),G)}return this._getMany(H,_,(Y,K)=>{if(Y)return I(Y);try{for(let Q=0;Q<K.length;Q++)K[Q]!==void 0&&(K[Q]=z.decode(K[Q]))}catch(Q){return I(new a(`Could not decode one or more of ${K.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:Q}))}I(null,K)}),I[y]}_getMany(P,_,I){this.nextTick(I,null,new Array(P.length).fill(void 0))}put(P,_,I,O){if(O=h(I,O),O=s(O,y),I=p(I,this[F].entry),this[j]==="opening")return this.defer(()=>this.put(P,_,I,O)),O[y];if(b(this,O))return O[y];let z=this._checkKey(P)||this._checkValue(_);if(z)return this.nextTick(O,z),O[y];let G=this.keyEncoding(I.keyEncoding),V=this.valueEncoding(I.valueEncoding),H=G.format,Y=V.format;(I.keyEncoding!==H||I.valueEncoding!==Y)&&(I=Object.assign({},I,{keyEncoding:H,valueEncoding:Y}));let K=this.prefixKey(G.encode(P),H),Q=V.encode(_);return this._put(K,Q,I,se=>{if(se)return O(se);this.emit("put",P,_),O()}),O[y]}_put(P,_,I,O){this.nextTick(O)}del(P,_,I){if(I=h(_,I),I=s(I,y),_=p(_,this[F].key),this[j]==="opening")return this.defer(()=>this.del(P,_,I)),I[y];if(b(this,I))return I[y];let O=this._checkKey(P);if(O)return this.nextTick(I,O),I[y];let z=this.keyEncoding(_.keyEncoding),G=z.format;return _.keyEncoding!==G&&(_=Object.assign({},_,{keyEncoding:G})),this._del(this.prefixKey(z.encode(P),G),_,V=>{if(V)return I(V);this.emit("del",P),I()}),I[y]}_del(P,_,I){this.nextTick(I)}batch(P,_,I){if(!arguments.length){if(this[j]==="opening")return new f(this);if(this[j]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof P=="function"?I=P:I=h(_,I),I=s(I,y),_=p(_,this[F].empty),this[j]==="opening")return this.defer(()=>this.batch(P,_,I)),I[y];if(b(this,I))return I[y];if(!Array.isArray(P))return this.nextTick(I,new TypeError("The first argument 'operations' must be an array")),I[y];if(P.length===0)return this.nextTick(I),I[y];let O=new Array(P.length),{keyEncoding:z,valueEncoding:G,...V}=_;for(let H=0;H<P.length;H++){if(typeof P[H]!="object"||P[H]===null)return this.nextTick(I,new TypeError("A batch operation must be an object")),I[y];let Y=Object.assign({},P[H]);if(Y.type!=="put"&&Y.type!=="del")return this.nextTick(I,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),I[y];let K=this._checkKey(Y.key);if(K)return this.nextTick(I,K),I[y];let Q=Y.sublevel!=null?Y.sublevel:this,se=Q.keyEncoding(Y.keyEncoding||z),re=se.format;if(Y.key=Q.prefixKey(se.encode(Y.key),re),Y.keyEncoding=re,Y.type==="put"){let Z=this._checkValue(Y.value);if(Z)return this.nextTick(I,Z),I[y];let de=Q.valueEncoding(Y.valueEncoding||G);Y.value=de.encode(Y.value),Y.valueEncoding=de.format}Q!==this&&(Y.sublevel=null),O[H]=Y}return this._batch(O,V,H=>{if(H)return I(H);this.emit("batch",P),I()}),I[y]}_batch(P,_,I){this.nextTick(I)}sublevel(P,_){return this._sublevel(P,$.defaults(_))}_sublevel(P,_){return new $(this,P,_)}prefixKey(P,_){return P}clear(P,_){if(_=h(P,_),_=s(_,y),P=p(P,this[F].empty),this[j]==="opening")return this.defer(()=>this.clear(P,_)),_[y];if(b(this,_))return _[y];let I=P,O=this.keyEncoding(P.keyEncoding);return P=m(P,O),P.keyEncoding=O.format,P.limit===0?this.nextTick(_):this._clear(P,z=>{if(z)return _(z);this.emit("clear",I),_()}),_[y]}_clear(P,_){this.nextTick(_)}iterator(P){let _=this.keyEncoding(P&&P.keyEncoding),I=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,_),P.keys=P.keys!==!1,P.values=P.values!==!1,P[o.keyEncoding]=_,P[o.valueEncoding]=I,P.keyEncoding=_.format,P.valueEncoding=I.format,this[j]==="opening")return new u(this,P);if(this[j]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(P)}_iterator(P){return new o(this,P)}keys(P){let _=this.keyEncoding(P&&P.keyEncoding),I=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,_),P[o.keyEncoding]=_,P[o.valueEncoding]=I,P.keyEncoding=_.format,P.valueEncoding=I.format,this[j]==="opening")return new d(this,P);if(this[j]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(P)}_keys(P){return new i(this,P)}values(P){let _=this.keyEncoding(P&&P.keyEncoding),I=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,_),P[o.keyEncoding]=_,P[o.valueEncoding]=I,P.keyEncoding=_.format,P.valueEncoding=I.format,this[j]==="opening")return new l(this,P);if(this[j]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(P)}_values(P){return new c(this,P)}defer(P){if(typeof P!="function")throw new TypeError("The first argument must be a function");this[k].push(P)}[A](){if(this[k].length===0)return;let P=this[k];this[k]=[];for(let _ of P)_()}attachResource(P){if(typeof P!="object"||P===null||typeof P.close!="function")throw new TypeError("The first argument must be a resource object");this[v].add(P)}detachResource(P){this[v].delete(P)}_chainedBatch(){return new f(this)}_checkKey(P){if(P==null)return new a("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(P){if(P==null)return new a("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};R.prototype.nextTick=wne();var{AbstractSublevel:$}=bne()({AbstractLevel:R});t.AbstractLevel=R,t.AbstractSublevel=$;var b=function(P,_){return P[j]!=="open"?(P.nextTick(_,new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},x=function(P){return Object.keys(P.supports.encodings).filter(_=>!!P.supports.encodings[_])}}),qU=Kt(t=>{"use strict";t.AbstractLevel=PN().AbstractLevel,t.AbstractSublevel=PN().AbstractSublevel,t.AbstractIterator=Sf().AbstractIterator,t.AbstractKeyIterator=Sf().AbstractKeyIterator,t.AbstractValueIterator=Sf().AbstractValueIterator,t.AbstractChainedBatch=KU().AbstractChainedBatch}),Pne=Kt((t,e)=>{e.exports=n;var r=zU();function n(s,a,o){if(typeof a!="number")throw new Error("second argument must be a Number");let i,c,u,d,l,f=!0,h;Array.isArray(s)?(i=[],u=c=s.length):(d=Object.keys(s),i={},u=c=d.length);function p(y){function S(){o&&o(y,i),o=null}f?r(S):S()}function m(y,S,v){if(i[y]=v,S&&(l=!0),--u===0||S)p(S);else if(!l&&h<c){let E;d?(E=d[h],h+=1,s[E](function(k,A){m(E,k,A)})):(E=h,h+=1,s[E](function(k,A){m(E,k,A)}))}}h=a,u?d?d.some(function(y,S){return s[y](function(v,E){m(y,v,E)}),S===a-1}):s.some(function(y,S){return y(function(v,E){m(S,v,E)}),S===a-1}):p(null),f=!1}}),FU=Kt((t,e)=>{"use strict";e.exports=function(r){let n=r.gte!==void 0?r.gte:r.gt!==void 0?r.gt:void 0,s=r.lte!==void 0?r.lte:r.lt!==void 0?r.lt:void 0,a=r.gte===void 0,o=r.lte===void 0;return n!==void 0&&s!==void 0?IDBKeyRange.bound(n,s,a,o):n!==void 0?IDBKeyRange.lowerBound(n,a):s!==void 0?IDBKeyRange.upperBound(s,o):null}}),GU=Kt((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)}}),xne=Kt(t=>{"use strict";var{AbstractIterator:e}=qU(),r=FU(),n=GU(),s=Symbol("cache"),a=Symbol("finished"),o=Symbol("options"),i=Symbol("currentOptions"),c=Symbol("position"),u=Symbol("location"),d=Symbol("first"),l={},f=class extends e{constructor(p,m,y){super(p,y),this[s]=[],this[a]=this.limit===0,this[o]=y,this[i]={...y},this[c]=void 0,this[u]=m,this[d]=!0}_nextv(p,m,y){if(this[d]=!1,this[a])return this.nextTick(y,null,[]);if(this[s].length>0)return p=Math.min(p,this[s].length),this.nextTick(y,null,this[s].splice(0,p));this[c]!==void 0&&(this[o].reverse?(this[i].lt=this[c],this[i].lte=void 0):(this[i].gt=this[c],this[i].gte=void 0));let S;try{S=r(this[i])}catch{return this[a]=!0,this.nextTick(y,null,[])}let v=this.db.db.transaction([this[u]],"readonly"),E=v.objectStore(this[u]),k=[];if(this[o].reverse){let A=!this[o].values&&E.openKeyCursor?"openKeyCursor":"openCursor";E[A](S,"prev").onsuccess=D=>{let B=D.target.result;if(B){let{key:j,value:F}=B;this[c]=j,k.push([this[o].keys&&j!==void 0?n(j):void 0,this[o].values&&F!==void 0?n(F):void 0]),k.length<p?B.continue():h(v)}else this[a]=!0}}else{let A,D,B=()=>{if(A===void 0||D===void 0)return;let j=Math.max(A.length,D.length);j===0||p===1/0?this[a]=!0:this[c]=A[j-1],k.length=j;for(let F=0;F<j;F++){let q=A[F],N=D[F];k[F]=[this[o].keys&&q!==void 0?n(q):void 0,this[o].values&&N!==void 0?n(N):void 0]}h(v)};this[o].keys||p<1/0?E.getAllKeys(S,p<1/0?p:void 0).onsuccess=j=>{A=j.target.result,B()}:(A=[],this.nextTick(B)),this[o].values?E.getAll(S,p<1/0?p:void 0).onsuccess=j=>{D=j.target.result,B()}:(D=[],this.nextTick(B))}v.onabort=()=>{y(v.error||new Error("aborted by user")),y=null},v.oncomplete=()=>{y(null,k),y=null}}_next(p){if(this[s].length>0){let[m,y]=this[s].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[d]&&(this[d]=!1,m=1),this._nextv(m,l,(y,S)=>{if(y)return p(y);this[s]=S,this._next(p)})}}_all(p,m){this[d]=!1;let y=this[s].splice(0,this[s].length),S=this.limit-this.count-y.length;if(S<=0)return this.nextTick(m,null,y);this._nextv(S,l,(v,E)=>{if(v)return m(v);y.length>0&&(E=y.concat(E)),m(null,E)})}_seek(p,m){this[d]=!0,this[s]=[],this[a]=!1,this[c]=void 0,this[i]={...this[o]};let y;try{y=r(this[o])}catch{this[a]=!0;return}y!==null&&!y.includes(p)?this[a]=!0:this[o].reverse?this[i].lte=p:this[i].gte=p}};t.Iterator=f;function h(p){typeof p.commit=="function"&&p.commit()}}),Sne=Kt((t,e)=>{"use strict";e.exports=function(r,n,s,a,o){if(a.limit===0)return r.nextTick(o);let i=r.db.transaction([n],"readwrite"),c=i.objectStore(n),u=0;i.oncomplete=function(){o()},i.onabort=function(){o(i.error||new Error("aborted by user"))};let d=c.openKeyCursor?"openKeyCursor":"openCursor",l=a.reverse?"prev":"next";c[d](s,l).onsuccess=function(f){let h=f.target.result;h&&(c.delete(h.key).onsuccess=function(){(a.limit<=0||++u<a.limit)&&h.continue()})}}}),Ene=Kt(t=>{"use strict";var{AbstractLevel:e}=qU(),r=_c(),n=Pne(),{fromCallback:s}=X1(),{Iterator:a}=xne(),o=GU(),i=Sne(),c=FU(),u="level-js-",d=Symbol("idb"),l=Symbol("namePrefix"),f=Symbol("location"),h=Symbol("version"),p=Symbol("store"),m=Symbol("onComplete"),y=Symbol("promise"),S=class extends e{constructor(v,E,k){if(typeof E=="function"||typeof k=="function")throw new r("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:A,version:D,...B}=E||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},B),typeof v!="string")throw new Error("constructor requires a location string argument");this[f]=v,this[l]=A??u,this[h]=parseInt(D||1,10),this[d]=null}get location(){return this[f]}get namePrefix(){return this[l]}get version(){return this[h]}get db(){return this[d]}get type(){return"browser-level"}_open(v,E){let k=indexedDB.open(this[l]+this[f],this[h]);k.onerror=function(){E(k.error||new Error("unknown error"))},k.onsuccess=()=>{this[d]=k.result,E()},k.onupgradeneeded=A=>{let D=A.target.result;D.objectStoreNames.contains(this[f])||D.createObjectStore(this[f])}}[p](v){return this[d].transaction([this[f]],v).objectStore(this[f])}[m](v,E){let k=v.transaction;k.onabort=function(){E(k.error||new Error("aborted by user"))},k.oncomplete=function(){E(null,v.result)}}_get(v,E,k){let A=this[p]("readonly"),D;try{D=A.get(v)}catch(B){return this.nextTick(k,B)}this[m](D,function(B,j){if(B)return k(B);if(j===void 0)return k(new r("Entry not found",{code:"LEVEL_NOT_FOUND"}));k(null,o(j))})}_getMany(v,E,k){let A=this[p]("readonly"),D=v.map(B=>j=>{let F;try{F=A.get(B)}catch(q){return j(q)}F.onsuccess=()=>{let q=F.result;j(null,q===void 0?q:o(q))},F.onerror=q=>{q.stopPropagation(),j(F.error)}});n(D,16,k)}_del(v,E,k){let A=this[p]("readwrite"),D;try{D=A.delete(v)}catch(B){return this.nextTick(k,B)}this[m](D,k)}_put(v,E,k,A){let D=this[p]("readwrite"),B;try{B=D.put(E,v)}catch(j){return this.nextTick(A,j)}this[m](B,A)}_iterator(v){return new a(this,this[f],v)}_batch(v,E,k){let A=this[p]("readwrite"),D=A.transaction,B=0,j;D.onabort=function(){k(j||D.error||new Error("aborted by user"))},D.oncomplete=function(){k()};function F(){let q=v[B++],N=q.key,W;try{W=q.type==="del"?A.delete(N):A.put(q.value,N)}catch(ee){j=ee,D.abort();return}B<v.length?W.onsuccess=F:typeof D.commit=="function"&&D.commit()}F()}_clear(v,E){let k,A;try{k=c(v)}catch{return this.nextTick(E)}if(v.limit>=0)return i(this,this[f],k,v,E);try{let D=this[p]("readwrite");A=k?D.delete(k):D.clear()}catch(D){return this.nextTick(E,D)}this[m](A,E)}_close(v){this[d].close(),this.nextTick(v)}};S.destroy=function(v,E,k){typeof E=="function"&&(k=E,E=u),k=s(k,y);let A=indexedDB.deleteDatabase(E+v);return A.onsuccess=function(){k()},A.onerror=function(D){k(D)},k[y]},t.BrowserLevel=S}),WU=Kt(t=>{t.Level=Ene().BrowserLevel}),_ne=Kt((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 J=arguments.length,ie=Array(J),oe=0;oe<J;oe++)ie[oe]=arguments[oe];if(ie.length>1){ie[0]=ie[0].slice(0,-1);for(var ye=ie.length-1,be=1;be<ye;++be)ie[be]=ie[be].slice(1,-1);return ie[ye]=ie[ye].slice(1),ie.join("")}else return ie[0]}function s(J){return"(?:"+J+")"}function a(J){return J===void 0?"undefined":J===null?"null":Object.prototype.toString.call(J).split(" ").pop().split("]").shift().toLowerCase()}function o(J){return J.toUpperCase()}function i(J){return J!=null?J instanceof Array?J:typeof J.length!="number"||J.split||J.setInterval||J.call?[J]:Array.prototype.slice.call(J):[]}function c(J,ie){var oe=J;if(ie)for(var ye in ie)oe[ye]=ie[ye];return oe}function u(J){var ie="[A-Za-z]",oe="[\\x0D]",ye="[0-9]",be="[\\x22]",ze=n(ye,"[A-Fa-f]"),At="[\\x0A]",dr="[\\x20]",Lr=s(s("%[EFef]"+ze+"%"+ze+ze+"%"+ze+ze)+"|"+s("%[89A-Fa-f]"+ze+"%"+ze+ze)+"|"+s("%"+ze+ze)),Kr="[\\:\\/\\?\\#\\[\\]\\@]",er="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",un=n(Kr,er),Cn=J?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",tn=J?"[\\uE000-\\uF8FF]":"[]",wr=n(ie,ye,"[\\-\\.\\_\\~]",Cn),hr=s(ie+n(ie,ye,"[\\+\\-\\.]")+"*"),Bs=s(s(Lr+"|"+n(wr,er,"[\\:]"))+"*"),nm=s(s("25[0-5]")+"|"+s("2[0-4]"+ye)+"|"+s("1"+ye+ye)+"|"+s("[1-9]"+ye)+"|"+ye),ki=s(s("25[0-5]")+"|"+s("2[0-4]"+ye)+"|"+s("1"+ye+ye)+"|"+s("0?[1-9]"+ye)+"|0?0?"+ye),Jo=s(ki+"\\."+ki+"\\."+ki+"\\."+ki),vr=s(ze+"{1,4}"),qi=s(s(vr+"\\:"+vr)+"|"+Jo),vo=s(s(vr+"\\:")+"{6}"+qi),kc=s("\\:\\:"+s(vr+"\\:")+"{5}"+qi),Zu=s(s(vr)+"?\\:\\:"+s(vr+"\\:")+"{4}"+qi),Da=s(s(s(vr+"\\:")+"{0,1}"+vr)+"?\\:\\:"+s(vr+"\\:")+"{3}"+qi),Ww=s(s(s(vr+"\\:")+"{0,2}"+vr)+"?\\:\\:"+s(vr+"\\:")+"{2}"+qi),Vw=s(s(s(vr+"\\:")+"{0,3}"+vr)+"?\\:\\:"+vr+"\\:"+qi),qf=s(s(s(vr+"\\:")+"{0,4}"+vr)+"?\\:\\:"+qi),Ff=s(s(s(vr+"\\:")+"{0,5}"+vr)+"?\\:\\:"+vr),Gf=s(s(s(vr+"\\:")+"{0,6}"+vr)+"?\\:\\:"),Yu=s([vo,kc,Zu,Da,Ww,Vw,qf,Ff,Gf].join("|")),Wf=s(s(wr+"|"+Lr)+"+"),Vf=s(Yu+"\\%25"+Wf),az=s(Yu+s("\\%25|\\%(?!"+ze+"{2})")+Wf),cz=s("[vV]"+ze+"+\\."+n(wr,er,"[\\:]")+"+"),dz=s("\\["+s(az+"|"+Yu+"|"+cz)+"\\]"),YA=s(s(Lr+"|"+n(wr,er))+"*"),sm=s(dz+"|"+Jo+"(?!"+YA+")|"+YA),im=s(ye+"*"),QA=s(s(Bs+"@")+"?"+sm+s("\\:"+im)+"?"),om=s(Lr+"|"+n(wr,er,"[\\:\\@]")),uz=s(om+"*"),XA=s(om+"+"),lz=s(s(Lr+"|"+n(wr,er,"[\\@]"))+"+"),Tc=s(s("\\/"+uz)+"*"),Hf=s("\\/"+s(XA+Tc)+"?"),CP=s(lz+Tc),Hw=s(XA+Tc),Jf="(?!"+om+")",hue=s(Tc+"|"+Hf+"|"+CP+"|"+Hw+"|"+Jf),Zf=s(s(om+"|"+n("[\\/\\?]",tn))+"*"),am=s(s(om+"|[\\/\\?]")+"*"),eR=s(s("\\/\\/"+QA+Tc)+"|"+Hf+"|"+Hw+"|"+Jf),fz=s(hr+"\\:"+eR+s("\\?"+Zf)+"?"+s("\\#"+am)+"?"),pz=s(s("\\/\\/"+QA+Tc)+"|"+Hf+"|"+CP+"|"+Jf),hz=s(pz+s("\\?"+Zf)+"?"+s("\\#"+am)+"?"),mue=s(fz+"|"+hz),yue=s(hr+"\\:"+eR+s("\\?"+Zf)+"?"),gue="^("+hr+")\\:"+s(s("\\/\\/("+s("("+Bs+")@")+"?("+sm+")"+s("\\:("+im+")")+"?)")+"?("+Tc+"|"+Hf+"|"+Hw+"|"+Jf+")")+s("\\?("+Zf+")")+"?"+s("\\#("+am+")")+"?$",wue="^(){0}"+s(s("\\/\\/("+s("("+Bs+")@")+"?("+sm+")"+s("\\:("+im+")")+"?)")+"?("+Tc+"|"+Hf+"|"+CP+"|"+Jf+")")+s("\\?("+Zf+")")+"?"+s("\\#("+am+")")+"?$",vue="^("+hr+")\\:"+s(s("\\/\\/("+s("("+Bs+")@")+"?("+sm+")"+s("\\:("+im+")")+"?)")+"?("+Tc+"|"+Hf+"|"+Hw+"|"+Jf+")")+s("\\?("+Zf+")")+"?$",bue="^"+s("\\#("+am+")")+"?$",Pue="^"+s("("+Bs+")@")+"?("+sm+")"+s("\\:("+im+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",ie,ye,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",wr,er),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",wr,er),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",wr,er),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",wr,er),"g"),NOT_QUERY:new RegExp(n("[^\\%]",wr,er,"[\\:\\@\\/\\?]",tn),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",wr,er,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",wr,er),"g"),UNRESERVED:new RegExp(wr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",wr,un),"g"),PCT_ENCODED:new RegExp(Lr,"g"),IPV4ADDRESS:new RegExp("^("+Jo+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Yu+")"+s(s("\\%25|\\%(?!"+ze+"{2})")+"("+Wf+")")+"?\\]?$")}}var d=u(!1),l=u(!0),f=function(){function J(ie,oe){var ye=[],be=!0,ze=!1,At=void 0;try{for(var dr=ie[Symbol.iterator](),Lr;!(be=(Lr=dr.next()).done)&&(ye.push(Lr.value),!(oe&&ye.length===oe));be=!0);}catch(Kr){ze=!0,At=Kr}finally{try{!be&&dr.return&&dr.return()}finally{if(ze)throw At}}return ye}return function(ie,oe){if(Array.isArray(ie))return ie;if(Symbol.iterator in Object(ie))return J(ie,oe);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),h=function(J){if(Array.isArray(J)){for(var ie=0,oe=Array(J.length);ie<J.length;ie++)oe[ie]=J[ie];return oe}else return Array.from(J)},p=2147483647,m=36,y=1,S=26,v=38,E=700,k=72,A=128,D="-",B=/^xn--/,j=/[^\0-\x7E]/,F=/[\x2E\u3002\uFF0E\uFF61]/g,q={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,W=Math.floor,ee=String.fromCharCode;function R(J){throw new RangeError(q[J])}function $(J,ie){for(var oe=[],ye=J.length;ye--;)oe[ye]=ie(J[ye]);return oe}function b(J,ie){var oe=J.split("@"),ye="";oe.length>1&&(ye=oe[0]+"@",J=oe[1]),J=J.replace(F,".");var be=J.split("."),ze=$(be,ie).join(".");return ye+ze}function x(J){for(var ie=[],oe=0,ye=J.length;oe<ye;){var be=J.charCodeAt(oe++);if(be>=55296&&be<=56319&&oe<ye){var ze=J.charCodeAt(oe++);(ze&64512)==56320?ie.push(((be&1023)<<10)+(ze&1023)+65536):(ie.push(be),oe--)}else ie.push(be)}return ie}var P=function(J){return String.fromCodePoint.apply(String,h(J))},_=function(J){return J-48<10?J-22:J-65<26?J-65:J-97<26?J-97:m},I=function(J,ie){return J+22+75*(J<26)-((ie!=0)<<5)},O=function(J,ie,oe){var ye=0;for(J=oe?W(J/E):J>>1,J+=W(J/ie);J>N*S>>1;ye+=m)J=W(J/N);return W(ye+(N+1)*J/(J+v))},z=function(J){var ie=[],oe=J.length,ye=0,be=A,ze=k,At=J.lastIndexOf(D);At<0&&(At=0);for(var dr=0;dr<At;++dr)J.charCodeAt(dr)>=128&&R("not-basic"),ie.push(J.charCodeAt(dr));for(var Lr=At>0?At+1:0;Lr<oe;){for(var Kr=ye,er=1,un=m;;un+=m){Lr>=oe&&R("invalid-input");var Cn=_(J.charCodeAt(Lr++));(Cn>=m||Cn>W((p-ye)/er))&&R("overflow"),ye+=Cn*er;var tn=un<=ze?y:un>=ze+S?S:un-ze;if(Cn<tn)break;var wr=m-tn;er>W(p/wr)&&R("overflow"),er*=wr}var hr=ie.length+1;ze=O(ye-Kr,hr,Kr==0),W(ye/hr)>p-be&&R("overflow"),be+=W(ye/hr),ye%=hr,ie.splice(ye++,0,be)}return String.fromCodePoint.apply(String,ie)},G=function(J){var ie=[];J=x(J);var oe=J.length,ye=A,be=0,ze=k,At=!0,dr=!1,Lr=void 0;try{for(var Kr=J[Symbol.iterator](),er;!(At=(er=Kr.next()).done);At=!0){var un=er.value;un<128&&ie.push(ee(un))}}catch(Vf){dr=!0,Lr=Vf}finally{try{!At&&Kr.return&&Kr.return()}finally{if(dr)throw Lr}}var Cn=ie.length,tn=Cn;for(Cn&&ie.push(D);tn<oe;){var wr=p,hr=!0,Bs=!1,nm=void 0;try{for(var ki=J[Symbol.iterator](),Jo;!(hr=(Jo=ki.next()).done);hr=!0){var vr=Jo.value;vr>=ye&&vr<wr&&(wr=vr)}}catch(Vf){Bs=!0,nm=Vf}finally{try{!hr&&ki.return&&ki.return()}finally{if(Bs)throw nm}}var qi=tn+1;wr-ye>W((p-be)/qi)&&R("overflow"),be+=(wr-ye)*qi,ye=wr;var vo=!0,kc=!1,Zu=void 0;try{for(var Da=J[Symbol.iterator](),Ww;!(vo=(Ww=Da.next()).done);vo=!0){var Vw=Ww.value;if(Vw<ye&&++be>p&&R("overflow"),Vw==ye){for(var qf=be,Ff=m;;Ff+=m){var Gf=Ff<=ze?y:Ff>=ze+S?S:Ff-ze;if(qf<Gf)break;var Yu=qf-Gf,Wf=m-Gf;ie.push(ee(I(Gf+Yu%Wf,0))),qf=W(Yu/Wf)}ie.push(ee(I(qf,0))),ze=O(be,qi,tn==Cn),be=0,++tn}}}catch(Vf){kc=!0,Zu=Vf}finally{try{!vo&&Da.return&&Da.return()}finally{if(kc)throw Zu}}++be,++ye}return ie.join("")},V=function(J){return b(J,function(ie){return B.test(ie)?z(ie.slice(4).toLowerCase()):ie})},H=function(J){return b(J,function(ie){return j.test(ie)?"xn--"+G(ie):ie})},Y={version:"2.1.0",ucs2:{decode:x,encode:P},decode:z,encode:G,toASCII:H,toUnicode:V},K={};function Q(J){var ie=J.charCodeAt(0),oe=void 0;return ie<16?oe="%0"+ie.toString(16).toUpperCase():ie<128?oe="%"+ie.toString(16).toUpperCase():ie<2048?oe="%"+(ie>>6|192).toString(16).toUpperCase()+"%"+(ie&63|128).toString(16).toUpperCase():oe="%"+(ie>>12|224).toString(16).toUpperCase()+"%"+(ie>>6&63|128).toString(16).toUpperCase()+"%"+(ie&63|128).toString(16).toUpperCase(),oe}function se(J){for(var ie="",oe=0,ye=J.length;oe<ye;){var be=parseInt(J.substr(oe+1,2),16);if(be<128)ie+=String.fromCharCode(be),oe+=3;else if(be>=194&&be<224){if(ye-oe>=6){var ze=parseInt(J.substr(oe+4,2),16);ie+=String.fromCharCode((be&31)<<6|ze&63)}else ie+=J.substr(oe,6);oe+=6}else if(be>=224){if(ye-oe>=9){var At=parseInt(J.substr(oe+4,2),16),dr=parseInt(J.substr(oe+7,2),16);ie+=String.fromCharCode((be&15)<<12|(At&63)<<6|dr&63)}else ie+=J.substr(oe,9);oe+=9}else ie+=J.substr(oe,3),oe+=3}return ie}function re(J,ie){function oe(ye){var be=se(ye);return be.match(ie.UNRESERVED)?be:ye}return J.scheme&&(J.scheme=String(J.scheme).replace(ie.PCT_ENCODED,oe).toLowerCase().replace(ie.NOT_SCHEME,"")),J.userinfo!==void 0&&(J.userinfo=String(J.userinfo).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_USERINFO,Q).replace(ie.PCT_ENCODED,o)),J.host!==void 0&&(J.host=String(J.host).replace(ie.PCT_ENCODED,oe).toLowerCase().replace(ie.NOT_HOST,Q).replace(ie.PCT_ENCODED,o)),J.path!==void 0&&(J.path=String(J.path).replace(ie.PCT_ENCODED,oe).replace(J.scheme?ie.NOT_PATH:ie.NOT_PATH_NOSCHEME,Q).replace(ie.PCT_ENCODED,o)),J.query!==void 0&&(J.query=String(J.query).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_QUERY,Q).replace(ie.PCT_ENCODED,o)),J.fragment!==void 0&&(J.fragment=String(J.fragment).replace(ie.PCT_ENCODED,oe).replace(ie.NOT_FRAGMENT,Q).replace(ie.PCT_ENCODED,o)),J}function Z(J){return J.replace(/^0*(.*)/,"$1")||"0"}function de(J,ie){var oe=J.match(ie.IPV4ADDRESS)||[],ye=f(oe,2),be=ye[1];return be?be.split(".").map(Z).join("."):J}function le(J,ie){var oe=J.match(ie.IPV6ADDRESS)||[],ye=f(oe,3),be=ye[1],ze=ye[2];if(be){for(var At=be.toLowerCase().split("::").reverse(),dr=f(At,2),Lr=dr[0],Kr=dr[1],er=Kr?Kr.split(":").map(Z):[],un=Lr.split(":").map(Z),Cn=ie.IPV4ADDRESS.test(un[un.length-1]),tn=Cn?7:8,wr=un.length-tn,hr=Array(tn),Bs=0;Bs<tn;++Bs)hr[Bs]=er[Bs]||un[wr+Bs]||"";Cn&&(hr[tn-1]=de(hr[tn-1],ie));var nm=hr.reduce(function(vo,kc,Zu){if(!kc||kc==="0"){var Da=vo[vo.length-1];Da&&Da.index+Da.length===Zu?Da.length++:vo.push({index:Zu,length:1})}return vo},[]),ki=nm.sort(function(vo,kc){return kc.length-vo.length})[0],Jo=void 0;if(ki&&ki.length>1){var vr=hr.slice(0,ki.index),qi=hr.slice(ki.index+ki.length);Jo=vr.join(":")+"::"+qi.join(":")}else Jo=hr.join(":");return ze&&(Jo+="%"+ze),Jo}else return J}var pe=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,ve="".match(/(){0}/)[1]===void 0;function ce(J){var ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe={},ye=ie.iri!==!1?l:d;ie.reference==="suffix"&&(J=(ie.scheme?ie.scheme+":":"")+"//"+J);var be=J.match(pe);if(be){ve?(oe.scheme=be[1],oe.userinfo=be[3],oe.host=be[4],oe.port=parseInt(be[5],10),oe.path=be[6]||"",oe.query=be[7],oe.fragment=be[8],isNaN(oe.port)&&(oe.port=be[5])):(oe.scheme=be[1]||void 0,oe.userinfo=J.indexOf("@")!==-1?be[3]:void 0,oe.host=J.indexOf("//")!==-1?be[4]:void 0,oe.port=parseInt(be[5],10),oe.path=be[6]||"",oe.query=J.indexOf("?")!==-1?be[7]:void 0,oe.fragment=J.indexOf("#")!==-1?be[8]:void 0,isNaN(oe.port)&&(oe.port=J.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?be[4]:void 0)),oe.host&&(oe.host=le(de(oe.host,ye),ye)),oe.scheme===void 0&&oe.userinfo===void 0&&oe.host===void 0&&oe.port===void 0&&!oe.path&&oe.query===void 0?oe.reference="same-document":oe.scheme===void 0?oe.reference="relative":oe.fragment===void 0?oe.reference="absolute":oe.reference="uri",ie.reference&&ie.reference!=="suffix"&&ie.reference!==oe.reference&&(oe.error=oe.error||"URI is not a "+ie.reference+" reference.");var ze=K[(ie.scheme||oe.scheme||"").toLowerCase()];if(!ie.unicodeSupport&&(!ze||!ze.unicodeSupport)){if(oe.host&&(ie.domainHost||ze&&ze.domainHost))try{oe.host=Y.toASCII(oe.host.replace(ye.PCT_ENCODED,se).toLowerCase())}catch(At){oe.error=oe.error||"Host's domain name can not be converted to ASCII via punycode: "+At}re(oe,d)}else re(oe,ye);ze&&ze.parse&&ze.parse(oe,ie)}else oe.error=oe.error||"URI can not be parsed.";return oe}function ge(J,ie){var oe=ie.iri!==!1?l:d,ye=[];return J.userinfo!==void 0&&(ye.push(J.userinfo),ye.push("@")),J.host!==void 0&&ye.push(le(de(String(J.host),oe),oe).replace(oe.IPV6ADDRESS,function(be,ze,At){return"["+ze+(At?"%25"+At:"")+"]"})),(typeof J.port=="number"||typeof J.port=="string")&&(ye.push(":"),ye.push(String(J.port))),ye.length?ye.join(""):void 0}var Me=/^\.\.?\//,Le=/^\/\.(\/|$)/,qe=/^\/\.\.(\/|$)/,Et=/^\/?(?:.|\n)*?(?=\/|$)/;function Se(J){for(var ie=[];J.length;)if(J.match(Me))J=J.replace(Me,"");else if(J.match(Le))J=J.replace(Le,"/");else if(J.match(qe))J=J.replace(qe,"/"),ie.pop();else if(J==="."||J==="..")J="";else{var oe=J.match(Et);if(oe){var ye=oe[0];J=J.slice(ye.length),ie.push(ye)}else throw new Error("Unexpected dot segment condition")}return ie.join("")}function et(J){var ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe=ie.iri?l:d,ye=[],be=K[(ie.scheme||J.scheme||"").toLowerCase()];if(be&&be.serialize&&be.serialize(J,ie),J.host&&!oe.IPV6ADDRESS.test(J.host)&&(ie.domainHost||be&&be.domainHost))try{J.host=ie.iri?Y.toUnicode(J.host):Y.toASCII(J.host.replace(oe.PCT_ENCODED,se).toLowerCase())}catch(dr){J.error=J.error||"Host's domain name can not be converted to "+(ie.iri?"Unicode":"ASCII")+" via punycode: "+dr}re(J,oe),ie.reference!=="suffix"&&J.scheme&&(ye.push(J.scheme),ye.push(":"));var ze=ge(J,ie);if(ze!==void 0&&(ie.reference!=="suffix"&&ye.push("//"),ye.push(ze),J.path&&J.path.charAt(0)!=="/"&&ye.push("/")),J.path!==void 0){var At=J.path;!ie.absolutePath&&(!be||!be.absolutePath)&&(At=Se(At)),ze===void 0&&(At=At.replace(/^\/\//,"/%2F")),ye.push(At)}return J.query!==void 0&&(ye.push("?"),ye.push(J.query)),J.fragment!==void 0&&(ye.push("#"),ye.push(J.fragment)),ye.join("")}function wt(J,ie){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},ye=arguments[3],be={};return ye||(J=ce(et(J,oe),oe),ie=ce(et(ie,oe),oe)),oe=oe||{},!oe.tolerant&&ie.scheme?(be.scheme=ie.scheme,be.userinfo=ie.userinfo,be.host=ie.host,be.port=ie.port,be.path=Se(ie.path||""),be.query=ie.query):(ie.userinfo!==void 0||ie.host!==void 0||ie.port!==void 0?(be.userinfo=ie.userinfo,be.host=ie.host,be.port=ie.port,be.path=Se(ie.path||""),be.query=ie.query):(ie.path?(ie.path.charAt(0)==="/"?be.path=Se(ie.path):((J.userinfo!==void 0||J.host!==void 0||J.port!==void 0)&&!J.path?be.path="/"+ie.path:J.path?be.path=J.path.slice(0,J.path.lastIndexOf("/")+1)+ie.path:be.path=ie.path,be.path=Se(be.path)),be.query=ie.query):(be.path=J.path,ie.query!==void 0?be.query=ie.query:be.query=J.query),be.userinfo=J.userinfo,be.host=J.host,be.port=J.port),be.scheme=J.scheme),be.fragment=ie.fragment,be}function xt(J,ie,oe){var ye=c({scheme:"null"},oe);return et(wt(ce(J,ye),ce(ie,ye),ye,!0),ye)}function $t(J,ie){return typeof J=="string"?J=et(ce(J,ie),ie):a(J)==="object"&&(J=ce(et(J,ie),ie)),J}function T(J,ie,oe){return typeof J=="string"?J=et(ce(J,oe),oe):a(J)==="object"&&(J=et(J,oe)),typeof ie=="string"?ie=et(ce(ie,oe),oe):a(ie)==="object"&&(ie=et(ie,oe)),J===ie}function M(J,ie){return J&&J.toString().replace(!ie||!ie.iri?d.ESCAPE:l.ESCAPE,Q)}function L(J,ie){return J&&J.toString().replace(!ie||!ie.iri?d.PCT_ENCODED:l.PCT_ENCODED,se)}var te={scheme:"http",domainHost:!0,parse:function(J,ie){return J.host||(J.error=J.error||"HTTP URIs must have a host."),J},serialize:function(J,ie){var oe=String(J.scheme).toLowerCase()==="https";return(J.port===(oe?443:80)||J.port==="")&&(J.port=void 0),J.path||(J.path="/"),J}},ae={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function he(J){return typeof J.secure=="boolean"?J.secure:String(J.scheme).toLowerCase()==="wss"}var xe={scheme:"ws",domainHost:!0,parse:function(J,ie){var oe=J;return oe.secure=he(oe),oe.resourceName=(oe.path||"/")+(oe.query?"?"+oe.query:""),oe.path=void 0,oe.query=void 0,oe},serialize:function(J,ie){if((J.port===(he(J)?443:80)||J.port==="")&&(J.port=void 0),typeof J.secure=="boolean"&&(J.scheme=J.secure?"wss":"ws",J.secure=void 0),J.resourceName){var oe=J.resourceName.split("?"),ye=f(oe,2),be=ye[0],ze=ye[1];J.path=be&&be!=="/"?be:void 0,J.query=ze,J.resourceName=void 0}return J.fragment=void 0,J}},Mt={scheme:"wss",domainHost:xe.domainHost,parse:xe.parse,serialize:xe.serialize},Bn={},$r=!0,pr="[A-Za-z0-9\\-\\.\\_\\~"+($r?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",sr="[0-9A-Fa-f]",Y9=s(s("%[EFef]"+sr+"%"+sr+sr+"%"+sr+sr)+"|"+s("%[89A-Fa-f]"+sr+"%"+sr+sr)+"|"+s("%"+sr+sr)),Q9="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",X9="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",ez=n(X9,'[\\"\\\\]'),tz="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",rz=new RegExp(pr,"g"),zf=new RegExp(Y9,"g"),nz=new RegExp(n("[^]",Q9,"[\\.]",'[\\"]',ez),"g"),VA=new RegExp(n("[^]",pr,tz),"g"),sz=VA;function DP(J){var ie=se(J);return ie.match(rz)?ie:J}var HA={scheme:"mailto",parse:function(J,ie){var oe=J,ye=oe.to=oe.path?oe.path.split(","):[];if(oe.path=void 0,oe.query){for(var be=!1,ze={},At=oe.query.split("&"),dr=0,Lr=At.length;dr<Lr;++dr){var Kr=At[dr].split("=");switch(Kr[0]){case"to":for(var er=Kr[1].split(","),un=0,Cn=er.length;un<Cn;++un)ye.push(er[un]);break;case"subject":oe.subject=L(Kr[1],ie);break;case"body":oe.body=L(Kr[1],ie);break;default:be=!0,ze[L(Kr[0],ie)]=L(Kr[1],ie);break}}be&&(oe.headers=ze)}oe.query=void 0;for(var tn=0,wr=ye.length;tn<wr;++tn){var hr=ye[tn].split("@");if(hr[0]=L(hr[0]),ie.unicodeSupport)hr[1]=L(hr[1],ie).toLowerCase();else try{hr[1]=Y.toASCII(L(hr[1],ie).toLowerCase())}catch(Bs){oe.error=oe.error||"Email address's domain name can not be converted to ASCII via punycode: "+Bs}ye[tn]=hr.join("@")}return oe},serialize:function(J,ie){var oe=J,ye=i(J.to);if(ye){for(var be=0,ze=ye.length;be<ze;++be){var At=String(ye[be]),dr=At.lastIndexOf("@"),Lr=At.slice(0,dr).replace(zf,DP).replace(zf,o).replace(nz,Q),Kr=At.slice(dr+1);try{Kr=ie.iri?Y.toUnicode(Kr):Y.toASCII(L(Kr,ie).toLowerCase())}catch(tn){oe.error=oe.error||"Email address's domain name can not be converted to "+(ie.iri?"Unicode":"ASCII")+" via punycode: "+tn}ye[be]=Lr+"@"+Kr}oe.path=ye.join(",")}var er=J.headers=J.headers||{};J.subject&&(er.subject=J.subject),J.body&&(er.body=J.body);var un=[];for(var Cn in er)er[Cn]!==Bn[Cn]&&un.push(Cn.replace(zf,DP).replace(zf,o).replace(VA,Q)+"="+er[Cn].replace(zf,DP).replace(zf,o).replace(sz,Q));return un.length&&(oe.query=un.join("&")),oe}},iz=/^([^\:]+)\:(.*)/,JA={scheme:"urn",parse:function(J,ie){var oe=J.path&&J.path.match(iz),ye=J;if(oe){var be=ie.scheme||ye.scheme||"urn",ze=oe[1].toLowerCase(),At=oe[2],dr=be+":"+(ie.nid||ze),Lr=K[dr];ye.nid=ze,ye.nss=At,ye.path=void 0,Lr&&(ye=Lr.parse(ye,ie))}else ye.error=ye.error||"URN can not be parsed.";return ye},serialize:function(J,ie){var oe=ie.scheme||J.scheme||"urn",ye=J.nid,be=oe+":"+(ie.nid||ye),ze=K[be];ze&&(J=ze.serialize(J,ie));var At=J,dr=J.nss;return At.path=(ye||ie.nid)+":"+dr,At}},oz=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,ZA={scheme:"urn:uuid",parse:function(J,ie){var oe=J;return oe.uuid=oe.nss,oe.nss=void 0,!ie.tolerant&&(!oe.uuid||!oe.uuid.match(oz))&&(oe.error=oe.error||"UUID is not valid."),oe},serialize:function(J,ie){var oe=J;return oe.nss=(J.uuid||"").toLowerCase(),oe}};K[te.scheme]=te,K[ae.scheme]=ae,K[xe.scheme]=xe,K[Mt.scheme]=Mt,K[HA.scheme]=HA,K[JA.scheme]=JA,K[ZA.scheme]=ZA,r.SCHEMES=K,r.pctEncChar=Q,r.pctDecChars=se,r.parse=ce,r.removeDotSegments=Se,r.serialize=et,r.resolveComponents=wt,r.resolve=xt,r.normalize=$t,r.equal=T,r.escapeComponent=M,r.unescapeComponent=L,Object.defineProperty(r,"__esModule",{value:!0})})}),kne=Kt((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((s,a,o)=>`${s}${o===0?"":","}${r(a===void 0||typeof a=="symbol"?null:a)}`,"")}]`:`{${Object.keys(n).sort().reduce((s,a)=>{if(n[a]===void 0||typeof n[a]=="symbol")return s;let o=s.length===0?"":",";return`${s}${o}${r(a)}:${r(n[a])}`},"")}}`}}),VU=Kt((t,e)=>{var r=1e3,n=r*60,s=n*60,a=s*24,o=a*7,i=a*365.25;e.exports=function(f,h){h=h||{};var p=typeof f;if(p==="string"&&f.length>0)return c(f);if(p==="number"&&isFinite(f))return h.long?d(f):u(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function c(f){if(f=String(f),!(f.length>100)){var 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*i;case"weeks":case"week":case"w":return p*o;case"days":case"day":case"d":return p*a;case"hours":case"hour":case"hrs":case"hr":case"h":return p*s;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 u(f){var h=Math.abs(f);return h>=a?Math.round(f/a)+"d":h>=s?Math.round(f/s)+"h":h>=n?Math.round(f/n)+"m":h>=r?Math.round(f/r)+"s":f+"ms"}function d(f){var h=Math.abs(f);return h>=a?l(f,h,a,"day"):h>=s?l(f,h,s,"hour"):h>=n?l(f,h,n,"minute"):h>=r?l(f,h,r,"second"):f+" ms"}function l(f,h,p,m){var y=h>=p*1.5;return Math.round(f/p)+" "+m+(y?"s":"")}}),eP=(t=>(t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation",t))(eP||{}),ds={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},Ds=class HU{constructor({method:e,id:r,path:n,query:s,fragment:a,params:o}){this.uri=`did:${e}:${r}`,this.method=e,this.id=r,this.path=n,this.query=s,this.fragment=a,this.params=o}static parse(e){if(!e||e.length>2048)return null;let r=HU.DID_URI_PATTERN.exec(e);if(!r||!r.groups)return null;let{method:n,id:s,path:a,query:o,fragment:i}=r.groups,c={uri:`did:${n}:${s}`,method:n,id:s};if(a&&(c.path=a),o&&(c.query=o.slice(1)),i&&(c.fragment=i.slice(1)),o){let u={},d=o.slice(1).split("&");for(let l of d){let[f,h]=l.split("=");u[f]=h}c.params=u}return c}};Ds.METHOD_PATTERN="([a-z0-9]+)",Ds.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",Ds.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${Ds.PCT_ENCODED_PATTERN})`,Ds.METHOD_ID_PATTERN=`((?:${Ds.ID_CHAR_PATTERN}*:)*(${Ds.ID_CHAR_PATTERN}+))`,Ds.PATH_PATTERN="(/[^#?]*)?",Ds.QUERY_PATTERN="([?][^#]*)?",Ds.FRAGMENT_PATTERN="(#.*)?",Ds.DID_URI_PATTERN=new RegExp("^did:(?<method>"+Ds.METHOD_PATTERN+"):(?<id>"+Ds.METHOD_ID_PATTERN+")(?<path>"+Ds.PATH_PATTERN+")(?<query>"+Ds.QUERY_PATTERN+")(?<fragment>"+Ds.FRAGMENT_PATTERN+")$");var us=Ds,Ze=class JU 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,JU)}},Tne=(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))(Tne||{}),Go=class ZU extends Error{constructor(e,r){super(r),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ZU)}},Li;(function(t){t.AlgorithmNotSupported="algorithmNotSupported",t.EncodingError="encodingError",t.InvalidCoseSign1="invalidCoseSign1",t.InvalidEat="invalidEat",t.InvalidJwe="invalidJwe",t.InvalidJwk="invalidJwk",t.OperationNotSupported="operationNotSupported"})(Li||(Li={}));var Ine=Rf(one(),1);function Ane(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 s=0;s<t.length;s++){var a=t.charAt(s),o=a.charCodeAt(0);if(r[o]!==255)throw new TypeError(a+" is ambiguous");r[o]=s}var i=t.length,c=t.charAt(0),u=Math.log(i)/Math.log(256),d=Math.log(256)/Math.log(i);function l(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,S=0,v=p.length;S!==v&&p[S]===0;)S++,m++;for(var E=(v-S)*d+1>>>0,k=new Uint8Array(E);S!==v;){for(var A=p[S],D=0,B=E-1;(A!==0||D<y)&&B!==-1;B--,D++)A+=256*k[B]>>>0,k[B]=A%i>>>0,A=A/i>>>0;if(A!==0)throw new Error("Non-zero carry");y=D,S++}for(var j=E-y;j!==E&&k[j]===0;)j++;for(var F=c.repeat(m);j<E;++j)F+=t.charAt(k[j]);return F}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,S=0;p[m]===c;)y++,m++;for(var v=(p.length-m)*u+1>>>0,E=new Uint8Array(v);p[m];){var k=r[p.charCodeAt(m)];if(k===255)return;for(var A=0,D=v-1;(k!==0||A<S)&&D!==-1;D--,A++)k+=i*E[D]>>>0,E[D]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");S=A,m++}if(p[m]!==" "){for(var B=v-S;B!==v&&E[B]===0;)B++;for(var j=new Uint8Array(y+(v-B)),F=y;B!==v;)j[F++]=E[B++];return j}}}function h(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:f,decode:h}}var Rne=Ane,Dne=Rne,Cne=Dne,Bje=new Uint8Array(0),jne=(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},LI=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")},$ne=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")}},Mne=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 YU(this,t)}},One=class{constructor(t){this.decoders=t}or(t){return YU(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`)}},YU=(t,e)=>new One({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Bne=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new $ne(t,e,r),this.decoder=new Mne(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},QU=({name:t,prefix:e,encode:r,decode:n})=>new Bne(t,e,r,n),XU=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:s}=Cne(r,e);return QU({prefix:t,name:e,encode:n,decode:a=>LI(s(a))})},Nne=(t,e,r,n)=>{let s={};for(let d=0;d<e.length;++d)s[e[d]]=d;let a=t.length;for(;t[a-1]==="=";)--a;let o=new Uint8Array(a*r/8|0),i=0,c=0,u=0;for(let d=0;d<a;++d){let l=s[t[d]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|l,i+=r,i>=8&&(i-=8,o[u++]=255&c>>i)}if(i>=r||255&c<<8-i)throw new SyntaxError("Unexpected end of data");return o},Une=(t,e,r)=>{let n=e[e.length-1]==="=",s=(1<<r)-1,a="",o=0,i=0;for(let c=0;c<t.length;++c)for(i=i<<8|t[c],o+=8;o>r;)o-=r,a+=e[s&i>>o];if(o&&(a+=e[s&i<<r-o]),n)for(;a.length*r&7;)a+="=";return a},yo=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>QU({prefix:e,name:t,encode(s){return Une(s,n,r)},decode(s){return Nne(s,n,r,t)}}),P1=yo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Nje=yo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Uje=yo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Lje=yo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Kje=yo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zje=yo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),qje=yo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Fje=yo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xN=yo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),qo=XU({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Gje=XU({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Wje=yo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Vje=yo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hd=yo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hje=yo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Lne(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function Kne(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function mI(t){let e=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[r,n]=e;return n}var Vg=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},SN=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(o){return new Promise(function(i,c){o=t[a](o),s(i,c,o.done,o.value)})}}function s(a,o,i,c){Promise.resolve(c).then(function(u){a({value:u,done:i})},o)}},p1=new TextEncoder,yf=new TextDecoder,Qe=class Ni{constructor(e,r){this.data=e,this.format=r}static arrayBuffer(e){return new Ni(e,"ArrayBuffer")}static asyncIterable(e){if(!Kne(e))throw new TypeError("Input must be of type AsyncIterable.");return new Ni(e,"AsyncIterable")}static base32Z(e){return new Ni(e,"Base32Z")}static base58Btc(e){return new Ni(e,"Base58Btc")}static base64Url(e){return new Ni(e,"Base64Url")}static bufferSource(e){return new Ni(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 Ni(e,"Hex")}static multibase(e){return new Ni(e,"Multibase")}static object(e){return new Ni(e,"Object")}static string(e){return new Ni(e,"String")}static uint8Array(e){return new Ni(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return qo.baseDecode(this.data).buffer;case"Base64Url":return hd.baseDecode(this.data).buffer;case"BufferSource":{if(mI(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return Lne(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 Vg(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 xN.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 qo.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return qo.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 hd.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return hd.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=p1.encode(e);return hd.baseEncode(r)}case"String":{let e=p1.encode(this.data);return hd.baseEncode(e)}case"Uint8Array":return hd.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return Vg(this,void 0,void 0,function*(){var e,r,n,s;switch(this.format){case"AsyncIterable":{let c=[];try{for(var a=!0,o=SN(this.data),i;i=yield o.next(),e=i.done,!e;a=!0){s=i.value,a=!1;let u=s;c.push(u)}}catch(u){r={error:u}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}return new Blob(c)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(r,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let r=this.toUint8Array();return Ni.uint8Array(r).toHex()}case"Base64Url":{let r=this.toUint8Array();return Ni.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=hd.baseDecode(this.data),r=yf.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=yf.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return Vg(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 yf.decode(this.data);case"Base64Url":{let e=hd.baseDecode(this.data);return yf.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return yf.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return Vg(this,void 0,void 0,function*(){var e,r,n,s;switch(this.format){case"AsyncIterable":{let c="";try{for(var a=!0,o=SN(this.data),i;i=yield o.next(),e=i.done,!e;a=!0){s=i.value,a=!1;let u=s;typeof u=="string"?c+=u:c+=yf.decode(u,{stream:!0})}}catch(u){r={error:u}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}return c+=yf.decode(void 0,{stream:!1}),c}default:throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`)}})}toUint8Array(){switch(this.format){case"ArrayBuffer":return new Uint8Array(this.data);case"Base32Z":return xN.baseDecode(this.data);case"Base58Btc":return qo.baseDecode(this.data);case"Base64Url":return hd.baseDecode(this.data);case"BufferSource":{let e=mI(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 p1.encode(e)}case"String":return p1.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return Vg(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.`)}})}},mw;(function(t){t.Debug="debug",t.Silent="silent"})(mw||(mw={}));var zne=class{constructor(){this.logLevel=mw.Silent}setLogLevel(t){this.logLevel=t}log(t){this.info(t)}info(t){this.logLevel!==mw.Silent&&console.info(t)}error(t){this.logLevel!==mw.Silent&&console.error(t)}},qne=new zne;typeof window<"u"&&(window.enboxLogger=qne);var ew={};BI(ew,{decode:()=>z1,encodeTo:()=>gw,encodingLength:()=>ww});var Fne=eL,EN=128,Gne=127,Wne=~Gne,Vne=Math.pow(2,31);function eL(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Vne;)e[r++]=t&255|EN,t/=128;for(;t&Wne;)e[r++]=t&255|EN,t>>>=7;return e[r]=t|0,eL.bytes=r-n+1,e}var Hne=yI,Jne=128,_N=127;function yI(t,n){var r=0,n=n||0,s=0,a=n,o,i=t.length;do{if(a>=i)throw yI.bytes=0,new RangeError("Could not decode varint");o=t[a++],r+=s<28?(o&_N)<<s:(o&_N)*Math.pow(2,s),s+=7}while(o>=Jne);return yI.bytes=a-n,r}var Zne=Math.pow(2,7),Yne=Math.pow(2,14),Qne=Math.pow(2,21),Xne=Math.pow(2,28),ese=Math.pow(2,35),tse=Math.pow(2,42),rse=Math.pow(2,49),nse=Math.pow(2,56),sse=Math.pow(2,63),ise=function(t){return t<Zne?1:t<Yne?2:t<Qne?3:t<Xne?4:t<ese?5:t<tse?6:t<rse?7:t<nse?8:t<sse?9:10},ose={encode:Fne,decode:Hne,encodingLength:ise},ase=ose,K1=ase,z1=(t,e=0)=>[K1.decode(t,e),K1.decode.bytes],gw=(t,e,r=0)=>(K1.encode(t,e,r),e),ww=t=>K1.encodingLength(t),cse=(t,e)=>{let r=e.byteLength,n=ww(t),s=n+ww(r),a=new Uint8Array(s+r);return gw(t,a,0),gw(r,a,n),a.set(e,s),new KI(t,r,e,a)},dse=t=>{let e=LI(t),[r,n]=z1(e),[s,a]=z1(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==s)throw new Error("Incorrect length");return new KI(r,s,o,e)},use=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&jne(t.bytes,r.bytes)}},KI=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},kN=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return fse(r,gI(t),e||qo.encoder);default:return pse(r,gI(t),e||P1.encoder)}},TN=new WeakMap,gI=t=>{let e=TN.get(t);if(e==null){let r=new Map;return TN.set(t,r),r}return e},Jje=class Qs{constructor(e,r,n,s){this.code=r,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==Hg)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==hse)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Qs.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=cse(e,r);return Qs.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 Qs.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&use(e.multihash,n.multihash)}toString(e){return kN(this,e)}toJSON(){return{"/":kN(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 Qs)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:s,multihash:a,bytes:o}=r;return new Qs(n,s,a,o||IN(n,s,a.bytes))}else if(r[mse]===!0){let{version:n,multihash:s,code:a}=r,o=dse(s);return Qs.create(n,a,o)}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!==Hg)throw new Error(`Version 0 CID must use dag-pb (code: ${Hg}) block encoding`);return new Qs(e,r,n,n.bytes)}case 1:{let s=IN(e,r,n.bytes);return new Qs(e,r,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return Qs.create(0,Hg,e)}static createV1(e,r){return Qs.create(1,e,r)}static decode(e){let[r,n]=Qs.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=Qs.inspectBytes(e),n=r.size-r.multihashSize,s=LI(e.subarray(n,n+r.multihashSize));if(s.byteLength!==r.multihashSize)throw new Error("Incorrect length");let a=s.subarray(r.multihashSize-r.digestSize),o=new KI(r.multihashCode,r.digestSize,a,s);return[r.version===0?Qs.createV0(o):Qs.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[l,f]=z1(e.subarray(r));return r+=f,l},s=n(),a=Hg;if(s===18?(s=0,r=0):a=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=r,i=n(),c=n(),u=r+c,d=u-o;return{version:s,codec:a,multihashCode:i,digestSize:c,multihashSize:d,size:u}}static parse(e,r){let[n,s]=lse(e,r),a=Qs.decode(s);if(a.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return gI(a).set(n,e),a}},lse=(t,e)=>{switch(t[0]){case"Q":{let r=e||qo;return[qo.prefix,r.decode(`${qo.prefix}${t}`)]}case qo.prefix:{let r=e||qo;return[qo.prefix,r.decode(t)]}case P1.prefix:{let r=e||P1;return[P1.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)]}}},fse=(t,e,r)=>{let{prefix:n}=r;if(n!==qo.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let s=e.get(n);if(s==null){let a=r.encode(t).slice(1);return e.set(n,a),a}else return s},pse=(t,e,r)=>{let{prefix:n}=r,s=e.get(n);if(s==null){let a=r.encode(t);return e.set(n,a),a}else return s},Hg=112,hse=18,IN=(t,e,r)=>{let n=ww(t),s=n+ww(e),a=new Uint8Array(s+r.byteLength);return gw(t,a,0),gw(e,a,n),a.set(r,s),a},mse=Symbol.for("@ipld/js-cid/CID"),Vo=class Uu{static addPrefix(e){var r;let{code:n,data:s,name:a}=e;if(!(a?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=Uu.codeToName.has(n)?n:Uu.nameToCode.get(a),n===void 0)throw new Error(`Unsupported multicodec: ${(r=e.name)!==null&&r!==void 0?r:e.code}`);let o=ew.encodingLength(n),i=new Uint8Array(o+s.byteLength);return i.set(s,o),ew.encodeTo(n,i),i}static getCodeFromData(e){let{prefixedData:r}=e,[n,s]=ew.decode(r);return n}static getCodeFromName(e){let{name:r}=e,n=Uu.nameToCode.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static getNameFromCode(e){let{code:r}=e,n=Uu.codeToName.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static registerCodec(e){Uu.codeToName.set(e.code,e.name),Uu.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:r}=e,[n,s]=ew.decode(r),a=Uu.codeToName.get(n);if(a===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:r.slice(s),name:a}}};Vo.codeToName=new Map;Vo.nameToCode=new Map;Vo.registerCodec({code:237,name:"ed25519-pub"});Vo.registerCodec({code:4864,name:"ed25519-priv"});Vo.registerCodec({code:236,name:"x25519-pub"});Vo.registerCodec({code:4866,name:"x25519-priv"});Vo.registerCodec({code:231,name:"secp256k1-pub"});Vo.registerCodec({code:4865,name:"secp256k1-priv"});function tL(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&tL(t[e])})}var Zje=Rf(WU(),1),Au=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},yse=class{constructor(){this.store=new Map}clear(){return Au(this,void 0,void 0,function*(){this.store.clear()})}open(){return Au(this,void 0,void 0,function*(){})}close(){return Au(this,void 0,void 0,function*(){})}delete(t){return Au(this,void 0,void 0,function*(){return this.store.delete(t)})}get(t){return Au(this,void 0,void 0,function*(){return this.store.get(t)})}has(t){return Au(this,void 0,void 0,function*(){return this.store.has(t)})}list(){return Au(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(t,e){return Au(this,void 0,void 0,function*(){this.store.set(t,e)})}},tP=class{},rL={};BI(rL,{bitGet:()=>Sse,bitLen:()=>xse,bitMask:()=>qI,bitSet:()=>Ese,bytesToHex:()=>Tf,bytesToNumberBE:()=>Ef,bytesToNumberLE:()=>Fu,concatBytes:()=>If,createHmacDrbg:()=>iL,ensureBytes:()=>Rn,equalBytes:()=>bse,hexToBytes:()=>qh,hexToNumber:()=>zI,isBytes:()=>xc,numberToBytesBE:()=>Sc,numberToBytesLE:()=>Fh,numberToHexUnpadded:()=>sL,numberToVarBytesBE:()=>vse,utf8ToBytes:()=>Pse,validateObject:()=>Df});var nL=BigInt(0),rP=BigInt(1),gse=BigInt(2);function xc(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var wse=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Tf(t){if(!xc(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=wse[t[r]];return e}function sL(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function zI(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var md={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function AN(t){if(t>=md._0&&t<=md._9)return t-md._0;if(t>=md._A&&t<=md._F)return t-(md._A-10);if(t>=md._a&&t<=md._f)return t-(md._a-10)}function qh(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 s=0,a=0;s<r;s++,a+=2){let o=AN(t.charCodeAt(a)),i=AN(t.charCodeAt(a+1));if(o===void 0||i===void 0){let c=t[a]+t[a+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+a)}n[s]=o*16+i}return n}function Ef(t){return zI(Tf(t))}function Fu(t){if(!xc(t))throw new Error("Uint8Array expected");return zI(Tf(Uint8Array.from(t).reverse()))}function Sc(t,e){return qh(t.toString(16).padStart(e*2,"0"))}function Fh(t,e){return Sc(t,e).reverse()}function vse(t){return qh(sL(t))}function Rn(t,e,r){let n;if(typeof e=="string")try{n=qh(e)}catch(a){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${a}`)}else if(xc(e))n=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);let s=n.length;if(typeof r=="number"&&s!==r)throw new Error(`${t} expected ${r} bytes, got ${s}`);return n}function If(...t){let e=0;for(let s=0;s<t.length;s++){let a=t[s];if(!xc(a))throw new Error("Uint8Array expected");e+=a.length}let r=new Uint8Array(e),n=0;for(let s=0;s<t.length;s++){let a=t[s];r.set(a,n),n+=a.length}return r}function bse(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 Pse(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function xse(t){let e;for(e=0;t>nL;t>>=rP,e+=1);return e}function Sse(t,e){return t>>BigInt(e)&rP}var Ese=(t,e,r)=>t|(r?rP:nL)<<BigInt(e),qI=t=>(gse<<BigInt(t-1))-rP,iI=t=>new Uint8Array(t),RN=t=>Uint8Array.from(t);function iL(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=iI(t),s=iI(t),a=0,o=()=>{n.fill(1),s.fill(0),a=0},i=(...d)=>r(s,n,...d),c=(d=iI())=>{s=i(RN([0]),d),n=i(),d.length!==0&&(s=i(RN([1]),d),n=i())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,l=[];for(;d<e;){n=i();let f=n.slice();l.push(f),d+=n.length}return If(...l)};return(d,l)=>{o(),c(d);let f;for(;!(f=l(u()));)c();return o(),f}}var _se={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"||xc(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)};function Df(t,e,r={}){let n=(s,a,o)=>{let i=_se[a];if(typeof i!="function")throw new Error(`Invalid validator "${a}", expected function`);let c=t[s];if(!(o&&c===void 0)&&!i(c,t))throw new Error(`Invalid param ${String(s)}=${c} (${typeof c}), expected ${a}`)};for(let[s,a]of Object.entries(e))n(s,a,!1);for(let[s,a]of Object.entries(r))n(s,a,!0);return t}function DN(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function kse(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function oL(t,...e){if(!kse(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 Tse(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");DN(t.outputLen),DN(t.blockLen)}function q1(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 Ise(t,e){oL(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var oI=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function aL(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var aI=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),hc=(t,e)=>t<<32-e|t>>>e,Ase=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ase)throw new Error("Non little-endian hardware is not supported");function cL(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function FI(t){if(typeof t=="string"&&(t=cL(t)),!aL(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function dL(...t){let e=0;for(let n=0;n<t.length;n++){let s=t[n];if(!aL(s))throw new Error("Uint8Array expected");e+=s.length}let r=new Uint8Array(e);for(let n=0,s=0;n<t.length;n++){let a=t[n];r.set(a,s),s+=a.length}return r}var uL=class{clone(){return this._cloneInto()}},Yje={}.toString;function lL(t){let e=n=>t().update(FI(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function GI(t=32){if(oI&&typeof oI.getRandomValues=="function")return oI.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Rse(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let s=BigInt(32),a=BigInt(4294967295),o=Number(r>>s&a),i=Number(r&a),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,i,n)}var fL=class extends uL{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=aI(this.buffer)}update(t){q1(this);let{view:e,buffer:r,blockLen:n}=this;t=FI(t);let s=t.length;for(let a=0;a<s;){let o=Math.min(n-this.pos,s-a);if(o===n){let i=aI(t);for(;n<=s-a;a+=n)this.process(i,a);continue}r.set(t.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){q1(this),Ise(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:n,isLE:s}=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 d=a;d<n;d++)e[d]=0;Rse(r,n-8,BigInt(this.length*8),s),this.process(r,0);let o=aI(t),i=this.outputLen;if(i%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=i/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,u[d],s)}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:s,destroyed:a,pos:o}=this;return t.length=n,t.pos=o,t.finished=s,t.destroyed=a,n%e&&t.buffer.set(r),t}},Dse=(t,e,r)=>t&e^~t&r,Cse=(t,e,r)=>t&e^t&r^e&r,jse=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]),Ru=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Du=new Uint32Array(64),$se=class extends fL{constructor(){super(64,32,8,!1),this.A=Ru[0]|0,this.B=Ru[1]|0,this.C=Ru[2]|0,this.D=Ru[3]|0,this.E=Ru[4]|0,this.F=Ru[5]|0,this.G=Ru[6]|0,this.H=Ru[7]|0}get(){let{A:t,B:e,C:r,D:n,E:s,F:a,G:o,H:i}=this;return[t,e,r,n,s,a,o,i]}set(t,e,r,n,s,a,o,i){this.A=t|0,this.B=e|0,this.C=r|0,this.D=n|0,this.E=s|0,this.F=a|0,this.G=o|0,this.H=i|0}process(t,e){for(let d=0;d<16;d++,e+=4)Du[d]=t.getUint32(e,!1);for(let d=16;d<64;d++){let l=Du[d-15],f=Du[d-2],h=hc(l,7)^hc(l,18)^l>>>3,p=hc(f,17)^hc(f,19)^f>>>10;Du[d]=p+Du[d-7]+h+Du[d-16]|0}let{A:r,B:n,C:s,D:a,E:o,F:i,G:c,H:u}=this;for(let d=0;d<64;d++){let l=hc(o,6)^hc(o,11)^hc(o,25),f=u+l+Dse(o,i,c)+jse[d]+Du[d]|0,h=(hc(r,2)^hc(r,13)^hc(r,22))+Cse(r,n,s)|0;u=c,c=i,i=o,o=a+f|0,a=s,s=n,n=r,r=f+h|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,i=i+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,s,a,o,i,c,u)}roundClean(){Du.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},pL=lL(()=>new $se),Jn=BigInt(0),en=BigInt(1),vf=BigInt(2),Mse=BigInt(3),wI=BigInt(4),CN=BigInt(5),jN=BigInt(8),Qje=BigInt(9),Ose=BigInt(16);function Ur(t,e){let r=t%e;return r>=Jn?r:e+r}function hL(t,e,r){if(r<=Jn||e<Jn)throw new Error("Expected power/modulo > 0");if(r===en)return Jn;let n=en;for(;e>Jn;)e&en&&(n=n*t%r),t=t*t%r,e>>=en;return n}function an(t,e,r){let n=t;for(;e-- >Jn;)n*=n,n%=r;return n}function vI(t,e){if(t===Jn||e<=Jn)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Ur(t,e),n=e,s=Jn,a=en,o=en,i=Jn;for(;r!==Jn;){let c=n/r,u=n%r,d=s-o*c,l=a-i*c;n=r,r=u,s=o,a=i,o=d,i=l}if(n!==en)throw new Error("invert: does not exist");return Ur(s,e)}function Bse(t){let e=(t-en)/vf,r,n,s;for(r=t-en,n=0;r%vf===Jn;r/=vf,n++);for(s=vf;s<t&&hL(s,e,t)!==t-en;s++);if(n===1){let o=(t+en)/wI;return function(i,c){let u=i.pow(c,o);if(!i.eql(i.sqr(u),c))throw new Error("Cannot find square root");return u}}let a=(r+en)/vf;return function(o,i){if(o.pow(i,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=n,u=o.pow(o.mul(o.ONE,s),r),d=o.pow(i,a),l=o.pow(i,r);for(;!o.eql(l,o.ONE);){if(o.eql(l,o.ZERO))return o.ZERO;let f=1;for(let p=o.sqr(l);f<c&&!o.eql(p,o.ONE);f++)p=o.sqr(p);let h=o.pow(u,en<<BigInt(c-f-1));u=o.sqr(h),d=o.mul(d,h),l=o.mul(l,u),c=f}return d}}function Nse(t){if(t%wI===Mse){let e=(t+en)/wI;return function(r,n){let s=r.pow(n,e);if(!r.eql(r.sqr(s),n))throw new Error("Cannot find square root");return s}}if(t%jN===CN){let e=(t-CN)/jN;return function(r,n){let s=r.mul(n,vf),a=r.pow(s,e),o=r.mul(n,a),i=r.mul(r.mul(o,vf),a),c=r.mul(o,r.sub(i,r.ONE));if(!r.eql(r.sqr(c),n))throw new Error("Cannot find square root");return c}}return t%Ose,Bse(t)}var Use=(t,e)=>(Ur(t,e)&en)===en,Lse=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Kse(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Lse.reduce((n,s)=>(n[s]="function",n),e);return Df(t,r)}function zse(t,e,r){if(r<Jn)throw new Error("Expected power > 0");if(r===Jn)return t.ONE;if(r===en)return e;let n=t.ONE,s=e;for(;r>Jn;)r&en&&(n=t.mul(n,s)),s=t.sqr(s),r>>=en;return n}function qse(t,e){let r=new Array(e.length),n=e.reduce((a,o,i)=>t.is0(o)?a:(r[i]=a,t.mul(a,o)),t.ONE),s=t.inv(n);return e.reduceRight((a,o,i)=>t.is0(o)?a:(r[i]=t.mul(a,r[i]),t.mul(a,o)),s),r}function mL(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function WI(t,e,r=!1,n={}){if(t<=Jn)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:s,nByteLength:a}=mL(t,e);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");let o=Nse(t),i=Object.freeze({ORDER:t,BITS:s,BYTES:a,MASK:qI(s),ZERO:Jn,ONE:en,create:c=>Ur(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Jn<=c&&c<t},is0:c=>c===Jn,isOdd:c=>(c&en)===en,neg:c=>Ur(-c,t),eql:(c,u)=>c===u,sqr:c=>Ur(c*c,t),add:(c,u)=>Ur(c+u,t),sub:(c,u)=>Ur(c-u,t),mul:(c,u)=>Ur(c*u,t),pow:(c,u)=>zse(i,c,u),div:(c,u)=>Ur(c*vI(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>vI(c,t),sqrt:n.sqrt||(c=>o(i,c)),invertBatch:c=>qse(i,c),cmov:(c,u,d)=>d?u:c,toBytes:c=>r?Fh(c,a):Sc(c,a),fromBytes:c=>{if(c.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${c.length}`);return r?Fu(c):Ef(c)}});return Object.freeze(i)}function Fse(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 yL(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 gL(t){let e=yL(t);return e+Math.ceil(e/2)}function Gse(t,e,r=!1){let n=t.length,s=yL(e),a=gL(e);if(n<16||n<a||n>1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);let o=r?Ef(t):Fu(t),i=Ur(o,e-en)+en;return r?Fh(i,s):Sc(i,s)}var Wse=BigInt(0),cI=BigInt(1);function wL(t,e){let r=(s,a)=>{let o=a.negate();return s?o:a},n=s=>{let a=Math.ceil(e/s)+1,o=2**(s-1);return{windows:a,windowSize:o}};return{constTimeNegate:r,unsafeLadder(s,a){let o=t.ZERO,i=s;for(;a>Wse;)a&cI&&(o=o.add(i)),i=i.double(),a>>=cI;return o},precomputeWindow(s,a){let{windows:o,windowSize:i}=n(a),c=[],u=s,d=u;for(let l=0;l<o;l++){d=u,c.push(d);for(let f=1;f<i;f++)d=d.add(u),c.push(d);u=d.double()}return c},wNAF(s,a,o){let{windows:i,windowSize:c}=n(s),u=t.ZERO,d=t.BASE,l=BigInt(2**s-1),f=2**s,h=BigInt(s);for(let p=0;p<i;p++){let m=p*c,y=Number(o&l);o>>=h,y>c&&(y-=f,o+=cI);let S=m,v=m+Math.abs(y)-1,E=p%2!==0,k=y<0;y===0?d=d.add(r(E,a[S])):u=u.add(r(k,a[v]))}return{p:u,f:d}},wNAFCached(s,a,o,i){let c=s._WINDOW_SIZE||1,u=a.get(s);return u||(u=this.precomputeWindow(s,c),c!==1&&a.set(s,i(u))),this.wNAF(c,u,o)}}}function VI(t){return Kse(t.Fp),Df(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...mL(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Vse(t){let e=VI(t);Df(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:s}=e;if(r){if(!n.eql(s,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})}var{bytesToNumberBE:Hse,hexToBytes:Jse}=rL,xf={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(t){let{Err:e}=xf;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:Hse(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=xf,r=typeof t=="string"?Jse(t):t;if(!xc(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:s,l:a}=xf._parseInt(r.subarray(2)),{d:o,l:i}=xf._parseInt(a);if(i.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:o}},hexFromSig(t){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let d=u.toString(16);return d.length&1?`0${d}`:d},n=e(r(t.s)),s=e(r(t.r)),a=n.length/2,o=s.length/2,i=r(a),c=r(o);return`30${r(o+a+4)}02${c}${s}02${i}${n}`}},Pd=BigInt(0),zo=BigInt(1),Xje=BigInt(2),$N=BigInt(3),e$e=BigInt(4);function Zse(t){let e=Vse(t),{Fp:r}=e,n=e.toBytes||((p,m,y)=>{let S=m.toAffine();return If(Uint8Array.from([4]),r.toBytes(S.x),r.toBytes(S.y))}),s=e.fromBytes||(p=>{let m=p.subarray(1),y=r.fromBytes(m.subarray(0,r.BYTES)),S=r.fromBytes(m.subarray(r.BYTES,2*r.BYTES));return{x:y,y:S}});function a(p){let{a:m,b:y}=e,S=r.sqr(p),v=r.mul(S,p);return r.add(r.add(v,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 o(p){return typeof p=="bigint"&&Pd<p&&p<e.n}function i(p){if(!o(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:S,n:v}=e;if(m&&typeof p!="bigint"){if(xc(p)&&(p=Tf(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let E;try{E=typeof p=="bigint"?p:Ef(Rn("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return S&&(E=Ur(E,v)),i(E),E}let u=new Map;function d(p){if(!(p instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(m,y,S){if(this.px=m,this.py=y,this.pz=S,m==null||!r.isValid(m))throw new Error("x required");if(y==null||!r.isValid(y))throw new Error("y required");if(S==null||!r.isValid(S))throw new Error("z required")}static fromAffine(m){let{x:y,y:S}=m||{};if(!m||!r.isValid(y)||!r.isValid(S))throw new Error("invalid affine point");if(m instanceof l)throw new Error("projective point not allowed");let v=E=>r.eql(E,r.ZERO);return v(y)&&v(S)?l.ZERO:new l(y,S,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=r.invertBatch(m.map(S=>S.pz));return m.map((S,v)=>S.toAffine(y[v])).map(l.fromAffine)}static fromHex(m){let y=l.fromAffine(s(Rn("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return l.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,u.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 S=r.sqr(y),v=a(m);if(!r.eql(S,v))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){d(m);let{px:y,py:S,pz:v}=this,{px:E,py:k,pz:A}=m,D=r.eql(r.mul(y,A),r.mul(E,v)),B=r.eql(r.mul(S,A),r.mul(k,v));return D&&B}negate(){return new l(this.px,r.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,S=r.mul(y,$N),{px:v,py:E,pz:k}=this,A=r.ZERO,D=r.ZERO,B=r.ZERO,j=r.mul(v,v),F=r.mul(E,E),q=r.mul(k,k),N=r.mul(v,E);return N=r.add(N,N),B=r.mul(v,k),B=r.add(B,B),A=r.mul(m,B),D=r.mul(S,q),D=r.add(A,D),A=r.sub(F,D),D=r.add(F,D),D=r.mul(A,D),A=r.mul(N,A),B=r.mul(S,B),q=r.mul(m,q),N=r.sub(j,q),N=r.mul(m,N),N=r.add(N,B),B=r.add(j,j),j=r.add(B,j),j=r.add(j,q),j=r.mul(j,N),D=r.add(D,j),q=r.mul(E,k),q=r.add(q,q),j=r.mul(q,N),A=r.sub(A,j),B=r.mul(q,F),B=r.add(B,B),B=r.add(B,B),new l(A,D,B)}add(m){d(m);let{px:y,py:S,pz:v}=this,{px:E,py:k,pz:A}=m,D=r.ZERO,B=r.ZERO,j=r.ZERO,F=e.a,q=r.mul(e.b,$N),N=r.mul(y,E),W=r.mul(S,k),ee=r.mul(v,A),R=r.add(y,S),$=r.add(E,k);R=r.mul(R,$),$=r.add(N,W),R=r.sub(R,$),$=r.add(y,v);let b=r.add(E,A);return $=r.mul($,b),b=r.add(N,ee),$=r.sub($,b),b=r.add(S,v),D=r.add(k,A),b=r.mul(b,D),D=r.add(W,ee),b=r.sub(b,D),j=r.mul(F,$),D=r.mul(q,ee),j=r.add(D,j),D=r.sub(W,j),j=r.add(W,j),B=r.mul(D,j),W=r.add(N,N),W=r.add(W,N),ee=r.mul(F,ee),$=r.mul(q,$),W=r.add(W,ee),ee=r.sub(N,ee),ee=r.mul(F,ee),$=r.add($,ee),N=r.mul(W,$),B=r.add(B,N),N=r.mul(b,$),D=r.mul(R,D),D=r.sub(D,N),N=r.mul(R,W),j=r.mul(b,j),j=r.add(j,N),new l(D,B,j)}subtract(m){return this.add(m.negate())}is0(){return this.equals(l.ZERO)}wNAF(m){return h.wNAFCached(this,u,m,y=>{let S=r.invertBatch(y.map(v=>v.pz));return y.map((v,E)=>v.toAffine(S[E])).map(l.fromAffine)})}multiplyUnsafe(m){let y=l.ZERO;if(m===Pd)return y;if(i(m),m===zo)return this;let{endo:S}=e;if(!S)return h.unsafeLadder(this,m);let{k1neg:v,k1:E,k2neg:k,k2:A}=S.splitScalar(m),D=y,B=y,j=this;for(;E>Pd||A>Pd;)E&zo&&(D=D.add(j)),A&zo&&(B=B.add(j)),j=j.double(),E>>=zo,A>>=zo;return v&&(D=D.negate()),k&&(B=B.negate()),B=new l(r.mul(B.px,S.beta),B.py,B.pz),D.add(B)}multiply(m){i(m);let y=m,S,v,{endo:E}=e;if(E){let{k1neg:k,k1:A,k2neg:D,k2:B}=E.splitScalar(y),{p:j,f:F}=this.wNAF(A),{p:q,f:N}=this.wNAF(B);j=h.constTimeNegate(k,j),q=h.constTimeNegate(D,q),q=new l(r.mul(q.px,E.beta),q.py,q.pz),S=j.add(q),v=F.add(N)}else{let{p:k,f:A}=this.wNAF(y);S=k,v=A}return l.normalizeZ([S,v])[0]}multiplyAndAddUnsafe(m,y,S){let v=l.BASE,E=(A,D)=>D===Pd||D===zo||!A.equals(v)?A.multiplyUnsafe(D):A.multiply(D),k=E(this,y).add(E(m,S));return k.is0()?void 0:k}toAffine(m){let{px:y,py:S,pz:v}=this,E=this.is0();m==null&&(m=E?r.ONE:r.inv(v));let k=r.mul(y,m),A=r.mul(S,m),D=r.mul(v,m);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(D,r.ONE))throw new Error("invZ was invalid");return{x:k,y:A}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===zo)return!0;if(y)return y(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===zo?this:y?y(l,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(l,this,m)}toHex(m=!0){return Tf(this.toRawBytes(m))}}l.BASE=new l(e.Gx,e.Gy,r.ONE),l.ZERO=new l(r.ZERO,r.ONE,r.ZERO);let f=e.nBitLength,h=wL(l,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:o}}function Yse(t){let e=VI(t);return Df(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Qse(t){let e=Yse(t),{Fp:r,n}=e,s=r.BYTES+1,a=2*r.BYTES+1;function o($){return Pd<$&&$<r.ORDER}function i($){return Ur($,n)}function c($){return vI($,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:l,isWithinCurveOrder:f}=Zse({...e,toBytes($,b,x){let P=b.toAffine(),_=r.toBytes(P.x),I=If;return x?I(Uint8Array.from([b.hasEvenY()?2:3]),_):I(Uint8Array.from([4]),_,r.toBytes(P.y))},fromBytes($){let b=$.length,x=$[0],P=$.subarray(1);if(b===s&&(x===2||x===3)){let _=Ef(P);if(!o(_))throw new Error("Point is not on curve");let I=l(_),O=r.sqrt(I),z=(O&zo)===zo;return(x&1)===1!==z&&(O=r.neg(O)),{x:_,y:O}}else if(b===a&&x===4){let _=r.fromBytes(P.subarray(0,r.BYTES)),I=r.fromBytes(P.subarray(r.BYTES,2*r.BYTES));return{x:_,y:I}}else throw new Error(`Point of length ${b} was invalid. Expected ${s} compressed bytes or ${a} uncompressed bytes`)}}),h=$=>Tf(Sc($,e.nByteLength));function p($){let b=n>>zo;return $>b}function m($){return p($)?i(-$):$}let y=($,b,x)=>Ef($.slice(b,x));class S{constructor(b,x,P){this.r=b,this.s=x,this.recovery=P,this.assertValidity()}static fromCompact(b){let x=e.nByteLength;return b=Rn("compactSignature",b,x*2),new S(y(b,0,x),y(b,x,2*x))}static fromDER(b){let{r:x,s:P}=xf.toSig(Rn("DER",b));return new S(x,P)}assertValidity(){if(!f(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!f(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(b){return new S(this.r,this.s,b)}recoverPublicKey(b){let{r:x,s:P,recovery:_}=this,I=B(Rn("msgHash",b));if(_==null||![0,1,2,3].includes(_))throw new Error("recovery id invalid");let O=_===2||_===3?x+e.n:x;if(O>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let z=_&1?"03":"02",G=u.fromHex(z+h(O)),V=c(O),H=i(-I*V),Y=i(P*V),K=u.BASE.multiplyAndAddUnsafe(G,H,Y);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return qh(this.toDERHex())}toDERHex(){return xf.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return qh(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let v={isValidPrivateKey($){try{return d($),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let $=gL(e.n);return Gse(e.randomBytes($),e.n)},precompute($=8,b=u.BASE){return b._setWindowSize($),b.multiply(BigInt(3)),b}};function E($,b=!0){return u.fromPrivateKey($).toRawBytes(b)}function k($){let b=xc($),x=typeof $=="string",P=(b||x)&&$.length;return b?P===s||P===a:x?P===2*s||P===2*a:$ instanceof u}function A($,b,x=!0){if(k($))throw new Error("first arg must be private key");if(!k(b))throw new Error("second arg must be public key");return u.fromHex(b).multiply(d($)).toRawBytes(x)}let D=e.bits2int||function($){let b=Ef($),x=$.length*8-e.nBitLength;return x>0?b>>BigInt(x):b},B=e.bits2int_modN||function($){return i(D($))},j=qI(e.nBitLength);function F($){if(typeof $!="bigint")throw new Error("bigint expected");if(!(Pd<=$&&$<j))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Sc($,e.nByteLength)}function q($,b,x=N){if(["recovered","canonical"].some(se=>se in x))throw new Error("sign() legacy options not supported");let{hash:P,randomBytes:_}=e,{lowS:I,prehash:O,extraEntropy:z}=x;I==null&&(I=!0),$=Rn("msgHash",$),O&&($=Rn("prehashed msgHash",P($)));let G=B($),V=d(b),H=[F(V),F(G)];if(z!=null){let se=z===!0?_(r.BYTES):z;H.push(Rn("extraEntropy",se))}let Y=If(...H),K=G;function Q(se){let re=D(se);if(!f(re))return;let Z=c(re),de=u.BASE.multiply(re).toAffine(),le=i(de.x);if(le===Pd)return;let pe=i(Z*i(K+le*V));if(pe===Pd)return;let ve=(de.x===le?0:2)|Number(de.y&zo),ce=pe;return I&&p(pe)&&(ce=m(pe),ve^=1),new S(le,ce,ve)}return{seed:Y,k2sig:Q}}let N={lowS:e.lowS,prehash:!1},W={lowS:e.lowS,prehash:!1};function ee($,b,x=N){let{seed:P,k2sig:_}=q($,b,x),I=e;return iL(I.hash.outputLen,I.nByteLength,I.hmac)(P,_)}u.BASE._setWindowSize(8);function R($,b,x,P=W){let _=$;if(b=Rn("msgHash",b),x=Rn("publicKey",x),"strict"in P)throw new Error("options.strict was renamed to lowS");let{lowS:I,prehash:O}=P,z,G;try{if(typeof _=="string"||xc(_))try{z=S.fromDER(_)}catch(Z){if(!(Z instanceof xf.Err))throw Z;z=S.fromCompact(_)}else if(typeof _=="object"&&typeof _.r=="bigint"&&typeof _.s=="bigint"){let{r:Z,s:de}=_;z=new S(Z,de)}else throw new Error("PARSE");G=u.fromHex(x)}catch(Z){if(Z.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(I&&z.hasHighS())return!1;O&&(b=e.hash(b));let{r:V,s:H}=z,Y=B(b),K=c(H),Q=i(Y*K),se=i(V*K),re=u.BASE.multiplyAndAddUnsafe(G,Q,se)?.toAffine();return re?i(re.x)===V:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:A,sign:ee,verify:R,ProjectivePoint:u,Signature:S,utils:v}}var vL=class extends uL{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Tse(t);let r=FI(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,s=new Uint8Array(n);s.set(r.length>n?t.create().update(r).digest():r);for(let a=0;a<s.length;a++)s[a]^=54;this.iHash.update(s),this.oHash=t.create();for(let a=0;a<s.length;a++)s[a]^=106;this.oHash.update(s),s.fill(0)}update(t){return q1(this),this.iHash.update(t),this}digestInto(t){q1(this),oL(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:s,blockLen:a,outputLen:o}=this;return t=t,t.finished=n,t.destroyed=s,t.blockLen=a,t.outputLen=o,t.oHash=e._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},bL=(t,e,r)=>new vL(t,e).update(r).digest();bL.create=(t,e)=>new vL(t,e);function Xse(t){return{hash:t,hmac:(e,...r)=>bL(t,e,dL(...r)),randomBytes:GI}}function PL(t,e){let r=n=>Qse({...t,...Xse(n)});return Object.freeze({...r(e),create:r})}var xL=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),MN=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),eie=BigInt(1),bI=BigInt(2),ON=(t,e)=>(t+e/bI)/e;function tie(t){let e=xL,r=BigInt(3),n=BigInt(6),s=BigInt(11),a=BigInt(22),o=BigInt(23),i=BigInt(44),c=BigInt(88),u=t*t*t%e,d=u*u*t%e,l=an(d,r,e)*d%e,f=an(l,r,e)*d%e,h=an(f,bI,e)*u%e,p=an(h,s,e)*h%e,m=an(p,a,e)*p%e,y=an(m,i,e)*m%e,S=an(y,c,e)*y%e,v=an(S,i,e)*m%e,E=an(v,r,e)*d%e,k=an(E,o,e)*p%e,A=an(k,n,e)*u%e,D=an(A,bI,e);if(!PI.eql(PI.sqr(D),t))throw new Error("Cannot find square root");return D}var PI=WI(xL,void 0,void 0,{sqrt:tie}),fo=PL({a:BigInt(0),b:BigInt(7),Fp:PI,n:MN,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=MN,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-eie*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=r,o=BigInt("0x100000000000000000000000000000000"),i=ON(a*t,e),c=ON(-n*t,e),u=Ur(t-i*r-c*s,e),d=Ur(-i*n-c*a,e),l=u>o,f=d>o;if(l&&(u=e-u),f&&(d=e-d),u>o||d>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:l,k1:u,k2neg:f,k2:d}}}},pL),t$e=BigInt(0),r$e=fo.ProjectivePoint;function rie(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function SL(t,...e){if(!rie(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 BN(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 nie(t,e){SL(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var x1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,dI=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),mc=(t,e)=>t<<32-e|t>>>e,n$e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function sie(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function EL(t){return typeof t=="string"&&(t=sie(t)),SL(t),t}var iie=class{clone(){return this._cloneInto()}},s$e={}.toString;function oie(t){let e=n=>t().update(EL(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function aie(t=32){if(x1&&typeof x1.getRandomValues=="function")return x1.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function cie(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let s=BigInt(32),a=BigInt(4294967295),o=Number(r>>s&a),i=Number(r&a),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,i,n)}var die=(t,e,r)=>t&e^~t&r,uie=(t,e,r)=>t&e^t&r^e&r,lie=class extends iie{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=dI(this.buffer)}update(t){BN(this);let{view:e,buffer:r,blockLen:n}=this;t=EL(t);let s=t.length;for(let a=0;a<s;){let o=Math.min(n-this.pos,s-a);if(o===n){let i=dI(t);for(;n<=s-a;a+=n)this.process(i,a);continue}r.set(t.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){BN(this),nie(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:n,isLE:s}=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 d=a;d<n;d++)e[d]=0;cie(r,n-8,BigInt(this.length*8),s),this.process(r,0);let o=dI(t),i=this.outputLen;if(i%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=i/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,u[d],s)}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:s,destroyed:a,pos:o}=this;return t.length=n,t.pos=o,t.finished=s,t.destroyed=a,n%e&&t.buffer.set(r),t}},fie=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]),Cu=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ju=new Uint32Array(64),pie=class extends lie{constructor(){super(64,32,8,!1),this.A=Cu[0]|0,this.B=Cu[1]|0,this.C=Cu[2]|0,this.D=Cu[3]|0,this.E=Cu[4]|0,this.F=Cu[5]|0,this.G=Cu[6]|0,this.H=Cu[7]|0}get(){let{A:t,B:e,C:r,D:n,E:s,F:a,G:o,H:i}=this;return[t,e,r,n,s,a,o,i]}set(t,e,r,n,s,a,o,i){this.A=t|0,this.B=e|0,this.C=r|0,this.D=n|0,this.E=s|0,this.F=a|0,this.G=o|0,this.H=i|0}process(t,e){for(let d=0;d<16;d++,e+=4)ju[d]=t.getUint32(e,!1);for(let d=16;d<64;d++){let l=ju[d-15],f=ju[d-2],h=mc(l,7)^mc(l,18)^l>>>3,p=mc(f,17)^mc(f,19)^f>>>10;ju[d]=p+ju[d-7]+h+ju[d-16]|0}let{A:r,B:n,C:s,D:a,E:o,F:i,G:c,H:u}=this;for(let d=0;d<64;d++){let l=mc(o,6)^mc(o,11)^mc(o,25),f=u+l+die(o,i,c)+fie[d]+ju[d]|0,h=(mc(r,2)^mc(r,13)^mc(r,22))+uie(r,n,s)|0;u=c,c=i,i=o,o=a+f|0,a=s,s=n,n=r,r=f+h|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,i=i+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,s,a,o,i,c,u)}roundClean(){ju.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},vw=oie(()=>new pie);function hie(t){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let s=Object.keys(n).sort(),a={};for(let o of s)a[o]=e(n[o]);return a}return n},r=e(t);return JSON.stringify(r)}var mie=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},_L=class{static digest(t){return mie(this,arguments,void 0,function*({data:e}){return vw(e)})}},yie=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},NN="urn:jwk:";function fr(t){return yie(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}`);tL(n);let s=hie(n),a=Qe.string(s).toUint8Array(),o=yield _L.digest({data:a});return Qe.uint8Array(o).toBase64Url()})}function _f(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 HI(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 Ed(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 JI(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 gie(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}}var As=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},wie=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 s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},js=class gc{static adjustSignatureToLowS(e){return As(this,arguments,void 0,function*({signature:r}){let n=fo.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return As(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield gc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"secp256k1",d:Qe.uint8Array(r).toBase64Url(),x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield fr({jwk:s}),s})}static bytesToPublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield gc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"secp256k1",x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield fr({jwk:s}),s})}static compressPublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){return fo.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return As(this,arguments,void 0,function*({key:r}){let n=yield gc.privateKeyToBytes({privateKey:r}),s=yield gc.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"secp256k1",x:Qe.uint8Array(s.x).toBase64Url(),y:Qe.uint8Array(s.y).toBase64Url()};return a.kid=yield fr({jwk:a}),a})}static convertDerToCompactSignature(e){return As(this,arguments,void 0,function*({derSignature:r}){return fo.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){return fo.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return As(this,void 0,void 0,function*(){let e=fo.utils.randomPrivateKey(),r=yield gc.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield fr({jwk:r}),r})}static getPublicKey(e){return As(this,arguments,void 0,function*({key:r}){var n;if(!(_f(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:s}=r,a=wie(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield fr({jwk:a})),a})}static privateKeyToBytes(e){return As(this,arguments,void 0,function*({privateKey:r}){if(!_f(r))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return As(this,arguments,void 0,function*({publicKey:r}){if(!(HI(r)&&r.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),s=Qe.base64Url(r.x).toUint8Array(),a=Qe.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...s,...a])})}static sharedSecret(e){return As(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 s=yield gc.privateKeyToBytes({privateKey:r}),a=yield gc.publicKeyToBytes({publicKey:n});return fo.getSharedSecret(s,a,!0).slice(1)})}static sign(e){return As(this,arguments,void 0,function*({data:r,key:n}){let s=yield gc.privateKeyToBytes({privateKey:n}),a=vw(r);return fo.sign(a,s).toCompactRawBytes()})}static validatePrivateKey(e){return As(this,arguments,void 0,function*({privateKeyBytes:r}){return fo.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return As(this,arguments,void 0,function*({publicKeyBytes:r}){try{fo.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return As(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield gc.publicKeyToBytes({publicKey:r}),o=vw(s);return fo.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return As(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=fo.getPublicKey(r));let n=fo.ProjectivePoint.fromHex(r),s=Sc(n.x,32),a=Sc(n.y,32);return{x:s,y:a}})}},kL=WI(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),vie=kL.create(BigInt("-3")),bie=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Pie=PL({a:vie,b:bie,Fp:kL,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},pL),Bo=Pie,Rs=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},xie=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 s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},Xs=class wc{static adjustSignatureToLowS(e){return Rs(this,arguments,void 0,function*({signature:r}){let n=Bo.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Rs(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield wc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"P-256",d:Qe.uint8Array(r).toBase64Url(),x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield fr({jwk:s}),s})}static bytesToPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield wc.getCurvePoint({keyBytes:r}),s={kty:"EC",crv:"P-256",x:Qe.uint8Array(n.x).toBase64Url(),y:Qe.uint8Array(n.y).toBase64Url()};return s.kid=yield fr({jwk:s}),s})}static compressPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){return Bo.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Rs(this,arguments,void 0,function*({key:r}){let n=yield wc.privateKeyToBytes({privateKey:r}),s=yield wc.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"P-256",x:Qe.uint8Array(s.x).toBase64Url(),y:Qe.uint8Array(s.y).toBase64Url()};return a.kid=yield fr({jwk:a}),a})}static convertDerToCompactSignature(e){return Rs(this,arguments,void 0,function*({derSignature:r}){return Bo.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){return Bo.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Rs(this,void 0,void 0,function*(){let e=Bo.utils.randomPrivateKey(),r=yield wc.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield fr({jwk:r}),r})}static getPublicKey(e){return Rs(this,arguments,void 0,function*({key:r}){var n;if(!(_f(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:s}=r,a=xie(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield fr({jwk:a})),a})}static privateKeyToBytes(e){return Rs(this,arguments,void 0,function*({privateKey:r}){if(!_f(r))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Rs(this,arguments,void 0,function*({publicKey:r}){if(!(HI(r)&&r.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),s=Qe.base64Url(r.x).toUint8Array(),a=Qe.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...s,...a])})}static sharedSecret(e){return Rs(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 s=yield wc.privateKeyToBytes({privateKey:r}),a=yield wc.publicKeyToBytes({publicKey:n});return Bo.getSharedSecret(s,a,!0).slice(1)})}static sign(e){return Rs(this,arguments,void 0,function*({data:r,key:n}){let s=yield wc.privateKeyToBytes({privateKey:n}),a=vw(r);return Bo.sign(a,s).toCompactRawBytes()})}static validatePrivateKey(e){return Rs(this,arguments,void 0,function*({privateKeyBytes:r}){return Bo.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Rs(this,arguments,void 0,function*({publicKeyBytes:r}){try{Bo.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Rs(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield wc.publicKeyToBytes({publicKey:r}),o=vw(s);return Bo.verify(n,o,a,{lowS:!1})})}static getCurvePoint(e){return Rs(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Bo.getPublicKey(r));let n=Bo.ProjectivePoint.fromHex(r),s=Sc(n.x,32),a=Sc(n.y,32);return{x:s,y:a}})}},yd=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},UN=class extends tP{bytesToPrivateKey(t){return yd(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield js.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Xs.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256",n}default:throw new Go(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return yd(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield js.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Xs.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256",n}default:throw new Go(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return yd(this,arguments,void 0,function*({key:e}){if(!_f(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield js.computePublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield Xs.computePublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return yd(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let r=yield js.generateKey();return r.alg="ES256K",r}case"ES256":case"secp256r1":{let r=yield Xs.generateKey();return r.alg="ES256",r}}})}getPublicKey(t){return yd(this,arguments,void 0,function*({key:e}){if(!_f(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield js.getPublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield Xs.getPublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return yd(this,arguments,void 0,function*({key:e,data:r}){if(!_f(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield js.sign({key:e,data:r});case"P-256":return yield Xs.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return yd(this,arguments,void 0,function*({key:e,signature:r,data:n}){if(!HI(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(e.crv){case"secp256k1":return yield js.verify({key:e,signature:r,data:n});case"P-256":return yield Xs.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return yd(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield js.privateKeyToBytes({privateKey:e});case"P-256":return yield Xs.privateKeyToBytes({privateKey:e});default:throw new Go(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return yd(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield js.publicKeyToBytes({publicKey:e});case"P-256":return yield Xs.publicKeyToBytes({publicKey:e});default:throw new Go(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},h1=BigInt(4294967295),xI=BigInt(32);function TL(t,e=!1){return e?{h:Number(t&h1),l:Number(t>>xI&h1)}:{h:Number(t>>xI&h1)|0,l:Number(t&h1)|0}}function Sie(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:a,l:o}=TL(t[s],e);[r[s],n[s]]=[a,o]}return[r,n]}var Eie=(t,e)=>BigInt(t>>>0)<<xI|BigInt(e>>>0),_ie=(t,e,r)=>t>>>r,kie=(t,e,r)=>t<<32-r|e>>>r,Tie=(t,e,r)=>t>>>r|e<<32-r,Iie=(t,e,r)=>t<<32-r|e>>>r,Aie=(t,e,r)=>t<<64-r|e>>>r-32,Rie=(t,e,r)=>t>>>r-32|e<<64-r,Die=(t,e)=>e,Cie=(t,e)=>t,jie=(t,e,r)=>t<<r|e>>>32-r,$ie=(t,e,r)=>e<<r|t>>>32-r,Mie=(t,e,r)=>e<<r-32|t>>>64-r,Oie=(t,e,r)=>t<<r-32|e>>>64-r;function Bie(t,e,r,n){let s=(e>>>0)+(n>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}var Nie=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Uie=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Lie=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Kie=(t,e,r,n,s)=>e+r+n+s+(t/2**32|0)|0,zie=(t,e,r,n,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(s>>>0),qie=(t,e,r,n,s,a)=>e+r+n+s+a+(t/2**32|0)|0,Fie={fromBig:TL,split:Sie,toBig:Eie,shrSH:_ie,shrSL:kie,rotrSH:Tie,rotrSL:Iie,rotrBH:Aie,rotrBL:Rie,rotr32H:Die,rotr32L:Cie,rotlSH:jie,rotlSL:$ie,rotlBH:Mie,rotlBL:Oie,add:Bie,add3L:Nie,add3H:Uie,add4L:Lie,add4H:Kie,add5H:qie,add5L:zie},Rt=Fie,[Gie,Wie]=Rt.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))),$u=new Uint32Array(80),Mu=new Uint32Array(80),Vie=class extends fL{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:s,Cl:a,Dh:o,Dl:i,Eh:c,El:u,Fh:d,Fl:l,Gh:f,Gl:h,Hh:p,Hl:m}=this;return[t,e,r,n,s,a,o,i,c,u,d,l,f,h,p,m]}set(t,e,r,n,s,a,o,i,c,u,d,l,f,h,p,m){this.Ah=t|0,this.Al=e|0,this.Bh=r|0,this.Bl=n|0,this.Ch=s|0,this.Cl=a|0,this.Dh=o|0,this.Dl=i|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=l|0,this.Gh=f|0,this.Gl=h|0,this.Hh=p|0,this.Hl=m|0}process(t,e){for(let v=0;v<16;v++,e+=4)$u[v]=t.getUint32(e),Mu[v]=t.getUint32(e+=4);for(let v=16;v<80;v++){let E=$u[v-15]|0,k=Mu[v-15]|0,A=Rt.rotrSH(E,k,1)^Rt.rotrSH(E,k,8)^Rt.shrSH(E,k,7),D=Rt.rotrSL(E,k,1)^Rt.rotrSL(E,k,8)^Rt.shrSL(E,k,7),B=$u[v-2]|0,j=Mu[v-2]|0,F=Rt.rotrSH(B,j,19)^Rt.rotrBH(B,j,61)^Rt.shrSH(B,j,6),q=Rt.rotrSL(B,j,19)^Rt.rotrBL(B,j,61)^Rt.shrSL(B,j,6),N=Rt.add4L(D,q,Mu[v-7],Mu[v-16]),W=Rt.add4H(N,A,F,$u[v-7],$u[v-16]);$u[v]=W|0,Mu[v]=N|0}let{Ah:r,Al:n,Bh:s,Bl:a,Ch:o,Cl:i,Dh:c,Dl:u,Eh:d,El:l,Fh:f,Fl:h,Gh:p,Gl:m,Hh:y,Hl:S}=this;for(let v=0;v<80;v++){let E=Rt.rotrSH(d,l,14)^Rt.rotrSH(d,l,18)^Rt.rotrBH(d,l,41),k=Rt.rotrSL(d,l,14)^Rt.rotrSL(d,l,18)^Rt.rotrBL(d,l,41),A=d&f^~d&p,D=l&h^~l&m,B=Rt.add5L(S,k,D,Wie[v],Mu[v]),j=Rt.add5H(B,y,E,A,Gie[v],$u[v]),F=B|0,q=Rt.rotrSH(r,n,28)^Rt.rotrBH(r,n,34)^Rt.rotrBH(r,n,39),N=Rt.rotrSL(r,n,28)^Rt.rotrBL(r,n,34)^Rt.rotrBL(r,n,39),W=r&s^r&o^s&o,ee=n&a^n&i^a&i;y=p|0,S=m|0,p=f|0,m=h|0,f=d|0,h=l|0,{h:d,l}=Rt.add(c|0,u|0,j|0,F|0),c=o|0,u=i|0,o=s|0,i=a|0,s=r|0,a=n|0;let R=Rt.add3L(F,N,ee);r=Rt.add3H(R,j,q,W),n=R|0}({h:r,l:n}=Rt.add(this.Ah|0,this.Al|0,r|0,n|0)),{h:s,l:a}=Rt.add(this.Bh|0,this.Bl|0,s|0,a|0),{h:o,l:i}=Rt.add(this.Ch|0,this.Cl|0,o|0,i|0),{h:c,l:u}=Rt.add(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=Rt.add(this.Eh|0,this.El|0,d|0,l|0),{h:f,l:h}=Rt.add(this.Fh|0,this.Fl|0,f|0,h|0),{h:p,l:m}=Rt.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:y,l:S}=Rt.add(this.Hh|0,this.Hl|0,y|0,S|0),this.set(r,n,s,a,o,i,c,u,d,l,f,h,p,m,y,S)}roundClean(){$u.fill(0),Mu.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)}},IL=lL(()=>new Vie),_a=BigInt(0),uo=BigInt(1),m1=BigInt(2),Hie=BigInt(8),Jie={zip215:!0};function Zie(t){let e=VI(t);return Df(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function ZI(t){let e=Zie(t),{Fp:r,n,prehash:s,hash:a,randomBytes:o,nByteLength:i,h:c}=e,u=m1<<BigInt(i*8)-uo,d=r.create,l=e.uvRatio||((x,P)=>{try{return{isValid:!0,value:r.sqrt(x*r.inv(P))}}catch{return{isValid:!1,value:_a}}}),f=e.adjustScalarBytes||(x=>x),h=e.domain||((x,P,_)=>{if(P.length||_)throw new Error("Contexts/pre-hash are not supported");return x}),p=x=>typeof x=="bigint"&&_a<x,m=(x,P)=>p(x)&&p(P)&&x<P,y=x=>x===_a||m(x,u);function S(x,P){if(m(x,P))return x;throw new Error(`Expected valid scalar < ${P}, got ${typeof x} ${x}`)}function v(x){return x===_a?x:S(x,n)}let E=new Map;function k(x){if(!(x instanceof A))throw new Error("ExtendedPoint expected")}class A{constructor(P,_,I,O){if(this.ex=P,this.ey=_,this.ez=I,this.et=O,!y(P))throw new Error("x required");if(!y(_))throw new Error("y required");if(!y(I))throw new Error("z required");if(!y(O))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(P){if(P instanceof A)throw new Error("extended point not allowed");let{x:_,y:I}=P||{};if(!y(_)||!y(I))throw new Error("invalid affine point");return new A(_,I,uo,d(_*I))}static normalizeZ(P){let _=r.invertBatch(P.map(I=>I.ez));return P.map((I,O)=>I.toAffine(_[O])).map(A.fromAffine)}_setWindowSize(P){this._WINDOW_SIZE=P,E.delete(this)}assertValidity(){let{a:P,d:_}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:I,ey:O,ez:z,et:G}=this,V=d(I*I),H=d(O*O),Y=d(z*z),K=d(Y*Y),Q=d(V*P),se=d(Y*d(Q+H)),re=d(K+d(_*d(V*H)));if(se!==re)throw new Error("bad point: equation left != right (1)");let Z=d(I*O),de=d(z*G);if(Z!==de)throw new Error("bad point: equation left != right (2)")}equals(P){k(P);let{ex:_,ey:I,ez:O}=this,{ex:z,ey:G,ez:V}=P,H=d(_*V),Y=d(z*O),K=d(I*V),Q=d(G*O);return H===Y&&K===Q}is0(){return this.equals(A.ZERO)}negate(){return new A(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:P}=e,{ex:_,ey:I,ez:O}=this,z=d(_*_),G=d(I*I),V=d(m1*d(O*O)),H=d(P*z),Y=_+I,K=d(d(Y*Y)-z-G),Q=H+G,se=Q-V,re=H-G,Z=d(K*se),de=d(Q*re),le=d(K*re),pe=d(se*Q);return new A(Z,de,pe,le)}add(P){k(P);let{a:_,d:I}=e,{ex:O,ey:z,ez:G,et:V}=this,{ex:H,ey:Y,ez:K,et:Q}=P;if(_===BigInt(-1)){let Et=d((z-O)*(Y+H)),Se=d((z+O)*(Y-H)),et=d(Se-Et);if(et===_a)return this.double();let wt=d(G*m1*Q),xt=d(V*m1*K),$t=xt+wt,T=Se+Et,M=xt-wt,L=d($t*et),te=d(T*M),ae=d($t*M),he=d(et*T);return new A(L,te,he,ae)}let se=d(O*H),re=d(z*Y),Z=d(V*I*Q),de=d(G*K),le=d((O+z)*(H+Y)-se-re),pe=de-Z,ve=de+Z,ce=d(re-_*se),ge=d(le*pe),Me=d(ve*ce),Le=d(le*ce),qe=d(pe*ve);return new A(ge,Me,qe,Le)}subtract(P){return this.add(P.negate())}wNAF(P){return j.wNAFCached(this,E,P,A.normalizeZ)}multiply(P){let{p:_,f:I}=this.wNAF(S(P,n));return A.normalizeZ([_,I])[0]}multiplyUnsafe(P){let _=v(P);return _===_a?B:this.equals(B)||_===uo?this:this.equals(D)?this.wNAF(_).p:j.unsafeLadder(this,_)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return j.unsafeLadder(this,n).is0()}toAffine(P){let{ex:_,ey:I,ez:O}=this,z=this.is0();P==null&&(P=z?Hie:r.inv(O));let G=d(_*P),V=d(I*P),H=d(O*P);if(z)return{x:_a,y:uo};if(H!==uo)throw new Error("invZ was invalid");return{x:G,y:V}}clearCofactor(){let{h:P}=e;return P===uo?this:this.multiplyUnsafe(P)}static fromHex(P,_=!1){let{d:I,a:O}=e,z=r.BYTES;P=Rn("pointHex",P,z);let G=P.slice(),V=P[z-1];G[z-1]=V&-129;let H=Fu(G);H===_a||(_?S(H,u):S(H,r.ORDER));let Y=d(H*H),K=d(Y-uo),Q=d(I*Y-O),{isValid:se,value:re}=l(K,Q);if(!se)throw new Error("Point.fromHex: invalid y coordinate");let Z=(re&uo)===uo,de=(V&128)!==0;if(!_&&re===_a&&de)throw new Error("Point.fromHex: x=0 and x_0=1");return de!==Z&&(re=d(-re)),A.fromAffine({x:re,y:H})}static fromPrivateKey(P){return N(P).point}toRawBytes(){let{x:P,y:_}=this.toAffine(),I=Fh(_,r.BYTES);return I[I.length-1]|=P&uo?128:0,I}toHex(){return Tf(this.toRawBytes())}}A.BASE=new A(e.Gx,e.Gy,uo,d(e.Gx*e.Gy)),A.ZERO=new A(_a,uo,uo,_a);let{BASE:D,ZERO:B}=A,j=wL(A,i*8);function F(x){return Ur(x,n)}function q(x){return F(Fu(x))}function N(x){let P=i;x=Rn("private key",x,P);let _=Rn("hashed private key",a(x),2*P),I=f(_.slice(0,P)),O=_.slice(P,2*P),z=q(I),G=D.multiply(z),V=G.toRawBytes();return{head:I,prefix:O,scalar:z,point:G,pointBytes:V}}function W(x){return N(x).pointBytes}function ee(x=new Uint8Array,...P){let _=If(...P);return q(a(h(_,Rn("context",x),!!s)))}function R(x,P,_={}){x=Rn("message",x),s&&(x=s(x));let{prefix:I,scalar:O,pointBytes:z}=N(P),G=ee(_.context,I,x),V=D.multiply(G).toRawBytes(),H=ee(_.context,V,z,x),Y=F(G+H*O);v(Y);let K=If(V,Fh(Y,r.BYTES));return Rn("result",K,i*2)}let $=Jie;function b(x,P,_,I=$){let{context:O,zip215:z}=I,G=r.BYTES;x=Rn("signature",x,2*G),P=Rn("message",P),s&&(P=s(P));let V=Fu(x.slice(G,2*G)),H,Y,K;try{H=A.fromHex(_,z),Y=A.fromHex(x.slice(0,G),z),K=D.multiplyUnsafe(V)}catch{return!1}if(!z&&H.isSmallOrder())return!1;let Q=ee(O,Y.toRawBytes(),H.toRawBytes(),P);return Y.add(H.multiplyUnsafe(Q)).subtract(K).clearCofactor().equals(A.ZERO)}return D._setWindowSize(8),{CURVE:e,getPublicKey:W,sign:R,verify:b,ExtendedPoint:A,utils:{getExtendedPublicKey:N,randomPrivateKey:()=>o(r.BYTES),precompute(x=8,P=A.BASE){return P._setWindowSize(x),P.multiply(BigInt(3)),P}}}}var Jg=BigInt(0),uI=BigInt(1);function Yie(t){return Df(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function Qie(t){let e=Yie(t),{P:r}=e,n=E=>Ur(E,r),s=e.montgomeryBits,a=Math.ceil(s/8),o=e.nByteLength,i=e.adjustScalarBytes||(E=>E),c=e.powPminus2||(E=>hL(E,r-BigInt(2),r));function u(E,k,A){let D=n(E*(k-A));return k=n(k-D),A=n(A+D),[k,A]}function d(E){if(typeof E=="bigint"&&Jg<=E&&E<r)return E;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let l=(e.a-BigInt(2))/BigInt(4);function f(E,k){let A=d(E),D=d(k),B=A,j=uI,F=Jg,q=A,N=uI,W=Jg,ee;for(let $=BigInt(s-1);$>=Jg;$--){let b=D>>$&uI;W^=b,ee=u(W,j,q),j=ee[0],q=ee[1],ee=u(W,F,N),F=ee[0],N=ee[1],W=b;let x=j+F,P=n(x*x),_=j-F,I=n(_*_),O=P-I,z=q+N,G=q-N,V=n(G*x),H=n(z*_),Y=V+H,K=V-H;q=n(Y*Y),N=n(B*n(K*K)),j=n(P*I),F=n(O*(P+n(l*O)))}ee=u(W,j,q),j=ee[0],q=ee[1],ee=u(W,F,N),F=ee[0],N=ee[1];let R=c(F);return n(j*R)}function h(E){return Fh(n(E),a)}function p(E){let k=Rn("u coordinate",E,a);return o===32&&(k[31]&=127),Fu(k)}function m(E){let k=Rn("scalar",E),A=k.length;if(A!==a&&A!==o)throw new Error(`Expected ${a} or ${o} bytes, got ${A}`);return Fu(i(k))}function y(E,k){let A=p(k),D=m(E),B=f(A,D);if(B===Jg)throw new Error("Invalid private or public key received");return h(B)}let S=h(e.Gu);function v(E){return y(E,S)}return{scalarMult:y,scalarMultBase:v,getSharedSecret:(E,k)=>y(E,k),getPublicKey:E=>v(E),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var bw=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),LN=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),i$e=BigInt(0),Xie=BigInt(1),SI=BigInt(2),eoe=BigInt(5),KN=BigInt(10),toe=BigInt(20),roe=BigInt(40),zN=BigInt(80);function AL(t){let e=bw,r=t*t%e*t%e,n=an(r,SI,e)*r%e,s=an(n,Xie,e)*t%e,a=an(s,eoe,e)*s%e,o=an(a,KN,e)*a%e,i=an(o,toe,e)*o%e,c=an(i,roe,e)*i%e,u=an(c,zN,e)*c%e,d=an(u,zN,e)*c%e,l=an(d,KN,e)*a%e;return{pow_p_5_8:an(l,SI,e)*t%e,b2:r}}function RL(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function noe(t,e){let r=bw,n=Ur(e*e*e,r),s=Ur(n*n*e,r),a=AL(t*s).pow_p_5_8,o=Ur(t*n*a,r),i=Ur(e*o*o,r),c=o,u=Ur(o*LN,r),d=i===t,l=i===Ur(-t,r),f=i===Ur(-t*LN,r);return d&&(o=c),(l||f)&&(o=u),Use(o,r)&&(o=Ur(-o,r)),{isValid:d||l,value:o}}var Wo=WI(bw,void 0,!0),Pw={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Wo,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:IL,randomBytes:GI,adjustScalarBytes:RL,uvRatio:noe},gf=ZI(Pw);function DL(t,e,r){if(e.length>255)throw new Error("Context is too big");return dL(cL("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var o$e=ZI({...Pw,domain:DL}),a$e=ZI({...Pw,domain:DL,prehash:IL}),tw=Qie({P:bw,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=bw,{pow_p_5_8:r,b2:n}=AL(t);return Ur(an(r,BigInt(3),e)*n,e)},adjustScalarBytes:RL,randomBytes:GI});function soe(t){let{y:e}=gf.ExtendedPoint.fromHex(t),r=BigInt(1);return Wo.toBytes(Wo.create((r+e)*Wo.inv(r-e)))}function ioe(t){let e=Pw.hash(t.subarray(0,32));return Pw.adjustScalarBytes(e).subarray(0,32)}var ooe=(Wo.ORDER+BigInt(3))/BigInt(8),c$e=Wo.pow(SI,ooe),d$e=Wo.sqrt(Wo.neg(Wo.ONE)),u$e=(Wo.ORDER-BigInt(5))/BigInt(8),l$e=BigInt(486662),f$e=Fse(Wo,Wo.neg(BigInt(486664))),p$e=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),h$e=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),m$e=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),y$e=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),g$e=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),No=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},aoe=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 s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},$s=class Lu{static bytesToPrivateKey(e){return No(this,arguments,void 0,function*({privateKeyBytes:r}){let n=gf.getPublicKey(r),s={crv:"Ed25519",d:Qe.uint8Array(r).toBase64Url(),kty:"OKP",x:Qe.uint8Array(n).toBase64Url()};return s.kid=yield fr({jwk:s}),s})}static bytesToPublicKey(e){return No(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:Qe.uint8Array(r).toBase64Url()};return n.kid=yield fr({jwk:n}),n})}static computePublicKey(e){return No(this,arguments,void 0,function*({key:r}){let n=yield Lu.privateKeyToBytes({privateKey:r}),s=gf.getPublicKey(n),a={kty:"OKP",crv:"Ed25519",x:Qe.uint8Array(s).toBase64Url()};return a.kid=yield fr({jwk:a}),a})}static convertPrivateKeyToX25519(e){return No(this,arguments,void 0,function*({privateKey:r}){let n=yield Lu.privateKeyToBytes({privateKey:r}),s=ioe(n),a=tw.getPublicKey(s),o={kty:"OKP",crv:"X25519",d:Qe.uint8Array(s).toBase64Url(),x:Qe.uint8Array(a).toBase64Url()};return o.kid=yield fr({jwk:o}),o})}static convertPublicKeyToX25519(e){return No(this,arguments,void 0,function*({publicKey:r}){let n=yield Lu.publicKeyToBytes({publicKey:r});if(!(yield Lu.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let s=soe(n),a={kty:"OKP",crv:"X25519",x:Qe.uint8Array(s).toBase64Url()};return a.kid=yield fr({jwk:a}),a})}static generateKey(){return No(this,void 0,void 0,function*(){let e=gf.utils.randomPrivateKey(),r=yield Lu.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield fr({jwk:r}),r})}static getPublicKey(e){return No(this,arguments,void 0,function*({key:r}){var n;if(!(Ed(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:s}=r,a=aoe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield fr({jwk:a})),a})}static privateKeyToBytes(e){return No(this,arguments,void 0,function*({privateKey:r}){if(!Ed(r))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return No(this,arguments,void 0,function*({publicKey:r}){if(!JI(r))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return Qe.base64Url(r.x).toUint8Array()})}static sign(e){return No(this,arguments,void 0,function*({key:r,data:n}){let s=yield Lu.privateKeyToBytes({privateKey:r});return gf.sign(n,s)})}static validatePublicKey(e){return No(this,arguments,void 0,function*({publicKeyBytes:r}){try{gf.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return No(this,arguments,void 0,function*({key:r,signature:n,data:s}){let a=yield Lu.publicKeyToBytes({publicKey:r});return gf.verify(n,s,a)})}},gd=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},coe=class extends tP{bytesToPrivateKey(t){return gd(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"Ed25519":{let n=yield $s.bytesToPrivateKey({privateKeyBytes:r});return n.alg="EdDSA",n}default:throw new Go(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return gd(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"Ed25519":{let n=yield $s.bytesToPublicKey({publicKeyBytes:r});return n.alg="EdDSA",n}default:throw new Go(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return gd(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield $s.computePublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return gd(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let r=yield $s.generateKey();return r.alg="EdDSA",r}}})}getPublicKey(t){return gd(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield $s.getPublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return gd(this,arguments,void 0,function*({key:e,data:r}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield $s.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return gd(this,arguments,void 0,function*({key:e,signature:r,data:n}){if(!JI(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield $s.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return gd(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"Ed25519":return yield $s.privateKeyToBytes({privateKey:e});default:throw new Go(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return gd(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield $s.publicKeyToBytes({publicKey:e});default:throw new Go(Li.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},doe=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},uoe=class extends tP{digest(t){return doe(this,arguments,void 0,function*({algorithm:e,data:r}){switch(e){case"SHA-256":return yield _L.digest({data:r})}})}},Ou=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},loe=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 s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r},Ch=class rw{static bytesToPrivateKey(e){return Ou(this,arguments,void 0,function*({privateKeyBytes:r}){let n=tw.getPublicKey(r),s={kty:"OKP",crv:"X25519",d:Qe.uint8Array(r).toBase64Url(),x:Qe.uint8Array(n).toBase64Url()};return s.kid=yield fr({jwk:s}),s})}static bytesToPublicKey(e){return Ou(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:Qe.uint8Array(r).toBase64Url()};return n.kid=yield fr({jwk:n}),n})}static computePublicKey(e){return Ou(this,arguments,void 0,function*({key:r}){let n=yield rw.privateKeyToBytes({privateKey:r}),s=tw.getPublicKey(n),a={kty:"OKP",crv:"X25519",x:Qe.uint8Array(s).toBase64Url()};return a.kid=yield fr({jwk:a}),a})}static generateKey(){return Ou(this,void 0,void 0,function*(){let e=tw.utils.randomPrivateKey(),r=yield rw.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield fr({jwk:r}),r})}static getPublicKey(e){return Ou(this,arguments,void 0,function*({key:r}){var n;if(!(Ed(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:s}=r,a=loe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield fr({jwk:a})),a})}static privateKeyToBytes(e){return Ou(this,arguments,void 0,function*({privateKey:r}){if(!Ed(r))throw new Error("X25519: The provided key is not a valid OKP private key.");return Qe.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Ou(this,arguments,void 0,function*({publicKey:r}){if(!JI(r))throw new Error("X25519: The provided key is not a valid OKP public key.");return Qe.base64Url(r.x).toUint8Array()})}static sharedSecret(e){return Ou(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 s=yield rw.privateKeyToBytes({privateKey:r}),a=yield rw.publicKeyToBytes({publicKey:n});return tw.getSharedSecret(s,a)})}},Zg=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},foe=class extends tP{bytesToPrivateKey(t){return Zg(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"X25519":return Ch.bytesToPrivateKey({privateKeyBytes:r});default:throw new Go(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return Zg(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Ch.computePublicKey({key:e});default:throw new Go(Li.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(t){return Zg(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return Ch.generateKey();default:throw new Go(Li.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(t){return Zg(this,arguments,void 0,function*({key:e}){if(!Ed(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Ch.getPublicKey({key:e});default:throw new Go(Li.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return Zg(this,arguments,void 0,function*({privateKey:e}){return Ch.privateKeyToBytes({privateKey:e})})}},wd=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},lI={Ed25519:{implementation:coe,names:["Ed25519"]},secp256k1:{implementation:UN,names:["ES256K","secp256k1"]},secp256r1:{implementation:UN,names:["ES256","secp256r1"]},"SHA-256":{implementation:uoe,names:["SHA-256"]},X25519:{implementation:foe,names:["X25519"]}},Ia=class{constructor(t){var e;this._algorithmInstances=new Map,this._keyStore=(e=t?.keyStore)!==null&&e!==void 0?e:new yse}digest(t){return wd(this,arguments,void 0,function*({algorithm:e,data:r}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:r})})}exportKey(t){return wd(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(t){return wd(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=`${NN}${r.kid}`;return yield this._keyStore.set(n,r),n})}getKeyUri(t){return wd(this,arguments,void 0,function*({key:e}){let r=yield fr({jwk:e});return`${NN}${r}`})}getPublicKey(t){return wd(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 wd(this,arguments,void 0,function*({key:e}){var r;if(!gie(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 fr({jwk:n}));let s=yield this.getKeyUri({key:n});return yield this._keyStore.set(s,n),s})}sign(t){return wd(this,arguments,void 0,function*({keyUri:e,data:r}){let n=yield this.getPrivateKey({keyUri:e}),s=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:s}).sign({data:r,key:n})})}verify(t){return wd(this,arguments,void 0,function*({key:e,signature:r,data:n}){let s=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:s}).verify({key:e,signature:r,data:n})})}getAlgorithm({algorithm:t}){var e;let r=(e=lI[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 lI){let s=lI[n];if(e&&s.names.includes(e)||r&&s.names.includes(r))return n}throw new Error(`Unable to determine algorithm based on provided input: alg=${e}, crv=${r}`)}getPrivateKey(t){return wd(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})}},poe=class EI{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 aie(e)}static randomUuid(){return x1.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 s=Math.pow(10,e);do{let a=EI.randomBytes(Math.ceil(e/2));n=new DataView(a.buffer).getUint16(0,!1)%s}while(n>r)}else{let s=Math.pow(10,10);do{let a=EI.randomBytes(4);n=new DataView(a.buffer).getUint32(0,!1)%s}while(n>r)}return n.toString().padStart(e,"0")}},hoe=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function moe(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":yoe(t)||"Object"}function yoe(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(hoe.includes(e))return e}var Pe=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}};Pe.uint=new Pe(0,"uint",!0);Pe.negint=new Pe(1,"negint",!0);Pe.bytes=new Pe(2,"bytes",!0);Pe.string=new Pe(3,"string",!0);Pe.array=new Pe(4,"array",!1);Pe.map=new Pe(5,"map",!1);Pe.tag=new Pe(6,"tag",!1);Pe.float=new Pe(7,"float",!0);Pe.false=new Pe(7,"false",!0);Pe.true=new Pe(7,"true",!0);Pe.null=new Pe(7,"null",!0);Pe.undefined=new Pe(7,"undefined",!0);Pe.break=new Pe(7,"break",!0);var Je=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}`}},Tw=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",goe=new TextEncoder;function F1(t){return Tw&&globalThis.Buffer.isBuffer(t)}function CL(t){return t instanceof Uint8Array?F1(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var woe=24,voe=200,boe=Tw?t=>t.length>=woe?globalThis.Buffer.from(t):qN(t):t=>t.length>=voe?goe.encode(t):qN(t),vd=t=>Uint8Array.from(t),Poe=Tw?(t,e,r)=>F1(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),xoe=Tw?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),CL(globalThis.Buffer.concat(t,e))):(t,e)=>{let r=new Uint8Array(e),n=0;for(let s of t)n+s.length>r.length&&(s=s.subarray(0,r.length-n)),r.set(s,n),n+=s.length;return r},Soe=Tw?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function jL(t,e){if(F1(t)&&F1(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 qN(t){let e=[],r=0;for(let n=0;n<t.length;n++){let s=t.charCodeAt(n);s<128?e[r++]=s:s<2048?(e[r++]=s>>6|192,e[r++]=s&63|128):(s&64512)===55296&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(s=65536+((s&1023)<<10)+(t.charCodeAt(++n)&1023),e[r++]=s>>18|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128,e[r++]=s&63|128):(s>=55296&&s<=57343&&(s=65533),e[r++]=s>>12|224,e[r++]=s>>6&63|128,e[r++]=s&63|128)}return e}var Eoe=256,$L=class{constructor(t=Eoe){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=Soe(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=Poe(r,0,this.cursor)}else e=xoe(this.chunks,this.cursor);return t&&this.reset(),e}},_oe=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}},cn="CBOR decode error:",ML="CBOR encode error:",Iw=[];Iw[23]=1;Iw[24]=2;Iw[25]=3;Iw[26]=5;Iw[27]=9;function Jh(t,e,r){if(t.length-e<r)throw new Error(`${cn} not enough data for type`)}var Ms=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Cf(t,e,r){Jh(t,e,1);let n=t[e];if(r.strict===!0&&n<Ms[0])throw new Error(`${cn} integer encoded in more bytes than necessary (strict decode)`);return n}function jf(t,e,r){Jh(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<Ms[1])throw new Error(`${cn} integer encoded in more bytes than necessary (strict decode)`);return n}function $f(t,e,r){Jh(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<Ms[2])throw new Error(`${cn} integer encoded in more bytes than necessary (strict decode)`);return n}function Mf(t,e,r){Jh(t,e,8);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],s=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],a=(BigInt(n)<<BigInt(32))+BigInt(s);if(r.strict===!0&&a<Ms[3])throw new Error(`${cn} 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(`${cn} integers outside of the safe integer range are not supported`)}function koe(t,e,r,n){return new Je(Pe.uint,Cf(t,e+1,n),2)}function Toe(t,e,r,n){return new Je(Pe.uint,jf(t,e+1,n),3)}function Ioe(t,e,r,n){return new Je(Pe.uint,$f(t,e+1,n),5)}function Aoe(t,e,r,n){return new Je(Pe.uint,Mf(t,e+1,n),9)}function Of(t,e){return Ho(t,0,e.value)}function Ho(t,e,r){if(r<Ms[0]){let n=Number(r);t.push([e|n])}else if(r<Ms[1]){let n=Number(r);t.push([e|24,n])}else if(r<Ms[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<Ms[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<Ms[4]){let s=[e|27,0,0,0,0,0,0,0],a=Number(n&BigInt(4294967295)),o=Number(n>>BigInt(32)&BigInt(4294967295));s[8]=a&255,a=a>>8,s[7]=a&255,a=a>>8,s[6]=a&255,a=a>>8,s[5]=a&255,s[4]=o&255,o=o>>8,s[3]=o&255,o=o>>8,s[2]=o&255,o=o>>8,s[1]=o&255,t.push(s)}else throw new Error(`${cn} encountered BigInt larger than allowable range`)}}Of.encodedSize=function(t){return Ho.encodedSize(t.value)};Ho.encodedSize=function(t){return t<Ms[0]?1:t<Ms[1]?2:t<Ms[2]?3:t<Ms[3]?5:9};Of.compareTokens=function(t,e){return t.value<e.value?-1:t.value>e.value?1:0};function Roe(t,e,r,n){return new Je(Pe.negint,-1-Cf(t,e+1,n),2)}function Doe(t,e,r,n){return new Je(Pe.negint,-1-jf(t,e+1,n),3)}function Coe(t,e,r,n){return new Je(Pe.negint,-1-$f(t,e+1,n),5)}var YI=BigInt(-1),OL=BigInt(1);function joe(t,e,r,n){let s=Mf(t,e+1,n);if(typeof s!="bigint"){let a=-1-s;if(a>=Number.MIN_SAFE_INTEGER)return new Je(Pe.negint,a,9)}if(n.allowBigInt!==!0)throw new Error(`${cn} integers outside of the safe integer range are not supported`);return new Je(Pe.negint,YI-BigInt(s),9)}function QI(t,e){let r=e.value,n=typeof r=="bigint"?r*YI-OL:r*-1-1;Ho(t,e.type.majorEncoded,n)}QI.encodedSize=function(t){let e=t.value,r=typeof e=="bigint"?e*YI-OL:e*-1-1;return r<Ms[0]?1:r<Ms[1]?2:r<Ms[2]?3:r<Ms[3]?5:9};QI.compareTokens=function(t,e){return t.value<e.value?1:t.value>e.value?-1:0};function Aw(t,e,r,n){Jh(t,e,r+n);let s=t.slice(e+r,e+r+n);return new Je(Pe.bytes,s,r+n)}function $oe(t,e,r,n){return Aw(t,e,1,r)}function Moe(t,e,r,n){return Aw(t,e,2,Cf(t,e+1,n))}function Ooe(t,e,r,n){return Aw(t,e,3,jf(t,e+1,n))}function Boe(t,e,r,n){return Aw(t,e,5,$f(t,e+1,n))}function Noe(t,e,r,n){let s=Mf(t,e+1,n);if(typeof s=="bigint")throw new Error(`${cn} 64-bit integer bytes lengths not supported`);return Aw(t,e,9,s)}function G1(t){return t.encodedBytes===void 0&&(t.encodedBytes=Pe.equals(t.type,Pe.string)?boe(t.value):t.value),t.encodedBytes}function nP(t,e){let r=G1(e);Ho(t,e.type.majorEncoded,r.length),t.push(r)}nP.encodedSize=function(t){let e=G1(t);return Ho.encodedSize(e.length)+e.length};nP.compareTokens=function(t,e){return Uoe(G1(t),G1(e))};function Uoe(t,e){return t.length<e.length?-1:t.length>e.length?1:jL(t,e)}var FN=new TextDecoder,Loe=32;function Koe(t,e,r){if(r-e<Loe){let n="";for(let s=e;s<r;s++){let a=t[s];if(a&128)return FN.decode(t.subarray(e,r));n+=String.fromCharCode(a)}return n}return FN.decode(t.subarray(e,r))}function Rw(t,e,r,n,s){let a=r+n;Jh(t,e,a);let o=new Je(Pe.string,Koe(t,e+r,e+a),a);return s.retainStringBytes===!0&&(o.byteValue=t.slice(e+r,e+a)),o}function zoe(t,e,r,n){return Rw(t,e,1,r,n)}function qoe(t,e,r,n){return Rw(t,e,2,Cf(t,e+1,n),n)}function Foe(t,e,r,n){return Rw(t,e,3,jf(t,e+1,n),n)}function Goe(t,e,r,n){return Rw(t,e,5,$f(t,e+1,n),n)}function Woe(t,e,r,n){let s=Mf(t,e+1,n);if(typeof s=="bigint")throw new Error(`${cn} 64-bit integer string lengths not supported`);return Rw(t,e,9,s,n)}var Voe=nP;function Zh(t,e,r,n){return new Je(Pe.array,n,r)}function Hoe(t,e,r,n){return Zh(t,e,1,r)}function Joe(t,e,r,n){return Zh(t,e,2,Cf(t,e+1,n))}function Zoe(t,e,r,n){return Zh(t,e,3,jf(t,e+1,n))}function Yoe(t,e,r,n){return Zh(t,e,5,$f(t,e+1,n))}function Qoe(t,e,r,n){let s=Mf(t,e+1,n);if(typeof s=="bigint")throw new Error(`${cn} 64-bit integer array lengths not supported`);return Zh(t,e,9,s)}function Xoe(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${cn} indefinite length items not allowed`);return Zh(t,e,1,1/0)}function XI(t,e){Ho(t,Pe.array.majorEncoded,e.value)}XI.compareTokens=Of.compareTokens;XI.encodedSize=function(t){return Ho.encodedSize(t.value)};function Yh(t,e,r,n){return new Je(Pe.map,n,r)}function eae(t,e,r,n){return Yh(t,e,1,r)}function tae(t,e,r,n){return Yh(t,e,2,Cf(t,e+1,n))}function rae(t,e,r,n){return Yh(t,e,3,jf(t,e+1,n))}function nae(t,e,r,n){return Yh(t,e,5,$f(t,e+1,n))}function sae(t,e,r,n){let s=Mf(t,e+1,n);if(typeof s=="bigint")throw new Error(`${cn} 64-bit integer map lengths not supported`);return Yh(t,e,9,s)}function iae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${cn} indefinite length items not allowed`);return Yh(t,e,1,1/0)}function eA(t,e){Ho(t,Pe.map.majorEncoded,e.value)}eA.compareTokens=Of.compareTokens;eA.encodedSize=function(t){return Ho.encodedSize(t.value)};function oae(t,e,r,n){return new Je(Pe.tag,r,1)}function aae(t,e,r,n){return new Je(Pe.tag,Cf(t,e+1,n),2)}function cae(t,e,r,n){return new Je(Pe.tag,jf(t,e+1,n),3)}function dae(t,e,r,n){return new Je(Pe.tag,$f(t,e+1,n),5)}function uae(t,e,r,n){return new Je(Pe.tag,Mf(t,e+1,n),9)}function tA(t,e){Ho(t,Pe.tag.majorEncoded,e.value)}tA.compareTokens=Of.compareTokens;tA.encodedSize=function(t){return Ho.encodedSize(t.value)};var BL=20,NL=21,UL=22,LL=23;function lae(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${cn} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Je(Pe.null,null,1):new Je(Pe.undefined,void 0,1)}function fae(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${cn} indefinite length items not allowed`);return new Je(Pe.break,void 0,1)}function rA(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${cn} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${cn} Infinity values are not supported`)}return new Je(Pe.float,t,e)}function pae(t,e,r,n){return rA(sA(t,e+1),3,n)}function hae(t,e,r,n){return rA(iA(t,e+1),5,n)}function mae(t,e,r,n){return rA(FL(t,e+1),9,n)}function nA(t,e,r){let n=e.value;if(n===!1)t.push([Pe.float.majorEncoded|BL]);else if(n===!0)t.push([Pe.float.majorEncoded|NL]);else if(n===null)t.push([Pe.float.majorEncoded|UL]);else if(n===void 0)t.push([Pe.float.majorEncoded|LL]);else{let s,a=!1;(!r||r.float64!==!0)&&(zL(n),s=sA(ka,1),n===s||Number.isNaN(n)?(ka[0]=249,t.push(ka.slice(0,3)),a=!0):(qL(n),s=iA(ka,1),n===s&&(ka[0]=250,t.push(ka.slice(0,5)),a=!0))),a||(yae(n),s=FL(ka,1),ka[0]=251,t.push(ka.slice(0,9)))}}nA.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){zL(r);let n=sA(ka,1);if(r===n||Number.isNaN(r))return 3;if(qL(r),n=iA(ka,1),r===n)return 5}return 9};var KL=new ArrayBuffer(9),Lo=new DataView(KL,1),ka=new Uint8Array(KL,0);function zL(t){if(t===1/0)Lo.setUint16(0,31744,!1);else if(t===-1/0)Lo.setUint16(0,64512,!1);else if(Number.isNaN(t))Lo.setUint16(0,32256,!1);else{Lo.setFloat32(0,t);let e=Lo.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)Lo.setUint16(0,31744,!1);else if(r===0)Lo.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let s=r-127;s<-24?Lo.setUint16(0,0):s<-14?Lo.setUint16(0,(e&2147483648)>>16|1<<24+s,!1):Lo.setUint16(0,(e&2147483648)>>16|s+15<<10|n>>13,!1)}}}function sA(t,e){if(t.length-e<2)throw new Error(`${cn} 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,s=r&1023,a;return n===0?a=s*2**-24:n!==31?a=(s+1024)*2**(n-25):a=s===0?1/0:NaN,r&32768?-a:a}function qL(t){Lo.setFloat32(0,t,!1)}function iA(t,e){if(t.length-e<4)throw new Error(`${cn} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function yae(t){Lo.setFloat64(0,t,!1)}function FL(t,e){if(t.length-e<8)throw new Error(`${cn} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}nA.compareTokens=Of.compareTokens;function nr(t,e,r){throw new Error(`${cn} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function sP(t){return()=>{throw new Error(`${cn} ${t}`)}}var Ce=[];for(let t=0;t<=23;t++)Ce[t]=nr;Ce[24]=koe;Ce[25]=Toe;Ce[26]=Ioe;Ce[27]=Aoe;Ce[28]=nr;Ce[29]=nr;Ce[30]=nr;Ce[31]=nr;for(let t=32;t<=55;t++)Ce[t]=nr;Ce[56]=Roe;Ce[57]=Doe;Ce[58]=Coe;Ce[59]=joe;Ce[60]=nr;Ce[61]=nr;Ce[62]=nr;Ce[63]=nr;for(let t=64;t<=87;t++)Ce[t]=$oe;Ce[88]=Moe;Ce[89]=Ooe;Ce[90]=Boe;Ce[91]=Noe;Ce[92]=nr;Ce[93]=nr;Ce[94]=nr;Ce[95]=sP("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)Ce[t]=zoe;Ce[120]=qoe;Ce[121]=Foe;Ce[122]=Goe;Ce[123]=Woe;Ce[124]=nr;Ce[125]=nr;Ce[126]=nr;Ce[127]=sP("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)Ce[t]=Hoe;Ce[152]=Joe;Ce[153]=Zoe;Ce[154]=Yoe;Ce[155]=Qoe;Ce[156]=nr;Ce[157]=nr;Ce[158]=nr;Ce[159]=Xoe;for(let t=160;t<=183;t++)Ce[t]=eae;Ce[184]=tae;Ce[185]=rae;Ce[186]=nae;Ce[187]=sae;Ce[188]=nr;Ce[189]=nr;Ce[190]=nr;Ce[191]=iae;for(let t=192;t<=215;t++)Ce[t]=oae;Ce[216]=aae;Ce[217]=cae;Ce[218]=dae;Ce[219]=uae;Ce[220]=nr;Ce[221]=nr;Ce[222]=nr;Ce[223]=nr;for(let t=224;t<=243;t++)Ce[t]=sP("simple values are not supported");Ce[244]=nr;Ce[245]=nr;Ce[246]=nr;Ce[247]=lae;Ce[248]=sP("simple values are not supported");Ce[249]=pae;Ce[250]=hae;Ce[251]=mae;Ce[252]=nr;Ce[253]=nr;Ce[254]=nr;Ce[255]=fae;var kd=[];for(let t=0;t<24;t++)kd[t]=new Je(Pe.uint,t,1);for(let t=-1;t>=-24;t--)kd[31-t]=new Je(Pe.negint,t,1);kd[64]=new Je(Pe.bytes,new Uint8Array(0),1);kd[96]=new Je(Pe.string,"",1);kd[128]=new Je(Pe.array,0,1);kd[160]=new Je(Pe.map,0,1);kd[244]=new Je(Pe.false,!1,1);kd[245]=new Je(Pe.true,!0,1);kd[246]=new Je(Pe.null,null,1);function gae(t){switch(t.type){case Pe.false:return vd([244]);case Pe.true:return vd([245]);case Pe.null:return vd([246]);case Pe.bytes:return t.value.length?void 0:vd([64]);case Pe.string:return t.value===""?vd([96]):void 0;case Pe.array:return t.value===0?vd([128]):void 0;case Pe.map:return t.value===0?vd([160]):void 0;case Pe.uint:return t.value<24?vd([Number(t.value)]):void 0;case Pe.negint:if(t.value>=-24)return vd([31-Number(t.value)])}}var wae=Object.freeze({float64:!0,mapSorter:Sae,quickEncodeToken:gae});function vae(){let t=[];return t[Pe.uint.major]=Of,t[Pe.negint.major]=QI,t[Pe.bytes.major]=nP,t[Pe.string.major]=Voe,t[Pe.array.major]=XI,t[Pe.map.major]=eA,t[Pe.tag.major]=tA,t[Pe.float.major]=nA,t}var bae=vae(),Pae=new $L,GN=class GL{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(`${ML} object contains circular references`);return new GL(r,e)}},Bu={null:new Je(Pe.null,null),undefined:new Je(Pe.undefined,void 0),true:new Je(Pe.true,!0),false:new Je(Pe.false,!1),emptyArray:new Je(Pe.array,0),emptyMap:new Je(Pe.map,0)},Wu={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new Je(Pe.float,t):t>=0?new Je(Pe.uint,t):new Je(Pe.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new Je(Pe.uint,t):new Je(Pe.negint,t)},Uint8Array(t,e,r,n){return new Je(Pe.bytes,t)},string(t,e,r,n){return new Je(Pe.string,t)},boolean(t,e,r,n){return t?Bu.true:Bu.false},null(t,e,r,n){return Bu.null},undefined(t,e,r,n){return Bu.undefined},ArrayBuffer(t,e,r,n){return new Je(Pe.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new Je(Pe.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[Bu.emptyArray,new Je(Pe.break)]:Bu.emptyArray;n=GN.createCheck(n,t);let s=[],a=0;for(let o of t)s[a++]=S1(o,r,n);return r.addBreakTokens?[new Je(Pe.array,t.length),s,new Je(Pe.break)]:[new Je(Pe.array,t.length),s]},Object(t,e,r,n){let s=e!=="Object",a=s?t.keys():Object.keys(t),o=s?t.size:a.length,i;if(o){i=new Array(o),n=GN.createCheck(n,t);let c=!s&&r.ignoreUndefinedProperties,u=0;for(let d of a){let l=s?t.get(d):t[d];c&&l===void 0||(i[u++]=[S1(d,r,n),S1(l,r,n)])}u<o&&(i.length=u)}return i?.length?(xae(i,r),r.addBreakTokens?[new Je(Pe.map,i.length),i,new Je(Pe.break)]:[new Je(Pe.map,i.length),i]):r.addBreakTokens===!0?[Bu.emptyMap,new Je(Pe.break)]:Bu.emptyMap}};Wu.Map=Wu.Object;Wu.Buffer=Wu.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Wu[`${t}Array`]=Wu.DataView;function S1(t,e={},r){let n=moe(t),s=e&&e.typeEncoders&&e.typeEncoders[n]||Wu[n];if(typeof s=="function"){let o=s(t,n,e,r);if(o!=null)return o}let a=Wu[n];if(!a)throw new Error(`${ML} unsupported type: ${n}`);return a(t,n,e,r)}function xae(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Sae(t,e){if(t[0]instanceof Je&&e[0]instanceof Je){let r=t[0],n=e[0];return r._keyBytes||(r._keyBytes=WN(r.value)),n._keyBytes||(n._keyBytes=WN(n.value)),jL(r._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function WN(t){return Eae(t,bae,wae)}function WL(t,e,r,n){if(Array.isArray(e))for(let s of e)WL(t,s,r,n);else r[e.type.major](t,e,n)}var w$e=Pe.uint.majorEncoded,v$e=Pe.negint.majorEncoded,b$e=Pe.bytes.majorEncoded,P$e=Pe.string.majorEncoded,x$e=Pe.array.majorEncoded,S$e=Pe.float.majorEncoded|BL,E$e=Pe.float.majorEncoded|NL,_$e=Pe.float.majorEncoded|UL,k$e=Pe.float.majorEncoded|LL,T$e=BigInt(-1),I$e=BigInt(1);function Eae(t,e,r,n){let s=n instanceof Uint8Array,a=s?new _oe(n):Pae,o=S1(t,r);if(!Array.isArray(o)&&r.quickEncodeToken){let i=r.quickEncodeToken(o);if(i)return s?(a.push(i),a.toBytes()):i;let c=e[o.type.major];if(c.encodedSize){let u=c.encodedSize(o,r);if(s||(a=new $L(u)),c(a,o,r),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${o} was wrong`);return s?a.toBytes():CL(a.chunks[0])}}return a.reset(),WL(a,o,e,r),a.toBytes(!0)}var A$e=Symbol.for("DONE"),R$e=Symbol.for("BREAK"),VN;(function(t){t[t.OKP=1]="OKP",t[t.EC2=2]="EC2",t[t.Symmetric=4]="Symmetric"})(VN||(VN={}));var ei;(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"})(ei||(ei={}));var Fo;(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"})(Fo||(Fo={}));var HN;(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"})(HN||(HN={}));var JN;(function(t){t[t.Crv=-1]="Crv",t[t.X=-2]="X",t[t.Y=-3]="Y",t[t.D=-4]="D"})(JN||(JN={}));var D$e={"P-256":ei.P256,"P-384":ei.P384,"P-521":ei.P521,X25519:ei.X25519,Ed25519:ei.Ed25519,Ed448:ei.Ed448,secp256k1:ei.Secp256k1},C$e={[ei.P256]:"P-256",[ei.P384]:"P-384",[ei.P521]:"P-521",[ei.X25519]:"X25519",[ei.Ed25519]:"Ed25519",[ei.Ed448]:"Ed448",[ei.Secp256k1]:"secp256k1"},j$e={EdDSA:Fo.EdDSA,ES256:Fo.ES256,ES384:Fo.ES384,ES512:Fo.ES512,ES256K:Fo.ES256K},$$e={[Fo.EdDSA]:"EdDSA",[Fo.ES256]:"ES256",[Fo.ES384]:"ES384",[Fo.ES512]:"ES512",[Fo.ES256K]:"ES256K"},ZN;(function(t){t[t.Alg=1]="Alg",t[t.Crit=2]="Crit",t[t.ContentType=3]="ContentType",t[t.Kid=4]="Kid"})(ZN||(ZN={}));var YN;(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"})(YN||(YN={}));var QN;(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"})(QN||(QN={}));var XN;(function(t){t[t.Unrestricted=1]="Unrestricted",t[t.Restricted=2]="Restricted",t[t.SecureRestricted=3]="SecureRestricted",t[t.Hardware=4]="Hardware"})(XN||(XN={}));var _ae={};BI(_ae,{extractDidFragment:()=>Ei,getServices:()=>kae,getVerificationMethodByKey:()=>Tae,getVerificationMethodTypes:()=>VL,getVerificationMethods:()=>iP,getVerificationRelationshipsById:()=>HL,isDidService:()=>JL,isDidVerificationMethod:()=>W1,isDwnDidService:()=>Iae,isPortableDid:()=>Aae,keyBytesToMultibaseId:()=>ZL,multibaseIdToKeyBytes:()=>YL});function Ei(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function kae({didDocument:t,id:e,type:r}){return t?.service?.filter(n=>!(e&&n.id!==e||r&&n.type!==r))??[]}async function Tae({didDocument:t,publicKeyJwk:e,publicKeyMultibase:r}){let n=iP({didDocument:t});for(let s of n)if(e&&s.publicKeyJwk){if(await fr({jwk:e})===await fr({jwk:s.publicKeyJwk}))return s}else if(r&&s.publicKeyMultibase&&r===s.publicKeyMultibase)return s;return null}function iP({didDocument:t}){if(!t)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...t.verificationMethod?.filter(W1)??[]),Object.keys(eP).forEach(r=>{e.push(...t[r]?.filter(W1)??[])}),e}function VL({didDocument:t}){let e=iP({didDocument:t}).map(r=>r.type);return[...new Set(e)]}function HL({didDocument:t,methodId:e}){let r=[];return Object.keys(eP).forEach(n=>{if(Array.isArray(t[n])){let s=t[n],a=Ei(e);s.some(o=>{let i=Ei(o)===a,c=W1(o)&&Ei(o.id)===a;return i||c})&&r.push(n)}}),r}function JL(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function Iae(t){return!(!JL(t)||t.type!=="DecentralizedWebNode")}function W1(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 Aae(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 ZL({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Vo.addPrefix({code:e,data:t,name:r}),s=Qe.uint8Array(n).toBase58Btc();return Qe.base58Btc(s).toMultibase()}function YL({multibaseKeyId:t}){try{let e=Qe.multibase(t).toBase58Btc(),r=Qe.base58Btc(e).toUint8Array(),{code:n,data:s,name:a}=Vo.removePrefix({prefixedData:r});return{keyBytes:s,multicodecCode:n,multicodecName:a}}catch{throw new Ze("invalidDid",`Invalid multibase identifier: ${t}`)}}var Ec=class QL{constructor({uri:e,document:r,metadata:n,keyManager:s}){this.uri=e,this.document=r,this.metadata=n,this.keyManager=s}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 s=await this.keyManager.getKeyUri({key:n.publicKeyJwk}),a=await this.keyManager.exportKey({keyUri:s});r.push({...a})}e.privateKeys=r}return e}async getSigner(e){let r=this.document.verificationMethod?.find(o=>Ei(o.id)===(Ei(e?.methodId)??Ei(this.document.assertionMethod?.[0])));if(!(r&&r.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");let n=await this.keyManager.getKeyUri({key:r.publicKeyJwk}),s=await this.keyManager.getPublicKey({keyUri:n}),a=this.keyManager;return{algorithm:poe.getJoseSignatureAlgorithmFromPublicKey(s),keyId:r.id,async sign({data:o}){return await a.sign({data:o,keyUri:n})},async verify({data:o,signature:i}){return await a.verify({data:o,key:s,signature:i})}}}static async import({portableDid:e,keyManager:r=new Ia}){let n=iP({didDocument:e.document});if(n.length===0)throw new Ze("invalidDidDocument","At least one verification method is required but 0 were given");for(let s of e.privateKeys??[]){let a=await r.getKeyUri({key:s});await r.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1)||await r.importKey({key:s})}for(let s of n){if(!s.publicKeyJwk)throw new Error(`Verification method '${s.id}' does not contain a public key in JWK format`);let a=await r.getKeyUri({key:s.publicKeyJwk});await r.getPublicKey({keyUri:a})}return new QL({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:r})}},Dw=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()")}},XL=(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))(XL||{}),oA=(t=>(t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519",t))(oA||{}),eK=(t=>(t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm",t))(eK||{}),eU="0123456789abcdef",tK=[],tU=[];for(let t=0;t<256;t++)tK[t]=eU[t>>4&15]+eU[t&15],t<16&&(t<10?tU[48+t]=t:tU[87+t]=t);var Rae=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=tK[t[n++]];return r},Dae=(t,e=0)=>{let r=t.length||0;if(!e){let o=r;for(;o--;)e+=t[o].length}let n=new Uint8Array(e),s=e,a=r;for(;a--;)s-=t[a].length,n.set(t[a],s);return n},rU="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Cae=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Yg=0;Yg<rU.length;Yg++)Cae[rU.charCodeAt(Yg)]=Yg;var Yg,jae=new TextDecoder,rK=(t,e)=>e?new TextDecoder(e).decode(t):jae.decode(t),$ae=new TextEncoder,_d=t=>$ae.encode(t),nU=typeof window<"u"?window:self,sU=nU.crypto||nU.msCrypto||{},M$e=sU.subtle||sU.webkitSubtle;function Cw(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function nK(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 cr(t,e,r){let n=[],s=null;return cr._encode(n,t),s=Dae(n),cr.bytes=s.length,ArrayBuffer.isView(e)?(e.set(s,r),e):s}cr.bytes=-1;cr._floatConversionDetected=!1;cr._encode=function(t,e){if(e!=null)switch(nK(e)){case"object":cr.dict(t,e);break;case"map":cr.dictMap(t,e);break;case"array":cr.list(t,e);break;case"set":cr.listSet(t,e);break;case"string":cr.string(t,e);break;case"number":cr.number(t,e);break;case"boolean":cr.number(t,e);break;case"arraybufferview":cr.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":cr.buffer(t,new Uint8Array(e));break}};var oP=new Uint8Array([101]),sK=new Uint8Array([100]),iK=new Uint8Array([108]);cr.buffer=function(t,e){t.push(_d(e.length+":"),e)};cr.string=function(t,e){t.push(_d(_d(e).byteLength+":"+e))};cr.number=function(t,e){if(Number.isInteger(e))return t.push(_d("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,s=e%r<<0,a=n*r+s;t.push(_d("i"+a+"e")),a!==e&&!cr._floatConversionDetected&&(cr._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())};cr.dict=function(t,e){t.push(sK);let r=0,n,s=Object.keys(e).sort(),a=s.length;for(;r<a;r++)n=s[r],e[n]!=null&&(cr.string(t,n),cr._encode(t,e[n]));t.push(oP)};cr.dictMap=function(t,e){t.push(sK);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?cr._encode(t,n):cr.string(t,String(n)),cr._encode(t,e.get(n)));t.push(oP)};cr.list=function(t,e){let r=0,n=e.length;for(t.push(iK);r<n;r++)e[r]!=null&&cr._encode(t,e[r]);t.push(oP)};cr.listSet=function(t,e){t.push(iK);for(let r of e)r!=null&&cr._encode(t,r);t.push(oP)};var Mae=cr,Oae=105,Bae=58,Nae=100,Uae=108,aA=101;function oK(t,e,r){let n=0,s=1;for(let a=e;a<r;a++){let o=t[a];if(o<58&&o>=48){n=n*10+(o-48);continue}if(!(a===e&&o===43)){if(a===e&&o===45){s=-1;continue}if(o===46)break;throw new Error("not a number: buffer["+a+"] = "+o)}}return n*s}function lt(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),lt.position=0,lt.encoding=n||null,lt.data=ArrayBuffer.isView(t)?new Uint8Array(t.slice(e,r)):_d(t),lt.bytes=lt.data.length,lt.next())}lt.bytes=0;lt.position=0;lt.data=null;lt.encoding=null;lt.next=function(){switch(lt.data[lt.position]){case Nae:return lt.dictionary();case Uae:return lt.list();case Oae:return lt.integer();default:return lt.buffer()}};lt.find=function(t){let e=lt.position,r=lt.data.length,n=lt.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)+"]")};lt.dictionary=function(){lt.position++;let t={};for(;lt.data[lt.position]!==aA;){let e=lt.buffer(),r=rK(e);r.includes("\uFFFD")&&(r=Rae(e)),t[r]=lt.next()}return lt.position++,t};lt.list=function(){lt.position++;let t=[];for(;lt.data[lt.position]!==aA;)t.push(lt.next());return lt.position++,t};lt.integer=function(){let t=lt.find(aA),e=oK(lt.data,lt.position+1,t);return lt.position+=t+1-lt.position,e};lt.buffer=function(){let t=lt.find(Bae),e=oK(lt.data,lt.position,t),r=++t+e;return lt.position=r,lt.encoding?rK(lt.data.slice(t,r)):lt.data.slice(t,r)};var Lae=lt;function Kae(t){let e=2;for(let r of t)e+=aP(r);return e}function zae(t){let e=2;for(let[r,n]of t){let s=_d(r).byteLength;e+=Cw(s)+1+s,e+=aP(n)}return e}function qae(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let s=_d(r[n]).byteLength;e+=Cw(s)+1+s,e+=aP(t[r[n]])}return e}function Fae(t){let e=_d(t).byteLength;return Cw(e)+1+e}function Gae(t){let e=t.byteLength-t.byteOffset;return Cw(e)+1+e}function aP(t){if(t==null)return 0;let e=nK(t);switch(e){case"arraybufferview":return Gae(t);case"string":return Fae(t);case"array":case"set":return Kae(t);case"number":return 1+Cw(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return qae(t);case"map":return zae(t);default:throw new TypeError(`Unsupported value of type "${e}"`)}}var aK=aP,Wae=aK,cK={encode:Mae,decode:Lae,byteLength:aK,encodingLength:Wae},Vae=/^(\d{1,3}\.){3,3}\d{1,3}$/,Hae=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,Pc={name:"v4",size:4,isFormat:t=>Vae.test(t),encode(t,e,r){r=~~r,e=e||new Uint8Array(r+4);let n=t.length,s=0;for(let a=0;a<n;){let o=t.charCodeAt(a++);o===46?(e[r++]=s,s=0):s=s*10+(o-48)}return e[r]=s,e},decode(t,e){return e=~~e,`${t[e++]}.${t[e++]}.${t[e++]}.${t[e]}`}},Gu={name:"v6",size:16,isFormat:t=>t.length>0&&Hae.test(t),encode(t,e,r){r=~~r;let n=r+16,s=-1,a=0,o=0,i=!0,c=!1;e=e||new Uint8Array(r+16);for(let u=0;u<t.length;u++){let d=t.charCodeAt(u);d===58?(i?s!==-1?(r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2):r<n&&(s=r):(c===!0?(r<n&&(e[r]=o),r++):(r<n&&(e[r]=a>>8),r<n-1&&(e[r+1]=a&255),r+=2),a=0,o=0),i=!0,c=!1):d===46?(r<n&&(e[r]=o),r++,o=0,a=0,i=!1,c=!0):(i=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,o=o*10+d),a=(a<<4)+d)}if(i===!1)c===!0?(r<n&&(e[r]=o),r++):(r<n&&(e[r]=a>>8),r<n-1&&(e[r+1]=a&255),r+=2);else if(s===0)r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2;else if(s!==-1){r+=2;for(let u=Math.min(r-1,n-1);u>=s+2;u--)e[u]=e[u-2];e[s]=0,e[s+1]=0,s=r}if(s!==r&&s!==-1)for(r>n-2&&(r=n-2);n>s;)e[--n]=r<n&&r>s?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}/,"::")}};function dK(t){if(Pc.isFormat(t))return Pc.size;if(Gu.isFormat(t))return Gu.size;throw Error(`Invalid ip address: ${t}`)}function Jae(t){return dK(t)===Pc.size?1:2}function Zae(t,e,r){r=~~r;let n=dK(t);return typeof e=="function"&&(e=e(r+n)),n===Pc.size?Pc.encode(t,e,r):Gu.encode(t,e,r)}function Yae(t,e,r){if(e=~~e,r=r||t.length-e,r===Pc.size)return Pc.decode(t,e,r);if(r===Gu.size)return Gu.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${Pc.size} for v4 or ${Gu.size} for v6.`)}function cP(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 xw(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 Qae(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 Xae(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 uK(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 lK(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 ece(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 iU(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 fK(t){let e=0,r=t.length;for(let n=0;n<r;n+=1){let s=t.charCodeAt(n);if(s<=127)e+=1;else if(s<=2047)e+=2;else if((s&63488)!==55296)e+=3;else{let a=n+1;a===r||s>=56320||(t.charCodeAt(a)&64512)!==56320?e+=3:(n=a,e+=4)}}return e}function Sw(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(fK(t)+r));let s=r;for(let a=0;a<n;a+=1){let o=t.charCodeAt(a);if(o<=127)e[s++]=o;else if(o<=2047)e[s++]=192|(o&1984)>>6,e[s++]=128|o&63;else if((o&63488)!==55296)e[s++]=224|(o&61440)>>12,e[s++]=128|(o&4032)>>6,e[s++]=128|o&63;else{let i=a+1;if(i===n||o>=56320)e[s++]=239,e[s++]=191,e[s++]=189;else{let c=t.charCodeAt(i);(c&64512)!==56320?(e[s++]=239,e[s++]=191,e[s++]=189):(a=i,o=65536|(o&1023)<<10|c&1023,e[s++]=240|(o&1835008)>>18,e[s++]=128|(o&258048)>>12,e[s++]=128|(o&4032)>>6,e[s++]=128|o&63)}}}return Sw.bytes=s-r,e}Sw.bytes=0;function jw(t,e,r){let n="";e==null&&(e=0),r==null&&(r=t.length);for(let s=e;s<r;){let a=t[s++],o;if(a<=128)o=a;else if(a>191&&a<224)o=(a&31)<<6|t[s++]&63;else if(a>239&&a<365){o=((a&7)<<18|(t[s++]&63)<<12|(t[s++]&63)<<6|t[s++]&63)-65536;let i=55296|o>>10&1023;n+=String.fromCharCode(i),o=56320|o&1023}else o=(a&15)<<12|(t[s++]&63)<<6|t[s++]&63;n+=String.fromCharCode(o)}return jw.bytes=r-e,n}jw.bytes=0;var Af=t=>t instanceof Uint8Array;function Vu(t){return typeof t=="string"?fK(t):t.byteLength}function cA(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Sw(t)}function dA(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Sw(e,t,r),Sw.bytes}var nw={},pK=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 s=n.toString(16),a=s.toUpperCase(),o=t<<4|n,i=`${e}${s}`;pK[o]=i,nw[i]=o,nw[`${r}${s}`]=o,nw[`${e}${a}`]=o,nw[`${r}${a}`]=o}}function tce(t,e,r){let n="";for(let s=e;s<r;){let a=t[s++];n+=pK[a]}return n}function oU(t){return t.length>>>1}function rce(t,e,r,n){let s=0;for(;r<n;){let a=e.substr(s,2),o=nw[a];if(o===void 0)return;t[r++]=o,s+=2}return t}var nce=Math.pow(2,24),sce=Math.pow(2,16),ice=Math.pow(2,8),xd=(t,e)=>t[e]*nce+t[e+1]*sce+t[e+2]*ice+t[e+3],Dt=(t,e)=>t[e]<<8|t[e+1],Sd=(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),Xe=(t,e,r)=>(t[r]=e>>8,t[r+1]=e&255,r+2);function mo(t,e,r,n,s){return r<0&&(n-=r,r=0),n<0&&(n=0),s<0?new Uint8Array(0):r>=e.length||n>=s?0:oce(t,e,r,n,s)}function oce(t,e,r,n,s){s-n>e.length-r&&(s=n+e.length-r);let a=s-n,o=t.length-n;return a>o&&(a=o),(n!==0||s<t.length)&&(t=new Uint8Array(t.buffer,t.byteOffset+n,a)),e.set(t,r),a}var ace=0,aU=32768,_I=32768,cce=~_I,hK=32768,dce=~hK;function jr({bytes:t=0,encode:e,decode:r,encodingLength:n}){return e.bytes=t,r.bytes=t,{encode:e,decode:r,encodingLength:n||(()=>t)}}var Fe=jr({encode(t,e,r){e||(e=new Uint8Array(Fe.encodingLength(t))),r||(r=0);let n=r,s=t.replace(/^\.|\.$/gm,"");if(s.length){let a=s.split(".");for(let o=0;o<a.length;o++){let i=dA(e,a[o],r+1);e[r]=i,r+=i+1}}return e[r++]=0,Fe.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=[],n=e,s=0,a=0,o=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let i=t[e++];if(a+=o?0:1,i===0)break;if(i&192)if((i&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let c=Dt(t,e-1)-49152;if(c>=n)throw new Error("Cannot decode name (bad pointer)");e=c,n=c,a+=o?0:1,o=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+i>t.length)throw new Error("Cannot decode name (buffer overflow)");if(s+=i+1,s>254)throw new Error("Cannot decode name (name too long)");r.push(jw(t,e,e+i)),e+=i,a+=o?0:i}}return Fe.decode.bytes=a,r.length===0?".":r.join(".")},encodingLength(t){return t==="."||t===".."?1:Vu(t.replace(/^\.|\.$/gm,""))+2}}),Hn=jr({encode(t,e,r){e||(e=new Uint8Array(Hn.encodingLength(t))),r||(r=0);let n=dA(e,t,r+1);return e[r]=n,Hn.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=jw(t,e+1,e+1+r);return Hn.decode.bytes=r+1,n},encodingLength(t){return Vu(t)+1}}),jh=jr({bytes:12,encode(t,e,r){e||(e=new Uint8Array(jh.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,s=t.type==="response"?aU:ace;return Xe(e,t.id||0,r),Xe(e,n|s,r+2),Xe(e,t.questions.length,r+4),Xe(e,t.answers.length,r+6),Xe(e,t.authorities.length,r+8),Xe(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=Dt(t,e+2);return{id:Dt(t,e),type:r&aU?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:Xae(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:Qae(r&15),questions:new Array(Dt(t,e+4)),answers:new Array(Dt(t,e+6)),authorities:new Array(Dt(t,e+8)),additionals:new Array(Dt(t,e+10))}},encodingLength(){return 12}}),E1=jr({encode(t,e,r){e||(e=new Uint8Array(E1.encodingLength(t))),r||(r=0);let n=t.length;return Xe(e,n,r),mo(t,e,r+2,0,n),E1.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=Dt(t,e),n=t.slice(e+2,e+2+r);return E1.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),_1=jr({encode(t,e,r){return e||(e=new Uint8Array(_1.encodingLength(t))),r||(r=0),Fe.encode(t,e,r+2),Xe(e,Fe.encode.bytes,r),_1.encode.bytes=Fe.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Dt(t,e),n=Fe.decode(t,e+2);return _1.decode.bytes=r+2,n},encodingLength(t){return Fe.encodingLength(t)+2}}),k1=jr({encode(t,e,r){e||(e=new Uint8Array(k1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Fe.encode(t.mname,e,r),r+=Fe.encode.bytes,Fe.encode(t.rname,e,r),r+=Fe.encode.bytes,Sd(e,t.serial||0,r),r+=4,Sd(e,t.refresh||0,r),r+=4,Sd(e,t.retry||0,r),r+=4,Sd(e,t.expire||0,r),r+=4,Sd(e,t.minimum||0,r),r+=4,Xe(e,r-n-2,n),k1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=Fe.decode(t,e),e+=Fe.decode.bytes,n.rname=Fe.decode(t,e),e+=Fe.decode.bytes,n.serial=xd(t,e),e+=4,n.refresh=xd(t,e),e+=4,n.retry=xd(t,e),e+=4,n.expire=xd(t,e),e+=4,n.minimum=xd(t,e),e+=4,k1.decode.bytes=e-r,n},encodingLength(t){return 22+Fe.encodingLength(t.mname)+Fe.encodingLength(t.rname)}}),T1=jr({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let s=0;s<t.length;s++)if(typeof t[s]=="string"&&(t[s]=cA(t[s])),!Af(t[s]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(T1.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(s){e[r++]=s.length,mo(s,e,r,0,s.length),r+=s.length}),Xe(e,r-n-2,n),T1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=Dt(t,e);e+=2;let s=[];for(;n>0;){let a=t[e++];if(--n,n<a)throw new Error("Buffer overflow");s.push(t.slice(e,e+a)),e+=a,n-=a}return T1.decode.bytes=e-r,s},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=Vu(r)+1:e+=r.length+1}),e}}),I1=jr({encode(t,e,r){e||(e=new Uint8Array(I1.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=cA(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let s=t.length;return mo(t,e,r,0,s),r+=s,Xe(e,r-n-2,n),I1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=Dt(t,e);e+=2;let s=t.slice(e,e+n);return e+=n,I1.decode.bytes=e-r,s},encodingLength(t){return t?(Af(t)?t.length:Vu(t))+2:2}}),A1=jr({encode(t,e,r){e||(e=new Uint8Array(A1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Hn.encode(t.cpu,e,r),r+=Hn.encode.bytes,Hn.encode(t.os,e,r),r+=Hn.encode.bytes,Xe(e,r-n-2,n),A1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Hn.decode(t,e),e+=Hn.decode.bytes,n.os=Hn.decode(t,e),e+=Hn.decode.bytes,A1.decode.bytes=e-r,n},encodingLength(t){return Hn.encodingLength(t.cpu)+Hn.encodingLength(t.os)+2}}),Lh=jr({encode(t,e,r){return e||(e=new Uint8Array(Lh.encodingLength(t))),r||(r=0),Fe.encode(t,e,r+2),Xe(e,Fe.encode.bytes,r),Lh.encode.bytes=Fe.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Fe.decode(t,e+2);return Lh.decode.bytes=Fe.decode.bytes+2,r},encodingLength(t){return Fe.encodingLength(t)+2}}),R1=jr({encode(t,e,r){e||(e=new Uint8Array(R1.encodingLength(t))),r||(r=0),Xe(e,t.priority||0,r+2),Xe(e,t.weight||0,r+4),Xe(e,t.port||0,r+6),Fe.encode(t.target,e,r+8);let n=Fe.encode.bytes+6;return Xe(e,n,r),R1.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=Dt(t,e),n={};return n.priority=Dt(t,e+2),n.weight=Dt(t,e+4),n.port=Dt(t,e+6),n.target=Fe.decode(t,e+8),R1.decode.bytes=r+2,n},encodingLength(t){return 8+Fe.encodingLength(t.target)}}),zu=jr({encode(t,e,r){let n=zu.encodingLength(t);return e||(e=new Uint8Array(zu.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=zu.ISSUER_CRITICAL),Xe(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,Hn.encode(t.tag,e,r),r+=Hn.encode.bytes,dA(e,t.value,r),r+=Vu(t.value),zu.encode.bytes=n,e},decode(t,e){e||(e=0);let r=Dt(t,e);e+=2;let n=e,s={};return s.flags=t[e],e+=1,s.tag=Hn.decode(t,e),e+=Hn.decode.bytes,s.value=jw(t,e,n+r),s.issuerCritical=!!(s.flags&zu.ISSUER_CRITICAL),zu.decode.bytes=r+2,s},encodingLength(t){return Hn.encodingLength(t.tag)+Hn.encodingLength(t.value)+2}});zu.ISSUER_CRITICAL=128;var D1=jr({encode(t,e,r){e||(e=new Uint8Array(D1.encodingLength(t))),r||(r=0);let n=r;return r+=2,Xe(e,t.preference||0,r),r+=2,Fe.encode(t.exchange,e,r),r+=Fe.encode.bytes,Xe(e,r-n-2,n),D1.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=Dt(t,e),e+=2,n.exchange=Fe.decode(t,e),e+=Fe.decode.bytes,D1.decode.bytes=e-r,n},encodingLength(t){return 4+Fe.encodingLength(t.exchange)}}),mK=jr({encode(t,e,r){return e||(e=new Uint8Array(mK.encodingLength(t))),r||(r=0),Xe(e,4,r),r+=2,Pc.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,Pc.decode(t,e)},bytes:6}),C1=jr({encode(t,e,r){return e||(e=new Uint8Array(C1.encodingLength(t))),r||(r=0),Xe(e,16,r),r+=2,Gu.encode(t,e,r),C1.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=Gu.decode(t,e);return C1.decode.bytes=18,r},bytes:18}),cU=t=>new Uint8Array(t),bd=jr({encode(t,e,r){e||(e=new Uint8Array(bd.encodingLength(t))),r||(r=0);let n=r,s=iU(t.code);if(Xe(e,s,r),r+=2,t.data)Xe(e,t.data.length,r),r+=2,mo(t.data,e,r),r+=t.data.length;else switch(s){case 8:{let a=t.sourcePrefixLength||0,o=t.family||Jae(t.ip,cU),i=Zae(t.ip,cU),c=Math.ceil(a/8);Xe(e,c+4,r),r+=2,Xe(e,o,r),r+=2,e[r++]=a,e[r++]=t.scopePrefixLength||0,mo(i,e,r,0,c),r+=c}break;case 11:t.timeout?(Xe(e,2,r),r+=2,Xe(e,t.timeout,r),r+=2):(Xe(e,0,r),r+=2);break;case 12:{let a=t.length||0;Xe(e,a,r),r+=2,e.fill(0,r,r+a),r+=a}break;case 14:{let a=t.tags.length*2;Xe(e,a,r),r+=2;for(let o of t.tags)Xe(e,o,r),r+=2}break;default:throw new Error(`Unknown roption code: ${t.code}`)}return bd.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=Dt(t,e),r.type=ece(r.code),e+=2;let n=Dt(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=Dt(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let s=new Uint8Array(r.family===1?4:16);mo(t,s,0,e,e+n-4),r.ip=Yae(s)}break;case 11:n>0&&(r.timeout=Dt(t,e),e+=2);break;case 14:r.tags=[];for(let s=0;s<n;s+=2)r.tags.push(Dt(t,e)),e+=2}return bd.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(iU(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}`)}}),qu=jr({encode(t,e,r){e||(e=new Uint8Array(qu.encodingLength(t))),r||(r=0);let n=r,s=Nh(t,bd);return Xe(e,s,r),r=dw(t,bd,e,r+2),qu.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],s=Dt(t,e);e+=2;let a=0;for(;s>0;)n[a++]=bd.decode(t,e),e+=bd.decode.bytes,s-=bd.decode.bytes;return qu.decode.bytes=e-r,n},encodingLength(t){return 2+Nh(t||[],bd)}}),bc=jr({encode(t,e,r){e||(e=new Uint8Array(bc.encodingLength(t))),r||(r=0);let n=r,s=t.key;if(!Af(s))throw new Error("Key must be a Buffer");return r+=2,Xe(e,t.flags,r),r+=2,e[r]=bc.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,mo(s,e,r,0,s.length),r+=s.length,bc.encode.bytes=r-n,Xe(e,bc.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);if(e+=2,n.flags=Dt(t,e),e+=2,t[e]!==bc.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t[e],e+=1,n.key=t.slice(e,r+s+2),e+=n.key.length,bc.decode.bytes=e-r,n},encodingLength(t){return 6+Vu(t.key)}});bc.PROTOCOL_DNSSEC=3;bc.ZONE_KEY=128;bc.SECURE_ENTRYPOINT=32768;var sw=jr({encode(t,e,r){e||(e=new Uint8Array(sw.encodingLength(t))),r||(r=0);let n=r,s=t.signature;if(!Af(s))throw new Error("Signature must be a Buffer");return r+=2,Xe(e,xw(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,Sd(e,t.originalTTL,r),r+=4,Sd(e,t.expiration,r),r+=4,Sd(e,t.inception,r),r+=4,Xe(e,t.keyTag,r),r+=2,Fe.encode(t.signersName,e,r),r+=Fe.encode.bytes,mo(s,e,r,0,s.length),r+=s.length,sw.encode.bytes=r-n,Xe(e,sw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);return e+=2,n.typeCovered=cP(Dt(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=xd(t,e),e+=4,n.expiration=xd(t,e),e+=4,n.inception=xd(t,e),e+=4,n.keyTag=Dt(t,e),e+=2,n.signersName=Fe.decode(t,e),e+=Fe.decode.bytes,n.signature=t.slice(e,r+s+2),e+=n.signature.length,sw.decode.bytes=e-r,n},encodingLength(t){return 20+Fe.encodingLength(t.signersName)+Vu(t.signature)}}),iw=jr({encode(t,e,r){e||(e=new Uint8Array(iw.encodingLength(t))),r||(r=0);let n=r;return r+=2,Fe.encode(t.mbox||".",e,r),r+=Fe.encode.bytes,Fe.encode(t.txt||".",e,r),r+=Fe.encode.bytes,iw.encode.bytes=r-n,Xe(e,iw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=Fe.decode(t,e)||".",e+=Fe.decode.bytes,n.txt=Fe.decode(t,e)||".",e+=Fe.decode.bytes,iw.decode.bytes=e-r,n},encodingLength(t){return 2+Fe.encodingLength(t.mbox||".")+Fe.encodingLength(t.txt||".")}}),ho=jr({encode(t,e,r){e||(e=new Uint8Array(ho.encodingLength(t))),r||(r=0);let n=r,s=[];for(let a=0;a<t.length;a++){let o=xw(t[a]);s[o>>8]===void 0&&(s[o>>8]=[]),s[o>>8][o>>3&31]|=1<<7-(o&7)}for(let a=0;a<s.length;a++)if(s[a]!==void 0){let o=cA(s[a]);e[r]=a,r+=1,e[r]=o.length,r+=1,mo(o,e,r,0,o.length),r+=o.length}return ho.encode.bytes=r-n,e},decode(t,e,r){e||(e=0);let n=e,s=[];for(;e-n<r;){let a=t[e];e+=1;let o=t[e];e+=1;for(let i=0;i<o;i++){let c=t[e+i];for(let u=0;u<8;u++)if(c&1<<7-u){let d=cP(a<<8|i<<3|u);s.push(d)}}e+=o}return ho.decode.bytes=e-n,s},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let s=xw(t[n]);e[s>>8]=Math.max(e[s>>8]||0,s&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}}),ow=jr({encode(t,e,r){e||(e=new Uint8Array(ow.encodingLength(t))),r||(r=0);let n=r;return r+=2,Fe.encode(t.nextDomain,e,r),r+=Fe.encode.bytes,ho.encode(t.rrtypes,e,r),r+=ho.encode.bytes,ow.encode.bytes=r-n,Xe(e,ow.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);return e+=2,n.nextDomain=Fe.decode(t,e),e+=Fe.decode.bytes,n.rrtypes=ho.decode(t,e,s-(e-r)),e+=ho.decode.bytes,ow.decode.bytes=e-r,n},encodingLength(t){return 2+Fe.encodingLength(t.nextDomain)+ho.encodingLength(t.rrtypes)}}),aw=jr({encode(t,e,r){e||(e=new Uint8Array(aw.encodingLength(t))),r||(r=0);let n=r,s=t.salt;if(!Af(s))throw new Error("salt must be a Buffer");let a=t.nextDomain;if(!Af(a))throw new Error("nextDomain must be a Buffer");return r+=2,e[r]=t.algorithm,r+=1,e[r]=t.flags,r+=1,Xe(e,t.iterations,r),r+=2,e[r]=s.length,r+=1,mo(s,e,r,0,s.length),r+=s.length,e[r]=a.length,r+=1,mo(a,e,r,0,a.length),r+=a.length,ho.encode(t.rrtypes,e,r),r+=ho.encode.bytes,aw.encode.bytes=r-n,Xe(e,aw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=Dt(t,e),e+=2;let a=t[e];e+=1,n.salt=t.slice(e,e+a),e+=a;let o=t[e];return e+=1,n.nextDomain=t.slice(e,e+o),e+=o,n.rrtypes=ho.decode(t,e,s-(e-r)),e+=ho.decode.bytes,aw.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+ho.encodingLength(t.rrtypes)}}),cw=jr({encode(t,e,r){e||(e=new Uint8Array(cw.encodingLength(t))),r||(r=0);let n=r,s=t.digest;if(!Af(s))throw new Error("Digest must be a Buffer");return r+=2,Xe(e,t.keyTag,r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.digestType,r+=1,mo(s,e,r,0,s.length),r+=s.length,cw.encode.bytes=r-n,Xe(e,cw.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},s=Dt(t,e);return e+=2,n.keyTag=Dt(t,e),e+=2,n.algorithm=t[e],e+=1,n.digestType=t[e],e+=1,n.digest=t.slice(e,r+s+2),e+=n.digest.length,cw.decode.bytes=e-r,n},encodingLength(t){return 6+Vu(t.digest)}}),Bh=jr({encode(t,e,r){e||(e=new Uint8Array(Bh.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let s=oU(t.fingerprint),a=kI(t.hash);if(s!==a)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${s} != ${a}`);return rce(e,t.fingerprint,r,r+=s),Bh.encode.bytes=r-n,Xe(e,Bh.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 s=kI(n.hash);return n.fingerprint=tce(t,e,e+s),e+=s,Bh.decode.bytes=e-r,n},encodingLength(t){return 4+oU(t.fingerprint)}});function kI(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}Bh.getFingerprintLengthForHashType=kI;function fI(t){switch(t.toUpperCase()){case"A":return mK;case"PTR":return Lh;case"CNAME":return Lh;case"DNAME":return Lh;case"TXT":return T1;case"NULL":return I1;case"AAAA":return C1;case"SRV":return R1;case"HINFO":return A1;case"CAA":return zu;case"NS":return _1;case"SOA":return k1;case"MX":return D1;case"OPT":return qu;case"DNSKEY":return bc;case"RRSIG":return sw;case"RP":return iw;case"NSEC":return ow;case"NSEC3":return aw;case"SSHFP":return Bh;case"DS":return cw}return E1}var Ko=jr({encode(t,e,r){e||(e=new Uint8Array(Ko.encodingLength(t))),r||(r=0);let n=r;if(Fe.encode(t.name,e,r),r+=Fe.encode.bytes,Xe(e,xw(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");Xe(e,t.udpPayloadSize||4096,r+2),e[r+4]=t.extendedRcode||0,e[r+5]=t.ednsVersion||0,Xe(e,t.flags||0,r+6),r+=8,qu.encode(t.options||[],e,r),r+=qu.encode.bytes}else{let s=lK(t.class===void 0?"IN":t.class);t.flush&&(s|=_I),Xe(e,s,r+2),Sd(e,t.ttl||0,r+4),r+=8;let a=fI(t.type);a.encode(t.data,e,r),r+=a.encode.bytes}return Ko.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={},n=e;if(r.name=Fe.decode(t,e),e+=Fe.decode.bytes,r.type=cP(Dt(t,e)),r.type==="OPT")r.udpPayloadSize=Dt(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=Dt(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=qu.decode(t,e+8),e+=8+qu.decode.bytes;else{let s=Dt(t,e+2);r.ttl=xd(t,e+4),r.class=uK(s&cce),r.flush=!!(s&_I);let a=fI(r.type);r.data=a.decode(t,e+8),e+=8+a.decode.bytes}return Ko.decode.bytes=e-n,r},encodingLength(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Fe.encodingLength(t.name)+8+fI(t.type).encodingLength(e)}}),Kh=jr({encode(t,e,r){e||(e=new Uint8Array(Kh.encodingLength(t))),r||(r=0);let n=r;return Fe.encode(t.name,e,r),r+=Fe.encode.bytes,Xe(e,xw(t.type),r),r+=2,Xe(e,lK(t.class===void 0?"IN":t.class),r),r+=2,Kh.encode.bytes=r-n,t},decode(t,e){e||(e=0);let r=e,n={};return n.name=Fe.decode(t,e),e+=Fe.decode.bytes,n.type=cP(Dt(t,e)),e+=2,n.class=uK(Dt(t,e)),e+=2,n.class&hK&&(n.class&=dce),Kh.decode.bytes=e-r,n},encodingLength(t){return Fe.encodingLength(t.name)+4}}),uce=1024,Os={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(lce(t))),r||(r=0);let s=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),jh.encode(t,e,r),r+=jh.encode.bytes,r=dw(t.questions,Kh,e,r),r=dw(t.answers,Ko,e,r),r=dw(t.authorities,Ko,e,r),r=dw(t.additionals,Ko,e,r),Os.encode.bytes=r-s,n&&Z1.bytes!==e.length?e.slice(0,Z1.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=jh.decode(t,e);return e+=jh.decode.bytes,e=y1(n.questions,Kh,t,e),e=y1(n.answers,Ko,t,e),e=y1(n.authorities,Ko,t,e),e=y1(n.additionals,Ko,t,e),Os.decode.bytes=e-r,n},encodingLength:function(t){return jh.encodingLength(t)+Nh(t.questions||[],Kh)+Nh(t.answers||[],Ko)+Nh(t.authorities||[],Ko)+Nh(t.additionals||[],Ko)}};Os.encode.bytes=0;Os.decode.bytes=0;function V1(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}var H1={encode:function(t,e,r){return e=Os.encode(V1(t,"query"),e,r),H1.encode.bytes=Os.encode.bytes,e},decode:function(t,e){let r=Os.decode(t,e);return H1.decode.bytes=Os.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Os.encodingLength(V1(t,"query"))}};H1.encode.bytes=0;H1.decode.bytes=0;var J1={encode:function(t,e,r){return e=Os.encode(V1(t,"response"),e,r),J1.encode.bytes=Os.encode.bytes,e},decode:function(t,e){let r=Os.decode(t,e);return J1.decode.bytes=Os.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Os.encodingLength(V1(t,"response"))}};J1.encode.bytes=0;J1.decode.bytes=0;var Z1=Os.encode,TI=Os.decode,lce=Os.encodingLength;function yK(t){let e=Z1(t),r=new Uint8Array(2+e.byteLength);return Xe(r,e.byteLength),mo(e,r,2,0,e.length),yK.bytes=r.byteLength,r}yK.bytes=0;function gK(t){let e=Dt(t,0);if(t.byteLength<e+2)return null;let r=TI(t.slice(2));return gK.bytes=TI.bytes,r}gK.bytes=0;function Nh(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function dw(t,e,r,n){for(let s=0;s<t.length;s++)e.encode(t[s],r,n),n+=e.encode.bytes;return n}function y1(t,e,r,n){for(let s=0;s<t.length;s++)t[s]=e.decode(r,n),n+=e.decode.bytes;return n}function wK(t,e){let r=Qe.uint8Array(t).toBase32Z();return new URL(r,e).href}async function fce({gatewayUri:t,publicKeyBytes:e}){let r=Qe.uint8Array(e).toBase32Z(),n=wK(e,t),s;try{if(s=await fetch(n,{method:"GET",signal:AbortSignal.timeout(3e4)}),!s.ok)throw new Ze("notFound",`Pkarr record not found for: ${r}`)}catch(o){throw o instanceof Ze?o:new Ze("internalError",`Failed to fetch Pkarr record: ${o.message}`)}let a=await s.arrayBuffer();if(!a)throw new Ze("notFound",`Pkarr record not found for: ${r}`);if(a.byteLength<72)throw new Ze("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${a.byteLength}`);if(a.byteLength>1072)throw new Ze("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 pce({gatewayUri:t,bep44Message:e}){let r=Qe.uint8Array(e.k).toBase32Z(),n=wK(e.k,t),s=new Uint8Array(e.v.length+72);s.set(e.sig,0),new DataView(s.buffer).setBigUint64(e.sig.length,BigInt(e.seq)),s.set(e.v,e.sig.length+8);let a;try{a=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:s,signal:AbortSignal.timeout(3e4)})}catch(o){throw new Ze("internalError",`Failed to put Pkarr record for identifier ${r}: ${o.message}`)}return a.ok}async function hce({dnsPacket:t,publicKeyBytes:e,signer:r}){let n=Math.ceil(Date.now()/1e3),s=Z1(t),a=cK.encode({seq:n,v:s}).subarray(1,-1);if(a.length>1e3)throw new Ze("invalidDidDocumentLength",`DNS packet exceeds the 1000 byte maximum size: ${a.length} bytes`);let o=await r.sign({data:new Uint8Array(a)});return{k:e,seq:n,sig:o,v:s}}async function mce({bep44Message:t}){let e=await $s.bytesToPublicKey({publicKeyBytes:t.k}),r=cK.encode({seq:t.seq,v:t.v}).subarray(1,-1);if(!await $s.verify({key:e,signature:t.sig,data:new Uint8Array(r)}))throw new Ze("invalidSignature","Invalid signature for DHT BEP44 message");return TI(t.v)}var vK="dht";async function bK({didUri:t}){let e=uA({didUri:t});return await $s.bytesToPublicKey({publicKeyBytes:e})}function uA({didUri:t}){let e=us.parse(t);if(!e)throw new Ze("invalidDid",`Invalid DID URI: ${t}`);if(e.method!==vK)throw new Ze("methodNotSupported",`Method not supported: ${e.method}`);let r;try{r=Qe.base32Z(e.id).toUint8Array()}catch{throw new Ze("invalidPublicKey","Failed to decode method-specific identifier")}if(r.length!==32)throw new Ze("invalidPublicKeyLength",`Invalid public key length: ${r.length}`);return r}async function yce({identityKey:t}){let e=await $s.publicKeyToBytes({publicKey:t}),r=Qe.uint8Array(e).toBase32Z();return`did:${vK}:${r}`}function lA(t){let e={Ed25519:$s,"P-256":{publicKeyToBytes:async({publicKey:r})=>{let n=await Xs.publicKeyToBytes({publicKey:r});return await Xs.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:Xs.bytesToPublicKey,privateKeyToBytes:Xs.privateKeyToBytes,bytesToPrivateKey:Xs.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:r})=>{let n=await js.publicKeyToBytes({publicKey:r});return await js.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:js.bytesToPublicKey,privateKeyToBytes:js.privateKeyToBytes,bytesToPrivateKey:js.bytesToPrivateKey},X25519:Ch}[t];if(!e)throw new Ze("invalidPublicKeyType",`Unsupported curve: ${t}`);return e}async function PK({newDid:t,previousDidProof:e}){let r=await bK({didUri:e.previousDid}),n=uA({didUri:t}),s=Qe.base64Url(e.signature).toUint8Array();if(!await $s.verify({key:r,data:n,signature:s}))throw new Ze("invalidPreviousDidProof","The previous DID proof is invalid.")}var gce=0,Nu=7200,j1=";",Si=",",xK={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},SK={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};function Ew(t){if(typeof t=="string")return t;if(t instanceof Uint8Array)return Qe.uint8Array(t).toString();if(Array.isArray(t))return t.map(e=>Ew(e)).join("");throw new Ze("internalError","Pkarr returned DNS TXT record with invalid data type")}function uw(t){return Ew(t).split(j1).reduce((e,r)=>{let[n,s]=r.split("=");return e[n]=s,e},{})}function EK(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 wce({didUri:t,dnsPacket:e}){let r={id:t},n={published:!0},s=new Map;for(let a of e?.answers??[]){if(a.type!=="TXT")continue;let o=a.name.split(".")[0].substring(1);switch(!0){case o.startsWith("aka"):{let i=Ew(a.data);r.alsoKnownAs=i.split(Si);break}case o.startsWith("cnt"):{let i=Ew(a.data);r.controller=i.includes(Si)?i.split(Si):i;break}case o.startsWith("k"):{let{id:i,t:c,k:u,c:d,a:l}=uw(a.data),f=Qe.base64Url(u).toUint8Array(),h=oA[Number(c)],p=await lA(h).bytesToPublicKey({publicKeyBytes:f});p.alg=l||SK[Number(c)];let m=o==="k0"?"0":i!==void 0?i:await fr({jwk:p});r.verificationMethod??=[];let y=`${t}#${m}`;r.verificationMethod.push({id:y,type:"JsonWebKey",controller:d??t,publicKeyJwk:p}),s.set(o,y);break}case o.startsWith("s"):{let{id:i,t:c,se:u,...d}=uw(a.data),l=u.includes(Si)?u.split(Si):[u],f=Object.fromEntries(Object.entries(d).map(([h,p])=>[h,p.includes(Si)?p.split(Si):p]));r.service??=[],r.service.push({...f,id:`${t}#${i}`,type:c,serviceEndpoint:l});break}case o.startsWith("typ"):{let{id:i}=uw(a.data);n.types=i.split(Si).map(c=>Number(c));break}case o.startsWith("did"):{let i=h=>h.split(Si).map(p=>s.get(p)).filter(p=>typeof p=="string"),{auth:c,asm:u,del:d,inv:l,agm:f}=uw(a.data);c&&(r.authentication=i(c)),u&&(r.assertionMethod=i(u)),d&&(r.capabilityDelegation=i(d)),l&&(r.capabilityInvocation=i(l)),f&&(r.keyAgreement=i(f));break}}}return{didDocument:r,didDocumentMetadata:n,didResolutionMetadata:{}}}async function vce({didDocument:t,didMetadata:e,authoritativeGatewayUris:r,previousDidProof:n}){let s=[],a=[],o=new Map,i=[],c=[];if(n!==void 0){let{signature:d,previousDid:l}=n;await PK({newDid:t.id,previousDidProof:n}),s.push({type:"TXT",name:"_prv._did.",ttl:Nu,data:`id=${l};s=${d}`})}if(t.alsoKnownAs&&s.push({type:"TXT",name:"_aka._did.",ttl:Nu,data:t.alsoKnownAs.join(Si)}),t.controller){let d=Array.isArray(t.controller)?t.controller.join(Si):t.controller;s.push({type:"TXT",name:"_cnt._did.",ttl:Nu,data:d})}for(let[d,l]of t.verificationMethod?.entries()??[]){let f=`k${d}`;c.push(f);let h=l.id.split("#").pop();o.set(h,f);let p=l.publicKeyJwk;if(!(p?.crv&&p.crv in xK))throw new Ze("invalidPublicKeyType",`Verification method '${l.id}' contains an unsupported key type: ${p?.crv??"undefined"}`);let m=oA[p.crv],y=await lA(p.crv).publicKeyToBytes({publicKey:p}),S=Qe.uint8Array(y).toBase64Url(),v=[`t=${m}`,`k=${S}`];h!=="0"&&await fr({jwk:p})!==h&&v.unshift(`id=${h}`),p.alg!==SK[m]&&v.push(`a=${p.alg}`),l.controller!==t.id&&v.push(`c=${l.controller}`),s.push({type:"TXT",name:`_${f}._did.`,ttl:Nu,data:v.join(j1)})}t.service?.forEach((d,l)=>{let f=`s${l}`;i.push(f);let{id:h,type:p,serviceEndpoint:m,...y}=d;h=Ei(h),m=Array.isArray(m)?m.join(","):m;let S=Object.entries({id:h,t:p,se:m,...y}).map(([E,k])=>`${E}=${k}`).join(j1),v=EK(S);s.push({type:"TXT",name:`_${f}._did.`,ttl:Nu,data:v})});let u=[`v=${gce}`];if(c.length&&u.push(`vm=${c.join(Si)}`),Object.keys(eP).forEach(d=>{let l=t[d]?.map(f=>o.get(f.split("#").pop()));if(l){let f=eK[d];u.push(`${f}=${l.join(Si)}`)}}),i.length&&u.push(`svc=${i.join(Si)}`),e.types?.length){let d=e.types.map(l=>typeof l=="string"?XL[l]:l);s.push({type:"TXT",name:"_typ._did.",ttl:Nu,data:`id=${d.join(Si)}`})}s.push({type:"TXT",name:"_did."+dU(t.id)+".",ttl:Nu,data:u.join(j1)});for(let d of r||[])a.push({type:"NS",name:"_did."+dU(t.id)+".",ttl:Nu,data:d+"."});return{id:0,type:"response",flags:uce,answers:[...s,...a]}}function dU(t){return t.split(":")[2]}var uU=U.DID_DHT_GATEWAY_URI||"https://enbox-did-dht.fly.dev",_K=class II extends Dw{static async create({keyManager:e=new Ia,options:r={}}={}){if(r.verificationMethods?.some(d=>!(d.algorithm in xK)))throw new Error("One or more verification method algorithms are not supported");let n=r.verificationMethods?.filter(d=>"id"in d).map(d=>d.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(r.services?.some(d=>!d.id||!d.type||!d.serviceEndpoint))throw new Error("One or more services are missing required properties");let s=await e.generateKey({algorithm:"Ed25519"}),a=await e.getPublicKey({keyUri:s}),o=await Uh.identityKeyToIdentifier({identityKey:a}),i={id:o,...r.alsoKnownAs&&{alsoKnownAs:r.alsoKnownAs},...r.controllers&&{controller:r.controllers}},c=[...r.verificationMethods??[]];c?.some(d=>d.id?.split("#").pop()==="0")||c.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let d of c){let l=d.id&&d.id.split("#").pop()==="0"?s:await e.generateKey({algorithm:d.algorithm}),f=await e.getPublicKey({keyUri:l}),h=d.id??f.kid??await fr({jwk:f});h=`${o}#${Ei(h)}`,i.verificationMethod??=[],i.verificationMethod.push({id:h,type:"JsonWebKey",controller:d.controller??o,publicKeyJwk:f});for(let p of d.purposes??[])i[p]??=[],i[p].push(h)}r.services?.forEach(d=>{i.service??=[],d.id=`${o}#${d.id.split("#").pop()}`,i.service.push(d)});let u=new Ec({uri:o,document:i,metadata:{published:!1,...r.types&&{types:r.types}},keyManager:e});if(r.publish??!0){let d=await II.publish({did:u,gatewayUri:r.gatewayUri});u.metadata=d.didDocumentMetadata}return u}static async import({portableDid:e,keyManager:r=new Ia}){if(us.parse(e.uri)?.method!==II.methodName)throw new Ze("methodNotSupported","Method not supported");let n=await Ec.import({portableDid:e,keyManager:r});if(!n.document.verificationMethod?.some(s=>s.id?.split("#").pop()==="0"))throw new Ze("invalidDidDocument","DID document must contain an Identity Key");return n}static async getSigningMethod({didDocument:e,methodId:r="#0"}){let n=us.parse(e.id);if(n&&n.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${n.method}`);let s=e.verificationMethod?.find(a=>Ei(a.id)===(Ei(r)??Ei(e.assertionMethod?.[0])));if(!(s&&s.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async publish({did:e,gatewayUri:r=uU}){return await lU.put({did:e,gatewayUri:r})}static async resolve(e,r={}){let n=r?.gatewayUri??uU;try{await Uh.identifierToIdentityKey({didUri:e});let{didDocument:s,didDocumentMetadata:a}=await lU.get({didUri:e,gatewayUri:n});return{...ds,didDocument:s,didDocumentMetadata:a}}catch(s){if(!(s instanceof Ze))throw new Error(s);return{...ds,didResolutionMetadata:{error:s.code,...s.message&&{errorMessage:s.message}}}}}};_K.methodName="dht";var kK=_K,lU=class lw{static async get({didUri:e,gatewayUri:r}){let n=Uh.identifierToIdentityKeyBytes({didUri:e}),s=await lw.pkarrGet({gatewayUri:r,publicKeyBytes:n}),a=await Uh.parseBep44GetMessage({bep44Message:s}),o=await lw.fromDnsPacket({didUri:e,dnsPacket:a});return o.didDocumentMetadata.versionId=s.seq.toString(),o}static async put({did:e,gatewayUri:r}){let n=await lw.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[r]}),s=await Uh.createBep44PutMessage({dnsPacket:n,publicKeyBytes:Uh.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),a=await lw.pkarrPut({gatewayUri:r,bep44Message:s});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:a,versionId:s.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return fce(e)}static async pkarrPut(e){return pce(e)}static async fromDnsPacket(e){return wce(e)}static async toDnsPacket(e){return vce(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},Uh=class{static async createBep44PutMessage(t){return hce(t)}static async identifierToIdentityKey(t){return bK(t)}static identifierToIdentityKeyBytes(t){return uA(t)}static async identityKeyToIdentifier(t){return yce(t)}static keyConverter(t){return lA(t)}static async parseBep44GetMessage(t){return mce(t)}static parseTxtDataToObject(t){return uw(t)}static parseTxtDataToString(t){return Ew(t)}static async validatePreviousDidProof(t){return PK(t)}static chunkDataIfNeeded(t){return EK(t)}},In={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"},An=class extends Error{constructor(t,e){super(`${t}: ${e}`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}},O$e=new Uint8Array(0),bce=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")},Pce=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")}},xce=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 TK(this,t)}},Sce=class{constructor(t){this.decoders=t}or(t){return TK(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`)}},TK=(t,e)=>new Sce({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Ece=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new Pce(t,e,r),this.decoder=new xce(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},_ce=({name:t,prefix:e,encode:r,decode:n})=>new Ece(t,e,r,n),kce=(t,e,r,n)=>{let s={};for(let d=0;d<e.length;++d)s[e[d]]=d;let a=t.length;for(;t[a-1]==="=";)--a;let o=new Uint8Array(a*r/8|0),i=0,c=0,u=0;for(let d=0;d<a;++d){let l=s[t[d]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|l,i+=r,i>=8&&(i-=8,o[u++]=255&c>>i)}if(i>=r||255&c<<8-i)throw new SyntaxError("Unexpected end of data");return o},Tce=(t,e,r)=>{let n=e[e.length-1]==="=",s=(1<<r)-1,a="",o=0,i=0;for(let c=0;c<t.length;++c)for(i=i<<8|t[c],o+=8;o>r;)o-=r,a+=e[s&i>>o];if(o&&(a+=e[s&i<<r-o]),n)for(;a.length*r&7;)a+="=";return a},dP=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>_ce({prefix:e,name:t,encode(s){return Tce(s,n,r)},decode(s){return kce(s,n,r,t)}}),B$e=dP({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),N$e=dP({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fU=dP({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),U$e=dP({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Gh=class $1{static encode(e){return fU.baseEncode(e)}static decodeAsBytes(e,r){if(!$1.isBase64UrlString(e))throw new An(In.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return fU.baseDecode(e)}static decodeAsString(e,r){let n=$1.decodeAsBytes(e,r);return $1.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)}},Ice=Rf(_ne(),1),AI;(function(t){t.Public="public",t.Private="private"})(AI||(AI={}));var vc=AI,lo=class{static validateEs256kOperationKey(t,e){let r=new Set(["kty","crv","x","y"]);e===vc.Private&&r.add("d");for(let n in t)if(!r.has(n))throw new An(In.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${n}'.`);if(t.crv!=="secp256k1")throw new An(In.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${t.crv}.'`);if(t.kty!=="EC")throw new An(In.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${t.kty}.'`);if(t.x.length!==43)throw new An(In.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(t.y.length!==43)throw new An(In.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(e===vc.Private&&(t.d===void 0||t.d.length!==43))throw new An(In.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(t){if(t.length>50)throw new An(In.IdTooLong,`Key ID length ${t.length} exceed max allowed length of 50.`);if(!Gh.isBase64UrlString(t))throw new An(In.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 An(In.PublicKeyPurposeDuplicated,`Public key purpose '${r}' already specified.`);e.add(r)}}},fA=class{};fA.hashAlgorithmInMultihashCode=18;fA.maxCanonicalizedDeltaSizeInBytes=1e3;var Ta=fA,Ace=Rf(kne(),1),_w=class RI{static canonicalizeAsBytes(e){let r=RI.removeAllUndefinedProperties(e),n=Ace.default(r);return Gh.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let r in e)typeof e[r]=="object"?RI.removeAllUndefinedProperties(e[r]):e[r]===void 0&&delete e[r];return e}},Rce=IK,pU=128,Dce=127,Cce=~Dce,jce=Math.pow(2,31);function IK(t,e,r){e=e||[],r=r||0;for(var n=r;t>=jce;)e[r++]=t&255|pU,t/=128;for(;t&Cce;)e[r++]=t&255|pU,t>>>=7;return e[r]=t|0,IK.bytes=r-n+1,e}var $ce=DI,Mce=128,hU=127;function DI(t,n){var r=0,n=n||0,s=0,a=n,o,i=t.length;do{if(a>=i)throw DI.bytes=0,new RangeError("Could not decode varint");o=t[a++],r+=s<28?(o&hU)<<s:(o&hU)*Math.pow(2,s),s+=7}while(o>=Mce);return DI.bytes=a-n,r}var Oce=Math.pow(2,7),Bce=Math.pow(2,14),Nce=Math.pow(2,21),Uce=Math.pow(2,28),Lce=Math.pow(2,35),Kce=Math.pow(2,42),zce=Math.pow(2,49),qce=Math.pow(2,56),Fce=Math.pow(2,63),Gce=function(t){return t<Oce?1:t<Bce?2:t<Nce?3:t<Uce?4:t<Lce?5:t<Kce?6:t<zce?7:t<qce?8:t<Fce?9:10},Wce={encode:Rce,decode:$ce,encodingLength:Gce},Vce=Wce,Y1=Vce,mU=(t,e=0)=>[Y1.decode(t,e),Y1.decode.bytes],yU=(t,e,r=0)=>(Y1.encode(t,e,r),e),gU=t=>Y1.encodingLength(t),wU=(t,e)=>{let r=e.byteLength,n=gU(t),s=n+gU(r),a=new Uint8Array(s+r);return yU(t,a,0),yU(r,a,n),a.set(e,s),new AK(t,r,e,a)},Hce=t=>{let e=bce(t),[r,n]=mU(e),[s,a]=mU(e.subarray(n)),o=e.subarray(n+a);if(o.byteLength!==s)throw new Error("Incorrect length");return new AK(r,s,o,e)},AK=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},RK=({name:t,code:e,encode:r})=>new Jce(t,e,r),Jce=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?wU(this.code,e):e.then(r=>wU(this.code,r))}else throw Error("Unknown type, must be binary type")}},DK=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),vU=RK({name:"sha2-256",code:18,encode:DK("SHA-256")}),L$e=RK({name:"sha2-512",code:19,encode:DK("SHA-512")}),Qg=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},po=class fw{static hash(e,r){return Qg(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield vU.digest(e)).bytes;break;default:throw new An(In.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return Qg(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield vU.encode(e);break;default:throw new An(In.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return Qg(this,void 0,void 0,function*(){let n=_w.canonicalizeAsBytes(e);return yield fw.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return Qg(this,void 0,void 0,function*(){let n=_w.canonicalizeAsBytes(e),s=yield fw.hashAsNonMultihashBytes(n,r);return yield fw.hashThenEncode(s,r)})}static hashThenEncode(e,r){return Qg(this,void 0,void 0,function*(){let n=yield fw.hash(e,r);return Gh.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,s=Gh.decodeAsBytes(e,r);try{n=Hce(s)}catch{throw new An(In.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let a=Ta.hashAlgorithmInMultihashCode;if(a!==n.code)throw new An(In.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${a} or change IonSdkConfig to desired hashing algorithm.`)}},CI;(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(CI||(CI={}));var g1=CI,jI;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})(jI||(jI={}));var Dh=jI,w1=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},CK=class Uo{static createCreateRequest(e){return w1(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,s=e.document.publicKeys,a=e.document.services;lo.validateEs256kOperationKey(r,vc.Public),lo.validateEs256kOperationKey(n,vc.Public),Uo.validateDidDocumentKeys(s),Uo.validateServices(a);let o=Ta.hashAlgorithmInMultihashCode,i=[{action:Dh.Replace,document:e.document}],c={updateCommitment:yield po.canonicalizeThenDoubleHashThenEncode(n,o),patches:i};Uo.validateDeltaSize(c);let u={deltaHash:yield po.canonicalizeThenHashThenEncode(c,o),recoveryCommitment:yield po.canonicalizeThenDoubleHashThenEncode(r,o)};return{type:g1.Create,suffixData:u,delta:c}})}static createDeactivateRequest(e){return w1(this,void 0,void 0,function*(){Uo.validateDidSuffix(e.didSuffix),lo.validateEs256kOperationKey(e.recoveryPublicKey,vc.Public);let r=Ta.hashAlgorithmInMultihashCode,n=yield po.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),s={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},a=yield e.signer.sign({alg:"ES256K"},s);return{type:g1.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:a}})}static createRecoverRequest(e){return w1(this,void 0,void 0,function*(){Uo.validateDidSuffix(e.didSuffix),lo.validateEs256kOperationKey(e.recoveryPublicKey,vc.Public),lo.validateEs256kOperationKey(e.nextRecoveryPublicKey,vc.Public),lo.validateEs256kOperationKey(e.nextUpdatePublicKey,vc.Public),Uo.validateDidDocumentKeys(e.document.publicKeys),Uo.validateServices(e.document.services);let r=Ta.hashAlgorithmInMultihashCode,n=yield po.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),s=[{action:Dh.Replace,document:e.document}],a=yield po.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),o={patches:s,updateCommitment:a},i=yield po.canonicalizeThenHashThenEncode(o,r),c={recoveryCommitment:yield po.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,r),recoveryKey:e.recoveryPublicKey,deltaHash:i},u=yield e.signer.sign({alg:"ES256K"},c);return{type:g1.Recover,didSuffix:e.didSuffix,revealValue:n,delta:o,signedData:u}})}static createUpdateRequest(e){return w1(this,void 0,void 0,function*(){if(Uo.validateDidSuffix(e.didSuffix),lo.validateEs256kOperationKey(e.updatePublicKey,vc.Public),lo.validateEs256kOperationKey(e.nextUpdatePublicKey,vc.Public),Uo.validateServices(e.servicesToAdd),Uo.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let p of e.idsOfServicesToRemove)lo.validateId(p);if(e.idsOfPublicKeysToRemove!==void 0)for(let p of e.idsOfPublicKeysToRemove)lo.validateId(p);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let p={action:Dh.AddServices,services:n};r.push(p)}let s=e.idsOfServicesToRemove;if(s!==void 0&&s.length>0){let p={action:Dh.RemoveServices,ids:s};r.push(p)}let a=e.publicKeysToAdd;if(a!==void 0&&a.length>0){let p={action:Dh.AddPublicKeys,publicKeys:a};r.push(p)}let o=e.idsOfPublicKeysToRemove;if(o!==void 0&&o.length>0){let p={action:Dh.RemovePublicKeys,ids:o};r.push(p)}let i=Ta.hashAlgorithmInMultihashCode,c=yield po.canonicalizeThenHashThenEncode(e.updatePublicKey,i),u=yield po.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,i),d={patches:r,updateCommitment:u},l=yield po.canonicalizeThenHashThenEncode(d,i),f={updateKey:e.updatePublicKey,deltaHash:l},h=yield e.signer.sign({alg:"ES256K"},f);return{type:g1.Update,didSuffix:e.didSuffix,revealValue:c,delta:d,signedData:h}})}static validateDidSuffix(e){po.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 An(In.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(lo.validateId(n.id),r.has(n.id))throw new An(In.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);r.add(n.id),lo.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let r=new Set;for(let n of e){if(Uo.validateService(n),r.has(n.id))throw new An(In.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){lo.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 An(In.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new An(In.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&Ice.parse(e.serviceEndpoint).error!==void 0)throw new An(In.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=_w.canonicalizeAsBytes(e);if(r.length>Ta.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${Ta.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new An(In.DeltaExceedsMaximumSize,n)}}},bU=function(t,e,r,n){function s(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function i(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):s(d.value).then(i,c)}u((n=n.apply(t,e||[])).next())})},Zce=class jK{static createLongFormDid(e){return bU(this,void 0,void 0,function*(){let r=yield CK.createCreateRequest(e),n=yield jK.computeDidUniqueSuffix(r.suffixData),s;Ta.network===void 0||Ta.network==="mainnet"?s=`did:ion:${n}`:s=`did:ion:${Ta.network}:${n}`;let a={suffixData:r.suffixData,delta:r.delta},o=_w.canonicalizeAsBytes(a),i=Gh.encode(o);return`${s}:${i}`})}static computeDidUniqueSuffix(e){return bU(this,void 0,void 0,function*(){let r=_w.canonicalizeAsBytes(e),n=yield po.hash(r,Ta.hashAlgorithmInMultihashCode);return Gh.encode(n)})}},Cs=2n**255n-19n,M1=2n**252n+27742317777372353535851937790883648493n,$I=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,MI=0x6666666666666666666666666666666666666666666666666666666666666658n,v1={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Cs,n:M1,h:8,Gx:$I,Gy:MI},Ui=(t="")=>{throw new Error(t)},$K=t=>typeof t=="string",pA=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?Ui("Uint8Array expected"):t,Wh=t=>new Uint8Array(t),Yce=(t,e)=>pA($K(t)?mA(t):Wh(t),e),nt=(t,e=Cs)=>{let r=t%e;return r>=0n?r:e+r},PU=t=>t instanceof Vh?t:Ui("Point expected"),xU,Vh=class $h{constructor(e,r,n,s){this.ex=e,this.ey=r,this.ez=n,this.et=s}static fromAffine(e){return new $h(e.x,e.y,1n,nt(e.x*e.y))}static fromHex(e,r=!0){let{d:n}=v1;e=Yce(e,32);let s=e.slice();s[31]=e[31]&-129;let a=Xce(s);a===0n||(r&&!(0n<a&&a<Cs)&&Ui("bad y coord 1"),!r&&!(0n<a&&a<2n**256n)&&Ui("bad y coord 2"));let o=nt(a*a),i=nt(o-1n),c=nt(n*o+1n),{isValid:u,value:d}=tde(i,c);u||Ui("bad y coordinate 3");let l=(d&1n)===1n;return(e[31]&128)!==0!==l&&(d=nt(-d)),new $h(d,a,1n,nt(d*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){let{ex:r,ey:n,ez:s}=this,{ex:a,ey:o,ez:i}=PU(e),c=nt(r*i),u=nt(a*s),d=nt(n*i),l=nt(o*s);return c===u&&d===l}is0(){return this.equals(O1)}negate(){return new $h(nt(-this.ex),this.ey,this.ez,nt(-this.et))}double(){let{ex:e,ey:r,ez:n}=this,{a:s}=v1,a=nt(e*e),o=nt(r*r),i=nt(2n*nt(n*n)),c=nt(s*a),u=e+r,d=nt(nt(u*u)-a-o),l=c+o,f=l-i,h=c-o,p=nt(d*f),m=nt(l*h),y=nt(d*h),S=nt(f*l);return new $h(p,m,S,y)}add(e){let{ex:r,ey:n,ez:s,et:a}=this,{ex:o,ey:i,ez:c,et:u}=PU(e),{a:d,d:l}=v1,f=nt(r*o),h=nt(n*i),p=nt(a*l*u),m=nt(s*c),y=nt((r+n)*(o+i)-f-h),S=nt(m-p),v=nt(m+p),E=nt(h-d*f),k=nt(y*S),A=nt(v*E),D=nt(y*E),B=nt(S*v);return new $h(k,A,B,D)}mul(e,r=!0){if(e===0n)return r===!0?Ui("cannot multiply by 0"):O1;if(typeof e=="bigint"&&0n<e&&e<M1||Ui("invalid scalar, must be < L"),!r&&this.is0()||e===1n)return this;if(this.equals(Q1))return sde(e).p;let n=O1,s=Q1;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):r&&(s=s.add(a));return n}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(v1.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(M1/2n,!1).double();return M1%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 s=OK(n);return nt(n*s)!==1n&&Ui("invalid inverse"),{x:nt(e*s),y:nt(r*s)}}toRawBytes(){let{x:e,y:r}=this.toAffine(),n=Qce(r);return n[31]|=e&1n?128:0,n}toHex(){return hA(this.toRawBytes())}};Vh.BASE=new Vh($I,MI,1n,nt($I*MI));Vh.ZERO=new Vh(0n,1n,1n,0n);var{BASE:Q1,ZERO:O1}=Vh,MK=(t,e)=>t.toString(16).padStart(e,"0"),hA=t=>Array.from(t).map(e=>MK(e,2)).join(""),mA=t=>{let e=t.length;(!$K(t)||e%2)&&Ui("hex invalid 1");let r=Wh(e/2);for(let n=0;n<r.length;n++){let s=n*2,a=t.slice(s,s+2),o=Number.parseInt(a,16);(Number.isNaN(o)||o<0)&&Ui("hex invalid 2"),r[n]=o}return r},Qce=t=>mA(MK(t,32*2)).reverse(),Xce=t=>BigInt("0x"+hA(Wh(pA(t)).reverse())),SU=(...t)=>{let e=Wh(t.reduce((n,s)=>n+pA(s).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},OK=(t,e=Cs)=>{(t===0n||e<=0n)&&Ui("no inverse n="+t+" mod="+e);let r=nt(t,e),n=e,s=0n,a=1n,o=1n,i=0n;for(;r!==0n;){let c=n/r,u=n%r,d=s-o*c,l=a-i*c;n=r,r=u,s=o,a=i,o=d,i=l}return n===1n?nt(s,e):Ui("no inverse")},yc=(t,e)=>{let r=t;for(;e-- >0n;)r*=r,r%=Cs;return r},ede=t=>{let e=t*t%Cs*t%Cs,r=yc(e,2n)*e%Cs,n=yc(r,1n)*t%Cs,s=yc(n,5n)*n%Cs,a=yc(s,10n)*s%Cs,o=yc(a,20n)*a%Cs,i=yc(o,40n)*o%Cs,c=yc(i,80n)*i%Cs,u=yc(c,80n)*i%Cs,d=yc(u,10n)*s%Cs;return{pow_p_5_8:yc(d,2n)*t%Cs,b2:e}},EU=19681161376707505956807079304988542015446066515923890162744021073123829784752n,tde=(t,e)=>{let r=nt(e*e*e),n=nt(r*r*e),s=ede(t*n).pow_p_5_8,a=nt(t*r*s),o=nt(e*a*a),i=a,c=nt(a*EU),u=o===t,d=o===nt(-t),l=o===nt(-t*EU);return u&&(a=i),(d||l)&&(a=c),(nt(a)&1n)===1n&&(a=nt(-a)),{isValid:u||d,value:a}},pI,_U=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,rde={bytesToHex:hA,hexToBytes:mA,concatBytes:SU,mod:nt,invert:OK,randomBytes:t=>{let e=_U();return e||Ui("crypto.getRandomValues must be defined"),e.getRandomValues(Wh(t))},sha512Async:async(...t)=>{let e=_U();e||Ui("crypto.subtle or etc.sha512Async must be defined");let r=SU(...t);return Wh(await e.subtle.digest("SHA-512",r.buffer))},sha512Sync:void 0};Object.defineProperties(rde,{sha512Sync:{configurable:!1,get(){return pI},set(t){pI||(pI=t)}}});var bf=8,nde=()=>{let t=[],e=256/bf+1,r=Q1,n=r;for(let s=0;s<e;s++){n=r,t.push(n);for(let a=1;a<2**(bf-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},sde=t=>{let e=xU||(xU=nde()),r=(d,l)=>{let f=l.negate();return d?f:l},n=O1,s=Q1,a=1+256/bf,o=2**(bf-1),i=BigInt(2**bf-1),c=2**bf,u=BigInt(bf);for(let d=0;d<a;d++){let l=d*o,f=Number(t&i);t>>=u,f>o&&(f-=c,t+=1n);let h=l,p=l+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?s=s.add(r(m,e[h])):n=n.add(r(y,e[p]))}return{p:n,f:s}},yA=2n**256n,kf=yA-0x1000003d1n,gA=yA-0x14551231950b75fc4402da1732fc9bebfn,BK=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,NK=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,UK={p:kf,n:gA,a:0n,b:7n,Gx:BK,Gy:NK},zh=32,kU=t=>He(He(t*t)*t+UK.b),cs=(t="")=>{throw new Error(t)},uP=t=>typeof t=="bigint",LK=t=>typeof t=="string",hI=t=>uP(t)&&0n<t&&t<kf,KK=t=>uP(t)&&0n<t&&t<gA,zK=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?cs("Uint8Array expected"):t,kw=t=>new Uint8Array(t),wA=(t,e)=>zK(LK(t)?lP(t):kw(t),e),He=(t,e=kf)=>{let r=t%e;return r>=0n?r:e+r},TU=t=>t instanceof Hh?t:cs("Point expected"),IU,Hh=class Mh{constructor(e,r,n){this.px=e,this.py=r,this.pz=n}static fromAffine(e){return new Mh(e.x,e.y,1n)}static fromHex(e){e=wA(e);let r,n=e[0],s=e.subarray(1),a=AU(s,0,zh),o=e.length;if(o===33&&[2,3].includes(n)){hI(a)||cs("Point hex invalid: x not FE");let i=ide(kU(a)),c=(i&1n)===1n;(n&1)===1!==c&&(i=He(-i)),r=new Mh(a,i,1n)}return o===65&&n===4&&(r=new Mh(a,AU(s,zh,2*zh),1n)),r?r.ok():cs("Point is not on curve")}static fromPrivateKey(e){return yw.mul(ode(e))}get x(){return this.aff().x}get y(){return this.aff().y}equals(e){let{px:r,py:n,pz:s}=this,{px:a,py:o,pz:i}=TU(e),c=He(r*i),u=He(a*s),d=He(n*i),l=He(o*s);return c===u&&d===l}negate(){return new Mh(this.px,He(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:r,py:n,pz:s}=this,{px:a,py:o,pz:i}=TU(e),{a:c,b:u}=UK,d=0n,l=0n,f=0n,h=He(u*3n),p=He(r*a),m=He(n*o),y=He(s*i),S=He(r+n),v=He(a+o);S=He(S*v),v=He(p+m),S=He(S-v),v=He(r+s);let E=He(a+i);return v=He(v*E),E=He(p+y),v=He(v-E),E=He(n+s),d=He(o+i),E=He(E*d),d=He(m+y),E=He(E-d),f=He(c*v),d=He(h*y),f=He(d+f),d=He(m-f),f=He(m+f),l=He(d*f),m=He(p+p),m=He(m+p),y=He(c*y),v=He(h*v),m=He(m+y),y=He(p-y),y=He(c*y),v=He(v+y),p=He(m*v),l=He(l+p),p=He(E*v),d=He(S*d),d=He(d-p),p=He(S*m),f=He(E*f),f=He(f+p),new Mh(d,l,f)}mul(e,r=!0){if(!r&&e===0n)return B1;if(KK(e)||cs("invalid scalar"),this.equals(yw))return ude(e).p;let n=B1,s=yw;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):r&&(s=s.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(B1))return{x:0n,y:0n};if(n===1n)return{x:e,y:r};let s=FK(n);return He(n*s)!==1n&&cs("invalid inverse"),{x:He(e*s),y:He(r*s)}}assertValidity(){let{x:e,y:r}=this.aff();return(!hI(e)||!hI(r))&&cs("Point invalid: x or y"),He(r*r)===kU(e)?this:cs("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")+RU(r)+(e?"":RU(n))}toRawBytes(e=!0){return lP(this.toHex(e))}};Hh.BASE=new Hh(BK,NK,1n);Hh.ZERO=new Hh(0n,1n,0n);var{BASE:yw,ZERO:B1}=Hh,qK=(t,e)=>t.toString(16).padStart(e,"0"),vA=t=>Array.from(t).map(e=>qK(e,2)).join(""),lP=t=>{let e=t.length;(!LK(t)||e%2)&&cs("hex invalid 1");let r=kw(e/2);for(let n=0;n<r.length;n++){let s=n*2,a=t.slice(s,s+2),o=Number.parseInt(a,16);(Number.isNaN(o)||o<0)&&cs("hex invalid 2"),r[n]=o}return r},fP=t=>BigInt("0x"+(vA(t)||"0")),AU=(t,e,r)=>fP(t.slice(e,r)),bA=t=>uP(t)&&t>=0n&&t<yA?lP(qK(t,2*zh)):cs("bigint expected"),RU=t=>vA(bA(t)),DU=(...t)=>{let e=kw(t.reduce((n,s)=>n+zK(s).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},FK=(t,e=kf)=>{(t===0n||e<=0n)&&cs("no inverse n="+t+" mod="+e);let r=He(t,e),n=e,s=0n,a=1n,o=1n,i=0n;for(;r!==0n;){let c=n/r,u=n%r,d=s-o*c,l=a-i*c;n=r,r=u,s=o,a=i,o=d,i=l}return n===1n?He(s,e):cs("no inverse")},ide=t=>{let e=1n;for(let r=t,n=(kf+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*r%kf),r=r*r%kf;return He(e*e)===t?e:cs("sqrt invalid")},ode=t=>(uP(t)||(t=fP(wA(t,zh))),KK(t)?t:cs("private key out of range")),CU=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,N1;function ade(t){t=wA(t);let e=zh+8;(t.length<e||t.length>1024)&&cs("expected proper params");let r=He(fP(t),gA-1n)+1n;return bA(r)}var cde={hexToBytes:lP,bytesToHex:vA,concatBytes:DU,bytesToNumberBE:fP,numberToBytesBE:bA,mod:He,invert:FK,hmacSha256Async:async(t,...e)=>{let r=CU();if(!r)return cs("etc.hmacSha256Async not set");let n=r.subtle,s=await n.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return kw(await n.sign("HMAC",s,DU(...e)))},hmacSha256Sync:N1,hashToPrivateKey:ade,randomBytes:t=>{let e=CU();return e||cs("crypto.getRandomValues must be defined"),e.getRandomValues(kw(t))}};Object.defineProperties(cde,{hmacSha256Sync:{configurable:!1,get(){return N1},set(t){N1||(N1=t)}}});var Pf=8,dde=()=>{let t=[],e=256/Pf+1,r=yw,n=r;for(let s=0;s<e;s++){n=r,t.push(n);for(let a=1;a<2**(Pf-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},ude=t=>{let e=IU||(IU=dde()),r=(d,l)=>{let f=l.negate();return d?f:l},n=B1,s=yw,a=1+256/Pf,o=2**(Pf-1),i=BigInt(2**Pf-1),c=2**Pf,u=BigInt(Pf);for(let d=0;d<a;d++){let l=d*o,f=Number(t&i);t>>=u,f>o&&(f-=c,t+=1n);let h=l,p=l+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?s=s.add(r(m,e[h])):n=n.add(r(y,e[p]))}return{p:n,f:s}},jU;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(jU||(jU={}));var $U;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})($U||($U={}));var Xg=class wf{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:s}){let a=await wf.createIonDocument({services:n,verificationMethods:s}),o=wf.normalizeJwk(e),i=wf.normalizeJwk(r);return await Zce.createLongFormDid({document:a,recoveryKey:o,updateKey:i})}static async constructCreateRequest({ionDocument:e,recoveryKey:r,updateKey:n}){return await CK.createCreateRequest({document:e,recoveryKey:wf.normalizeJwk(r),updateKey:wf.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:r}){let n=[];for(let a of r){let o=a.id??a.publicKeyJwk.kid??await fr({jwk:a.publicKeyJwk});o=`${o.split("#").pop()}`;let i={id:o,publicKeyJwk:wf.normalizeJwk(a.publicKeyJwk),purposes:a.purposes,type:"JsonWebKey2020"};n.push(i)}let s=e.map(a=>({...a,id:`${a.id.split("#").pop()}`}));return{publicKeys:n,services:s}}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}},lde=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519",t))(lde||{}),fde={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},MU="https://ion.tbd.engineering",pde=class pw extends Dw{static async create({keyManager:e=new Ia,options:r={}}={}){if(r.verificationMethods?.some(p=>!(p.algorithm in fde)))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 s={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},a=[];for(let p of r.verificationMethods??[s]){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 o=await e.generateKey({algorithm:"secp256k1"}),i=await e.getPublicKey({keyUri:o}),c=await e.generateKey({algorithm:"secp256k1"}),u=await e.getPublicKey({keyUri:c}),d=await Xg.computeLongFormDidUri({recoveryKey:i,updateKey:u,services:r.services??[],verificationMethods:a}),{didDocument:l,didResolutionMetadata:f}=await pw.resolve(d,{gatewayUri:r.gatewayUri});if(l===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let h=new Ec({uri:d,document:l,metadata:{published:!1,canonicalId:d.split(":",3).join(":"),recoveryKey:i,updateKey:u},keyManager:e});if(r.publish??!0){let p=await pw.publish({did:h,gatewayUri:r.gatewayUri});h.metadata=p.didDocumentMetadata}return h}static async getSigningMethod({didDocument:e,methodId:r}){let n=us.parse(e.id);if(n&&n.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${n.method}`);let s=e.verificationMethod?.find(a=>a.id===(r??e.assertionMethod?.[0]));if(!(s&&s.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async import({portableDid:e,keyManager:r=new Ia}){if(us.parse(e.uri)?.method!==pw.methodName)throw new Ze("methodNotSupported","Method not supported");return await Ec.import({portableDid:e,keyManager:r})}static async publish({did:e,gatewayUri:r=MU}){let n=e.document.verificationMethod?.map(o=>({id:o.id,publicKeyJwk:o.publicKeyJwk,purposes:HL({didDocument:e.document,methodId:o.id})}))??[],s=await Xg.createIonDocument({services:e.document.service??[],verificationMethods:n}),a=await Xg.constructCreateRequest({ionDocument:s,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let o=Xg.appendPathToUrl({baseUrl:r,path:"/operations"}),i=await fetch(o,{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:i.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=us.parse(e);if(!n)return{...ds,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==pw.methodName)return{...ds,didResolutionMetadata:{error:"methodNotSupported"}};let s=r?.gatewayUri??MU;try{let a=Xg.appendPathToUrl({baseUrl:s,path:`/identifiers/${e}`}),o=await fetch(a,{signal:AbortSignal.timeout(3e4)});if(!o.ok)throw new Ze("notFound",`Unable to find DID document for: ${e}`);let{didDocument:i,didDocumentMetadata:c}=await o.json();return{...ds,...i&&{didDocument:i},didDocumentMetadata:{published:c?.method?.published,...c}}}catch(a){if(!(a instanceof Ze))throw new Error(a);return{...ds,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};pde.methodName="ion";var GK=class hw extends Dw{static async create({keyManager:e=new Ia,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",s=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:s}),o=Qe.object(a).toBase64Url(),i=`did:${hw.methodName}:${o}`,c=(await hw.resolve(i)).didDocument;return new Ec({uri:i,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let r=us.parse(e.id);if(r&&r.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.verificationMethod??[];if(!(n&&n.publicKeyJwk))throw new Ze("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 Ia}){if(us.parse(e.uri)?.method!==hw.methodName)throw new Ze("methodNotSupported","Method not supported");let n=await Ec.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new Ze("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){let n=us.parse(e),s;try{s=n?Qe.base64Url(n.id).toObject():void 0}catch{}if(!n||!s)return{...ds,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==hw.methodName)return{...ds,didResolutionMetadata:{error:"methodNotSupported"}};let a={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},o=`${a.id}#0`;switch(a.verificationMethod=[{id:o,type:"JsonWebKey",controller:a.id,publicKeyJwk:s}],a.authentication=[o],a.assertionMethod=[o],a.capabilityInvocation=[o],a.capabilityDelegation=[o],a.keyAgreement=[o],s.use){case"sig":{delete a.keyAgreement;break}case"enc":{delete a.authentication,delete a.assertionMethod,delete a.capabilityInvocation,delete a.capabilityDelegation;break}}return{...ds,didDocument:a}}};GK.methodName="jwk";var WK=GK,hde={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},U1=class Oh{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(":"),s=Oh.JWK_TO_MULTICODEC[n];if(s===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:Vo.getCodeFromName({name:s}),name:s}}static keyCompressor(e){let r={"P-256":Xs.compressPublicKey,secp256k1:js.compressPublicKey}[e];if(!r)throw new Ze("invalidPublicKeyType",`Unsupported curve: ${e}`);return r}static keyConverter(e){let r={Ed25519:$s,"P-256":Xs,secp256k1:js}[e];if(!r)throw new Ze("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?Vo.getNameFromCode({code:e}):r;let n=r,s=Oh.MULTICODEC_TO_JWK[n];if(s===void 0)throw new Error("Unsupported Multicodec to JWK conversion");return{...s}}static async publicKeyToMultibaseId({publicKey:e}){if(!(e?.crv&&e.crv in hde))throw new Ze("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let r=await Oh.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(r=await Oh.keyCompressor(e.crv)({publicKeyBytes:r}));let{name:n}=await Oh.jwkToMulticodec({jwk:e});return ZL({keyBytes:r,multicodecName:n})}};U1.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},U1.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},U1.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:""}};var b1=U1,mde=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t))(mde||{}),OU={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},VK=class Ku extends Dw{static async create({keyManager:e=new Ia,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",s=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:s}),o=await b1.publicKeyToMultibaseId({publicKey:a}),i=`did:${Ku.methodName}:${o}`,c=(await Ku.resolve(i,r)).didDocument;return new Ec({uri:i,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let r=us.parse(e.id);if(r&&r.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.assertionMethod||[],s=e.verificationMethod?.find(a=>a.id===n);if(!(s&&s.publicKeyJwk))throw new Ze("internalError","A verification method intended for signing could not be determined from the DID Document");return s}static async import({portableDid:e,keyManager:r=new Ia}){if(us.parse(e.uri)?.method!==Ku.methodName)throw new Ze("methodNotSupported","Method not supported");let n=await Ec.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new Ze("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){try{let n=await Ku.createDocument({didUri:e,options:r});return{...ds,didDocument:n}}catch(n){if(!(n instanceof Ze))throw new Error(n);return{...ds,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:s=!1,publicKeyFormat:a="JsonWebKey2020"}=r,o={id:""},i=us.parse(e);if(!i)throw new Ze("invalidDid",`Invalid DID URI: ${e}`);let c=i.id;if(i.method!==Ku.methodName)throw new Ze("methodNotSupported",`Method not supported: ${i.method}`);if(!Ku.validateIdentifier(i))throw new Ze("invalidDid",`Invalid DID URI: ${e}`);let u=await Ku.createSignatureMethod({didUri:e,multibaseValue:c,options:{enableExperimentalPublicKeyTypes:s,publicKeyFormat:a}});o.id=i.uri,o.verificationMethod=[u],o.authentication=[u.id],o.assertionMethod=[u.id],o.capabilityInvocation=[u.id],o.capabilityDelegation=[u.id];let d=[n];return VL({didDocument:o}).forEach(l=>{let f=OU[l];d.push(f)}),o["@context"]=d,o}static async createSignatureMethod({didUri:e,multibaseValue:r,options:n}){let{enableExperimentalPublicKeyTypes:s,publicKeyFormat:a}=n,o={id:"",type:"",controller:""},{keyBytes:i,multicodecCode:c,multicodecName:u}=YL({multibaseKeyId:r}),d=i.byteLength,l=b1.MULTICODEC_PUBLIC_KEY_LENGTH[c];if(d!==l)throw new Ze("invalidPublicKeyLength",`Expected ${d} bytes. Actual: ${l}`);let f=!1;switch(u){case"secp256k1-pub":f=await js.validatePublicKey({publicKeyBytes:i});break;case"ed25519-pub":f=await $s.validatePublicKey({publicKeyBytes:i});break}if(!f)throw new Ze("invalidPublicKey","Invalid public key detected.");o.id=`${e}#${r}`;try{new URL(o.id)}catch{throw new Ze("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(a in OU))throw new Ze("unsupportedPublicKeyType",`Unsupported format: ${a}`);if(s===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(a))throw new Ze("invalidPublicKeyType",`Specified '${a}' without setting enableExperimentalPublicKeyTypes to true.`);if(o.type=a,o.controller=e,a==="Ed25519VerificationKey2020"&&(o.publicKeyMultibase=r),a==="JsonWebKey2020"){let{crv:h}=await b1.multicodecToJwk({code:c});o.publicKeyJwk=await b1.keyConverter(h).bytesToPublicKey({publicKeyBytes:i})}return o}static validateIdentifier(e){let{method:r,id:n}=e,[s]=e.uri.split(":",1);return s==="did"&&r==="key"&&!0&&mI(n)==="String"&&n.startsWith("z")}};VK.methodName="key";var $w=VK,yde=3e4;function gde(t){let e=t.toLowerCase();if(e==="localhost"||e==="localhost.")return!0;let r=e.split(".");if(r.length===4){let s=r.map(Number);if(s.every(a=>!Number.isNaN(a)&&a>=0&&a<=255)){let[a,o]=s;if(a===10||a===172&&o>=16&&o<=31||a===192&&o===168||a===127||a===169&&o===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 HK=class L1 extends Dw{static async create({keyManager:e=new Ia,options:r}){if(!r.domain)throw new Ze("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,s=`did:${L1.methodName}:${n}`;if(!us.parse(s))throw new Ze("invalidDid",`The constructed DID URI is invalid: ${s}`);let a=r.verificationMethods??[{algorithm:r.algorithm??"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]}],o={"@context":["https://www.w3.org/ns/did/v1"],id:s};for(let i=0;i<a.length;i++){let c=a[i],u=await e.generateKey({algorithm:c.algorithm}),d=await e.getPublicKey({keyUri:u}),l=c.id?.split("#").pop()??`key-${i}`,f=`${s}#${l}`;o.verificationMethod??=[],o.verificationMethod.push({id:f,type:"JsonWebKey",controller:c.controller??s,publicKeyJwk:d});for(let h of c.purposes??[])o[h]??=[],o[h].push(f)}return r.services&&(o.service=r.services.map(i=>({...i,id:`${s}#${i.id.split("#").pop()}`}))),new Ec({uri:s,document:o,metadata:{published:!1},keyManager:e})}static async getSigningMethod({didDocument:e,methodId:r}){let n=us.parse(e.id);if(n&&n.method!==this.methodName)throw new Ze("methodNotSupported",`Method not supported: ${n.method}`);let s=Ei(r)??Ei(e.assertionMethod?.[0]),a=s?e.verificationMethod?.find(o=>Ei(o.id)===s):e.verificationMethod?.[0];if(!(a&&a.publicKeyJwk))throw new Ze("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 Ia}){if(us.parse(e.uri)?.method!==L1.methodName)throw new Ze("methodNotSupported","Method not supported");return await Ec.import({portableDid:e,keyManager:r})}static async resolve(e,r){let n=us.parse(e);if(!n)return{...ds,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==L1.methodName)return{...ds,didResolutionMetadata:{error:"methodNotSupported"}};let s=`https://${n.id.replace(/:/g,"/")}`;s=decodeURIComponent(s);let a=n.id.includes(":")?`${s}/did.json`:`${s}/.well-known/did.json`;try{let o=new URL(a);if(gde(o.hostname))return{...ds,didResolutionMetadata:{error:"notFound"}};let i=await fetch(a,{signal:AbortSignal.timeout(yde)});if(!i.ok)throw new Error("HTTP error status code returned");let c=await i.json();return{...ds,didDocument:c}}catch{return{...ds,didResolutionMetadata:{error:"notFound"}}}}};HK.methodName="web";var JK=HK,K$e=Rf(WU(),1),z$e=Rf(VU(),1);var wde=Rf(VU(),1),ZK=class{constructor({ttl:t="15m"}={}){this.cache=new Ine.default({ttl:(0,wde.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(){}},vde={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()}},YK=class{constructor({cache:t,didResolvers:e}){this.didResolvers=new Map,this.cache=t||vde;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=us.parse(t);if(!r)return{...ds,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${t}`}};let n=this.didResolvers.get(r.method);if(!n)return{...ds,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${r.method}`}};let s=await this.cache.get(r.uri);if(s)return s;{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=us.parse(t);if(!r)return{dereferencingMetadata:{error:"invalidDidUrl"},contentStream:null,contentMetadata:{}};let{didDocument:n,didResolutionMetadata:s,didDocumentMetadata:a}=await this.resolve(r.uri);if(!n)return{dereferencingMetadata:{error:s.error},contentStream:null,contentMetadata:{}};if(!r.fragment||r.query)return{dereferencingMetadata:{contentType:"application/did+json"},contentStream:n,contentMetadata:a};let{service:o=[],verificationMethod:i=[]}=n,c=new Set([t,r.fragment,`#${r.fragment}`]),u;for(let d of i)if(c.has(d.id)){u=d;break}for(let d of o)if(c.has(d.id)){u=d;break}return u?{dereferencingMetadata:{contentType:"application/did+json"},contentStream:u,contentMetadata:s}:{dereferencingMetadata:{error:"notFound"},contentStream:null,contentMetadata:{}}}};Qt();var PA=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 Rh({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new a1(e.resumableTaskStore,this.storageController),this._coreProtocols=new ag,this._coreProtocols.register(new Tr);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={["MessagesRead"]:new vb(r),["MessagesSubscribe"]:new Pb(r),["MessagesSync"]:new xb(r),["ProtocolsConfigure"]:new s1(r),["ProtocolsQuery"]:new i1(r),["RecordsCount"]:new o1(r),["RecordsDelete"]:new c1(r),["RecordsQuery"]:new d1(r),["RecordsRead"]:new u1(r),["RecordsSubscribe"]:new l1(r),["RecordsWrite"]:new f1(r)}}static async create(e){e.didResolver||(e.didResolver=new YK({didResolvers:[kK,WK,$w,JK],cache:new ZK}),e.ownsResolver=!0),e.tenantGate??=new cg;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 s=await this.validateTenant(e)??await this.validateMessageIntegrity(r);if(s!==void 0)return s;let{dataStream:a,subscriptionHandler:o}=n,i=r.descriptor.interface+r.descriptor.method;return await this.methodHandlers[i].handle({tenant:e,message:r,dataStream:a,subscriptionHandler:o})}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(s){return ut(s,400)}}};ht();Qt();ln();Dy();vi();w();function bde(t){return new Promise((e,r)=>{if(t.aborted){r(t.reason);return}t.addEventListener("abort",()=>{r(t.reason)})})}async function On(t,e){return e?Promise.race([t,bde(e)]):t}Oa();ir();la();k0();$n();c0();e2();Ja();Vs();zE();Il();w();Xm();w();import{Level as Pde}from"level";async function Ki(t,e){return new Pde(t,{...e,keyEncoding:"utf8"})}var Aa=class t{config;db;constructor(e,r){this.config={createLevelDatabase:Ki,...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 On(this.createLevelDatabase(),r?.signal);try{return await On(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 On(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 On(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 On(this.createLevelDatabase(),n?.signal),On(this.db.put(String(e),r),n?.signal)}async delete(e,r){return r?.signal?.throwIfAborted(),await On(this.createLevelDatabase(),r?.signal),On(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 On(this.createLevelDatabase(),r?.signal),On(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 On(this.createLevelDatabase(),e?.signal);let r=this.sublevelRange;if(!r)return;let n=this.root;if(n.db.supports.additionalMethods.compactRange)return On(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 Bf=class t{config;db;constructor(e,r){this.config={createLevelDatabase:Ki,...e},this.db=r??new Aa({...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),zt.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,s]of r)yield{cid:zt.decode(n),block:s}}async*deleteMany(e,r){for await(let n of e)await this.delete(n,r),yield n}async clear(){return this.db.clear()}};w();Vd();w();var kP=Nn(ko(),1);w();function xde(t){return t[Symbol.asyncIterator]!=null}function Sde(t){if(xde(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 QK=Sde;Fc();w();Tp();To();var $9=Nn(ko(),1);fy();w();Qu();rp();var XK=0,Ede="identity",e9=Zo,_de=t=>sl(XK,e9(t)),t9={code:XK,name:Ede,encode:e9,digest:_de};w();Tp();var r9=Nn(ko(),1);Fc();var kde=async(t,e,r,n,s,a,o,i)=>{let c=await o.get(t,i),u=q2(c),d=u,l=r;for(;n.length>0;){let f=n[0];if(f in d){n.shift(),l=`${l}/${f}`;let h=zt.asCID(d[f]);if(h!=null)return{entry:{type:"object",name:e,path:r,cid:t,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield u}},next:{cid:h,name:f,path:l,toResolve:n}};d=d[f]}else throw(0,r9.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:c,depth:a,size:BigInt(c.length),content:async function*(){yield u}}}},n9=kde;w();var s9=Nn(ko(),1);rp();Wc();w();function Tde(t,e,r,n){let s=BigInt(t.length),a=BigInt(e+s);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 Nf=Tde;w();var Mw=Nn(ko(),1),Ide=(t,e=0,r=t)=>{let n=BigInt(t),s=BigInt(e??0),a=BigInt(r);if(a!==n&&(a=s+a),a>n&&(a=n),s<0n)throw(0,Mw.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(s>n)throw(0,Mw.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(a<0n)throw(0,Mw.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(a>n)throw(0,Mw.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:s,end:a}},Qh=Ide;var Ade=t=>{async function*e(r={}){let{start:n,end:s}=Qh(t.length,r.offset,r.length),a=Nf(t,0n,n,s);r.onProgress?.(new mn("unixfs:exporter:progress:identity",{bytesRead:BigInt(a.byteLength),totalBytes:s-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Rde=async(t,e,r,n,s,a,o,i)=>{if(n.length>0)throw(0,s9.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let c=a0(t.multihash.bytes);return{entry:{type:"identity",name:e,path:r,cid:t,content:Ade(c.digest),depth:a,size:BigInt(c.digest.length),node:c.digest}}},i9=Rde;w();var o9=Nn(ko(),1);Wc();var Dde=t=>{async function*e(r={}){let{start:n,end:s}=Qh(t.length,r.offset,r.length),a=Nf(t,0n,n,s);r.onProgress?.(new mn("unixfs:exporter:progress:raw",{bytesRead:BigInt(a.byteLength),totalBytes:s-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Cde=async(t,e,r,n,s,a,o,i)=>{if(n.length>0)throw(0,o9.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let c=await o.get(t,i);return{entry:{type:"raw",name:e,path:r,cid:t,content:Dde(c),depth:a,size:BigInt(c.length),node:c}}},a9=Cde;w();To();var qw=Nn(ko(),1);Zd();w();To();qS();FS();var jde=async function(t){return(await dv.encode(t)).slice(0,8).reverse()},$de=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 s=parseInt(n.Name,16);e._putObjectAt(s,new Fa({hash:r._options.hash,bits:r._options.bits},e,s));return}await r.put(n.Name.substring(2),!0)}))},c9=t=>t.toString(16).toUpperCase().padStart(2,"0").substring(0,2),Mde=t=>{let e=t.bucket,r=[];for(;e._parent!=null;)r.push(e),e=e._parent;return r.push(e),r.reverse()},d9=async(t,e,r,n,s)=>{if(n==null){let d=fv({hashFn:jde});n={rootBucket:d,hamtDepth:1,lastBucket:d}}await $de(t.Links,n.lastBucket,n.rootBucket);let a=await n.rootBucket._findNewBucketAndPos(e),o=c9(a.pos),i=Mde(a);i.length>n.hamtDepth&&(n.lastBucket=i[n.hamtDepth],o=c9(n.lastBucket._posAtParent));let c=t.Links.find(d=>{if(d.Name==null)return!1;let l=d.Name.substring(0,2),f=d.Name.substring(2);return!(l!==o||f!==""&&f!==e)});if(c==null)return;if(c.Name!=null&&c.Name.substring(2)===e)return c.Hash;n.hamtDepth++;let u=await r.get(c.Hash,s);return t=Gc(u),d9(t,e,r,n,s)},u9=d9;w();w();w();function Ode(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[r](){return this}}}var pP=Ode;function Bde(t){return t[Symbol.asyncIterator]!=null}function Nde(t,e){let r=0;if(Bde(t))return async function*(){for await(let c of t)await e(c,r++)&&(yield c)}();let n=pP(t),{value:s,done:a}=n.next();if(a===!0)return function*(){}();let o=e(s,r++);if(typeof o.then=="function")return async function*(){await o&&(yield s);for(let c of n)await e(c,r++)&&(yield c)}();let i=e;return function*(){o===!0&&(yield s);for(let c of n)i(c,r++)&&(yield c)}()}var l9=Nde;w();function Ude(t){return t[Symbol.asyncIterator]!=null}function Lde(t,e){let r=0;if(Ude(t))return async function*(){for await(let c of t)yield e(c,r++)}();let n=pP(t),{value:s,done:a}=n.next();if(a===!0)return function*(){}();let o=e(s,r++);if(typeof o.then=="function")return async function*(){yield await o;for(let c of n)yield e(c,r++)}();let i=e;return function*(){yield o;for(let c of n)yield i(c,r++)}()}var Xh=Lde;w();w();function zi(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var hP=globalThis.CustomEvent??Event;async function*Uf(t,e={}){let r=e.concurrency??1/0;r<1&&(r=1/0);let n=e.ordered??!1,s=new EventTarget,a=[],o=zi(),i=zi(),c=!1,u,d=!1;s.addEventListener("task-complete",()=>{i.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of t){if(a.length===r&&(o=zi(),await o.promise),d)break;let m={done:!1};a.push(m),p().then(y=>{m.done=!0,m.ok=!0,m.value=y,s.dispatchEvent(new hP("task-complete"))},y=>{m.done=!0,m.err=y,s.dispatchEvent(new hP("task-complete"))})}c=!0,s.dispatchEvent(new hP("task-complete"))}catch(p){u=p,s.dispatchEvent(new hP("task-complete"))}});function l(){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 d=!0,o.resolve(),p.err;o.resolve()}}function*h(){for(;l();)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 d=!0,o.resolve(),m.err;o.resolve()}}for(;;){if(l()||(i=zi(),await i.promise),u!=null||(n?yield*f():yield*h(),u!=null))throw u;if(c&&a.length===0)break}}w();w();w();var mP=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}},em=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new mP(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 mP(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()}};var xA=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function yP(t={}){return Kde(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 Kde(t,e){e=e??{};let r=e.onEnd,n=new em,s,a,o,i=zi(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,S)=>{a=v=>{a=null,n.push(v);try{y(t(n))}catch(E){S(E)}return s}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{i.resolve(),i=zi()})}},u=y=>a!=null?a(y):(n.push(y),s),d=y=>(n=new em,a!=null?a({error:y}):(n.push({error:y}),s)),l=y=>{if(o)return s;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},f=y=>o?s:(o=!0,y!=null?d(y):u({done:!0})),h=()=>(n=new em,f(),{done:!0}),p=y=>(f(y),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:l,end:f,get readableLength(){return n.size},onEmpty:async y=>{let S=y?.signal;if(S?.throwIfAborted(),n.isEmpty())return;let v,E;S!=null&&(v=new Promise((k,A)=>{E=()=>{A(new xA)},S.addEventListener("abort",E)}));try{await Promise.race([i.promise,v])}finally{E!=null&&S!=null&&S?.removeEventListener("abort",E)}}},r==null)return s;let m=s;return s={[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:l,end(y){return m.end(y),r!=null&&(r(y),r=void 0),s},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},s}w();w();w();function zde(t){return t.reason}async function f9(t,e,r){if(e==null)return t;let n=r?.translateError??zde;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([t,new Promise((a,o)=>{s=()=>{o(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var SA=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=zi(),this.haveNext=zi()}[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=zi(),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=zi(),await f9(this.readNext.promise,r?.signal,r)}};function p9(){return new SA}function qde(t){return t[Symbol.asyncIterator]!=null}async function Fde(t,e,r){try{await Promise.all(t.map(async n=>{for await(let s of n)await e.push(s,{signal:r}),r.throwIfAborted()})),await e.end(void 0,{signal:r})}catch(n){await e.end(n,{signal:r}).catch(()=>{})}}async function*Gde(t){let e=new AbortController,r=p9();Fde(t,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort()}}function*Wde(t){for(let e of t)yield*e}function Vde(...t){let e=[];for(let r of t)qde(r)||e.push(r);return e.length===t.length?Wde(e):Gde(t)}var h9=Vde;function tm(t,...e){if(t==null)throw new Error("Empty pipeline");if(EA(t)){let n=t;t=()=>n.source}else if(y9(t)||m9(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&EA(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++)EA(r[n])&&(r[n]=Jde(r[n]));return Hde(...r)}var Hde=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},m9=t=>t?.[Symbol.asyncIterator]!=null,y9=t=>t?.[Symbol.iterator]!=null,EA=t=>t==null?!1:t.sink!=null&&t.source!=null,Jde=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=yP({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let s,a=t.source;if(m9(a))s=async function*(){yield*a,n.end()};else if(y9(a))s=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return h9(n,s())}return t.source};Wc();var Zde=(t,e,r,n,s,a,o)=>{async function*i(c={}){let u=c.offset??0,d=c.length??e.Links.length,l=e.Links.slice(u,d);c.onProgress?.(new mn("unixfs:exporter:walk:directory",{cid:t})),yield*tm(l,f=>Xh(f,h=>async()=>{let p=h.Name??"",m=`${n}/${p}`;return(await s(h.Hash,p,m,[],a+1,o,c)).entry}),f=>Uf(f,{ordered:!0}),f=>l9(f,h=>h!=null))}return i},g9=Zde;w();To();var Kf=Nn(ko(),1);Zd();fy();w();w();var kA=Nn(v9(),1);w();var Bw=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},TA=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},b9=t=>globalThis.DOMException===void 0?new TA(t):new DOMException(t),P9=t=>{let e=t.reason===void 0?b9("This operation was aborted."):t.reason;return e instanceof Error?e:b9(e)};function IA(t,e,r,n){let s,a=new Promise((o,i)=>{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){o(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&i(P9(c)),c.addEventListener("abort",()=>{i(P9(c))})}s=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{o(r())}catch(d){i(d)}return}let c=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new Bw(c);typeof t.cancel=="function"&&t.cancel(),i(u)},e),(async()=>{try{o(await t)}catch(c){i(c)}finally{n.customTimers.clearTimeout.call(void 0,s)}})()});return a.clear=()=>{clearTimeout(s),s=void 0},a}w();w();function AA(t,e,r){let n=0,s=t.length;for(;s>0;){let a=Math.trunc(s/2),o=n+a;r(t[o],e)<=0?(n=++o,s-=a+1):s=a}return n}var Lf=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)},Td,RA=class{constructor(){Td.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&Lf(this,Td,"f")[this.size-1].priority>=r.priority){Lf(this,Td,"f").push(n);return}let s=AA(Lf(this,Td,"f"),n,(a,o)=>o.priority-a.priority);Lf(this,Td,"f").splice(s,0,n)}dequeue(){let e=Lf(this,Td,"f").shift();return e?.run}filter(e){return Lf(this,Td,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return Lf(this,Td,"f").length}};Td=new WeakMap;var x9=RA;var dn=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},Ge=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)},Dn,Uw,Lw,Ju,SP,Kw,wP,Ra,Nw,go,vP,wo,zw,Hu,bP,S9,E9,T9,_9,k9,PP,DA,CA,EP,I9,xP,_P=class extends Error{},jA=class extends kA.default{constructor(e){var r,n,s,a;if(super(),Dn.add(this),Uw.set(this,void 0),Lw.set(this,void 0),Ju.set(this,0),SP.set(this,void 0),Kw.set(this,void 0),wP.set(this,0),Ra.set(this,void 0),Nw.set(this,void 0),go.set(this,void 0),vP.set(this,void 0),wo.set(this,0),zw.set(this,void 0),Hu.set(this,void 0),bP.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:x9,...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=(s=e.interval)===null||s===void 0?void 0:s.toString())!==null&&a!==void 0?a:""}\` (${typeof e.interval})`);dn(this,Uw,e.carryoverConcurrencyCount,"f"),dn(this,Lw,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),dn(this,SP,e.intervalCap,"f"),dn(this,Kw,e.interval,"f"),dn(this,go,new e.queueClass,"f"),dn(this,vP,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,dn(this,bP,e.throwOnTimeout===!0,"f"),dn(this,Hu,e.autoStart===!1,"f")}get concurrency(){return Ge(this,zw,"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})`);dn(this,zw,e,"f"),Ge(this,Dn,"m",EP).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:Ge(this,bP,"f"),...r},new Promise((n,s)=>{Ge(this,go,"f").enqueue(async()=>{var a,o,i;dn(this,wo,(o=Ge(this,wo,"f"),o++,o),"f"),dn(this,Ju,(i=Ge(this,Ju,"f"),i++,i),"f");try{if(!((a=r.signal)===null||a===void 0)&&a.aborted)throw new _P("The task was aborted.");let c=e({signal:r.signal});r.timeout&&(c=IA(Promise.resolve(c),r.timeout)),r.signal&&(c=Promise.race([c,Ge(this,Dn,"m",I9).call(this,r.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Bw&&!r.throwOnTimeout){n();return}s(c),this.emit("error",c)}finally{Ge(this,Dn,"m",T9).call(this)}},r),this.emit("add"),Ge(this,Dn,"m",PP).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return Ge(this,Hu,"f")?(dn(this,Hu,!1,"f"),Ge(this,Dn,"m",EP).call(this),this):this}pause(){dn(this,Hu,!0,"f")}clear(){dn(this,go,new(Ge(this,vP,"f")),"f")}async onEmpty(){Ge(this,go,"f").size!==0&&await Ge(this,Dn,"m",xP).call(this,"empty")}async onSizeLessThan(e){Ge(this,go,"f").size<e||await Ge(this,Dn,"m",xP).call(this,"next",()=>Ge(this,go,"f").size<e)}async onIdle(){Ge(this,wo,"f")===0&&Ge(this,go,"f").size===0||await Ge(this,Dn,"m",xP).call(this,"idle")}get size(){return Ge(this,go,"f").size}sizeBy(e){return Ge(this,go,"f").filter(e).length}get pending(){return Ge(this,wo,"f")}get isPaused(){return Ge(this,Hu,"f")}};Uw=new WeakMap,Lw=new WeakMap,Ju=new WeakMap,SP=new WeakMap,Kw=new WeakMap,wP=new WeakMap,Ra=new WeakMap,Nw=new WeakMap,go=new WeakMap,vP=new WeakMap,wo=new WeakMap,zw=new WeakMap,Hu=new WeakMap,bP=new WeakMap,Dn=new WeakSet,S9=function(){return Ge(this,Lw,"f")||Ge(this,Ju,"f")<Ge(this,SP,"f")},E9=function(){return Ge(this,wo,"f")<Ge(this,zw,"f")},T9=function(){var e;dn(this,wo,(e=Ge(this,wo,"f"),e--,e),"f"),Ge(this,Dn,"m",PP).call(this),this.emit("next")},_9=function(){Ge(this,Dn,"m",CA).call(this),Ge(this,Dn,"m",DA).call(this),dn(this,Nw,void 0,"f")},k9=function(){let e=Date.now();if(Ge(this,Ra,"f")===void 0){let r=Ge(this,wP,"f")-e;if(r<0)dn(this,Ju,Ge(this,Uw,"f")?Ge(this,wo,"f"):0,"f");else return Ge(this,Nw,"f")===void 0&&dn(this,Nw,setTimeout(()=>{Ge(this,Dn,"m",_9).call(this)},r),"f"),!0}return!1},PP=function(){if(Ge(this,go,"f").size===0)return Ge(this,Ra,"f")&&clearInterval(Ge(this,Ra,"f")),dn(this,Ra,void 0,"f"),this.emit("empty"),Ge(this,wo,"f")===0&&this.emit("idle"),!1;if(!Ge(this,Hu,"f")){let e=!Ge(this,Dn,"a",k9);if(Ge(this,Dn,"a",S9)&&Ge(this,Dn,"a",E9)){let r=Ge(this,go,"f").dequeue();return r?(this.emit("active"),r(),e&&Ge(this,Dn,"m",DA).call(this),!0):!1}}return!1},DA=function(){Ge(this,Lw,"f")||Ge(this,Ra,"f")!==void 0||(dn(this,Ra,setInterval(()=>{Ge(this,Dn,"m",CA).call(this)},Ge(this,Kw,"f")),"f"),dn(this,wP,Date.now()+Ge(this,Kw,"f"),"f"))},CA=function(){Ge(this,Ju,"f")===0&&Ge(this,wo,"f")===0&&Ge(this,Ra,"f")&&(clearInterval(Ge(this,Ra,"f")),dn(this,Ra,void 0,"f")),dn(this,Ju,Ge(this,Uw,"f")?Ge(this,wo,"f"):0,"f"),Ge(this,Dn,"m",EP).call(this)},EP=function(){for(;Ge(this,Dn,"m",PP).call(this););},I9=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new _P("The task was aborted."))},{once:!0})})},xP=async function(e,r){return new Promise(n=>{let s=()=>{r&&!r()||(this.off(e,s),n())};this.on(e,s)})};var A9=jA;Wc();async function R9(t,e,r,n,s,a,o){if(e instanceof Uint8Array){let u=Nf(e,n,s,a);r.push(u);return}if(e.Data==null)throw(0,Kf.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let i;try{i=rs.unmarshal(e.Data)}catch(u){throw(0,Kf.default)(u,"ERR_NOT_UNIXFS")}if(i.data!=null){let u=i.data,d=Nf(u,n,s,a);r.push(d),n+=BigInt(d.byteLength)}let c=[];if(e.Links.length!==i.blockSizes.length)throw(0,Kf.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let u=0;u<e.Links.length;u++){let d=e.Links[u],l=n,f=l+i.blockSizes[u];if((s>=l&&s<f||a>=l&&a<=f||s<l&&a>f)&&c.push({link:d,blockStart:n}),n=f,n>a)break}await tm(c,u=>Xh(u,d=>async()=>{let l=await t.get(d.link.Hash,o);return{...d,block:l}}),u=>Uf(u,{ordered:!0}),async u=>{for await(let{link:d,block:l,blockStart:f}of u){let h;switch(d.Hash.code){case sy:h=Gc(l);break;case Yd:h=l;break;default:r.end((0,Kf.default)(new Error(`Unsupported codec: ${d.Hash.code}`),"ERR_NOT_UNIXFS"));return}let p=new A9({concurrency:1});p.on("error",m=>{r.end(m)}),p.add(async()=>{o.onProgress?.(new mn("unixfs:exporter:walk:file",{cid:d.Hash})),await R9(t,h,r,f,s,a,o)}),await p.onIdle()}}),n>=a&&r.end()}var Xde=(t,e,r,n,s,a,o)=>{async function*i(c={}){let u=r.fileSize();if(u===void 0)throw new Error("File was a directory");let{start:d,end:l}=Qh(u,c.offset,c.length);if(l===0n)return;let f=0n,h=l-d,p=yP();c.onProgress?.(new mn("unixfs:exporter:walk:file",{cid:t})),R9(o,e,p,0n,d,l,c).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,Kf.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(),c.onProgress?.(new mn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:h,fileSize:u})),yield m}if(f<h)throw(0,Kf.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return i},$A=Xde;w();To();Wc();var eue=(t,e,r,n,s,a,o)=>{function i(c={}){return c.onProgress?.(new mn("unixfs:exporter:walk:hamt-sharded-directory",{cid:t})),D9(e,n,s,a,o,c)}return i};async function*D9(t,e,r,n,s,a){let o=t.Links,i=tm(o,c=>Xh(c,u=>async()=>{let d=u.Name!=null?u.Name.substring(2):null;if(d!=null&&d!==""){let l=await r(u.Hash,d,`${e}/${d}`,[],n+1,s,a);return{entries:l.entry==null?[]:[l.entry]}}else{let l=await s.get(u.Hash,a);return t=Gc(l),a.onProgress?.(new mn("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:D9(t,e,r,n,s,a)}}}),c=>Uf(c,{ordered:!0}));for await(let{entries:c}of i)yield*c}var C9=eue;var tue=(t,e)=>t.Links.find(n=>n.Name===e)?.Hash,rue={raw:$A,file:$A,directory:g9,"hamt-sharded-directory":C9,metadata:(t,e,r,n,s,a,o)=>()=>[],symlink:(t,e,r,n,s,a,o)=>()=>[]},nue=async(t,e,r,n,s,a,o,i)=>{let c=await o.get(t,i),u=Gc(c),d,l;if(e==null&&(e=t.toString()),u.Data==null)throw(0,qw.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{d=rs.unmarshal(u.Data)}catch(h){throw(0,qw.default)(h,"ERR_NOT_UNIXFS")}if(r==null&&(r=e),n.length>0){let h;if(d?.type==="hamt-sharded-directory"?h=await u9(u,n[0],o):h=tue(u,n[0]),h==null)throw(0,qw.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let p=n.shift(),m=`${r}/${p}`;l={cid:h,toResolve:n,name:p??"",path:m}}let f=rue[d.type](t,u,d,r,s,a,o);if(f==null)throw(0,qw.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return d.isDirectory()?{entry:{type:"directory",name:e,path:r,cid:t,content:f,unixfs:d,depth:a,node:u,size:d.fileSize()},next:l}:{entry:{type:"file",name:e,path:r,cid:t,content:f,unixfs:d,depth:a,node:u,size:d.fileSize()},next:l}},j9=nue;var sue={[sy]:j9,[Yd]:a9,[Wd]:n9,[t9.code]:i9},M9=async(t,e,r,n,s,a,o)=>{let i=sue[t.code];if(i==null)throw(0,$9.default)(new Error(`No resolver for code ${t.code}`),"ERR_NO_RESOLVER");return i(t,e,r,n,M9,s,a,o)},O9=M9;var iue=(t="")=>(t.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),oue=t=>{if(t instanceof Uint8Array)return{cid:zt.decode(t),toResolve:[]};let e=zt.asCID(t);if(e!=null)return{cid:e,toResolve:[]};if(typeof t=="string"){t.indexOf("/ipfs/")===0&&(t=t.substring(6));let r=iue(t);return{cid:zt.parse(r[0]),toResolve:r.slice(1)}}throw(0,kP.default)(new Error(`Unknown path type ${t}`),"ERR_BAD_PATH")};async function*aue(t,e,r={}){let{cid:n,toResolve:s}=oue(t),a=n.toString(),o=a,i=s.length;for(;;){let c=await O9(n,a,o,s,i,e,r);if(c.entry==null&&c.next==null)throw(0,kP.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");if(c.entry!=null&&(yield c.entry),c.next==null)return;s=c.next.toResolve,n=c.next.cid,a=c.next.name,o=c.next.path}}async function B9(t,e,r={}){let n=await QK(aue(t,e,r));if(n==null)throw(0,kP.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");return n}VS();var MA=new TextEncoder,TP=new TextDecoder,OA=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:Ki,...e},this.blockstore=new Bf({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,s){let a=await this.getRefsPartition(e,r),o=await a.get(n);if(o){await s.cancel();let{dataSize:l}=JSON.parse(TP.decode(o));return{dataSize:l}}let i=await this.getRefcountsPartition(),c=await i.get(n),u=c?JSON.parse(TP.decode(c)):{count:0,dataSize:0},d;if(u.count>0)await s.cancel(),d=u.dataSize;else{let l=await this.getBlocksPartition(n),f=my([{content:ts.asAsyncIterable(s)}],l,{cidVersion:1}),h;for await(h of f);d=Number(h.unixfs?.fileSize()??h.size)}return await a.put(n,MA.encode(JSON.stringify({dataSize:d}))),await i.put(n,MA.encode(JSON.stringify({count:u.count+1,dataSize:d}))),{dataSize:d}}async get(e,r,n){let a=await(await this.getRefsPartition(e,r)).get(n);if(!a)return;let{dataSize:o}=JSON.parse(TP.decode(a)),i=await this.getBlocksPartition(n);if(!await i.has(n))return;let d=(await B9(n,i)).content(),l=new ReadableStream({async pull(f){let h=await d.next();h.done?f.close():f.enqueue(h.value)}});return{dataSize:o,dataStream:l}}async delete(e,r,n){let s=await this.getRefsPartition(e,r);if(!await s.get(n))return;await s.delete(n);let o=await this.getRefcountsPartition(),i=await o.get(n);if(!i)return;let c=JSON.parse(TP.decode(i)),u=c.count-1;u<=0?(await(await this.getBlocksPartition(n)).clear(),await o.delete(n)):await o.put(n,MA.encode(JSON.stringify({count:u,dataSize:c.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")}};w();hs();JS();Ja();w();ya();Ja();var IP="";async function N9(t,e,r){let n=`__compound:${r.name}__`;return(await t.partition(e)).partition(n)}function U9(t,e,r,n,s){let a=[];for(let u of r.properties){let d=e[u];if(d===void 0||Array.isArray(d))return;a.push(n(d))}let o=e[r.sortProperty];if(o===void 0||Array.isArray(o))return;let i=a.join(IP),c=n(o);return i+IP+c+s+t}function L9(t,e,r){let n=[];for(let s of e.properties){let a=t[s];if(a===void 0||typeof a=="object")return;n.push(r(a))}return n.join(IP)+IP}function K9(t,e,r,n,s,a){let o=U9(r.messageCid,r.indexes,n,s,a);if(o!==void 0)return q9(t,e,`__compound:${n.name}__`,{type:"put",key:o,value:JSON.stringify(r)})}function z9(t,e,r,n,s,a,o){let i=U9(r,n,s,a,o);if(i!==void 0)return q9(t,e,`__compound:${s.name}__`,{type:"del",key:i})}async function q9(t,e,r,n){return(await t.partition(e)).createPartitionOperation(r,n)}function BA(t,e,r){let n,s=0;for(let a of r){if(a.sortProperty!==e.sortProperty)continue;let o=!0;for(let i of a.properties){let c=t[i];if(c===void 0||typeof c=="object"){o=!1;break}}o&&a.properties.length>s&&(n=a,s=a.properties.length)}return n}async function F9(t,e,r,n,s,a,o,i,c){let{sortDirection:u=1,cursor:d,limit:l}=n,f=L9(r,s,a);if(f===void 0)return i(e,[r],n,c);let h=await N9(t,e,s),p={};if(d!==void 0){let E=a(d.value),k=f+E+o+d.messageCid;u===1?(p.gt=k,p.lt=f+"\xFF"):(p.lt=k,p.gt=f,p.reverse=!0)}else u===1?(p.gt=f,p.lt=f+"\xFF"):(p.gt=f,p.lt=f+"\xFF",p.reverse=!0);let m=new Set(s.properties),y={},S=!1;for(let E in r)m.has(E)||(y[E]=r[E],S=!0);let v=[];for await(let[E,k]of h.iterator(p,c)){if(l!==void 0&&v.length===l)break;let A=JSON.parse(k);S&&!Wt.matchFilter(A.indexes,y)||v.push(A)}return v}async function G9(t,e,r,n,s,a,o){let i=L9(r,n,s);if(i===void 0)return(await a(e,[r],{sortProperty:n.sortProperty},o)).length;let c=await N9(t,e,n),u=new Set(n.properties),d=!1,l={};for(let p in r)u.has(p)||(l[p]=r[p],d=!0);let f={gt:i,lt:i+"\xFF"},h=0;if(d)for await(let[p,m]of c.iterator(f,o)){let y=JSON.parse(m);Wt.matchFilter(y.indexes,l)&&h++}else for await(let[p,m]of c.iterator(f,o))h++;return h}ht();ya();var W9="index",rm=class t{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:Ki,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new Aa({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,s){if(Tl(n))throw new ne("IndexMissingIndexableProperty","Index must include at least one valid indexable property");let a={messageCid:r,indexes:n},o=[];for(let d in n){let l=n[d];if(Array.isArray(l))for(let f of l){let h=this.createPutIndexedItemOperation(e,a,d,f);o.push(h)}else{let f=this.createPutIndexedItemOperation(e,a,d,l);o.push(f)}}for(let d of this._compoundIndexes){let l=K9(this.db,e,a,d,t.encodeValue,t.delimiter);l!==void 0&&o.push(l)}let i=this.createOperationForIndexesLookupPartition(e,{type:"put",key:r,value:JSON.stringify(n)});o.push(i);let c=await Promise.all(o);await(await this.db.partition(e)).batch(c,s)}async delete(e,r,n){let s=[],a=await this.getIndexes(e,r);if(a===void 0)return;let o=this.createOperationForIndexesLookupPartition(e,{type:"del",key:r});s.push(o);for(let u in a){let d=a[u];if(Array.isArray(d))for(let l of d){let f=this.createDeleteIndexedItemOperation(e,r,u,l);s.push(f)}else{let l=this.createDeleteIndexedItemOperation(e,r,u,d);s.push(l)}}for(let u of this._compoundIndexes){let d=z9(this.db,e,r,a,u,t.encodeValue,t.delimiter);d!==void 0&&s.push(d)}let i=await Promise.all(s);await(await this.db.partition(e)).batch(i,n)}async createPutIndexedItemOperation(e,r,n,s){let{messageCid:a}=r,o=t.keySegmentJoin(t.encodeValue(s),a);return this.createOperationForIndexPartition(e,n,{type:"put",key:o,value:JSON.stringify(r)})}async createDeleteIndexedItemOperation(e,r,n,s){let a=t.keySegmentJoin(t.encodeValue(s),r);return this.createOperationForIndexPartition(e,n,{type:"del",key:a})}async createOperationForIndexPartition(e,r,n){let s=await this.db.partition(e),a=t.getIndexPartitionName(r);return s.createPartitionOperation(a,n)}async createOperationForIndexesLookupPartition(e,r){return(await this.db.partition(e)).createPartitionOperation(W9,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(W9)}async query(e,r,n,s){if(r.length===1&&!Tl(r[0])){let a=BA(r[0],n,this._compoundIndexes);if(a!==void 0)return F9(this.db,e,r[0],n,a,t.encodeValue,t.delimiter,this.queryWithIteratorPaging.bind(this),s)}return t.shouldQueryWithInMemoryPaging(r,n)?this.queryWithInMemoryPaging(e,r,n,s):this.queryWithIteratorPaging(e,r,n,s)}async count(e,r,n,s){if(r.length===1&&!Tl(r[0])){let o=BA(r[0],{...n},this._compoundIndexes);if(o!==void 0)return G9(this.db,e,r[0],o,t.encodeValue,this.query.bind(this),s)}return(await this.query(e,r,{...n},s)).length}async queryWithIteratorPaging(e,r,n,s){let{cursor:a,limit:o}=n,i=a?this.createStartingKeyFromCursor(a):"",c=[];for await(let u of this.getIndexIterator(e,i,n,s)){if(o!==void 0&&o===c.length)break;let{indexes:d}=u;Wt.matchAnyFilter(d,r)&&c.push(u)}return c}async*getIndexIterator(e,r,n,s){let{sortProperty:a,sortDirection:o=1,cursor:i}=n,c={gt:r};o===-1&&(c.reverse=!0,i!==void 0&&(c.lt=r,delete c.gt));let u=await this.getIndexPartition(e,a);for await(let[d,l]of u.iterator(c,s)){let{indexes:f,messageCid:h}=JSON.parse(l);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:s}=e,a=s[r];if(a===void 0)throw new ne("IndexInvalidCursorSortProperty",`the sort property '${r}' is not defined within the given item.`);if(typeof a=="boolean"||Array.isArray(a))throw new 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,s){let{sortProperty:a,sortDirection:o=1,cursor:i,limit:c}=n,u=i?this.createStartingKeyFromCursor(i):void 0,d=new Map;r.length===0&&(r=[{}]);try{for(let p of r)await this.executeSingleFilterQuery(e,p,a,d,s)}catch(p){if(p.code==="IndexInvalidSortPropertyInMemory")return[]}let l=[...d.values()].sort((p,m)=>this.sortItems(p,m,a,o)),f=u!==void 0?this.findCursorStartingIndex(l,o,a,u):0;if(f<0)return[];let h=c!==void 0?f+c:void 0;return l.slice(f,h)}async executeSingleFilterQuery(e,r,n,s,a){let o=c=>{for(let u of c)if(!(s.has(u.messageCid)||!Wt.matchFilter(u.indexes,r))){if(u.indexes[n]===void 0)throw new ne("IndexInvalidSortPropertyInMemory",`invalid sort property ${n}`);s.set(u.messageCid,u)}};if(Tl(r)){let c=await this.getAllItems(e,n);o(c);return}let i=jv.reduceFilter(r);for(let c in i){let u=i[c];if(Wt.isEqualFilter(u)){let d=await this.filterExactMatches(e,c,u,a);o(d)}else if(Wt.isOneOfFilter(u))for(let d of new Set(u)){let l=await this.filterExactMatches(e,c,d,a);o(l)}else if(Wt.isRangeFilter(u)){let d=await this.filterRangeMatches(e,c,u,a);o(d)}}}async getAllItems(e,r){let n=await this.getIndexPartition(e,r),s=[];for await(let[a,o]of n.iterator())s.push(JSON.parse(o));return s}async filterExactMatches(e,r,n,s){let a=t.keySegmentJoin(t.encodeValue(n)),o={gt:a},i=await this.getIndexPartition(e,r),c=[];for await(let[u,d]of i.iterator(o,s)){if(!u.startsWith(a))break;c.push(JSON.parse(d))}return c}async filterRangeMatches(e,r,n,s){let a={};for(let c in n){let u=c,d=t.encodeValue(n[u]);u==="lte"?a[u]=d+"\xFF":a[u]=d}a.gt===void 0&&a.gte===void 0&&(a.reverse=!0);let o=[],i=await this.getIndexPartition(e,r);for await(let[c,u]of i.iterator(a,s))"gt"in n&&this.extractIndexValueFromKey(c)===t.encodeValue(n.gt)||o.push(JSON.parse(u));return o}sortItems(e,r,n,s){let a=e.indexes[n],o=r.indexes[n],i=t.encodeValue(a)+e.messageCid,c=t.encodeValue(o)+r.messageCid;return s===1?yy(i,c):yy(c,i)}findCursorStartingIndex(e,r,n,s){let a=c=>{let{messageCid:u,indexes:d}=c,l=d[n],f=t.keySegmentJoin(t.encodeValue(l),u);return r===1?f>s:f<s},o=0,i=e.length;for(;o<i;){let c=o+i>>>1;a(e[c])?i=c:o=c+1}return o<e.length?o:-1}async getIndexes(e,r){let s=await(await this.getIndexesLookupPartition(e)).get(r);if(s!==void 0)return JSON.parse(s)}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="!",s=String(Number.MAX_SAFE_INTEGER).length,a=e<0?n:"",o=e<0?r:0;return a+String(e+o).padStart(s,"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}};w();w();Xm();J2();function AP({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*cue(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let s=[...t,r],a=zt.asCID(n);a?yield[s.join("/"),a]:typeof n=="object"&&(yield*NA(n,s))}else{let r=zt.asCID(e);r?yield[t.join("/"),r]:yield*NA(e,t)}}function*NA(t,e){if(t==null||t instanceof Uint8Array)return;let r=zt.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,s]of Object.entries(t)){let a=[...e,n];yield*cue(a,s)}}function*due(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let s=[...t,r];yield s.join("/"),typeof n=="object"&&!zt.asCID(n)&&(yield*UA(n,s))}else yield*UA(e,t)}function*UA(t,e){if(!(t==null||typeof t!="object"))for(let[r,n]of Object.entries(t)){let s=[...e,r];yield s.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!zt.asCID(n)&&(yield*due(s,n))}}function uue(t,e){let r=t;for(let[n,s]of e.entries()){if(r=r[s],r==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(o=>`[${JSON.stringify(o)}]`).join("")}`);let a=zt.asCID(r);if(a)return{value:a,remaining:e.slice(n+1).join("/")}}return{value:r}}var RP=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:AP(),bytes:AP(),value:AP(),asBlock:AP()})}links(){return NA(this.value,[])}tree(){return UA(this.value,[])}get(e="/"){return uue(this.value,e.split("/").filter(Boolean))}};async function V9({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),s=await r.digest(n),a=zt.create(1,e.code,s);return new RP({value:t,bytes:n,cid:a})}async function H9({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),s=await r.digest(t),a=zt.create(1,e.code,s);return new RP({value:n,bytes:t,cid:a})}Tp();Vc();Fc();ir();Rd();Ja();var fue=[{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"}],LA=class t{config;blockstore;index;constructor(e={}){this.config={blockstoreLocation:"MESSAGESTORE",indexLocation:"INDEX",createLevelDatabase:Ki,...e},this.blockstore=new Bf({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new rm({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??fue})}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 s=await On(this.blockstore.partition(e),n?.signal),a=zt.parse(r),o=await s.get(a,n);return o?(await On(H9({bytes:o,codec:qc,hasher:Pn}),n?.signal)).value:void 0}async query(e,r,n,s,a){a?.signal?.throwIfAborted();let o=t.buildQueryOptions(n,s),i=await this.index.query(e,r,o,a),c;s?.limit!==void 0&&s.limit<i.length&&(i.splice(-1),c=rm.createCursorFromLastArrayItem(i,o.sortProperty));let u=[];for(let d=0;d<i.length;d++){let{messageCid:l}=i[d],f=await this.get(e,l,a);f&&u.push(f)}return{messages:u,cursor:c}}async count(e,r,n,s){s?.signal?.throwIfAborted();let a=t.buildQueryOptions(n);return this.index.count(e,r,a,s)}static buildQueryOptions(e={},r={}){let{limit:n,cursor:s}=r,{dateCreated:a,datePublished:o,messageTimestamp:i}=e,c=1,u="messageTimestamp";return a!==void 0?u="dateCreated":o!==void 0?u="datePublished":i!==void 0&&(u="messageTimestamp"),e[u]!==void 0&&(c=e[u]),n!==void 0&&n>0&&(n=n+1),{sortDirection:c,sortProperty:u,limit:n,cursor:s}}async delete(e,r,n){n?.signal?.throwIfAborted();let s=await On(this.blockstore.partition(e),n?.signal),a=zt.parse(r);await s.delete(a,n),await this.index.delete(e,r,n)}async put(e,r,n,s){s?.signal?.throwIfAborted();let a=await On(this.blockstore.partition(e),s?.signal),o=await On(V9({value:r,codec:qc,hasher:Pn}),s?.signal),i=Ar.parseCid(await we.getCid(r));await a.put(i,o.bytes,s);let c=i.toString();await this.index.put(e,c,n,s)}async clear(){await this.blockstore.clear(),await this.index.clear()}};w();Vc();var KA=class t{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:Ki,...e},this.db=new Aa({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 Ar.computeCid(e),s={id:n,timeout:Date.now()+r*1e3,retryCount:0,task:e};return await this.db.put(n,JSON.stringify(s)),s}async grab(e){let r=[];for await(let[n,s]of this.db.iterator()){let a=JSON.parse(s);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 s=JSON.parse(n);s.timeout=Date.now()+r*1e3,await this.db.put(s.id,JSON.stringify(s))}}async delete(e){return this.db.delete(e)}async clear(){await this.db.clear()}};w();w();function J9(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(s){s(r)}),(n=t.get("*"))&&n.slice().map(function(s){s(e,r)})}}}ya();ht();var Z9="events",zA=class t{emitter=J9();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 ne("EventLogNotOpenError","a message emitted when EventLog is closed")),"";let a=(this.tenantSeqs.get(e)??0)+1;this.tenantSeqs.set(e,a);let o=this.tenantLogs.get(e);if(o===void 0&&(o=new Map,this.tenantLogs.set(e,o)),o.set(a,{event:r,indexes:n}),o.size>this.maxEventsPerTenant){let c=o.size-this.maxEventsPerTenant,u=0;for(let d of o.keys()){if(u>=c)break;o.delete(d),u++}}let i=`${e}_${Z9}`;return this.emitter.emit(i,{tenant:e,event:r,indexes:n,seq:a}),String(a)}async read(e,r={}){let{cursor:n,limit:s,filters:a}=r,o=n!==void 0?t.parseCursor(n):void 0,i=this.tenantLogs.get(e);if(i===void 0||i.size===0)return{events:[],cursor:n};let c=[],u=s??Number.MAX_SAFE_INTEGER;for(let[l,f]of i)if(!(o!==void 0&&l<=o)&&!(a!==void 0&&a.length>0&&!Wt.matchAnyFilter(f.indexes,a))&&(c.push({seq:l,event:f.event,indexes:f.indexes}),c.length>=u))break;let d=c.length>0?c[c.length-1].seq:void 0;return{events:c,cursor:d!==void 0?String(d):n}}static parseCursor(e){let r=Number(e);if(Number.isNaN(r)||r<0)throw new ne("EventLogNotOpenError",`invalid cursor: '${e}'`);return r}async subscribe(e,r,n,s){let a=`${e}_${Z9}`,{cursor:o,filters:i}=s??{};if(o!==void 0){let u=t.parseCursor(o),d=[],l=!1,f=y=>{i!==void 0&&i.length>0&&!Wt.matchAnyFilter(y.indexes,i)||(l?n({type:"event",cursor:String(y.seq),event:y.event}):d.push({event:y.event,seq:y.seq}))};this.emitter.on(a,f);let h=await this.read(e,{cursor:o,filters:i}),p=h.cursor??o,m=h.cursor!==void 0?Number(h.cursor):u;for(let y of h.events)n({type:"event",cursor:String(y.seq),event:y.event});l=!0;for(let y of d)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 c=u=>{i!==void 0&&i.length>0&&!Wt.matchAnyFilter(u.indexes,i)||n({type:"event",cursor:String(u.seq),event:u.event})};return this.emitter.on(a,c),{id:r,close:async()=>{this.emitter.off(a,c)}}}async trim(e,r){let n=this.tenantLogs.get(e);if(n!==void 0)if(typeof r=="number")for(let s of n.keys())if(s<r)n.delete(s);else break;else for(let[s,a]of n)(a.indexes.messageTimestamp??"")<r&&n.delete(s)}};w();vu();w();vu();var Fw=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=Vn(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=Vn(e),s=this.serializeNode(r);await this.nodesPartition.put(n,JSON.stringify(s))}async deleteNode(e){this.ensureInitialized();let r=Vn(e);await this.nodesPartition.delete(r)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return ef(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",Vn(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:Vn(e.leftHash),rightHash:Vn(e.rightHash)}:{type:"leaf",keyHash:Vn(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:ef(e.leftHash),rightHash:ef(e.rightHash)}:{type:"leaf",keyHash:ef(e.keyHash),valueCid:e.valueCid}}};w();vu();var Gw=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await ph()}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 Xl(e),n=await ug(r,e),s={type:"leaf",keyHash:r,valueCid:e};await this.store.putNode(n,s);let a=await this.getRoot(),o=await this.insertAtNode(a,r,n,s,0);return await this.store.setRoot(o),o}async delete(e){let r=await Xl(e),n=await this.getRoot(),s=await this.deleteAtNode(n,r,0);return await this.store.setRoot(s),s}async has(e){let r=await Xl(e),n=await this.getRoot();return this.existsAtNode(n,r,0)}async getProof(e){let r=await Xl(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(Xr(r,this.defaultHashes[n]))return this.defaultHashes[e.length];let s=await this.store.getNode(r);if(s===void 0||s.type==="leaf")return s!==void 0&&s.type==="leaf"?this.computeSubtreeHashForLeaf(s,n,e):this.defaultHashes[e.length];let a=s;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(Xr(r,this.defaultHashes[n]))return[];let s=await this.store.getNode(r);if(s===void 0)return[];if(s.type==="leaf")return this.leafMatchesPrefix(s.keyHash,e)?[s.valueCid]:[];let a=s;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(Xr(r,n))return{onlyLocal:[],onlyRemote:[]};let s=[],a=[];return await this.diffAtNode(r,n,0,this,e,s,a),{onlyLocal:s,onlyRemote:a}}async insertAtNode(e,r,n,s,a){if(a>=bi||Xr(e,this.defaultHashes[a]))return n;let o=await this.store.getNode(e);if(o===void 0)return n;if(o.type==="leaf")return Xr(o.keyHash,r)?(await this.store.deleteNode(e),n):this.splitLeaves(o,e,s,n,a);let i=o,c=co(r,a),u,d;c?(u=i.leftHash,d=await this.insertAtNode(i.rightHash,r,n,s,a+1)):(u=await this.insertAtNode(i.leftHash,r,n,s,a+1),d=i.rightHash);let l=await wu(u,d);if(!Xr(l,e)){let f={type:"internal",leftHash:u,rightHash:d};await this.store.putNode(l,f),await this.store.deleteNode(e)}return l}async splitLeaves(e,r,n,s,a){let o=a;for(;o<bi&&co(e.keyHash,o)===co(n.keyHash,o);)o++;if(o>=bi)return s;let i=co(e.keyHash,o),c,u;i?(c=s,u=r):(c=r,u=s);let d=await wu(c,u);await this.store.putNode(d,{type:"internal",leftHash:c,rightHash:u});for(let l=o-1;l>=a;l--){let f=co(e.keyHash,l),h=this.defaultHashes[l+1],p,m;f?(p=h,m=d):(p=d,m=h),d=await wu(p,m),await this.store.putNode(d,{type:"internal",leftHash:p,rightHash:m})}return d}async deleteAtNode(e,r,n){if(n>=bi)return this.defaultHashes[bi];if(Xr(e,this.defaultHashes[n]))return e;let s=await this.store.getNode(e);if(s===void 0)return this.defaultHashes[n];if(s.type==="leaf")return Xr(s.keyHash,r)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let a=s,o=co(r,n),i,c;if(o?(i=a.leftHash,c=await this.deleteAtNode(a.rightHash,r,n+1)):(i=await this.deleteAtNode(a.leftHash,r,n+1),c=a.rightHash),Xr(i,this.defaultHashes[n+1])&&Xr(c,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let u=Xr(i,this.defaultHashes[n+1]),d=Xr(c,this.defaultHashes[n+1]);if(u||d){let f=u?c:i,h=await this.store.getNode(f);if(h!==void 0&&h.type==="leaf")return await this.store.deleteNode(e),f}let l=await wu(i,c);if(!Xr(l,e)){let f={type:"internal",leftHash:i,rightHash:c};await this.store.putNode(l,f),await this.store.deleteNode(e)}return l}async existsAtNode(e,r,n){if(n>=bi||Xr(e,this.defaultHashes[n]))return!1;let s=await this.store.getNode(e);if(s===void 0)return!1;if(s.type==="leaf")return Xr(s.keyHash,r);let a=s;return co(r,n)?this.existsAtNode(a.rightHash,r,n+1):this.existsAtNode(a.leftHash,r,n+1)}async generateProof(e,r,n){if(n>=bi)return{siblings:[],leafNode:void 0,depth:n};if(Xr(e,this.defaultHashes[n]))return{siblings:[],leafNode:void 0,depth:n};let s=await this.store.getNode(e);if(s===void 0)return{siblings:[],leafNode:void 0,depth:n};if(s.type==="leaf")return{siblings:[],leafNode:s,depth:n};let a=s,o=co(r,n),i,c;o?(i=a.rightHash,c=a.leftHash):(i=a.leftHash,c=a.rightHash);let u=await this.generateProof(i,r,n+1);return u.siblings.unshift(c),u}async computeSubtreeHashForLeaf(e,r,n){for(let s=r;s<n.length;s++)if(co(e.keyHash,s)!==n[s])return this.defaultHashes[n.length];return await ug(e.keyHash,e.valueCid)}leafMatchesPrefix(e,r){for(let n=0;n<r.length;n++)if(co(e,n)!==r[n])return!1;return!0}async collectLeaves(e,r){if(r>=bi||Xr(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 s=n,a=await this.collectLeaves(s.leftHash,r+1),o=await this.collectLeaves(s.rightHash,r+1);return[...a,...o]}async diffAtNode(e,r,n,s,a,o,i){if(Xr(e,r)||n>=bi)return;let c=Xr(e,this.defaultHashes[n]),u=Xr(r,this.defaultHashes[n]);if(c&&!u){let f=await a.collectLeaves(r,n);i.push(...f);return}if(!c&&u){let f=await s.collectLeaves(e,n);o.push(...f);return}let d=await s.store.getNode(e),l=await a.store.getNode(r);if(d?.type==="leaf"&&l?.type==="leaf"){Xr(d.keyHash,l.keyHash)?d.valueCid!==l.valueCid&&(o.push(d.valueCid),i.push(l.valueCid)):(o.push(d.valueCid),i.push(l.valueCid));return}if(d?.type==="leaf"){let f=await a.collectLeaves(r,n),h=d.valueCid;new Set(f).has(h)||o.push(h);for(let m of f)m!==h&&i.push(m);return}if(l?.type==="leaf"){let f=await s.collectLeaves(e,n),h=l.valueCid;new Set(f).has(h)||i.push(h);for(let m of f)m!==h&&o.push(m);return}if(d?.type==="internal"&&l?.type==="internal"){await this.diffAtNode(d.leftHash,l.leftHash,n+1,s,a,o,i),await this.diffAtNode(d.rightHash,l.rightHash,n+1,s,a,o,i);return}if(d===void 0){let f=await a.collectLeaves(r,n);i.push(...f)}if(l===void 0){let f=await s.collectLeaves(e,n);o.push(...f)}}};var qA=class{config;db;globalTrees=new Map;protocolTrees=new Map;constructor(e){this.config={location:"STATEINDEX",createLevelDatabase:Ki,...e}}async open(){this.db=new Aa({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await ph()}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 s of r){let a=await this.getStoredIndexes(e,s);if(await n.delete(s),a!==void 0){let o=a.protocol;o!==void 0&&await(await this.getProtocolTree(e,o)).delete(s)}await this.deleteStoredIndexes(e,s)}}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}`,s=this.protocolTrees.get(n);return s!==void 0||(s=this.createTree(this.db,[e,"proto",r]),this.protocolTrees.set(n,s)),s}async createTree(e,r){let n=e;for(let o of r)n=await n.partition(o);let s=new Fw(n),a=new Gw(s);return await a.initialize(),a}async storeIndexes(e,r,n){let s=await this.getMetaPartition(e),a={protocol:n.protocol};await s.put(r,JSON.stringify(a))}async getStoredIndexes(e,r){let s=await(await this.getMetaPartition(e)).get(r);if(s!==void 0)return JSON.parse(s)}async deleteStoredIndexes(e,r){await(await this.getMetaPartition(e)).delete(r)}async getMetaPartition(e){return(await this.db.partition(e)).partition("meta")}};w();vu();var FA=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(Vn(e))}async putNode(e,r){this.nodes.set(Vn(e),r)}async deleteNode(e){this.nodes.delete(Vn(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}};vu();w();Tp();Fc();Vd();ZP();ln();Oa();k0();$n();vi();hs();c0();Rd();Vs();Up();Dy();Qt();Kp();var pue={protocol:"http://test-protocol.xyz",published:!1,types:{testRecord:{}},structure:{testRecord:{}}},GA=class t{static async generatePersona(e){let r=e?.did;r||(r=`did:example:${t.randomString(32)}`);let n=t.randomString(10),s=e?.keyId??`${r}#${n}`,a=e?.keyPair??await $a.generateKeyPair(),o=e?.encryptionKeyPair;if(!o){let c=await gn.generateKey();o={publicJwk:await gn.getPublicKey({key:c}),privateJwk:c}}return{did:r,keyId:s,keyPair:a,encryptionKeyPair:o,signer:new Ud({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:`${r}#${s}`})}}static async installDefaultTestProtocol(e,r){let n=await fd.create({definition:pue,signer:vt.createSigner(r)}),s=await e.processMessage(r.did,n.message);if(s.status.code!==202)throw new Error(`Failed to install default test protocol: ${s.status.code} ${s.status.detail}`)}static async generateProtocolsConfigure(e){let r=e?.author??await t.generatePersona(),n=e?.protocolDefinition;if(!n){let i="record"+t.randomString(10);n={protocol:t.randomString(20),published:e?.published??!1,types:{},structure:{}},n.types[i]={schema:"test-object",dataFormats:["text/plain"]},n.structure[i]={}}let s=vt.createSigner(r),a={messageTimestamp:e?.messageTimestamp,definition:n,signer:s,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},o=await fd.create(a);return{author:r,message:o.message,protocolsConfigure:o}}static async generateProtocolsQuery(e){let r=e?.author??await t.generatePersona(),n=vt.createSigner(r),s={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};qt(s);let a=await hf.create(s);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(),s=e?.dateExpires??yt.createOffsetTimestamp({seconds:10}),a=e?.scope??{interface:"Messages",method:"Read"},o=vt.createSigner(r),i=n.did,c={signer:o,grantedTo:i,dateExpires:s,scope:a,description:e?.description??t.randomString(10),delegated:e?.delegated??!1,requestId:e?.requestId,conditions:e?.conditions},u=await Tr.createGrant(c);return{dataStream:ts.fromBytes(u.permissionGrantBytes),recordsWrite:u.recordsWrite,dataBytes:u.permissionGrantBytes,message:u.recordsWrite.message,dataEncodedMessage:u.dataEncodedMessage}}static async generateRecordsWrite(e){let r=e?.author??await t.generatePersona(),n=vt.createSigner(r),s=vt.createSigners(e?.attesters??[]),a=e?.dataCid,o=e?.dataSize,i,c;a===void 0&&o===void 0&&(i=e?.data??t.randomBytes(32),c=ts.fromBytes(i));let u={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:i,dataCid:a,dataSize:o,signer:n,attestationSigners:s,encryptionInput:e?.encryptionInput,permissionGrantId:e?.permissionGrantId,squash:e?.squash},d=await St.create(u),l=d.message;return{author:r,message:l,dataCid:a,dataSize:o,dataBytes:i,dataStream:c,recordsWrite:d}}static async generateProtocolEncryptedRecordsWrite(e){let{plaintextBytes:r,author:n,recipient:s,protocolDefinition:a,protocolPath:o,protocolParentContextId:i,protocolContextDerivingRootKeyId:c,protocolContextDerivedPublicKeyJwk:u}=e,d=t.randomBytes(12),l=t.randomBytes(32),{ciphertext:f,tag:h}=await ma.aeadEncrypt("A256GCM",l,d,r),p=o.split("/"),m=p[p.length-1],{message:y,dataStream:S,recordsWrite:v}=await t.generateRecordsWrite({author:n,recipient:s,protocol:a.protocol,protocolPath:o,parentContextId:i,schema:a.types[m].schema,dataFormat:a.types[m].dataFormats?.[0],data:f}),E={initializationVector:d,key:l,authenticationTag:h,keyEncryptionInputs:[]};if(e.encryptSymmetricKeyWithProtocolPathDerivedKey){let k=a.structure;for(let j of p)k=k[j];let A=k.$encryption?.publicKeyJwk,B={publicKeyId:k.$encryption?.rootKeyId,publicKey:A,derivationScheme:"protocolPath"};E.keyEncryptionInputs.push(B)}if(e.encryptSymmetricKeyWithProtocolContextDerivedKey){let k;if(i===void 0){let A={rootKeyId:n.keyId,derivationScheme:"protocolContext",derivedPrivateKey:n.encryptionKeyPair.privateJwk},D=await St.getEntryId(n.did,y.descriptor),B=ke.constructKeyDerivationPathUsingProtocolContextScheme(D),j=await Va.derivePublicKey(A,B);k={publicKeyId:n.keyId,publicKey:j,derivationScheme:"protocolContext"}}else{if(c===void 0||u===void 0)throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicKeyJwk` must both be defined if `protocolContextId` is given");k={publicKeyId:c,publicKey:u,derivationScheme:"protocolContext"}}E.keyEncryptionInputs.push(k)}return await v.encryptSymmetricEncryptionKey(E),await v.sign({signer:vt.createSigner(n)}),{message:y,dataStream:S,recordsWrite:v,encryptedDataBytes:f,encryptionInput:E}}static async generateFromRecordsWrite(e){let r=e.existingWrite.message,n=yt.getCurrentTimestamp(),s=!(e.published??r.descriptor.published),a=e.datePublished??(s?n:void 0),o=e.data??t.randomBytes(32),i=ts.fromBytes(o),c={recordsWriteMessage:e.existingWrite.message,data:o,published:s,datePublished:a,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:vt.createSigner(e.author)},u=await St.createFrom(c);return{message:u.message,recordsWrite:u,dataBytes:o,dataStream:i}}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 s;r!==void 0&&(s=vt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole};qt(a);let i=(await Jl.create(a)).message;return{author:r,message:i}}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 s;r!==void 0&&(s=vt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole,cursor:e?.cursor};qt(a);let i=(await mf.create(a)).message;return{author:r,message:i}}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 s;r!==void 0&&(s=vt.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:s,filter:e?.filter??{schema:t.randomString(10)},protocolRole:e?.protocolRole};qt(a);let i=(await Hl.create(a)).message;return{author:r,message:i}}static async generateRecordsDelete(e){let r=e?.author??await t.generateDidKeyPersona(),n=await pd.create({recordId:e?.recordId??await t.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:vt.createSigner(r)});return{author:r,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let r=e?.author??await t.generatePersona(),n=vt.createSigner(r),s={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};qt(s);let a=await Yl.create(s),o=a.message;return{author:r,messagesSubscribe:a,message:o}}static async generateMessagesRead(e){let r=e?.author??await t.generatePersona(),s={signer:vt.createSigner(r),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},a=await Zl.create(s);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 fm.generateKeyPair(),r=await fm.sign(t.randomBytes(32),e.privateJwk);return Te.bytesToBase64Url(r)}static randomString(e){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="";for(let s=0;s<e;s++)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 Pn.digest(e);return(await zt.createV1(Wd,r)).toString()}static randomInt(e,r){return Math.floor(Math.random()*(r-e)+e)}static randomTimestamp(e){let{year:r,month:n,day:s,hour:a,minute:o,second:i,millisecond:c,microsecond:u}=e||{};return yt.createTimestamp({year:r||this.randomInt(2e3,2022),month:n||this.randomInt(1,12),day:s||this.randomInt(1,28),hour:a||this.randomInt(0,23),minute:o||this.randomInt(0,59),second:i||this.randomInt(0,59),millisecond:c||this.randomInt(0,1e3),microsecond:u||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 $w.create(),r=await $w.getSigningMethod({didDocument:e.document}),n=r.id,s=await e.export(),a={publicJwk:r.publicKeyJwk,privateJwk:s.privateKeys[0]},o=await gn.generateKey(),c={publicJwk:await gn.getPublicKey({key:o}),privateJwk:o};return{did:e.uri,keyId:n,keyPair:a,encryptionKeyPair:c,signer:new Ud({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:n})}}};w();Vs();var WA=class t{static pollRetrySleep=20;static pollTimeout=2e3;static async pollUntilSuccessOrTimeout(e,r=t.pollRetrySleep,n=t.pollTimeout){let s=Date.now();for(;;)try{return await e()}catch{if(Date.now()-s>=n)throw new Error("Operation timed out");await yt.sleep(r)}}};export{cg as AllowAllTenantGate,Bf as BlockstoreLevel,Ar as Cid,UE as ContentEncryptionAlgorithm,ag as CoreProtocolRegistry,OA as DataStoreLevel,ts as DataStream,$p as DateSort,PA as Dwn,dc as DwnConstant,ne as DwnError,pt as DwnErrorCode,Yt as DwnInterfaceName,ar as DwnMethodName,Te as Encoder,ma as Encryption,zA as EventEmitterEventLog,Va as HdKey,rm as IndexLevel,vt as Jws,y3 as KeyAgreementAlgorithm,Lp as KeyDerivationScheme,Aa as LevelWrapper,we as Message,LA as MessageStoreLevel,Zl as MessagesRead,Yl as MessagesSubscribe,lg as MessagesSync,LE as PERMISSIONS_REVOCATION_PATH,w3 as PermissionConditionPublication,Zr as PermissionGrant,dg as PermissionRequest,Tr as PermissionsProtocol,WA as Poller,Ud as PrivateKeySigner,cm as ProtocolRecordLimitStrategy,nI as Protocols,fd as ProtocolsConfigure,hf as ProtocolsQuery,ke as Records,Hl as RecordsCount,pd as RecordsDelete,Jl as RecordsQuery,Wg as RecordsRead,mf as RecordsSubscribe,St as RecordsWrite,KA as ResumableTaskStoreLevel,Fw as SMTStoreLevel,FA as SMTStoreMemory,bi as SMT_DEPTH,$a as Secp256k1,Nd as Secp256r1,Ha as SortDirection,Gw as SparseMerkleTree,qA as StateIndexLevel,GA as TestDataGenerator,yt as Time,nk as ZERO_HASH,on as authenticate,Ki as createLevelDatabase,On as executeUnlessAborted,co as getBit,yO as getDefaultHashes,ld as getRuleSetAtPath,wu as hashChildren,Xr as hashEquals,Xl as hashKey,ug as hashLeaf,Vn as hashToHex,ef as hexToHash,ph as initDefaultHashes,pf as isCrossProtocolRef,Bi as parseCrossProtocolRef};
11
11
  /*! Bundled license information:
12
12
 
13
13
  ieee754/index.js: