@typeberry/jam 0.0.1-baf6f80 → 0.0.1-cd1b798

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/typeberry.mjs +1 -1
package/typeberry.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  /*! For license information please see typeberry.mjs.LICENSE.txt */
2
- import{fileURLToPath as e}from"node:url";import{createRequire as t}from"node:module";import*as r from"minimist";import*as s from"lmdb";var i={8:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.matchingBitCount=t.intLog2=t.cidrPrefixToMaskBinaryString=t.leftPadWithZeroBit=t.dottedDecimalNotationToBinaryString=t.parseBinaryStringToBigInt=t.decimalNumberToOctetString=t.numberToBinaryString=void 0,t.numberToBinaryString=e=>e.toString(2),t.decimalNumberToOctetString=e=>{let r=t.numberToBinaryString(e);if(r.length>8)throw new Error("Given decimal in binary contains digits greater than an octet");return t.leftPadWithZeroBit(r,8)},t.parseBinaryStringToBigInt=e=>BigInt(`0b${e}`),t.dottedDecimalNotationToBinaryString=e=>e.split(".").reduce((e,r)=>e.concat(t.decimalNumberToOctetString(parseInt(r))),""),t.leftPadWithZeroBit=(e,t)=>{if(e.length>t)throw new Error(`Given string is already longer than given final length after padding: ${t}`);return"0".repeat(t-e.length).concat(e)},t.cidrPrefixToMaskBinaryString=(e,t)=>{let r;if(r="IPv4"==t?32:128,e>r)throw Error(`Value is greater than ${r}`);return`${"1".repeat(e)}${"0".repeat(r-e)}`},t.intLog2=e=>{let t=0;for(;e%2n==0n;){if(2n===e){t++;break}if((e>>=1n)%2n!=0n){t=0;break}t++}if(0==t)throw new Error(`The value of log2 for ${e.toString()} is not an integer`);return t},t.matchingBitCount=(e,t)=>{let r,s;e.length>=t.length?(r=e,s=t):(r=t,s=e);let i=0;for(;i<r.length&&r.charAt(i)===s.charAt(i);i++);return i}},54:e=>{e.exports=function e(r,s){if(!r){var i=new t(s);throw Error.captureStackTrace&&Error.captureStackTrace(i,e),i}};class t extends Error{}t.prototype.name="AssertionError"},154:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Hexadecatet=void 0;const s=r(660);class i{constructor(e){let t;t="string"==typeof e?parseInt(e,16):parseInt(String(e),16);let[r,i]=s.Validator.isValidIPv6Hexadecatet(BigInt(t));if(!r)throw Error(i.filter(e=>""!==e).toString());this.value=t}static fromString(e){return new i(e)}static fromNumber(e){return new i(e)}getValue(){return this.value}toString(){return this.value.toString(16)}}t.Hexadecatet=i},212:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIPv4=t.IPv6Mask=t.IPv4Mask=t.IPv6=t.Asn=t.IPv4=t.AbstractIPNum=void 0;const s=r(301),i=r(660),n=r(8),o=r(8),a=r(8),c=r(8),l=r(154),h=r(984),u=r(872),d=r(984);class f{getValue(){return this.value}toBinaryString(){return a.leftPadWithZeroBit(this.value.toString(2),this.bitSize)}hasNext(){return this.value<this.maximumBitSize}hasPrevious(){return this.value>0n}isEquals(e){return this.value===e.value}isLessThan(e){return this.value<e.value}isGreaterThan(e){return this.value>e.value}isLessThanOrEquals(e){return this.value<=e.value}isGreaterThanOrEquals(e){return this.value>=e.value}}t.AbstractIPNum=f;class p extends f{constructor(e){if(super(),this.bitSize=32,this.maximumBitSize=i.Validator.THIRTY_TWO_BIT_SIZE,this.type="IPv4",this.octets=[],this.separator=".","string"==typeof e){let[t,r]=this.constructFromDecimalDottedString(e);this.value=t,this.octets=r}else{let[t,r]=this.constructFromBigIntValue(e);this.value=t,this.octets=r}}static fromNumber(e){return new p(e)}static fromDecimalDottedString(e){return new p(e)}static fromString(e){return p.fromDecimalDottedString(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new p(o.parseBinaryStringToBigInt(e));throw Error(t[1].join(","))}toString(){return this.octets.map(e=>e.toString()).join(this.separator)}getOctets(){return this.octets}nextIPNumber(){return p.fromNumber(this.getValue()+1n)}previousIPNumber(){return p.fromNumber(this.getValue()-1n)}toIPv4MappedIPv6(){let e="1".repeat(16)+this.toBinaryString();return y.fromBinaryString(e)}constructFromDecimalDottedString(e){let t,r,[o,a]=i.Validator.isValidIPv4String(e);if(!o)throw new Error(a.filter(e=>""!==e).toString());return t=e.split(".").map(e=>s.Octet.fromString(e)),r=BigInt(`0b${n.dottedDecimalNotationToBinaryString(e)}`),[r,t]}constructFromBigIntValue(e){let[t,r]=i.Validator.isValidIPv4Number(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let s=c.numberToBinaryString(e);return[e="bigint"==typeof e?e:BigInt(e),this.binaryStringToDecimalOctets(s)]}binaryStringToDecimalOctets(e){return e.length<32&&(e=a.leftPadWithZeroBit(e,32)),e.match(/.{1,8}/g).map(e=>s.Octet.fromString(o.parseBinaryStringToBigInt(e).toString()))}}t.IPv4=p;class g extends f{constructor(e){if(super(),this.bitSize=32,this.maximumBitSize=i.Validator.THIRTY_TWO_BIT_SIZE,this.type="ASN","string"==typeof e)g.startWithASPrefix(e)?this.value=BigInt(parseInt(e.substring(2))):-1!=e.indexOf(".")?this.value=BigInt(this.parseFromDotNotation(e)):this.value=BigInt(parseInt(e));else{let t=BigInt(e),[r,s]=i.Validator.isValidAsnNumber(t);if(!r)throw Error(s.filter(e=>""!==e).toString());this.value=t}}static fromString(e){return new g(e)}static fromNumber(e){return new g(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new g(parseInt(e,2));throw Error(t[1].join(","))}toString(){let e=this.value.toString();return`${g.AS_PREFIX}${e}`}toASPlain(){return this.value.toString()}toASDot(){return this.value.valueOf()>=65536n?this.toASDotPlus():this.toASPlain()}toASDotPlus(){let e=this.value.valueOf()/65535n;return`${e}.${this.value.valueOf()%65535n-e}`}toBinaryString(){return c.numberToBinaryString(this.value)}is16Bit(){let[e]=i.Validator.isValid16BitAsnNumber(this.value);return e}is32Bit(){return!this.is16Bit()}nextIPNumber(){return new g(this.value.valueOf()+1n)}previousIPNumber(){return new g(this.value.valueOf()-1n)}static startWithASPrefix(e){return 0===e.indexOf(g.AS_PREFIX)}parseFromDotNotation(e){let t=e.split("."),r=parseInt(t[0]);return 65535*r+(parseInt(t[1])+r)}}t.Asn=g,g.AS_PREFIX="AS";class y extends f{constructor(e){if(super(),this.bitSize=128,this.maximumBitSize=i.Validator.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE,this.type="IPv6",this.hexadecatet=[],this.separator=":","string"==typeof e){let t=u.expandIPv6Number(e),[r,s]=this.constructFromHexadecimalDottedString(t);this.value=r,this.hexadecatet=s}else{let[t,r]=this.constructFromBigIntValue(e);this.value=t,this.hexadecatet=r}}static fromBigInt(e){return new y(e)}static fromHexadecatet(e){return new y(e)}static fromString(e){return y.fromHexadecatet(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0]){let t=a.leftPadWithZeroBit(e,128);return new y(o.parseBinaryStringToBigInt(t))}throw Error(t[1].join(","))}static fromIPv4(e){return e.toIPv4MappedIPv6()}static fromIPv4DotDecimalString(e){return new p(e).toIPv4MappedIPv6()}toString(){let e=this.hexadecatet.map(e=>e.toString()).join(":");return this.hexadecatet.length<8?"::"+e:e}getHexadecatet(){return this.hexadecatet}nextIPNumber(){return y.fromBigInt(this.getValue()+1n)}previousIPNumber(){return y.fromBigInt(this.getValue()-1n)}constructFromBigIntValue(e){let[t,r]=i.Validator.isValidIPv6Number(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let s=c.numberToBinaryString(e);return[e,this.binaryStringToHexadecatets(s)]}constructFromHexadecimalDottedString(e){let[t,r]=i.Validator.isValidIPv6String(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let s=e.split(":").map(e=>l.Hexadecatet.fromString(e));return[BigInt(`0b${d.hexadectetNotationToBinaryString(e)}`),s]}binaryStringToHexadecatets(e){let t=h.binaryStringToHexadecimalString(e);for(;t.length%4!=0;)t="0"+t;return t.match(/.{1,4}/g).map(e=>l.Hexadecatet.fromString(e))}}t.IPv6=y;class m extends p{constructor(e){let t,r;if(super(e),this.octets=[],[t,r]=i.Validator.isValidIPv4Mask(e),!t)throw new Error(r.filter(e=>""!==e).toString());let o=e.split(".");this.octets=o.map(e=>s.Octet.fromString(e));let a=n.dottedDecimalNotationToBinaryString(e);this.prefix=(a.match(/1/g)||[]).length,this.value=BigInt(`0b${a}`)}static fromDecimalDottedString(e){return new m(e)}}t.IPv4Mask=m;class b extends y{constructor(e){let t,r;super(e),this.hexadecatet=[];let s=u.expandIPv6Number(e);if([t,r]=i.Validator.isValidIPv6Mask(s),!t)throw new Error(r.filter(e=>""!==e).toString());let n=s.split(":");this.hexadecatet=n.map(e=>l.Hexadecatet.fromString(e));let o=d.hexadectetNotationToBinaryString(s);this.prefix=(o.match(/1/g)||[]).length,this.value=BigInt(`0b${o}`),this.value=BigInt(`0b${d.hexadectetNotationToBinaryString(s)}`)}static fromHexadecatet(e){return new b(e)}}t.IPv6Mask=b,t.isIPv4=function(e){return 32===e.bitSize}},259:e=>{var t,r,s=(()=>{for(var e=new Uint8Array(128),t=0;t<64;t++)e[t<26?t+65:t<52?t+71:t<62?t-4:4*t-205]=t;return t=>{for(var r=t.length,s=new Uint8Array(3*(r-("="==t[r-1])-("="==t[r-2]))/4|0),i=0,n=0;i<r;){var o=e[t.charCodeAt(i++)],a=e[t.charCodeAt(i++)],c=e[t.charCodeAt(i++)],l=e[t.charCodeAt(i++)];s[n++]=o<<2|a>>4,s[n++]=a<<4|c>>2,s[n++]=c<<6|l}return s}})(),i=(t={"wasm-binary:./blake2b.wat"(e,t){t.exports=s("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMKvz8EwAIAIABCADcDACAAQgA3AwggAEIANwMQIABCADcDGCAAQgA3AyAgAEIANwMoIABCADcDMCAAQgA3AzggAEIANwNAIABCADcDSCAAQgA3A1AgAEIANwNYIABCADcDYCAAQgA3A2ggAEIANwNwIABCADcDeCAAQoiS853/zPmE6gBBACkDAIU3A4ABIABCu86qptjQ67O7f0EIKQMAhTcDiAEgAEKr8NP0r+68tzxBECkDAIU3A5ABIABC8e30+KWn/aelf0EYKQMAhTcDmAEgAELRhZrv+s+Uh9EAQSApAwCFNwOgASAAQp/Y+dnCkdqCm39BKCkDAIU3A6gBIABC6/qG2r+19sEfQTApAwCFNwOwASAAQvnC+JuRo7Pw2wBBOCkDAIU3A7gBIABCADcDwAEgAEIANwPIASAAQgA3A9ABC20BA38gAEHAAWohAyAAQcgBaiEEIAQpAwCnIQUCQANAIAEgAkYNASAFQYABRgRAIAMgAykDACAFrXw3AwBBACEFIAAQAwsgACAFaiABLQAAOgAAIAVBAWohBSABQQFqIQEMAAsLIAQgBa03AwALYQEDfyAAQcABaiEBIABByAFqIQIgASABKQMAIAIpAwB8NwMAIABCfzcD0AEgAikDAKchAwJAA0AgA0GAAUYNASAAIANqQQA6AAAgA0EBaiEDDAALCyACIAOtNwMAIAAQAwuqOwIgfgl/IABBgAFqISEgAEGIAWohIiAAQZABaiEjIABBmAFqISQgAEGgAWohJSAAQagBaiEmIABBsAFqIScgAEG4AWohKCAhKQMAIQEgIikDACECICMpAwAhAyAkKQMAIQQgJSkDACEFICYpAwAhBiAnKQMAIQcgKCkDACEIQoiS853/zPmE6gAhCUK7zqqm2NDrs7t/IQpCq/DT9K/uvLc8IQtC8e30+KWn/aelfyEMQtGFmu/6z5SH0QAhDUKf2PnZwpHagpt/IQ5C6/qG2r+19sEfIQ9C+cL4m5Gjs/DbACEQIAApAwAhESAAKQMIIRIgACkDECETIAApAxghFCAAKQMgIRUgACkDKCEWIAApAzAhFyAAKQM4IRggACkDQCEZIAApA0ghGiAAKQNQIRsgACkDWCEcIAApA2AhHSAAKQNoIR4gACkDcCEfIAApA3ghICANIAApA8ABhSENIA8gACkD0AGFIQ8gASAFIBF8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSASfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgE3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBR8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAVfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFnx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBd8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAYfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgGXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBp8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAbfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgHHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIB18fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAefHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgH3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFICB8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAffHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgG3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBV8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAZfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHICB8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAefHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggF3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBJ8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAdfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgEXx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBN8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAcfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggGHx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBZ8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAUfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHHx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBl8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAdfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgEXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBZ8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByATfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggIHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIB58fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAbfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgH3x8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBR8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAXfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBJ8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAafHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFXx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBh8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAafHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFHx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBJ8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAefHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHXx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBx8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAffHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgE3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBd8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAWfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgG3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBV8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCARfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgIHx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBl8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAafHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEXx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBZ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAYfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgE3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBV8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAbfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggIHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIB98fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiASfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgHHx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB18fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAXfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggGXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBR8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAefHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgE3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIB18fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAXfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgG3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBF8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAcfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggGXx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBR8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAVfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBh8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAWfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggIHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB98fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSASfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgGnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB18fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAWfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgEnx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGICB8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAffHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHnx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBV8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAbfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBh8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAXfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBp8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCATfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGXx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBx8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAefHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgHHx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBh8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAffHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBJ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAUfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBZ8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiARfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgIHx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBV8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAZfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggF3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBN8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAbfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgF3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFICB8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAffHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGnx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBx8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAUfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggEXx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBl8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAdfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgE3x8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIB58fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAYfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggEnx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBV8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAbfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBt8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSATfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgGXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBV8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAYfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgF3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBJ8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAWfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgIHx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBx8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAafHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgH3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBR8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAdfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgHnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBF8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgISAhKQMAIAEgCYWFNwMAICIgIikDACACIAqFhTcDACAjICMpAwAgAyALhYU3AwAgJCAkKQMAIAQgDIWFNwMAICUgJSkDACAFIA2FhTcDACAmICYpAwAgBiAOhYU3AwAgJyAnKQMAIAcgD4WFNwMAICggKCkDACAIIBCFhTcDAAs=")}},function(){return r||(0,t[Object.keys(t)[0]])((r={exports:{}}).exports,r),r.exports})(),n=WebAssembly.compile(i);e.exports=async e=>(await WebAssembly.instantiate(await n,e)).exports},287:e=>{function t(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}e.exports={isBuffer:function(e){return Buffer.isBuffer(e)||e instanceof Uint8Array},isEncoding:function(e){return Buffer.isEncoding(e)},alloc:function(e,t,r){return Buffer.alloc(e,t,r)},allocUnsafe:function(e){return Buffer.allocUnsafe(e)},allocUnsafeSlow:function(e){return Buffer.allocUnsafeSlow(e)},byteLength:function(e,t){return Buffer.byteLength(e,t)},compare:function(e,t){return Buffer.compare(e,t)},concat:function(e,t){return Buffer.concat(e,t)},copy:function(e,r,s,i,n){return t(e).copy(r,s,i,n)},equals:function(e,r){return t(e).equals(r)},fill:function(e,r,s,i,n){return t(e).fill(r,s,i,n)},from:function(e,t,r){return Buffer.from(e,t,r)},includes:function(e,r,s,i){return t(e).includes(r,s,i)},indexOf:function(e,r,s,i){return t(e).indexOf(r,s,i)},lastIndexOf:function(e,r,s,i){return t(e).lastIndexOf(r,s,i)},swap16:function(e){return t(e).swap16()},swap32:function(e){return t(e).swap32()},swap64:function(e){return t(e).swap64()},toBuffer:t,toString:function(e,r,s,i){return t(e).toString(r,s,i)},write:function(e,r,s,i,n){return t(e).write(r,s,i,n)},writeDoubleLE:function(e,r,s){return t(e).writeDoubleLE(r,s)},writeFloatLE:function(e,r,s){return t(e).writeFloatLE(r,s)},writeUInt32LE:function(e,r,s){return t(e).writeUInt32LE(r,s)},writeInt32LE:function(e,r,s){return t(e).writeInt32LE(r,s)},readDoubleLE:function(e,r){return t(e).readDoubleLE(r)},readFloatLE:function(e,r){return t(e).readFloatLE(r)},readUInt32LE:function(e,r){return t(e).readUInt32LE(r)},readInt32LE:function(e,r){return t(e).readInt32LE(r)}}},301:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Octet=void 0;const s=r(660);class i{constructor(e){let t;t="string"==typeof e?parseInt(e):e;let[r,i]=s.Validator.isValidIPv4Octet(BigInt(t));if(!r)throw Error(i.filter(e=>""!==e).toString());this.value=t}static fromString(e){return new i(e)}static fromNumber(e){return new i(e)}getValue(){return this.value}toString(){return this.value.toString(10)}}t.Octet=i},405:(t,r,s)=>{var i=e(import.meta.url+"/..").slice(0,-1);let n,o=null;function a(){return null!==o&&0!==o.byteLength||(o=new Uint8Array(n.memory.buffer)),o}let c=0;function l(e,t){const r=t(1*e.length,1)>>>0;return a().set(e,r/1),c=e.length,r}let h=null;function u(){return null!==h&&0!==h.byteLength||(h=new Int32Array(n.memory.buffer)),h}function d(e,t){return e>>>=0,a().subarray(e/1,e/1+t)}t.exports.hc=function(e){try{const i=n.__wbindgen_add_to_stack_pointer(-16),o=l(e,n.__wbindgen_malloc),a=c;n.ring_commitment(i,o,a);var t=u()[i/4+0],r=u()[i/4+1],s=d(t,r).slice();return n.__wbindgen_free(t,1*r,1),s}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.KG=function(e,t,r,s,i){try{const f=n.__wbindgen_add_to_stack_pointer(-16),p=l(e,n.__wbindgen_malloc),g=c,y=l(r,n.__wbindgen_malloc),m=c,b=l(s,n.__wbindgen_malloc),A=c,I=l(i,n.__wbindgen_malloc),v=c;n.verify_seal(f,p,g,t,y,m,b,A,I,v);var o=u()[f/4+0],a=u()[f/4+1],h=d(o,a).slice();return n.__wbindgen_free(o,1*a,1),h}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.ZJ=function(e,t,r){try{const a=n.__wbindgen_add_to_stack_pointer(-16),h=l(e,n.__wbindgen_malloc),f=c,p=l(t,n.__wbindgen_malloc),g=c;n.batch_verify_tickets(a,h,f,p,g,r);var s=u()[a/4+0],i=u()[a/4+1],o=d(s,i).slice();return n.__wbindgen_free(s,1*i,1),o}finally{n.__wbindgen_add_to_stack_pointer(16)}};const f=s(928).join(i,"bandersnatch_bg.wasm"),p=s(896).readFileSync(f),g=new WebAssembly.Module(p),y=new WebAssembly.Instance(g,{});n=y.exports},412:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIPv4CidrRange=t.IPv6CidrRange=t.IPv4CidrRange=t.AbstractIPRange=t.RangedSet=void 0;const s=r(212),i=r(516),n=r(8),o=r(660);class a{constructor(e,t){if(this.first=e,this.last=t,e.isGreaterThan(t))throw new Error(`${e.toString()} should be lower than ${t.toString()}`);this.currentValue=e,this.bitValue=BigInt(e.bitSize)}static fromSingleIP(e){return new a(e,e)}static fromCidrRange(e){return new a(e.getFirst(),e.getLast())}static fromRangeString(e){let t=e.split("-").map(e=>e.trim());if(2!==t.length)throw new Error("Argument should be in the format firstip-lastip");let[r,i]=t,[n]=o.Validator.isValidIPv4String(r),[c]=o.Validator.isValidIPv4String(i),[l]=o.Validator.isValidIPv6String(r),[h]=o.Validator.isValidIPv6String(i);if(n&&c)return new a(s.IPv4.fromDecimalDottedString(r),s.IPv4.fromDecimalDottedString(i));if(l&&h)return new a(s.IPv6.fromHexadecatet(r),s.IPv6.fromHexadecatet(i));throw new Error("First IP and Last IP should be valid and same type")}getFirst(){return this.first}getLast(){return this.last}getSize(){return this.last.getValue()-this.first.getValue()+1n}toRangeString(){return`${this.getFirst()}-${this.getLast()}`}inside(e){return e.contains(this)}contains(e){let t=this.getFirst(),r=this.getLast(),s=e.getFirst(),i=e.getLast();return t.isLessThanOrEquals(s)&&r.isGreaterThanOrEquals(i)}isEquals(e){return this.getFirst().isEquals(e.getFirst())&&this.getLast().isEquals(e.getLast())}isLessThan(e){return!this.isEquals(e)&&(this.getFirst().isEquals(e.getFirst())?this.getSize()<e.getSize():this.getFirst().isLessThan(e.getFirst()))}isGreaterThan(e){return!this.isEquals(e)&&(this.getFirst().isEquals(e.getFirst())?this.getSize()>e.getSize():this.getFirst().isGreaterThan(e.getFirst()))}isOverlapping(e){let t=this.getFirst(),r=this.getLast(),s=e.getFirst(),i=e.getLast();return r.isGreaterThan(s)&&r.isLessThanOrEquals(i)&&t.isLessThan(s)||i.isGreaterThan(t)&&i.isLessThanOrEquals(r)&&s.isLessThan(t)}isCidrAble(){if(1n===this.getSize())return!0;try{let e=n.intLog2(this.getSize()),t=n.parseBinaryStringToBigInt(n.cidrPrefixToMaskBinaryString(e,s.isIPv4(this.currentValue)?"IPv4":"IPv6"));return this.first.getValue()===(t&this.first.getValue())}catch(e){return!1}}toCidrRange(){return s.isIPv4(this.currentValue)?this.toIPv4CidrRange():this.toIPv6CidrRange()}isConsecutive(e){let t=this.getFirst(),r=this.getLast(),s=e.getFirst(),i=e.getLast();return r.hasNext()&&r.nextIPNumber().isEquals(s)||i.hasNext()&&i.nextIPNumber().isEquals(t)}union(e){if(this.isEquals(e))return new a(e.getFirst(),e.getLast());if(this.isOverlapping(e))return this.getFirst().isLessThan(e.getFirst())?new a(this.getFirst(),e.getLast()):new a(e.getFirst(),this.getLast());if(this.contains(e))return new a(this.getFirst(),this.getLast());if(e.contains(this))return new a(e.getFirst(),e.getLast());throw new Error("Ranges do not overlap nor are equal")}prepend(e){if(e.getLast().nextIPNumber().isEquals(this.getFirst()))return new a(e.getFirst(),this.getLast());throw new Error("Range to prepend must be adjacent")}append(e){if(this.getLast().nextIPNumber().isEquals(e.getFirst()))return new a(this.getFirst(),e.getLast());throw new Error("Range to append must be adjacent")}subtract(e){if(!this.isOverlapping(e))throw new Error("Cannot subtract ranges that are not overlapping");if(!this.isLessThan(e))throw new Error("Cannot subtract a larger range from this range");return new a(this.getFirst(),e.getLast())}takeSubRange(e,t){if(e+t>this.getSize())throw new RangeError("Requested range is greater than what can be taken");if(0n===t)throw new Error("Sub range cannot be zero");let r=this.getFirst().value+e,i=s.isIPv4(this.getFirst())?s.IPv4.fromNumber(r):s.IPv6.fromBigInt(r),n=i.value+(t-1n),o=s.isIPv4(i)?s.IPv4.fromNumber(n):s.IPv6.fromBigInt(n);return new a(i,o)}difference(e){if(e.getSize()>this.getSize())throw new Error("Range is greater than range to be subtracted from");if(!this.contains(e))throw new Error("Range to subtract is not contained in this range");let t=[];try{t.push(new a(this.getFirst(),e.getFirst().previousIPNumber()))}catch(e){}try{t.push(new a(e.getLast().nextIPNumber(),this.getLast()))}catch(e){}return t}*take(e){let t=this.getFirst(),r=void 0===e?this.getSize().valueOf():e;for(;r>0;)r--,yield t,t=t.nextIPNumber()}*[Symbol.iterator](){yield*this.take()}toIPv4CidrRange(){let e=new l(s.IPv4.fromNumber(this.getFirst().getValue()),i.IPv4Prefix.fromRangeSize(this.getSize()));if(e.getFirst().isEquals(this.getFirst()))return e;throw new Error("Range cannot be converted to CIDR")}toIPv6CidrRange(){let e=new h(s.IPv6.fromBigInt(this.getFirst().getValue()),i.IPv6Prefix.fromRangeSize(this.getSize()));if(e.getFirst().isEquals(this.getFirst()))return e;throw new Error("Range cannot be converted to CIDR")}}t.RangedSet=a;class c{hasNextRange(){let e=this.getSize();return 2n**this.bitValue-e>=this.getFirst().getValue()+e}hasPreviousRange(){return this.getSize()<=this.getFirst().getValue()}toRangeSet(){return new a(this.getFirst(),this.getLast())}inside(e){return this.toRangeSet().inside(e.toRangeSet())}contains(e){return this.toRangeSet().contains(e.toRangeSet())}toRangeString(){return this.toRangeSet().toRangeString()}isOverlapping(e){return this.toRangeSet().isOverlapping(e.toRangeSet())}isConsecutive(e){return this.toRangeSet().isConsecutive(e.toRangeSet())}isCidrMergeable(e){const t=BigInt(n.matchingBitCount(this.getFirst().toBinaryString(),e.getFirst().toBinaryString()));return this.getPrefix().value-t===1n&&this.isConsecutive(e)&&this.getSize()===e.getSize()}isMergeable(e){return this.isCidrMergeable(e)||this.contains(e)||this.inside(e)}isEquals(e){return this.toRangeSet().isEquals(e.toRangeSet())}merge(e){if(!this.isCidrMergeable(e))throw new Error(`Cannot merge. Ranges (${this.toRangeString()},${e.toRangeString()}) are not consecutive and/or of same size`);return this.newInstance(this.getFirst(),this.getPrefix().merge())}*takeStream(e){return this.toRangeSet().take(e)}*[Symbol.iterator](){yield*this.toRangeSet()}}t.AbstractIPRange=c;class l extends c{constructor(e,t){super(),this.ipv4=e,this.cidrPrefix=t,this.bitValue=32n}static fromCidr(e){let[t,r]=o.Validator.isValidIPv4CidrNotation(e);if(!t){let e=r.filter(e=>""!==e);throw new Error(e.join(" and "))}let n=e.split("/"),a=n[0],c=BigInt(parseInt(n[1]));return new l(s.IPv4.fromDecimalDottedString(a),i.IPv4Prefix.fromNumber(c))}getSize(){return this.cidrPrefix.toRangeSize()}toCidrString(){return`${this.ipv4.toString().toString()}/${this.cidrPrefix.toString()}`}toRangeString(){return super.toRangeString()}getFirst(){return s.IPv4.fromNumber(this.ipv4.getValue()&this.cidrPrefix.toMask().getValue())}getLast(){return u(this,this.ipv4)}newInstance(e,t){return new l(e,t)}getPrefix(){return this.cidrPrefix}isConsecutive(e){return super.isConsecutive(e)}contains(e){return super.contains(e)}inside(e){return super.inside(e)}isOverlapping(e){return super.isOverlapping(e)}take(e){let t=[this.getFirst()],r=this.getFirst();if(e>this.getSize()){let t=o.Validator.takeOutOfRangeSizeMessage.replace("$count",e.toString()).replace("$size",this.getSize().toString());throw new Error(t)}for(let s=0;s<e-1n;s++)t.push(r.nextIPNumber()),r=r.nextIPNumber();return t}split(){let e=this.cidrPrefix.getValue();if(32n===e)throw new Error("Cannot split an IP range with a single IP number");let t=i.IPv4Prefix.fromNumber(e+1n),r=this.getFirst(),s=new l(r,t),n=s.getLast().nextIPNumber();return[s,new l(n,t)]}splitInto(e){let t=e.getValue()-this.cidrPrefix.getValue();if(t<0)throw new Error("Prefix to split into is larger than source prefix");if(0n===t)return[new l(this.getFirst(),e)];if(1n===t)return this.split();{let e=this.split();for(;t>1;)e=e.flatMap(e=>e.split()),t-=1n;return e}}hasNextRange(){return super.hasNextRange()}hasPreviousRange(){return super.hasPreviousRange()}nextRange(){if(this.hasNextRange()){let e=this.getSize(),t=this.getFirst().getValue()+e;return new l(new s.IPv4(t),this.cidrPrefix)}}previousRange(){if(this.hasPreviousRange()){let e=this.getSize(),t=this.getFirst().getValue()-e;return new l(new s.IPv4(t),this.cidrPrefix)}}}t.IPv4CidrRange=l;class h extends c{constructor(e,t){super(),this.ipv6=e,this.cidrPrefix=t,this.bitValue=128n}static fromCidr(e){let[t,r]=o.Validator.isValidIPv6CidrNotation(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let n=e.split("/"),a=n[0],c=BigInt(parseInt(n[1]));return new h(s.IPv6.fromHexadecatet(a),i.IPv6Prefix.fromNumber(c))}getSize(){return this.cidrPrefix.toRangeSize()}toCidrString(){return`${this.ipv6.toString().toString()}/${this.cidrPrefix.toString()}`}toRangeString(){return super.toRangeString()}getFirst(){return s.IPv6.fromBigInt(this.ipv6.getValue()&this.cidrPrefix.toMask().getValue())}getLast(){return u(this,this.ipv6)}newInstance(e,t){return new h(e,t)}getPrefix(){return this.cidrPrefix}isConsecutive(e){return super.isConsecutive(e)}contains(e){return super.contains(e)}inside(e){return super.inside(e)}isOverlapping(e){return super.isOverlapping(e)}take(e){let t=[this.getFirst()],r=this.getFirst();if(e>this.getSize())throw new Error(`${e.toString()} is greater than ${this.getSize().toString()}, the size of the range`);for(var s=0;s<e-1n;s++)t.push(r.nextIPNumber()),r=r.nextIPNumber();return t}split(){let e=this.cidrPrefix.getValue();if(128n===e)throw new Error("Cannot split an IP range with a single IP number");let t=i.IPv6Prefix.fromNumber(e+1n),r=this.getFirst(),s=new h(r,t),n=s.getLast().nextIPNumber();return[s,new h(n,t)]}splitInto(e){let t=e.getValue()-this.cidrPrefix.getValue();if(t<0)throw new Error("Prefix to split into is larger than source prefix");if(0n===t)return[new h(this.getFirst(),e)];if(1n===t)return this.split();{let e=this.split();for(;t>1;)e=e.flatMap(e=>e.split()),t-=1n;return e}}hasNextRange(){return super.hasNextRange()}hasPreviousRange(){return super.hasPreviousRange()}nextRange(){if(this.hasNextRange()){let e=this.getSize(),t=this.getFirst().getValue()+e;return new h(new s.IPv6(t),this.cidrPrefix)}}previousRange(){if(this.hasPreviousRange()){let e=this.getSize(),t=this.getFirst().getValue()-e;return new h(new s.IPv6(t),this.cidrPrefix)}}}t.IPv6CidrRange=h;let u=(e,t)=>{let r=Number(e.bitValue.valueOf()),i=BigInt(`0b${"1".repeat(r)}`),o=e.cidrPrefix.toMask().getValue(),a=n.leftPadWithZeroBit((o^i).toString(2),r);return d(e)?s.IPv4.fromNumber(t.getValue()|n.parseBinaryStringToBigInt(a)):s.IPv6.fromBigInt(t.getValue()|n.parseBinaryStringToBigInt(a))};function d(e){return 32n===e.bitValue.valueOf()}t.isIPv4CidrRange=d},429:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},516:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIPv4Prefix=t.IPv6Prefix=t.IPv4Prefix=void 0;const s=r(660),i=r(212),n=r(8),o=r(984),a=r(154);class c{constructor(e){let t,r;if(this.type="IPv4",this.bitValue=32n,[t,r]=s.Validator.isValidPrefixValue(e,"IPv4"),!t)throw new Error(r.filter(e=>""!==e).toString());this.value=e}static fromNumber(e){return new c(e)}static fromRangeSize(e){let t=1n===e?32:32-h(e,s.Validator.IPV4_SIZE);return c.fromNumber(BigInt(t))}getValue(){return this.value}toString(){return this.value.toString()}toMask(){let e="1".repeat(Number(this.value)),t="0".repeat(Number(32n-this.value));return i.IPv4Mask.fromDecimalDottedString(this.toDecimalNotation(`${e}${t}`))}toRangeSize(){return 1n<<this.bitValue-this.getValue()}merge(){return new c(this.value-1n)}split(){return new c(this.value+1n)}toDecimalNotation(e){return`${n.parseBinaryStringToBigInt(e.substr(0,8))}.${n.parseBinaryStringToBigInt(e.substr(8,8))}.${n.parseBinaryStringToBigInt(e.substr(16,8))}.${n.parseBinaryStringToBigInt(e.substr(24,8))}`}}t.IPv4Prefix=c;class l{constructor(e){let t,r;if(this.type="IPv6",this.bitValue=128n,[t,r]=s.Validator.isValidPrefixValue(e,"IPv6"),!t)throw new Error(r.filter(e=>""!==e).toString());this.value=e}static fromNumber(e){return new l(e)}static fromRangeSize(e){let t=1n===e?128:128-h(e,s.Validator.IPV6_SIZE);return l.fromNumber(BigInt(t))}getValue(){return this.value}toString(){return this.value.toString()}toMask(){let e="1".repeat(Number(this.value)),t="0".repeat(128-Number(this.value));return i.IPv6Mask.fromHexadecatet(this.toHexadecatetNotation(`${e}${t}`))}toRangeSize(){return 1n<<this.bitValue-this.getValue()}merge(){return new l(this.value-1n)}split(){return new l(this.value+1n)}toHexadecatetNotation(e){return e.match(/.{1,16}/g).map(e=>a.Hexadecatet.fromString(o.binaryStringToHexadecimalString(e))).map(e=>e.toString()).join(":")}}function h(e,t){let r=t>s.Validator.IPV4_SIZE?"IPv6":"IPv4";if(e>t||0n===e)throw new Error(s.Validator.invalidIPRangeSizeMessage.replace("$iptype",r));try{return n.intLog2(e)}catch(e){throw new Error(s.Validator.invalidIPRangeSizeForCidrMessage)}}t.IPv6Prefix=l,t.isIPv4Prefix=function(e){return"IPv4"===e.type}},578:(e,t,r)=>{var s=r(54),i=r(287),n=null,o="undefined"!=typeof WebAssembly&&r(259)().then(e=>{n=e}),a=64,c=[];e.exports=g;var l=e.exports.BYTES_MIN=16,h=e.exports.BYTES_MAX=64,u=(e.exports.BYTES=32,e.exports.KEYBYTES_MIN=16),d=e.exports.KEYBYTES_MAX=64,f=(e.exports.KEYBYTES=32,e.exports.SALTBYTES=16),p=e.exports.PERSONALBYTES=16;function g(e,t,r,i,o){if(!(this instanceof g))return new g(e,t,r,i,o);if(!n)throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");e||(e=32),!0!==o&&(s(e>=l,"digestLength must be at least "+l+", was given "+e),s(e<=h,"digestLength must be at most "+h+", was given "+e),null!=t&&(s(t instanceof Uint8Array,"key must be Uint8Array or Buffer"),s(t.length>=u,"key must be at least "+u+", was given "+t.length),s(t.length<=d,"key must be at least "+d+", was given "+t.length)),null!=r&&(s(r instanceof Uint8Array,"salt must be Uint8Array or Buffer"),s(r.length===f,"salt must be exactly "+f+", was given "+r.length)),null!=i&&(s(i instanceof Uint8Array,"personal must be Uint8Array or Buffer"),s(i.length===p,"personal must be exactly "+p+", was given "+i.length))),c.length||(c.push(a),a+=216),this.digestLength=e,this.finalized=!1,this.pointer=c.pop(),this._memory=new Uint8Array(n.memory.buffer),this._memory.fill(0,0,64),this._memory[0]=this.digestLength,this._memory[1]=t?t.length:0,this._memory[2]=1,this._memory[3]=1,r&&this._memory.set(r,32),i&&this._memory.set(i,48),this.pointer+216>this._memory.length&&this._realloc(this.pointer+216),n.blake2b_init(this.pointer,this.digestLength),t&&(this.update(t),this._memory.fill(0,a,a+t.length),this._memory[this.pointer+200]=128)}function y(){}g.prototype._realloc=function(e){n.memory.grow(Math.max(0,Math.ceil(Math.abs(e-this._memory.length)/65536))),this._memory=new Uint8Array(n.memory.buffer)},g.prototype.update=function(e){return s(!1===this.finalized,"Hash instance finalized"),s(e instanceof Uint8Array,"input must be Uint8Array or Buffer"),a+e.length>this._memory.length&&this._realloc(a+e.length),this._memory.set(e,a),n.blake2b_update(this.pointer,a,a+e.length),this},g.prototype.digest=function(e){if(s(!1===this.finalized,"Hash instance finalized"),this.finalized=!0,c.push(this.pointer),n.blake2b_final(this.pointer),!e||"binary"===e)return this._memory.slice(this.pointer+128,this.pointer+128+this.digestLength);if("string"==typeof e)return i.toString(this._memory,e,this.pointer+128,this.pointer+128+this.digestLength);s(e instanceof Uint8Array&&e.length>=this.digestLength,"input must be Uint8Array or Buffer");for(var t=0;t<this.digestLength;t++)e[t]=this._memory[this.pointer+128+t];return e},g.prototype.final=g.prototype.digest,g.WASM=n,g.SUPPORTED="undefined"!=typeof WebAssembly,g.ready=function(e){return e||(e=y),o?o.then(()=>e(),e):e(new Error("WebAssembly not supported"))},g.prototype.ready=g.ready,g.prototype.getPartialHash=function(){return this._memory.slice(this.pointer,this.pointer+216)},g.prototype.setPartialHash=function(e){this._memory.set(e,this.pointer)}},618:function(e,t,r){var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||t.hasOwnProperty(r)||s(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(8),t),i(r(154),t),i(r(984),t),i(r(212),t),i(r(429),t),i(r(951),t),i(r(412),t),i(r(872),t),i(r(301),t),i(r(516),t),i(r(660),t)},625:(t,r,s)=>{var i=e(import.meta.url+"/..").slice(0,-1);let n,o={};o.__wbindgen_placeholder__=t.exports;let a=null;function c(){return null!==a&&0!==a.byteLength||(a=new Uint8Array(n.memory.buffer)),a}let l=0;function h(e,t){const r=t(1*e.length,1)>>>0;return c().set(e,r/1),l=e.length,r}t.exports.verify_ed25519=function(e){const t=h(e,n.__wbindgen_malloc),r=l,s=n.verify_ed25519(t,r);var i,o,a=(i=s[0],o=s[1],i>>>=0,c().subarray(i/1,i/1+o)).slice();return n.__wbindgen_free(s[0],1*s[1],1),a},t.exports.verify_ed25519_batch=function(e){const t=h(e,n.__wbindgen_malloc),r=l;return 0!==n.verify_ed25519_batch(t,r)},t.exports.__wbindgen_init_externref_table=function(){const e=n.__wbindgen_export_0,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)};const u=s(928).join(i,"ed25519_wasm_bg.wasm"),d=s(896).readFileSync(u),f=new WebAssembly.Module(d),p=new WebAssembly.Instance(f,o);n=p.exports,t.exports.__wasm=n,n.__wbindgen_start()},660:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Validator=void 0;const s=r(8),i=r(8),n=r(872),o=r(984),a=r(984);class c{static isWithinRange(e,t,r){return e>=t&&e<=r}static isValidAsnNumber(e){let t=this.isWithinRange(e,0n,this.THIRTY_TWO_BIT_SIZE);return[t,t?[]:[c.invalidAsnRangeMessage]]}static isValid16BitAsnNumber(e){let t=c.isWithinRange(e,0n,c.SIXTEEN_BIT_SIZE);return[t,t?[]:[c.invalid16BitAsnRangeMessage]]}static isValidIPv4Number(e){e="bigint"==typeof e?e:BigInt(e);let t=this.isWithinRange(e,0n,this.THIRTY_TWO_BIT_SIZE);return t?[t,[]]:[t,[c.invalidIPv4NumberMessage]]}static isValidIPv6Number(e){let t=this.isWithinRange(e,0n,this.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE);return t?[t,[]]:[t,[c.invalidIPv6NumberMessage]]}static isValidIPv4Octet(e){let t=this.isWithinRange(e,0n,this.EIGHT_BIT_SIZE);return[t,t?[]:[c.invalidOctetRangeMessage]]}static isValidIPv6Hexadecatet(e){let t=this.isWithinRange(e,0n,this.SIXTEEN_BIT_SIZE);return t?[t,[]]:[t,[c.invalidHexadecatetMessage]]}static isValidIPv4String(e){let t=e.split(".");if(4!=t.length||t.includes(""))return[!1,[c.invalidOctetCountMessage]];let r=t.every(e=>!!c.isNumeric(e)&&c.isValidIPv4Octet(BigInt(e))[0]);return r?(r=c.IPV4_PATTERN.test(e),[r,r?[]:[c.invalidIPv4PatternMessage]]):[!1,[c.invalidOctetRangeMessage]]}static isValidIPv6String(e){try{let t=n.expandIPv6Number(e).split(":");if(8!=t.length)return[!1,[c.invalidHexadecatetCountMessage]];let r=t.every(e=>!!c.isHexadecatet(e)&&c.isValidIPv6Hexadecatet(BigInt(`0x${e}`))[0]);return r?(r=c.IPV6_PATTERN.test(e),[r,r?[]:[c.invalidIPv6PatternMessage]]):[!1,[c.invalidHexadecatetMessage]]}catch(e){return[!1,[e]]}}static isValidPrefixValue(e,t){if("IPv4"===t){let t=c.isWithinRange(BigInt(e),0n,32n);return[t,t?[]:[c.invalidPrefixValueMessage]]}if("IPv6"===t){let t=c.isWithinRange(BigInt(e),0n,128n);return[t,t?[]:[c.invalidPrefixValueMessage]]}return[!1,[c.invalidInetNumType]]}static isValidIPv4Mask(e){let t=s.dottedDecimalNotationToBinaryString(e),r=c.IPV4_CONTIGUOUS_MASK_BIT_PATTERN.test(t);return r?[r,[]]:[r,[c.invalidMaskMessage]]}static isValidIPv6Mask(e){let t=a.hexadectetNotationToBinaryString(e),r=c.IPV6_CONTIGUOUS_MASK_BIT_PATTERN.test(t);return r?[r,[]]:[r,[c.invalidMaskMessage]]}static isValidIPv4CidrNotation(e){let t=e.split("/");if(2!==t.length||0===t[0].length||0===t[1].length)return[!1,[c.invalidIPv4CidrNotationMessage]];let r=t[0],s=t[1];if(isNaN(Number(s)))return[!1,[c.invalidIPv4CidrNotationMessage]];let[i,n]=c.isValidIPv4String(r),[o,a]=c.isValidPrefixValue(BigInt(s),"IPv4"),l=i&&o,h=n.concat(a);return l?[l,[]]:[l,h]}static isValidIPv4CidrRange(e){return c.isValidCidrRange(e,c.isValidIPv4CidrNotation,s.dottedDecimalNotationToBinaryString,e=>i.cidrPrefixToMaskBinaryString(e,"IPv4"))}static isValidIPv6CidrRange(e){return c.isValidCidrRange(e,c.isValidIPv6CidrNotation,o.colonHexadecimalNotationToBinaryString,e=>i.cidrPrefixToMaskBinaryString(e,"IPv6"))}static isValidCidrRange(e,t,r,s){let i=t(e);if(!i[0])return i;let n=e.split("/"),o=n[0],a=n[1],l=BigInt(`0b${r(o)}`),h=(l&BigInt(`0b${s(parseInt(a))}`))===l;return h?[h,[]]:[h,[c.InvalidIPCidrRangeMessage]]}static isValidIPv4RangeString(e){return this.isValidRange(e,c.isValidIPv4String,(e,t)=>BigInt(`0b${s.dottedDecimalNotationToBinaryString(e)}`)>=BigInt(`0b${s.dottedDecimalNotationToBinaryString(t)}`))}static isValidIPv6RangeString(e){return this.isValidRange(e,c.isValidIPv6String,(e,t)=>BigInt(`0b${a.hexadectetNotationToBinaryString(e)}`)>=BigInt(`0b${a.hexadectetNotationToBinaryString(t)}`))}static isValidRange(e,t,r){let s=e.split("-").map(e=>e.trim());if(2!==s.length||0===s[0].length||0===s[1].length)return[!1,[c.invalidRangeNotationMessage]];let i=s[0],n=s[1],[o,a]=t(i),[l,h]=t(n),u=o&&l;if(u&&r(i,n))return[!1,[c.invalidRangeFirstNotGreaterThanLastMessage]];let d=a.concat(h);return u?[u,[]]:[u,d]}static isValidIPv6CidrNotation(e){let t=c.IPV6_RANGE_PATTERN.test(e);return t?[t,[]]:[t,[c.invalidIPv6CidrNotationString]]}static isValidBinaryString(e){return/^([10])+$/.test(e)?[!0,[]]:[!1,[c.invalidBinaryStringErrorMessage]]}static isNumeric(e){return/^(\d+)$/.test(e)}static isHexadecatet(e){return/^[0-9A-Fa-f]{4}$/.test(e)}}t.Validator=c,c.IPV4_PATTERN=new RegExp(/^(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/),c.IPV6_PATTERN=new RegExp(/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/),c.IPV4_RANGE_PATTERN=new RegExp(/^(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/)([1-9]|[1-2][0-9]|3[0-2])$/),c.IPV6_RANGE_PATTERN=new RegExp(/^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$/),c.IPV4_CONTIGUOUS_MASK_BIT_PATTERN=new RegExp(/^(1){0,32}(0){0,32}$/),c.IPV6_CONTIGUOUS_MASK_BIT_PATTERN=new RegExp(/^(1){0,128}(0){0,128}$/),c.EIGHT_BIT_SIZE=BigInt(`0b${"1".repeat(8)}`),c.SIXTEEN_BIT_SIZE=BigInt(`0b${"1".repeat(16)}`),c.THIRTY_TWO_BIT_SIZE=BigInt(`0b${"1".repeat(32)}`),c.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE=BigInt(`0b${"1".repeat(128)}`),c.IPV4_SIZE=BigInt("4294967296"),c.IPV6_SIZE=BigInt("340282366920938463463374607431768211456"),c.invalidAsnRangeMessage="ASN number given less than zero or is greater than 32bit",c.invalid16BitAsnRangeMessage="ASN number given less than zero or is greater than 16bit",c.invalidIPv4NumberMessage="IPv4 number given less than zero or is greater than 32bit",c.invalidIPv6NumberMessage="IPv6 number given less than zero or is greater than 128bit",c.invalidOctetRangeMessage="Value given contains an invalid Octet; Value is less than zero or is greater than 8bit",c.invalidHexadecatetMessage="The value given is less than zero or is greater than 16bit",c.invalidOctetCountMessage="An IP4 number cannot have less or greater than 4 octets",c.invalidHexadecatetCountMessage="An IP6 number must have exactly 8 hexadecatet",c.invalidMaskMessage="The Mask is invalid",c.invalidPrefixValueMessage="A Prefix value cannot be less than 0 or greater than 32",c.invalidIPv4CidrNotationMessage="Cidr notation should be in the form [ip number]/[range]",c.InvalidIPCidrRangeMessage="Given IP number portion must is not the start of the range",c.invalidRangeNotationMessage="Range notation should be in the form [first ip]-[last ip]",c.invalidRangeFirstNotGreaterThanLastMessage="First IP in [first ip]-[last ip] must be less than Last IP",c.invalidIPv6CidrNotationString="A Cidr notation string should contain an IPv6 number and prefix",c.takeOutOfRangeSizeMessage="$count is greater than $size, the size of the range",c.cannotSplitSingleRangeErrorMessage="Cannot split an IP range with a single IP number",c.invalidInetNumType="Given ipNumType must be either InetNumType.IPv4 or InetNumType.IPv6",c.invalidBinaryStringErrorMessage="Binary string should contain only contiguous 1s and 0s",c.invalidIPRangeSizeMessage="Given size is zero or greater than maximum size of $iptype",c.invalidIPRangeSizeForCidrMessage="Given size can't be created via cidr prefix",c.invalidIPv4PatternMessage="Given IPv4 is not confirm to a valid IPv6 address",c.invalidIPv6PatternMessage="Given IPv6 is not confirm to a valid IPv6 address"},675:(e,t,r)=>{var s=r(54),i=r(578);function n(e,t,r){var s=e[t]+e[r],i=e[t+1]+e[r+1];s>=4294967296&&i++,e[t]=s,e[t+1]=i}function o(e,t,r,s){var i=e[t]+r;r<0&&(i+=4294967296);var n=e[t+1]+s;i>=4294967296&&n++,e[t]=i,e[t+1]=n}function a(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function c(e,t,r,s,i,a){var c=d[i],l=d[i+1],h=d[a],f=d[a+1];n(u,e,t),o(u,e,c,l);var p=u[s]^u[e],g=u[s+1]^u[e+1];u[s]=g,u[s+1]=p,n(u,r,s),p=u[t]^u[r],g=u[t+1]^u[r+1],u[t]=p>>>24^g<<8,u[t+1]=g>>>24^p<<8,n(u,e,t),o(u,e,h,f),p=u[s]^u[e],g=u[s+1]^u[e+1],u[s]=p>>>16^g<<16,u[s+1]=g>>>16^p<<16,n(u,r,s),p=u[t]^u[r],g=u[t+1]^u[r+1],u[t]=g>>>31^p<<1,u[t+1]=p>>>31^g<<1}var l=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),h=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map(function(e){return 2*e})),u=new Uint32Array(32),d=new Uint32Array(32);function f(e,t){var r=0;for(r=0;r<16;r++)u[r]=e.h[r],u[r+16]=l[r];for(u[24]=u[24]^e.t,u[25]=u[25]^e.t/4294967296,t&&(u[28]=~u[28],u[29]=~u[29]),r=0;r<32;r++)d[r]=a(e.b,4*r);for(r=0;r<12;r++)c(0,8,16,24,h[16*r+0],h[16*r+1]),c(2,10,18,26,h[16*r+2],h[16*r+3]),c(4,12,20,28,h[16*r+4],h[16*r+5]),c(6,14,22,30,h[16*r+6],h[16*r+7]),c(0,10,20,30,h[16*r+8],h[16*r+9]),c(2,12,22,24,h[16*r+10],h[16*r+11]),c(4,14,16,26,h[16*r+12],h[16*r+13]),c(6,8,18,28,h[16*r+14],h[16*r+15]);for(r=0;r<16;r++)e.h[r]=e.h[r]^u[r]^u[r+16]}var p=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function g(e,t,r,s){p.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=e,p[0]=e,t&&(p[1]=t.length),p[2]=1,p[3]=1,r&&p.set(r,32),s&&p.set(s,48);for(var i=0;i<16;i++)this.h[i]=l[i]^a(p,4*i);t&&(y(this,t),this.c=128)}function y(e,t){for(var r=0;r<t.length;r++)128===e.c&&(e.t+=e.c,f(e,!1),e.c=0),e.b[e.c++]=t[r]}function m(e){return e<16?"0"+e.toString(16):e.toString(16)}g.prototype.update=function(e){return s(e instanceof Uint8Array,"input must be Uint8Array or Buffer"),y(this,e),this},g.prototype.digest=function(e){var t=e&&"binary"!==e&&"hex"!==e?e:new Uint8Array(this.outlen);return s(t instanceof Uint8Array,'out must be "binary", "hex", Uint8Array, or Buffer'),s(t.length>=this.outlen,"out must have at least outlen bytes of space"),function(e,t){for(e.t+=e.c;e.c<128;)e.b[e.c++]=0;f(e,!0);for(var r=0;r<e.outlen;r++)t[r]=e.h[r>>2]>>8*(3&r)}(this,t),"hex"===e?function(e){for(var t="",r=0;r<e.length;r++)t+=m(e[r]);return t}(t):t},g.prototype.final=g.prototype.digest,g.ready=function(e){i.ready(function(){e()})};var b=g;e.exports=function(e,t,r,i,n){return!0!==n&&(s(e>=A,"outlen must be at least "+A+", was given "+e),s(e<=I,"outlen must be at most "+I+", was given "+e),null!=t&&(s(t instanceof Uint8Array,"key must be Uint8Array or Buffer"),s(t.length>=v,"key must be at least "+v+", was given "+t.length),s(t.length<=w,"key must be at most "+w+", was given "+t.length)),null!=r&&(s(r instanceof Uint8Array,"salt must be Uint8Array or Buffer"),s(r.length===S,"salt must be exactly "+S+", was given "+r.length)),null!=i&&(s(i instanceof Uint8Array,"personal must be Uint8Array or Buffer"),s(i.length===E,"personal must be exactly "+E+", was given "+i.length))),new b(e,t,r,i)},e.exports.ready=function(e){i.ready(function(){e()})},e.exports.WASM_SUPPORTED=i.SUPPORTED,e.exports.WASM_LOADED=!1;var A=e.exports.BYTES_MIN=16,I=e.exports.BYTES_MAX=64,v=(e.exports.BYTES=32,e.exports.KEYBYTES_MIN=16),w=e.exports.KEYBYTES_MAX=64,S=(e.exports.KEYBYTES=32,e.exports.SALTBYTES=16),E=e.exports.PERSONALBYTES=16;i.ready(function(t){t||(e.exports.WASM_LOADED=!0,e.exports=i)})},810:(e,t,r)=>{e.exports=r.p+"b0733caf1cf3aa68.js"},872:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.collapseIPv6Number=t.expandIPv6Number=void 0;const s=r(8),i=r(660);let n=e=>e.includes("/")?`/${e.split("/")[1]}`:"";t.expandIPv6Number=e=>{let t=e=>e.map(e=>s.leftPadWithZeroBit(e,4)).join(":");if(/(:){3,}/.test(e))throw"given IPv6 contains consecutive : more than two";const r=n(e);if(e.includes("/")&&(e=e.split("/")[0]),!i.Validator.IPV6_PATTERN.test(e))throw Error(i.Validator.invalidIPv6PatternMessage);if(e.includes("::")){let s=e.split("::"),i=s[0],n=s[1],o=i.split(":").filter(e=>""!==e),a=n.split(":").filter(e=>""!==e),c=(e=>{let t=[];for(let r=0;r<e;r++)t.push("0000");return t.join(":")})(8-(o.length+a.length)),l=t(o);""!==l&&(l+=":");let h=t(a);return""!==h&&(h=":"+h),`${l}${c}${h}${r}`}return`${t(e.split(":"))}${r}`},t.collapseIPv6Number=e=>{const t=n(e);if(e.includes("/")&&(e=e.split("/")[0]),!i.Validator.IPV6_PATTERN.test(e))throw Error(i.Validator.invalidIPv6PatternMessage);let r=e.split(":").map(e=>{let t=e.replace(/^0+/,"");return""!==t?t:"0"}).join(":").replace(/((^0)?(:0){2,}|(^0)(:0){1,})/,":");return":"===r.slice(-1)?`${r}:${t}`:(r=r.replace(":0:","::"),`${r}${t}`)}},884:e=>{e.exports="data:application/javascript;base64,aW1wb3J0IHsgdHNJbXBvcnQgfSBmcm9tICJ0c3gvZXNtL2FwaSI7CmNvbnN0IHsgd29ya2VyIH0gPSBhd2FpdCB0c0ltcG9ydCgiLi93b3JrZXIudHMiLCBpbXBvcnQubWV0YS51cmwpOwp3b3JrZXIubGlzdGVuVG9QYXJlbnRQb3J0KCk7Cg=="},896:e=>{e.exports=t(import.meta.url)("fs")},909:()=>{var e;!function(e){!function(){var t="object"==typeof globalThis?globalThis:"object"==typeof global?global:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),r=s(e);function s(e,t){return function(r,s){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:s}),t&&t(r,s)}}void 0!==t.Reflect&&(r=s(t.Reflect,r)),function(e,t){var r=Object.prototype.hasOwnProperty,s="function"==typeof Symbol,i=s&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",n=s&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",o="function"==typeof Object.create,a={__proto__:[]}instanceof Array,c=!o&&!a,l={create:o?function(){return V(Object.create(null))}:a?function(){return V({__proto__:null})}:function(){return V({})},has:c?function(e,t){return r.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return r.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},h=Object.getPrototypeOf(Function),u="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:function(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[n]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:r,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}(),s=function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var r=this._find(e,!0);return this._values[r]=t,this},t.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var s=this._keys.length,i=r+1;i<s;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,N(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new r(this._keys,this._values,i)},t.prototype.values=function(){return new r(this._keys,this._values,o)},t.prototype.entries=function(){return new r(this._keys,this._values,a)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[n]=function(){return this.entries()},t.prototype._find=function(e,t){if(!N(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(N(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();return s;function i(e,t){return e}function o(e,t){return t}function a(e,t){return[e,t]}}(),d="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:function(){function e(){this._map=new u}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[n]=function(){return this.keys()},e}(),f="function"==typeof WeakMap?WeakMap:function(){var e=l.create(),t=s();return function(){function e(){this._key=s()}return e.prototype.has=function(e){var t=i(e,!1);return void 0!==t&&l.has(t,this._key)},e.prototype.get=function(e){var t=i(e,!1);return void 0!==t?l.get(t,this._key):void 0},e.prototype.set=function(e,t){return i(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=i(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=s()},e}();function s(){var t;do{t="@@WeakMap@@"+o()}while(l.has(e,t));return e[t]=!0,t}function i(e,s){if(!r.call(e,t)){if(!s)return;Object.defineProperty(e,t,{value:l.create()})}return e[t]}function n(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}function o(){var e=function(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):n(t,e),t}return n(new Array(e),e)}(16);e[6]=79&e[6]|64,e[8]=191&e[8]|128;for(var t="",r=0;r<16;++r){var s=e[r];4!==r&&6!==r&&8!==r||(t+="-"),s<16&&(t+="0"),t+=s.toString(16).toLowerCase()}return t}}(),p=s?Symbol.for("@reflect-metadata:registry"):void 0,g=function(){var e;return!C(p)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[p]),C(e)&&(e=function(){var e,r,s,i;C(p)||void 0===t.Reflect||p in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=function(e){var t=e.defineMetadata,r=e.hasOwnMetadata,s=e.getOwnMetadata,i=e.getOwnMetadataKeys,n=e.deleteMetadata,o=new f,a={isProviderFor:function(e,t){var r=o.get(e);return!(C(r)||!r.has(t))||!!i(e,t).length&&(C(r)&&(r=new d,o.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:s,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:n};return a}(t.Reflect));var n=new f,o={registerProvider:a,getProvider:l,setProvider:g};return o;function a(t){if(!Object.isExtensible(o))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case C(r):r=t;break;case r===t:break;case C(s):s=t;break;case s===t:break;default:void 0===i&&(i=new d),i.add(t)}}function c(t,n){if(!C(r)){if(r.isProviderFor(t,n))return r;if(!C(s)){if(s.isProviderFor(t,n))return r;if(!C(i))for(var o=M(i);;){var a=L(o);if(!a)return;var c=P(a);if(c.isProviderFor(t,n))return H(o),c}}}if(!C(e)&&e.isProviderFor(t,n))return e}function l(e,t){var r,s=n.get(e);return C(s)||(r=s.get(t)),C(r)?(C(r=c(e,t))||(C(s)&&(s=new u,n.set(e,s)),s.set(t,r)),r):r}function h(e){if(C(e))throw new TypeError;return r===e||s===e||!C(i)&&i.has(e)}function g(e,t,r){if(!h(r))throw new Error("Metadata provider not registered.");var s=l(e,t);if(s!==r){if(!C(s))return!1;var i=n.get(e);C(i)&&(i=new u,n.set(e,i)),i.set(t,r)}return!0}}()),!C(p)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,p,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}(),y=function(e){var t=new f,r={isProviderFor:function(e,r){var s=t.get(e);return!C(s)&&s.has(r)},OrdinaryDefineOwnMetadata:function(e,t,r,i){s(r,i,!0).set(e,t)},OrdinaryHasOwnMetadata:function(e,t,r){var i=s(t,r,!1);return!C(i)&&B(i.has(e))},OrdinaryGetOwnMetadata:function(e,t,r){var i=s(t,r,!1);if(!C(i))return i.get(e)},OrdinaryOwnMetadataKeys:function(e,t){var r=[],i=s(e,t,!1);if(C(i))return r;for(var n=M(i.keys()),o=0;;){var a=L(n);if(!a)return r.length=o,r;var c=P(a);try{r[o]=c}catch(e){try{H(n)}finally{throw e}}o++}},OrdinaryDeleteMetadata:function(e,r,i){var n=s(r,i,!1);if(C(n))return!1;if(!n.delete(e))return!1;if(0===n.size){var o=t.get(r);C(o)||(o.delete(i),0===o.size&&t.delete(o))}return!0}};return g.registerProvider(r),r;function s(s,i,n){var o=t.get(s),a=!1;if(C(o)){if(!n)return;o=new u,t.set(s,o),a=!0}var c=o.get(i);if(C(c)){if(!n)return;if(c=new u,o.set(i,c),!e.setProvider(s,i,r))throw o.delete(i),a&&t.delete(s),new Error("Wrong provider for target.")}return c}}(g);function m(e,t,r){if(b(e,t,r))return!0;var s=K(t);return!k(s)&&m(e,s,r)}function b(e,t,r){var s=Q(t,r,!1);return!C(s)&&B(s.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(b(e,t,r))return I(e,t,r);var s=K(t);return k(s)?void 0:A(e,s,r)}function I(e,t,r){var s=Q(t,r,!1);if(!C(s))return s.OrdinaryGetOwnMetadata(e,t,r)}function v(e,t,r,s){Q(r,s,!0).OrdinaryDefineOwnMetadata(e,t,r,s)}function w(e,t){var r=S(e,t),s=K(e);if(null===s)return r;var i=w(s,t);if(i.length<=0)return r;if(r.length<=0)return i;for(var n=new d,o=[],a=0,c=r;a<c.length;a++){var l=c[a];n.has(l)||(n.add(l),o.push(l))}for(var h=0,u=i;h<u.length;h++)l=u[h],n.has(l)||(n.add(l),o.push(l));return o}function S(e,t){var r=Q(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function E(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function C(e){return void 0===e}function k(e){return null===e}function x(e){return"object"==typeof e?null!==e:"function"==typeof e}function _(e,t){switch(E(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var r=3===t?"string":5===t?"number":"default",s=D(e,i);if(void 0!==s){var n=s.call(e,r);if(x(n))throw new TypeError;return n}return function(e,t){if("string"===t){var r=e.toString;if(U(r)&&!x(i=r.call(e)))return i;if(U(s=e.valueOf)&&!x(i=s.call(e)))return i}else{var s;if(U(s=e.valueOf)&&!x(i=s.call(e)))return i;var i,n=e.toString;if(U(n)&&!x(i=n.call(e)))return i}throw new TypeError}(e,"default"===r?"number":r)}function B(e){return!!e}function R(e){var t=_(e,3);return"symbol"==typeof t?t:function(e){return""+e}(t)}function O(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function U(e){return"function"==typeof e}function T(e){return"function"==typeof e}function N(e,t){return e===t||e!=e&&t!=t}function D(e,t){var r=e[t];if(null!=r){if(!U(r))throw new TypeError;return r}}function M(e){var t=D(e,n);if(!U(t))throw new TypeError;var r=t.call(e);if(!x(r))throw new TypeError;return r}function P(e){return e.value}function L(e){var t=e.next();return!t.done&&t}function H(e){var t=e.return;t&&t.call(e)}function K(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===h)return t;if(t!==h)return t;var r=e.prototype,s=r&&Object.getPrototypeOf(r);if(null==s||s===Object.prototype)return t;var i=s.constructor;return"function"!=typeof i||i===e?t:i}function Q(e,t,r){var s=g.getProvider(e,t);if(!C(s))return s;if(r){if(g.setProvider(e,t,y))return y;throw new Error("Illegal state.")}}function V(e){return e.__=void 0,delete e.__,e}e("decorate",function(e,t,r,s){if(C(r)){if(!O(e))throw new TypeError;if(!T(t))throw new TypeError;return function(e,t){for(var r=e.length-1;r>=0;--r){var s=(0,e[r])(t);if(!C(s)&&!k(s)){if(!T(s))throw new TypeError;t=s}}return t}(e,t)}if(!O(e))throw new TypeError;if(!x(t))throw new TypeError;if(!x(s)&&!C(s)&&!k(s))throw new TypeError;return k(s)&&(s=void 0),function(e,t,r,s){for(var i=e.length-1;i>=0;--i){var n=(0,e[i])(t,r,s);if(!C(n)&&!k(n)){if(!x(n))throw new TypeError;s=n}}return s}(e,t,r=R(r),s)}),e("metadata",function(e,t){return function(r,s){if(!x(r))throw new TypeError;if(!C(s)&&!function(e){switch(E(e)){case 3:case 4:return!0;default:return!1}}(s))throw new TypeError;v(e,t,r,s)}}),e("defineMetadata",function(e,t,r,s){if(!x(r))throw new TypeError;return C(s)||(s=R(s)),v(e,t,r,s)}),e("hasMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),m(e,t,r)}),e("hasOwnMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),b(e,t,r)}),e("getMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),A(e,t,r)}),e("getOwnMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),I(e,t,r)}),e("getMetadataKeys",function(e,t){if(!x(e))throw new TypeError;return C(t)||(t=R(t)),w(e,t)}),e("getOwnMetadataKeys",function(e,t){if(!x(e))throw new TypeError;return C(t)||(t=R(t)),S(e,t)}),e("deleteMetadata",function(e,t,r){if(!x(t))throw new TypeError;if(C(r)||(r=R(r)),!x(t))throw new TypeError;C(r)||(r=R(r));var s=Q(t,r,!1);return!C(s)&&s.OrdinaryDeleteMetadata(e,t,r)})}(r,t),void 0===t.Reflect&&(t.Reflect=e)}()}(e||(e={}))},928:e=>{e.exports=t(import.meta.url)("path")},951:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Pool=void 0;const s=r(412),i=r(516);class n{constructor(e){this.backingSet=new o,e.forEach(e=>{this.backingSet.add(e)})}static fromIP(e){let t=e.map(e=>s.RangedSet.fromSingleIP(e));return new n(t)}static fromRangeSet(e){return new n(e)}static fromCidrRanges(e){let t=e.map(e=>e.toRangeSet());return new n(t)}getRanges(){return this.backingSet.asArray()}aggregate(){let e=this.backingSet.asArray().reduce((e,t,r,s)=>{if(0==e.length)return e.push(t),e;{let r=e.pop(),s=r.toCidrRange(),i=t.toCidrRange();if(s.isCidrMergeable(i)){let t=s.merge(i);return e.push(t.toRangeSet()),e}return r.contains(t)?e.push(r):(e.push(r),e.push(t)),e}},[]),t=n.fromRangeSet(e);return t.getRanges().length!==this.getRanges().length?t.aggregate():t}getCidrRange(e){if(e.toRangeSize()>this.getSize())throw new Error(`Not enough IP number in the pool for requested prefix: ${e}`);let t,r;e:for(let s of this.getRanges())for(let i=0n;i+e.toRangeSize()<=s.getSize();i+=1n)try{let r=s.takeSubRange(i,e.toRangeSize());t=r.toCidrRange();let n=s.difference(r);this.removeExact(s),this.add(n);break e}catch(e){if(e instanceof RangeError)continue e;r=e}if(t)return t;throw void 0===r?new Error(`No range big enough in the pool for requested prefix: ${e}`):r}getCidrRanges(e){if(e.toRangeSize()>this.getSize())throw new Error("Prefix greater than pool");let t=(e,r,s)=>{try{let i=this.getCidrRange(r);s.push(i);let n=s.reduce((e,t)=>e+t.getSize(),0n);return e.toRangeSize()===n?s:t(e,r,s)}catch(n){let o=i.isIPv4Prefix(r)?i.IPv4Prefix.fromNumber(r.getValue()+1n):i.IPv6Prefix.fromNumber(r.getValue()+1n);return t(e,o,s)}};return t(e,e,[])}getSize(){return this.aggregate().getRanges().reduce((e,t)=>e+t.getSize(),0n)}resetWith(e){this.backingSet.clear(),this.backingSet=this.backingSet.add(e)}removeExact(e){let t=this.backingSet.removeExact(e),r=!this.backingSet.isEquals(t);return this.backingSet=t,r}removeOverlapping(e){let t=this.backingSet.removeOverlapping(e),r=!this.backingSet.isEquals(t);return this.backingSet=t,r}add(e){this.backingSet=this.backingSet.add(e)}clear(){this.backingSet.clear()}}t.Pool=n;class o{constructor(e){this.backingArray=e?this.sortArray(e):new Array}sortArray(e){return e.sort((e,t)=>e.isLessThan(t)?-1:e.isGreaterThan(t)?1:0),e}asArray(){return this.backingArray}isEquals(e){return this.backingArray.length===e.asArray().length&&this.backingArray.every((t,r)=>t.getSize()===e.asArray()[r].getSize())}add(e){let t=this.backingArray;return"push"in e?t=t.concat(e):t.push(e),new o(this.sortArray(t))}removeExact(e){let t=this.backingArray.filter(t=>"push"in e?void 0!==e.find(e=>e.isEquals(t)):!e.isEquals(t));return new o(this.sortArray(t))}removeOverlapping(e){let t=this.backingArray.flatMap(t=>{if("push"in e)return e.flatMap(e=>t.contains(e)?t.difference(e):t.inside(e)?new Array:t.isOverlapping(e)?[t.subtract(e)]:[e]);try{return t.difference(e)}catch(e){return t}});return new o(this.sortArray(t))}clear(){this.backingArray=[]}}},984:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.hexadectetNotationToBinaryString=t.binaryStringToHexadecimalString=t.colonHexadecimalNotationToBinaryString=t.hexadecimalStringToHexadecatetString=t.hexadecimalStringToBinaryString=t.bigIntToHexadecimalString=void 0;const s=r(872),i=r(8);t.bigIntToHexadecimalString=e=>e.toString(16),t.hexadecimalStringToBinaryString=e=>BigInt(`0x${e}`).toString(2),t.hexadecimalStringToHexadecatetString=e=>{let r=t.hexadecimalStringToBinaryString(e);if(r.length>16)throw new Error("Given decimal in binary contains digits greater than an Hexadecatet");return i.leftPadWithZeroBit(r,16)},t.colonHexadecimalNotationToBinaryString=e=>s.expandIPv6Number(e).split(":").reduce((e,r)=>e.concat(t.hexadecimalStringToHexadecatetString(r)),""),t.binaryStringToHexadecimalString=e=>BigInt(`0b${e}`).toString(16),t.hexadectetNotationToBinaryString=e=>s.expandIPv6Number(e).split(":").reduce((e,r)=>e.concat(i.leftPadWithZeroBit(t.hexadecimalStringToBinaryString(r),16)),"")}},n={};function o(e){var t=n[e];if(void 0!==t)return t.exports;var r=n[e]={exports:{}};return i[e].call(r.exports,r,r.exports,o),r.exports}o.m=i,o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;if("string"==typeof import.meta.url&&(e=import.meta.url),!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o.p=e})(),o.b=new URL("./",import.meta.url);var a={};o.r(a),o.d(a,{Any:()=>cm,BaseBlock:()=>wg,BaseStringBlock:()=>Eg,BitString:()=>wy,BmpString:()=>Fy,Boolean:()=>by,CharacterString:()=>em,Choice:()=>lm,Constructed:()=>fy,DATE:()=>sm,DateTime:()=>nm,Duration:()=>om,EndOfContent:()=>gy,Enumerated:()=>_y,GeneralString:()=>Zy,GeneralizedTime:()=>rm,GraphicString:()=>Yy,HexBlock:()=>yg,IA5String:()=>Jy,Integer:()=>xy,Null:()=>yy,NumericString:()=>Gy,ObjectIdentifier:()=>Oy,OctetString:()=>Iy,Primitive:()=>cy,PrintableString:()=>qy,RawData:()=>um,RelativeObjectIdentifier:()=>Ny,Repeated:()=>hm,Sequence:()=>Dy,Set:()=>My,TIME:()=>am,TeletexString:()=>zy,TimeOfDay:()=>im,UTCTime:()=>tm,UniversalString:()=>jy,Utf8String:()=>Qy,ValueBlock:()=>bg,VideotexString:()=>Wy,ViewWriter:()=>Yp,VisibleString:()=>Xy,compareSchema:()=>dm,fromBER:()=>hy,verifySchema:()=>fm});const c=t(import.meta.url)("node:url");var l;function h(e){const t="debug"===e?"LOG":e.toUpperCase();if(void 0===l[t])throw new Error(`Unknown logging level: "${e}". Use one of "trace", "debug", "log","info", "warn", "error"`);return l[t]}!function(e){e[e.TRACE=1]="TRACE",e[e.LOG=2]="LOG",e[e.INFO=3]="INFO",e[e.WARN=4]="WARN",e[e.ERROR=5]="ERROR"}(l||(l={}));class u{options;static create(e,t){return e===l.TRACE?new d(t):e===l.LOG?new f(t):e===l.INFO?new p(t):new u(t)}constructor(e){this.options=e}trace(e,t,r){}log(e,t,r){}info(e,t,r){}warn(e,t,r){this.push(l.WARN,e,t,r)}error(e,t,r){this.push(l.ERROR,e,t,r)}push(e,t,r,s){const i=r.replace(this.options.workingDir,""),n=t.replace(this.options.workingDir,""),o=function(e,t){let r=t;for(;;){const s=e.modules.get(r);if(void 0!==s)return s;const i=r.lastIndexOf("/");if(-1===i)return e.defaultLevel;r=t.substring(0,i)}}(this.options,t),a=l[e].padEnd(5);if(e<o)return;const c=`${a} [${n}] ${s}\n\t@ ${i}`;e===l.WARN?console.warn(c):e===l.ERROR?console.error(c):console.info(c)}}class d extends u{trace(e,t,r){this.push(l.TRACE,e,t,r)}log(e,t,r){this.push(l.LOG,e,t,r)}info(e,t,r){this.push(l.INFO,e,t,r)}}class f extends u{trace(e,t,r){}log(e,t,r){this.push(l.LOG,e,t,r)}info(e,t,r){this.push(l.INFO,e,t,r)}}class p extends u{trace(e,t,r){}log(e,t,r){}info(e,t,r){this.push(l.INFO,e,t,r)}}const g={workingDir:"",defaultLevel:l.LOG,modules:new Map},y={options:g,transport:u.create(g.defaultLevel,g)};class m{moduleName;fileName;config;static new(e,t){const r=e??"unknown";return new m(t??r,r,y)}static configureAllFromOptions(e){const t=Array.from(e.modules.values()).reduce((e,t)=>e<t?e:t,e.defaultLevel),r=u.create(t,e);y.options=e,y.transport=r}static configureAll(e,t,r){const s=function(e,t,r){const s=new Map,i=e.toLowerCase().split(",");let n=t;for(const e of i){const t=e.trim();if(0!==t.length)if(t.includes("=")){const[e,r]=t.split("=");s.set(e.trim(),h(r.trim()))}else n=h(t)}const o="".split("/");return o.pop(),o.pop(),{defaultLevel:n,modules:s,workingDir:r??o.join("/")}}(e,t,r);m.configureAllFromOptions(s)}constructor(e,t,r){this.moduleName=e,this.fileName=t,this.config=r}trace(e){this.config.transport.trace(this.moduleName,this.fileName,e)}log(e){this.config.transport.log(this.moduleName,this.fileName,e)}info(e){this.config.transport.info(this.moduleName,this.fileName,e)}warn(e){this.config.transport.warn(this.moduleName,this.fileName,e)}error(e){this.config.transport.error(this.moduleName,this.fileName,e)}}const b=t(import.meta.url)("node:os");var A=o.n(b);const I=(E={default:()=>r.default},C={},o.d(C,E),C),v="dev",w={name:A().hostname(),config:v},S=`\n@typeberry/jam 0.0.1 by Fluffy Labs.\n\nUsage:\n jam [options]\n jam [options] import <bin-or-json-blocks>\n\nOptions:\n --name Override node name. Affects networking key and db location.\n [default: ${w.name}]\n --config Path to a config file or '${v}'.\n [default: ${w.config}]\n`;var E,C,k;function x(e,t){const{name:r}=B(e,"name",e=>e,w.name),{config:s}=B(e,"config",e=>e===v?v:t(e),w.config);return{nodeName:r,configPath:s}}function _(e,t){const r=(0,I.default)(e),s=r._.shift()??k.Run;switch(s){case k.Run:{const e=x(r,t);return R(r),{command:k.Run,args:e}}case k.Import:{const e=x(r,t),s=r._.map(e=>t(e));return r._=[],R(r),{command:k.Import,args:{...e,files:s}}}default:r._.unshift(s),R(r)}throw new Error(`Invalid arguments: ${JSON.stringify(r)}`)}function B(e,t,r,s){const i=e[t];if(void 0===i)return{[t]:s};if(delete e[t],"string"!=typeof i)throw new Error(`Option '--${t}' requires an argument.`);try{const e=r(i);return{[t]:e??s}}catch(e){throw new Error(`Invalid value '${i}' for option '${t}': ${e}`)}}function R(e){const t=Object.keys(e).filter(e=>"_"!==e&&"--"!==e);if(e._.length>0)throw new Error(`Unexpected command: '${e._[0]}'`);if((e["--"]?.length??0)>0)throw new Error(`Unexpected parameters: '${e["--"]?.[0]}'...`);if(t.length>0)throw new Error(`Unrecognized options: '${t}'`)}!function(e){e.Run="run",e.Import="import"}(k||(k={}));const O=t(import.meta.url)("node:fs");var U=o.n(O);const T=t(import.meta.url)("node:worker_threads");var N;!function(e){e[e.Less=-1]="Less",e[e.Equal=0]="Equal",e[e.Greater=1]="Greater"}(N||(N={}));class D{value;constructor(e){this.value=e}static Less=new D(N.Less);static Greater=new D(N.Greater);static Equal=new D(N.Equal);isLess(){return this.value===N.Less}isGreater(){return this.value===N.Greater}isEqual(){return this.value===N.Equal}isNotEqual(){return!this.isEqual()}isGreaterOrEqual(){return this.isEqual()||this.isGreater()}isLessOrEqual(){return this.isEqual()||this.isLess()}}function M(e,t){if(!e)throw new Error(`Assertion failure: ${t??""}`)}function P(e,t,r){if(function(e,t){return t}(0,t))return e;throw new Error(`Assertion failure: ${r??""}`)}function L(e){throw new Error(`Unexpected value: ${e}`)}function H(e){const t=e=>e.split("\n").map(e=>` ${e}`).join("\n").trim();if(null===e)return"<null>";if(void 0===e)return"<undefined>";if(Array.isArray(e))return`[${e.map(e=>H(e))}]`;if(e instanceof Map)return H(Array.from(e.entries()));if("number"==typeof e)return`${e} (0x${e.toString(16)})`;if("object"!=typeof e)return`${e}`;if("toString"in e&&Object.prototype.toString!==e.toString&&Q.prototype.toString!==e.toString)return`${e}`;const r=e.constructor.name;let s="Object"!==r?`${r} {`:"{";const i=Object.keys(e),n=i.length<3;for(const r of i)"string"==typeof r&&(s+=n?"":"\n ",s+=`${r}: ${t(H(e[r]))}`,s+=n?",":"");return s+=n?"}":"\n}",s}const K="undefined"==typeof process?e=>{const t=performance.now();return()=>`${e} took ${performance.now()-t}ms`}:e=>{const t=process.hrtime.bigint();return()=>{const r=process.hrtime.bigint()-t,s=Number(r/1000000n).toFixed(2);return`${e} took ${s}ms`}};class Q{toString(){return H(this)}}function V(e){return e}function F(e){return e}const $=Symbol("ok");class j{kind;error;enumMapping;constructor(e,t,r){this.kind=e,this.error=t,this.enumMapping=r}toString(){const e=Object.keys(this.enumMapping).find(e=>this.enumMapping[e]===this.kind)??"?";return`${e} (${this.kind}) - ${G(this.error)}`}}const G=e=>{return null!==(t=e)&&"object"==typeof t&&"kind"in t&&"error"in t?e instanceof j?e.toString():`${e.kind} - ${G(e.error)}`:`${e}`;var t};function q(e){return e.isOk?`OK: ${"symbol"==typeof e.ok?e.ok.toString():e.ok}`:`${e.details}\nError: ${G(e.error)}`}const z={ok:e=>(M(void 0!==e,"`Ok` type cannot be undefined."),{isOk:!0,isError:!1,ok:e}),error:(e,t="")=>(M(void 0!==e,"`Error` type cannot be undefined."),{isOk:!1,isError:!0,error:e,details:t}),taggedError:(e,t,r)=>z.error(new j(t,r.error,e),r.details)},W=(t(import.meta.url)("node:assert"),Symbol("compare via string"));class J{[W]=!0;raw;length=0;constructor(e){this.raw=e,this.length=e.byteLength}toString(){return function(e){const t=e=>e>=ne?String.fromCharCode(e+te-ne):String.fromCharCode(e+Z);let r="0x";for(const s of e)r+=t(s>>>4),r+=t(15&s);return r}(this.raw)}asText(){return(new TextDecoder).decode(this.raw)}isEqualTo(e){return this.length===e.length&&ae(this.raw,e.raw)}compare(e){const t=Math.min(this.length,e.length),r=this.raw,s=e.raw;for(let e=0;e<t;e++){if(r[e]<s[e])return D.Less;if(r[e]>s[e])return D.Greater}return this.length<e.length?D.Less:this.length>e.length?D.Greater:D.Equal}static empty(){return new J(new Uint8Array)}static blobFromString(e){const t=new TextEncoder;return J.blobFrom(t.encode(e))}static blobFrom(e){return new J(e)}static blobFromParts(e,...t){const r=e instanceof Uint8Array?[e]:e,s=r.reduce((e,t)=>e+t.length,0)+t.reduce((e,t)=>e+t.length,0),i=new Uint8Array(s);let n=0;for(const e of r)i.set(e,n),n+=e.length;for(const e of t)i.set(e,n),n+=e.length;return new J(i)}static blobFromNumbers(e){M(void 0===e.find(e=>(255&e)!==e),"BytesBlob.blobFromNumbers used with non-byte number array.");const t=new Uint8Array(e);return new J(t)}static parseBlobNoPrefix(e){const t=e.length;if(t%2==1)throw new Error(`Odd number of nibbles. Invalid hex string: ${e}.`);const r=new ArrayBuffer(t/2),s=new Uint8Array(r);for(let r=0;r<t-1;r+=2){const t=e.substring(r,r+2);s[r/2]=X(t)}return new J(s)}static parseBlob(e){if(!e.startsWith("0x"))throw new Error(`Missing 0x prefix: ${e}.`);return J.parseBlobNoPrefix(e.substring(2))}*chunks(e){for(let t=0;t<this.length;t+=e)yield J.blobFrom(this.raw.subarray(t,t+e))}}class Y extends J{length;constructor(e,t){super(e),M(e.byteLength===t,`Given buffer has incorrect size ${e.byteLength} vs expected ${t}`),this.length=t}static fromBlob(e,t){return new Y(e,t)}static fromNumbers(e,t){M(void 0===e.find(e=>(255&e)!==e),"Bytes.fromNumbers used with non-byte number array.");const r=new Uint8Array(e);return new Y(r,t)}static zero(e){return new Y(new Uint8Array(e),e)}static fill(e,t){M((255&t)===t,"Input has to be a byte.");const r=Y.zero(e);return r.raw.fill(t,0,e),r}static parseBytesNoPrefix(e,t){if(e.length>2*t)throw new Error(`Input string too long. Expected ${t}, got ${e.length/2}`);const r=J.parseBlobNoPrefix(e);return new Y(r.raw,t)}static parseBytes(e,t){if(e.length>2*t+2)throw new Error(`Input string too long. Expected ${t}, got ${e.length/2-1}`);const r=J.parseBlob(e);return new Y(r.raw,t)}isEqualTo(e){return M(this.length===e.length,"Comparing incorrectly typed bytes!"),ae(this.raw,e.raw)}asOpaque(){return this}}function X(e){return M(2===e.length,"Two-character string expected"),oe(e.charCodeAt(0))<<4|oe(e.charCodeAt(1))}const Z="0".charCodeAt(0),ee="9".charCodeAt(0),te="a".charCodeAt(0),re="f".charCodeAt(0),se="A".charCodeAt(0),ie="F".charCodeAt(0),ne=10;function oe(e){if(e>=Z&&e<=ee)return e-Z;if(e>=te&&e<=re)return e-te+ne;if(e>=se&&e<=ie)return e-se+ne;throw new Error(`Invalid characters in hex byte string: ${String.fromCharCode(e)}`)}function ae(e,t){for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}const ce=(e,t)=>e.compare(t);class le{data;bitLength;static fromBlob(e,t){return new le(e,t)}static fromBytes(e,t){return new le(e.raw,t)}static empty(e){const t=new Uint8Array(Math.ceil(e/8));return new le(t,e)}byteLength;constructor(e,t){this.data=e,this.bitLength=t,M(8*e.length>=t,`Not enough bytes in the data array. Need ${8*e.length} has ${t}.`),this.byteLength=Math.ceil(t/8)}get raw(){return this.data.subarray(0,this.byteLength)}sumWith(e){M(e.bitLength===this.bitLength,`Invalid bit length for sumWith: ${e.bitLength} vs ${this.bitLength}`);const t=e.raw;for(let e=0;e<this.byteLength;e++)this.data[e]|=t[e]}setBit(e,t){M(e<this.bitLength,`Index out of bounds. Need ${e} has ${this.bitLength}.`);const r=Math.floor(e/8),s=1<<e%8;t?this.data[r]|=s:this.data[r]&=~s}isSet(e){M(e<this.bitLength,`Index out of bounds. Need ${e} has ${this.bitLength}.`);const t=Math.floor(e/8),r=1<<e%8;return(this.data[t]&r)>0}*indicesOfSetBits(){for(let e=0;e<this.bitLength;e++){const t=e>>3,r=e-(t<<3);1&~(this.data[t]>>r)||(yield e)}}}const he=e=>P(e,ue(e),`input must have one-byte representation, got ${e}`),ue=e=>(255&e)===e,de=e=>P(e,fe(e),`input must have two-byte representation, got ${e}`),fe=e=>(65535&e)===e,pe=e=>P(e,ge(e),`input must have four-byte representation, got ${e}`),ge=e=>(4294967295&e)>>>0===e,ye=e=>{const t=BigInt(e);return P(t,me(t),`input must have eight-byte representation, got ${e}`)},me=e=>(18446744073709551615n&e)===e;function be(...e){let t=0n;for(const r of e)t+=r;const r=!me(t);return t&=0xffffffffffffffffn,{overflow:r,value:ye(t)}}function Ae(e){return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}function Ie(e){return M(4===e.length,"Input must be a Uint8Array of length 4"),e[0]|e[1]<<8|e[2]<<16|e[3]<<24}const ve=(e,...t)=>t.reduce((e,t)=>t>e?e:t,e);class we{source;offset;context;static fromBytesBlob(e,t){return new we(e.raw,t)}static fromBlob(e){return new we(e)}static decodeObject(e,t,r){const s=t instanceof J?we.fromBytesBlob(t):we.fromBlob(t);s.attachContext(r);const i=s.object(e);return s.finish(),i}static decodeSequence(e,t,r){const s=t instanceof J?we.fromBytesBlob(t):we.fromBlob(t);s.attachContext(r);const i=[];for(;s.bytesRead()<s.source.length;)i.push(s.object(e));return s.finish(),i}dataView;constructor(e,t=0,r){this.source=e,this.offset=t,this.context=r,this.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)}attachContext(e){this.context=e}getContext(){return this.context}clone(){return new we(this.source,this.offset,this.context)}bytesRead(){return this.offset}remainingBytes(){const e=this.source.subarray(this.offset),t=e.length;return this.offset+=t,Y.fromBlob(e,t)}i8(){return this.getNum(1,()=>this.dataView.getInt8(this.offset))}u8(){return this.getNum(1,()=>this.dataView.getUint8(this.offset))}i16(){return this.getNum(2,()=>this.dataView.getInt16(this.offset,!0))}u16(){return this.getNum(2,()=>this.dataView.getUint16(this.offset,!0))}i24(){const e=this.u24();return e>=2**23?e-2**24:e}u24(){return this.getNum(3,()=>{let e=this.dataView.getUint8(this.offset);return e|=this.dataView.getUint16(this.offset+1,!0)<<8,e})}i32(){return this.getNum(4,()=>this.dataView.getInt32(this.offset,!0))}u32(){return this.getNum(4,()=>this.dataView.getUint32(this.offset,!0))}i64(){return this.getNum(8,()=>this.dataView.getBigInt64(this.offset,!0))}u64(){return this.getNum(8,()=>this.dataView.getBigUint64(this.offset,!0))}bool(){const e=this.u8();if(0===e)return!1;if(1===e)return!0;throw new Error(`Unexpected number when decoding a boolean: ${e}`)}varU32(){this.ensureHasBytes(1);const e=this.source[this.offset],t=Ee(e);if(this.offset+=1,0===t)return e;if(t>4)throw new Error(`Unexpectedly large value for u32. l=${t}`);this.ensureHasBytes(t);const r=e+2**(8-t)-256<<8*t;if(1===t)return r+this.u8();if(2===t)return r+this.u16();if(3===t)return r+this.u24();if(0===r)return this.u32();throw new Error(`Unexpectedly large value for u32. l=${t}, mostSignificantByte=${r}`)}varU64(){this.ensureHasBytes(1);const e=this.source[this.offset],t=Ee(e);if(this.offset+=1,0===t)return ye(e);if(this.ensureHasBytes(t),this.offset+=t,8===t)return ye(this.dataView.getBigUint64(this.offset-t,!0));let r=BigInt(e+2**(8-t)-256)<<BigInt(8*t);for(let e=0;e<t;e+=1)r|=BigInt(this.source[this.offset-t+e])<<BigInt(8*e);return ye(r)}bytes(e){if(0===e)return Y.zero(e);this.ensureHasBytes(e);const t=this.source.subarray(this.offset,this.offset+e);return this.offset+=e,Y.fromBlob(t,e)}bytesBlob(){const e=this.varU32();this.ensureHasBytes(e);const t=this.source.subarray(this.offset,this.offset+e);return this.offset+=e,J.blobFrom(t)}bitVecFixLen(e){if(0===e)return le.empty(0);const t=Math.ceil(e/8),r=this.bytes(t),s=e%8;if(s>0&&r.raw[t-1]>>s>0)throw new Error("Non-zero bits found in the last byte of bitvec encoding.");return le.fromBytes(r,e)}bitVecVarLen(){const e=this.varU32();return this.bitVecFixLen(e)}object(e){return e.decode(this)}optional(e){return this.bool()?e.decode(this):null}sequenceFixLen(e,t){const r=Array(t);for(let s=0;s<t;s+=1)r[s]=e.decode(this);return r}sequenceVarLen(e){const t=this.varU32();return this.sequenceFixLen(e,t)}resetTo(e){this.offset<e?this.skip(e-this.offset):(M(e>=0,"The offset has to be positive"),this.offset=e)}skip(e){this.ensureHasBytes(e),this.offset+=e}finish(){if(this.offset<this.source.length)throw new Error(`Expecting end of input, yet there are still ${this.source.length-this.offset} bytes left.`)}getNum(e,t){this.ensureHasBytes(e);const r=t();return this.offset+=e,r}ensureHasBytes(e){if(M(e>=0,"Negative number of bytes given."),this.offset+e>this.source.length)throw new Error(`Attempting to decode more data than there is left. Need ${e}, left: ${this.source.length-this.offset}.`)}}const Se=[255,254,252,248,240,224,192,128];function Ee(e){M(e>=0&&e<256,`Incorrect byte value: ${e}`);for(let t=0;t<Se.length;t++)if(e>=Se[t])return 8-t;return 0}function Ce(e){return M(e.isExact,"The value is not exact size estimation!"),e.bytes}function ke(e,t){return{bytes:e.bytes+t.bytes,isExact:e.isExact&&t.isExact}}const xe=10485760;class _e{destination;buffer;static create(e){if(void 0!==e&&"destination"in e)return new _e(e.destination);const t=e?.expectedLength??512,r=new ArrayBuffer(Math.min(xe,t),{maxByteLength:xe}),s=new Uint8Array(r);return new _e(s,r)}static encodeObject(e,t,r){const s=_e.create({expectedLength:e.sizeHint.bytes||512});return s.attachContext(r),s.object(e,t),s.viewResult()}offset=0;context;dataView;constructor(e,t){this.destination=e,this.buffer=t,this.dataView=void 0!==t?new DataView(t):new DataView(e.buffer,e.byteOffset,e.byteLength)}attachContext(e){this.context=e}getContext(){return this.context}viewResult(){return J.blobFrom(this.destination.subarray(0,this.offset))}i32(e){this.prepareIntegerN(e,4),this.dataView.setInt32(this.offset,e,!0),this.offset+=4}i64(e){const t=2n**64n;M(e<t,"Only for numbers up to 2**64 - 1"),M(-e<=t/2n,"Only for numbers down to -2**63"),this.ensureBigEnough(8),this.dataView.setBigInt64(this.offset,e,!0),this.offset+=8}i24(e){this.prepareIntegerN(e,3),this.dataView.setInt8(this.offset,255&e),this.dataView.setInt16(this.offset+1,e>>8,!0),this.offset+=3}i16(e){this.prepareIntegerN(e,2),this.dataView.setInt16(this.offset,e,!0),this.offset+=2}i8(e){this.prepareIntegerN(e,1),this.dataView.setInt8(this.offset,e),this.offset+=1}bool(e){this.varU32(pe(e?1:0))}prepareIntegerN(e,t){const r=2**(8*t);M(e<r,`Only for numbers up to 2**${8*t} - 1`),M(-e<=r/2,"Only for numbers down to -2**"+(8*t-1)),this.ensureBigEnough(t)}varU32(e){M(e>=0,"Only for natural numbers."),M(e<2**32,"Only for numbers up to 2**32"),this.varU64(BigInt(e))}varU64(e){const t=BigInt(e);if(0n===t)return this.ensureBigEnough(1),this.destination[this.offset]=0,void(this.offset+=1);let r=2n**56n;if(t>=r)return this.ensureBigEnough(9),this.destination[this.offset]=255,this.dataView.setBigUint64(this.offset+1,t,!0),void(this.offset+=9);let s=r>>7n;for(let e=7;e>=0;e-=1){if(t>=s){this.ensureBigEnough(e+1);const r=2n**BigInt(8*e),s=BigInt(256-2**(8-e))+t/r;this.destination[this.offset]=255&Number(s),this.offset+=1;let i=t%r;for(let t=this.offset;t<this.offset+e;t+=1)this.destination[t]=Number(0xffn&i),i>>=8n;return void(this.offset+=e)}r=s,s>>=7n}throw new Error(`Unhandled number encoding: ${t}`)}bytesBlob(e){this.blob(e.raw)}blob(e){this.varU32(pe(e.length)),this.ensureBigEnough(e.length),this.destination.set(e,this.offset),this.offset+=e.length}bytes(e){this.ensureBigEnough(e.length),this.destination.set(e.raw,this.offset),this.offset+=e.length}bitVecFixLen(e){const t=e.raw;this.bytes(Y.fromBlob(t,t.length))}bitVecVarLen(e){const t=e.bitLength;this.varU32(pe(t)),this.bitVecFixLen(e)}object(e,t){this.applySizeHint(e),e.encode(this,t)}optional(e,t){const r=null!=t;this.bool(r),r&&(this.applySizeHint(e),e.encode(this,t))}sequenceFixLen(e,t){this.applySizeHint(e,t.length);for(const r of t)e.encode(this,r)}sequenceVarLen(e,t){M(t.length<=2**32,"Wow, that's a nice long sequence you've got here."),this.varU32(pe(t.length)),this.sequenceFixLen(e,t)}applySizeHint(e,t=1){const r=e.sizeHint.bytes;r>0&&t>0&&this.ensureBigEnough(r*t,{silent:!0})}ensureBigEnough(e,t={silent:!1}){M(e>=0,"Negative length given");const r=this.offset+e;if(r>xe){if(t.silent)return;throw new Error("The encoded size would reach the maximum of 10485760.")}if(r>this.destination.length){if(void 0!==this.buffer){const e=Math.max(r,this.buffer.byteLength<<1);this.buffer.resize(Math.min(xe,e))}if(r>this.destination.length){if(t.silent)return;throw new Error(`Not enough space in the destination array. Needs ${r}, has ${this.destination.length}.`)}}}}class Be{decoder;constructor(e){this.decoder=e}u64=()=>this.decoder.skip(8);u32=()=>this.decoder.skip(4);u24=()=>this.decoder.skip(3);u16=()=>this.decoder.skip(2);u8=()=>this.decoder.skip(1);bool=()=>this.decoder.skip(1);varU32=()=>this.varU64();varU64(){const e=Ee(this.decoder.u8());this.decoder.skip(e)}bytes(e){this.decoder.skip(e)}bytesBlob(){const e=this.decoder.varU32();this.decoder.skip(e)}bitVecFixLen(e){this.decoder.skip(Math.ceil(e/8))}bitVecVarLen(){const e=this.decoder.varU32();this.bitVecFixLen(e)}object(e){e.skip(this)}optional(e){this.decoder.bool()&&e.skip(this)}sequenceFixLen(e,t){for(let r=0;r<t;r+=1)e.skip(this)}sequenceVarLen(e){const t=this.decoder.varU32();return this.sequenceFixLen(e,t)}}function Re(e,t,r){if(t<e.minLength)throw new Error(`${r}: length is below minimal. ${t} < ${e.minLength}`);if(t>e.maxLength)throw new Error(`${r}: length is above maximal. ${t} > ${e.maxLength}`)}class Oe{getView;getValue;getEncoded;cachedValue;cachedView;cachedBlob;constructor(e,t,r){this.getView=e,this.getValue=t,this.getEncoded=r}materialize(){return void 0===this.cachedValue&&(this.cachedValue=this.getValue()),this.cachedValue}view(){return void 0===this.cachedView&&(this.cachedView=this.getView()),this.cachedView}encoded(){return void 0===this.cachedBlob&&(this.cachedBlob=this.getEncoded()),this.cachedBlob}}class Ue{decoder;materializedConstructor;descriptors;descriptorsKeys;cache=new Map;initialDecoderOffset;lastDecodedFieldIdx=-1;constructor(e,t,r){this.decoder=e,this.materializedConstructor=t,this.descriptors=r,this.descriptorsKeys=Object.keys(r),this.initialDecoderOffset=e.bytesRead()}materialize(){const e=this.descriptorsKeys,t=Object.fromEntries(e.map(e=>[e,this.get(e).materialize()]));return this.materializedConstructor.create(t)}encoded(){const e=this.descriptorsKeys;if(0===e.length)return J.blobFromNumbers([]);if(this.lastDecodedFieldIdx<e.length-1){const t=e[e.length-1];this.decodeUpTo(t)}return J.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset,this.decoder.bytesRead()))}get(e){const t=this.cache.get(e);return void 0!==t?t:this.decodeUpTo(e)}decodeUpTo(e){const t=this.descriptorsKeys.indexOf(e),r=this.descriptorsKeys[this.lastDecodedFieldIdx];M(this.lastDecodedFieldIdx<t,`Unjustified call to 'decodeUpTo' -\n the index ($Blobindex}, ${String(e)})\n is already decoded (${this.lastDecodedFieldIdx}, ${String(r)}).\n `);let s=this.cache.get(r);const i=new Be(this.decoder);for(let e=this.lastDecodedFieldIdx+1;e<=t;e++){const t=i.decoder.clone(),r=this.descriptorsKeys[e],n=this.descriptors[r];s=new Oe(()=>n.View.decode(t.clone()),()=>n.decode(t.clone()),()=>n.skipEncoded(t.clone())),n.skip(i),this.cache.set(r,s),this.lastDecodedFieldIdx=e}return P(s,void 0!==s,"Last item must be set, since the loop turns at least once.")}}class Te{decoder;descriptor;length;cache=new Map;initialDecoderOffset;lastDecodedIdx=-1;constructor(e,t,r){this.decoder=e,this.descriptor=t,this.initialDecoderOffset=this.decoder.bytesRead(),this.length=r??e.varU32()}*[Symbol.iterator](){for(let e=0;e<this.length;e++){const t=this.get(e),r=P(t,void 0!==t,"We are within 0..this.length so all items are defined.");yield r}}map(e){const t=new Array(this.length);let r=0;for(const s of this)t[r]=e(s),r++;return t}get(e){if(e>=this.length)return;const t=this.cache.get(e);return void 0!==t?t:this.decodeUpTo(e)}encoded(){return 0===this.length?J.blobFromNumbers([]):(this.lastDecodedIdx<this.length-1&&this.decodeUpTo(this.length-1),J.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset,this.decoder.bytesRead())))}decodeUpTo(e){M(this.lastDecodedIdx<e,`Unjustified call to 'decodeUpTo' - the index (${e}) is already decoded (${this.lastDecodedIdx}).`);let t=this.cache.get(this.lastDecodedIdx);const r=new Be(this.decoder);for(let s=this.lastDecodedIdx+1;s<=e;s++){const e=r.decoder.clone(),i=this.descriptor;t=new Oe(()=>i.View.decode(e.clone()),()=>i.decode(e.clone()),()=>i.skipEncoded(e.clone())),i.skip(r),this.cache.set(s,t),this.lastDecodedIdx=s}return P(t,void 0!==t,"Last item must be set, since the loop turns at least once.")}}class Ne{name;sizeHint;encode;decode;skip;View;static withView(e,t,r,s,i,n){return new Ne(e,t,r,s,i,n)}static new(e,t,r,s,i){return new Ne(e,t,r,s,i,null)}constructor(e,t,r,s,i,n){this.name=e,this.sizeHint=t,this.encode=r,this.decode=s,this.skip=i,this.View=n??this}skipEncoded(e){const t=e.bytesRead();this.skip(new Be(e));const r=e.bytesRead();return J.blobFrom(e.source.subarray(t,r))}convert(e,t){return new Ne(this.name,this.sizeHint,(t,r)=>this.encode(t,e(r)),e=>t(this.decode(e)),this.skip,this.View)}asOpaque(){return this.convert(e=>e,e=>e)}}function De(e){return e.convert(e=>(M(Array.isArray(e),`Non-arrays are not supported as 'readonly': got ${typeof e}, ${e}`),e),e=>e)}function Me(e){return{bytes:e,isExact:!0}}var Pe,Le;function He(e,t){for(const r in e)"string"==typeof r&&r in e&&t(r,e[r])}function Ke(e){return e.View!==e}(Le=Pe||(Pe={})).bytes=(()=>{const e=new Map;return t=>{let r=e.get(t);return void 0===r&&(r=Ne.new(`Bytes<${t}>`,Me(t),(e,t)=>e.bytes(t),e=>e.bytes(t),e=>e.bytes(t)),e.set(t,r)),r}})(),Le.varU32=Ne.new("var_u32",{bytes:4,isExact:!1},(e,t)=>e.varU32(t),e=>e.varU32(),e=>e.varU32()),Le.varU64=Ne.new("var_u64",{bytes:8,isExact:!1},(e,t)=>e.varU64(t),e=>e.varU64(),e=>e.varU64()),Le.u64=Ne.withView("u64",Me(8),(e,t)=>e.i64(t),e=>e.u64(),e=>e.u64(),Le.bytes(8)),Le.u32=Ne.withView("u32",Me(4),(e,t)=>e.i32(t),e=>e.u32(),e=>e.u32(),Le.bytes(4)),Le.u24=Ne.withView("u24",Me(3),(e,t)=>e.i24(t),e=>e.u24(),e=>e.u24(),Le.bytes(3)),Le.u16=Ne.withView("u16",Me(2),(e,t)=>e.i16(t),e=>e.u16(),e=>e.u16(),Le.bytes(2)),Le.u8=Ne.new("u8",Me(1),(e,t)=>e.i8(t),e=>e.u8(),e=>e.u8()),Le.i64=Ne.withView("u64",Me(8),(e,t)=>e.i64(t),e=>e.i64(),e=>e.u64(),Le.bytes(8)),Le.i32=Ne.withView("i32",Me(4),(e,t)=>e.i32(t),e=>e.i32(),e=>e.u32(),Le.bytes(4)),Le.i24=Ne.withView("i24",Me(3),(e,t)=>e.i24(t),e=>e.i24(),e=>e.u24(),Le.bytes(3)),Le.i16=Ne.withView("i16",Me(2),(e,t)=>e.i16(t),e=>e.i16(),e=>e.u16(),Le.bytes(2)),Le.i8=Ne.new("i8",Me(1),(e,t)=>e.i8(t),e=>e.i8(),e=>e.u8()),Le.bool=Ne.new("bool",Me(1),(e,t)=>e.bool(t),e=>e.bool(),e=>e.bool()),Le.blob=Ne.new("BytesBlob",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(t),e=>e.bytesBlob(),e=>e.bytesBlob()),Le.string=Ne.withView("string",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(J.blobFrom((new TextEncoder).encode(t))),e=>new TextDecoder("utf8",{fatal:!0}).decode(e.bytesBlob().raw),e=>e.bytesBlob(),Le.blob),Le.bitVecVarLen=Ne.new("BitVec[?]",{bytes:8,isExact:!1},(e,t)=>e.bitVecVarLen(t),e=>e.bitVecVarLen(),e=>e.bitVecVarLen()),Le.bitVecFixLen=e=>Ne.new(`BitVec[${e}]`,Me(e>>>3),(e,t)=>e.bitVecFixLen(t),t=>t.bitVecFixLen(e),t=>t.bitVecFixLen(e)),Le.optional=e=>{const t=Ne.new(`Optional<${e.name}>`,ke({bytes:1,isExact:!1},e.sizeHint),(t,r)=>t.optional(e,r),t=>t.optional(e),t=>t.optional(e));return Ke(e)?Ne.withView(t.name,t.sizeHint,t.encode,t.decode,t.skip,Le.optional(e.View)):t},Le.sequenceVarLen=(e,t={minLength:0,maxLength:2**32-1})=>{const r=`Sequence<${e.name}>[?]`,s=t.typicalLength??64;return Ne.withView(r,{bytes:s*e.sizeHint.bytes,isExact:!1},(s,i)=>{Re(t,i.length,r),s.sequenceVarLen(e,i)},s=>{const i=s.varU32();return Re(t,i,r),s.sequenceFixLen(e,i)},s=>{const i=s.decoder.varU32();return Re(t,i,r),s.sequenceFixLen(e,i)},function(e,t){const r={bytes:64*e.sizeHint.bytes,isExact:!1},s=e.name!==e.View.name?`, ${e.View.name}`:"",i=`SeqView<${e.name}${s}>[?]`,n=r=>{const s=r.decoder.varU32();return Re(t,s,i),r.sequenceFixLen(e,s)};return Ne.new(i,r,(e,r)=>{Re(t,r.length,i);const s=r.encoded();e.bytes(Y.fromBlob(s.raw,s.length))},t=>{const r=new Te(t.clone(),e);return n(new Be(t)),r},n)}(e,t))},Le.sequenceFixLen=(e,t)=>Ne.withView(`Sequence<${e.name}>[${t}]`,{bytes:t*e.sizeHint.bytes,isExact:e.sizeHint.isExact},(t,r)=>t.sequenceFixLen(e,r),r=>r.sequenceFixLen(e,t),r=>r.sequenceFixLen(e,t),function(e,{fixedLength:t}){const r={bytes:e.sizeHint.bytes*t,isExact:e.sizeHint.isExact},s=r=>r.sequenceFixLen(e,t),i=e.name!==e.View.name?`, ${e.View.name}`:"",n=`SeqView<${e.name}${i}>[${t}]`;return Ne.new(n,r,(e,t)=>{const r=t.encoded();e.bytes(Y.fromBlob(r.raw,r.length))},r=>{const i=new Te(r.clone(),e,t);return s(new Be(r)),i},s)}(e,{fixedLength:t})),Le.dictionary=(e,t,{sortKeys:r,fixedLength:s})=>{const i=Ne.new(`Dictionary<${e.name}, ${t.name}>[${s??"?"}]`,{bytes:void 0!==s?s*ke(e.sizeHint,t.sizeHint).bytes:32*(ke(e.sizeHint,t.sizeHint).bytes??0),isExact:void 0!==s&&e.sizeHint.isExact&&t.sizeHint.isExact},(i,n)=>{const o=Array.from(n.entries());o.sort((e,t)=>r(e[0],t[0])),void 0!==s&&0!==s||i.varU32(pe(o.length));for(const[r,s]of o)e.encode(i,r),t.encode(i,s)},i=>{const n=new Map,o=s??i.varU32();let a=null;for(let s=0;s<o;s+=1){const s=e.decode(i),o=t.decode(i);if(n.has(s))throw new Error(`Duplicate item in the dictionary encoding: "${s}"!`);if(null!==a&&r(a,s)>=0)throw new Error(`The keys in dictionary encoding are not sorted "${a}" >= "${s}"!`);n.set(s,o),a=s}return n},r=>{const i=s??r.decoder.varU32();r.sequenceFixLen(e,i),r.sequenceFixLen(t,i)});return Ke(t)?Ne.withView(i.name,i.sizeHint,i.encode,i.decode,i.skip,Le.dictionary(e,t.View,{sortKeys:r,fixedLength:s})):i},Le.custom=({name:e,sizeHint:t={bytes:0,isExact:!1}},r,s,i)=>Ne.new(e,t,r,s,i),Le.select=({name:e,sizeHint:t},r)=>Ne.withView(e,t,(e,t)=>r(e.getContext()).encode(e,t),e=>r(e.getContext()).decode(e),e=>r(e.decoder.getContext()).skip(e),r(null).View),Le.object=(e,t="object",r=e=>e)=>Le.Class({name:t,create:r},e),Le.Class=(e,t)=>{let r=Me(0);He(t,(e,t)=>{r=ke(r,t.sizeHint)});const s=e=>{if(r.isExact)return e.decoder.skip(r.bytes);He(t,(t,r)=>{r.skip(e)})},i=function(e,t,r,s){class i extends Ue{constructor(r){super(r,e,t)}}return He(t,e=>{"string"==typeof e&&Object.defineProperty(i.prototype,e,{get:function(){return this.get(e)}})}),Ne.new(`View<${e.name}>`,r,(e,t)=>{const r=t.encoded();e.bytes(Y.fromBlob(r.raw,r.length))},e=>{const t=new i(e.clone());return s(new Be(e)),t},s)}(e,t,r,s);return Ne.withView(e.name,r,(e,r)=>{He(t,(t,s)=>{const i=r[t];s.encode(e,i)})},r=>{const s={};return He(t,(e,t)=>{const i=t.decode(r);s[e]=i}),e.create(s)},s,i)};const Qe=2n**255n-19n,Ve=2n**252n+27742317777372353535851937790883648493n,Fe=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,$e=0x6666666666666666666666666666666666666666666666666666666666666658n,je={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Qe,n:Ve,h:8,Gx:Fe,Gy:$e},Ge=(e="")=>{throw new Error(e)},qe=e=>"string"==typeof e,ze=(e,t)=>!(e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name)(e)||"number"==typeof t&&t>0&&e.length!==t?Ge("Uint8Array of valid length expected"):e,We=e=>new Uint8Array(e),Je=(e,t=Qe)=>{let r=e%t;return r>=0n?r:t+r},Ye=e=>e instanceof Xe?e:Ge("Point expected");class Xe{constructor(e,t,r,s){this.ex=e,this.ey=t,this.ez=r,this.et=s}static fromAffine(e){return new Xe(e.x,e.y,1n,Je(e.x*e.y))}static fromHex(e,t=!1){const{d:r}=je,s=(n=e,o=32,e=ze(qe(n)?it(n):We(ze(n)),o)).slice(),i=e[31];var n,o;s[31]=-129&i;const a=ot(s);!t||0n<=a&&a<2n**256n||Ge("bad y coord 1"),t||0n<=a&&a<Qe||Ge("bad y coord 2");const c=Je(a*a),l=Je(c-1n),h=Je(r*c+1n);let{isValid:u,value:d}=ut(l,h);u||Ge("bad y coordinate 3");const f=1n==(1n&d),p=!!(128&i);return!t&&0n===d&&p&&Ge("bad y coord 3"),p!==f&&(d=Je(-d)),new Xe(d,a,1n,Je(d*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){const{ex:t,ey:r,ez:s}=this,{ex:i,ey:n,ez:o}=Ye(e),a=Je(t*o),c=Je(i*s),l=Je(r*o),h=Je(n*s);return a===c&&l===h}is0(){return this.equals(et)}negate(){return new Xe(Je(-this.ex),this.ey,this.ez,Je(-this.et))}double(){const{ex:e,ey:t,ez:r}=this,{a:s}=je,i=Je(e*e),n=Je(t*t),o=Je(2n*Je(r*r)),a=Je(s*i),c=e+t,l=Je(Je(c*c)-i-n),h=a+n,u=h-o,d=a-n,f=Je(l*u),p=Je(h*d),g=Je(l*d),y=Je(u*h);return new Xe(f,p,y,g)}add(e){const{ex:t,ey:r,ez:s,et:i}=this,{ex:n,ey:o,ez:a,et:c}=Ye(e),{a:l,d:h}=je,u=Je(t*n),d=Je(r*o),f=Je(i*h*c),p=Je(s*a),g=Je((t+r)*(n+o)-u-d),y=Je(p-f),m=Je(p+f),b=Je(d-l*u),A=Je(g*y),I=Je(m*b),v=Je(g*b),w=Je(y*m);return new Xe(A,I,w,v)}mul(e,t=!0){if(0n===e)return!0===t?Ge("cannot multiply by 0"):et;if("bigint"==typeof e&&0n<e&&e<Ve||Ge("invalid scalar, must be < L"),!t&&this.is0()||1n===e)return this;if(this.equals(Ze))return yt(e).p;let r=et,s=Ze;for(let i=this;e>0n;i=i.double(),e>>=1n)1n&e?r=r.add(i):t&&(s=s.add(i));return r}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(je.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(Ve/2n,!1).double();return e=e.add(this),e.is0()}toAffine(){const{ex:e,ey:t,ez:r}=this;if(this.equals(et))return{x:0n,y:1n};const s=ct(r,Qe);return 1n!==Je(r*s)&&Ge("invalid inverse"),{x:Je(e*s),y:Je(t*s)}}toRawBytes(){const{x:e,y:t}=this.toAffine(),r=nt(t);return r[31]|=1n&e?128:0,r}toHex(){return rt(this.toRawBytes())}}Xe.BASE=new Xe(Fe,$e,1n,Je(Fe*$e)),Xe.ZERO=new Xe(0n,1n,1n,0n);const{BASE:Ze,ZERO:et}=Xe,tt=(e,t)=>e.toString(16).padStart(t,"0"),rt=e=>Array.from(ze(e)).map(e=>tt(e,2)).join(""),st=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0,it=e=>{const t="hex invalid";if(!qe(e))return Ge(t);const r=e.length,s=r/2;if(r%2)return Ge(t);const i=We(s);for(let r=0,n=0;r<s;r++,n+=2){const s=st(e.charCodeAt(n)),o=st(e.charCodeAt(n+1));if(void 0===s||void 0===o)return Ge(t);i[r]=16*s+o}return i},nt=e=>it(tt(e,64)).reverse(),ot=e=>BigInt("0x"+rt(We(ze(e)).reverse())),at=(...e)=>{const t=We(e.reduce((e,t)=>e+ze(t).length,0));let r=0;return e.forEach(e=>{t.set(e,r),r+=e.length}),t},ct=(e,t)=>{(0n===e||t<=0n)&&Ge("no inverse n="+e+" mod="+t);let r=Je(e,t),s=t,i=0n,n=1n,o=1n,a=0n;for(;0n!==r;){const e=s/r,t=s%r,c=i-o*e,l=n-a*e;s=r,r=t,i=o,n=a,o=c,a=l}return 1n===s?Je(i,t):Ge("no inverse")},lt=(e,t)=>{let r=e;for(;t-- >0n;)r*=r,r%=Qe;return r},ht=19681161376707505956807079304988542015446066515923890162744021073123829784752n,ut=(e,t)=>{const r=Je(t*t*t),s=(e=>{const t=e*e%Qe*e%Qe,r=lt(t,2n)*t%Qe,s=lt(r,1n)*e%Qe,i=lt(s,5n)*s%Qe,n=lt(i,10n)*i%Qe,o=lt(n,20n)*n%Qe,a=lt(o,40n)*o%Qe,c=lt(a,80n)*a%Qe,l=lt(c,80n)*a%Qe,h=lt(l,10n)*i%Qe;return{pow_p_5_8:lt(h,2n)*e%Qe,b2:t}})(e*Je(r*r*t)).pow_p_5_8;let i=Je(e*r*s);const n=Je(t*i*i),o=i,a=Je(i*ht),c=n===e,l=n===Je(-e),h=n===Je(-e*ht);return c&&(i=o),(l||h)&&(i=a),1n==(1n&Je(i))&&(i=Je(-i)),{isValid:c||l,value:i}};let dt;const ft=()=>"object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,pt={bytesToHex:rt,hexToBytes:it,concatBytes:at,mod:Je,invert:ct,randomBytes:(e=32)=>{const t=ft();return t&&t.getRandomValues||Ge("crypto.getRandomValues must be defined"),t.getRandomValues(We(e))},sha512Async:async(...e)=>{const t=ft(),r=t&&t.subtle;r||Ge("etc.sha512Async or crypto.subtle must be defined");const s=at(...e);return We(await r.digest("SHA-512",s.buffer))},sha512Sync:void 0};let gt;Object.defineProperties(pt,{sha512Sync:{configurable:!1,get:()=>dt,set(e){dt||(dt=e)}}});const yt=e=>{const t=gt||(gt=(()=>{const e=[];let t=Ze,r=t;for(let s=0;s<33;s++){r=t,e.push(r);for(let s=1;s<128;s++)r=r.add(t),e.push(r);t=r.double()}return e})()),r=(e,t)=>{let r=t.negate();return e?r:t};let s=et,i=Ze;const n=BigInt(255),o=BigInt(8);for(let a=0;a<33;a++){const c=128*a;let l=Number(e&n);e>>=o,l>128&&(l-=256,e+=1n);const h=c,u=c+Math.abs(l)-1,d=a%2!=0,f=l<0;0===l?i=i.add(r(d,t[h])):s=s.add(r(f,t[u]))}return{p:s,f:i}};var mt=o(625);const bt=32,At=64;async function It(e){if(0===e.length)return Promise.resolve([]);const t=e.reduce((e,{message:t,key:r,signature:s})=>e+r.length+s.length+t.length+1,0),r=new Uint8Array(t);let s=0;for(const{key:t,message:i,signature:n}of e){r.set(t.raw,s),s+=bt,r.set(n.raw,s),s+=At;const e=i.length;M(e<256,`Message needs to be shorter than 256 bytes. Got: ${e}`),r[s]=e,s+=1,r.set(i.raw,s),s+=e}const i=Array.from((0,mt.verify_ed25519)(r)).map(e=>1===e);return Promise.resolve(i)}var vt=o(405);const wt=32,St=144,Et=144,Ct=32;class kt extends Q{hash;data;constructor(e,t){super(),this.hash=e,this.data=t}}class xt extends kt{encoded;constructor(e,t,r){super(e,t),this.encoded=r}}class _t{emptyHash(){return Y.zero(Ct)}}const Bt=new _t;var Rt,Ot=o(675),Ut=o.n(Ot);function Tt(e,t=Bt){const r=t.emptyHash();if(0===e.length)return r.asOpaque();const s=Ut()(Ct);for(const t of e)s?.update(t instanceof J?t.raw:t);return s?.digest(r.raw),r.asOpaque()}function Nt(e,t=Bt){const r=Ut()(Ct),s=e instanceof J?e.raw:e;r?.update(s);const i=t.emptyHash();return r?.digest(i.raw),i}function Dt(e,t=Bt){return Nt(J.blobFromString(e),t)}function Mt(e,t,r,s){return new(r||(r=Promise))(function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class Pt{constructor(){this.mutex=Promise.resolve()}lock(){let e=()=>{};return this.mutex=this.mutex.then(()=>new Promise(e)),new Promise(t=>{e=t})}dispatch(e){return Mt(this,void 0,void 0,function*(){const t=yield this.lock();try{return yield Promise.resolve(e())}finally{t()}})}}const Lt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Ht=null!==(Rt=Lt.Buffer)&&void 0!==Rt?Rt:null,Kt=Lt.TextEncoder?new Lt.TextEncoder:null;function Qt(e,t){return(15&e)+(e>>6|e>>3&8)<<4|(15&t)+(t>>6|t>>3&8)}const Vt="a".charCodeAt(0)-10,Ft="0".charCodeAt(0);function $t(e,t,r){let s=0;for(let i=0;i<r;i++){let r=t[i]>>>4;e[s++]=r>9?r+Vt:r+Ft,r=15&t[i],e[s++]=r>9?r+Vt:r+Ft}return String.fromCharCode.apply(null,e)}const jt=null!==Ht?e=>{if("string"==typeof e){const t=Ht.from(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.length)}if(Ht.isBuffer(e))return new Uint8Array(e.buffer,e.byteOffset,e.length);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")}:e=>{if("string"==typeof e)return Kt.encode(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")},Gt=new Uint8Array(256);for(let e=0;e<64;e++)Gt["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;function qt(e){const t=function(e){let t=Math.floor(.75*e.length);const r=e.length;return"="===e[r-1]&&(t-=1,"="===e[r-2]&&(t-=1)),t}(e),r=e.length,s=new Uint8Array(t);let i=0;for(let t=0;t<r;t+=4){const r=Gt[e.charCodeAt(t)],n=Gt[e.charCodeAt(t+1)],o=Gt[e.charCodeAt(t+2)],a=Gt[e.charCodeAt(t+3)];s[i]=r<<2|n>>4,i+=1,s[i]=(15&n)<<4|o>>2,i+=1,s[i]=(3&o)<<6|63&a,i+=1}return s}const zt=16384,Wt=new Pt,Jt=new Map;function Yt(e,t){return Mt(this,void 0,void 0,function*(){let r=null,s=null,i=!1;if("undefined"==typeof WebAssembly)throw new Error("WebAssembly is not supported in this environment!");const n=()=>new DataView(r.exports.memory.buffer).getUint32(r.exports.STATE_SIZE,!0),o=Wt.dispatch(()=>Mt(this,void 0,void 0,function*(){if(!Jt.has(e.name)){const t=qt(e.data),r=WebAssembly.compile(t);Jt.set(e.name,r)}const t=yield Jt.get(e.name);r=yield WebAssembly.instantiate(t,{})})),a=(e=null)=>{i=!0,r.exports.Hash_Init(e)},c=e=>{if(!i)throw new Error("update() called before init()");(e=>{let t=0;for(;t<e.length;){const i=e.subarray(t,t+zt);t+=i.length,s.set(i),r.exports.Hash_Update(i.length)}})(jt(e))},l=new Uint8Array(2*t),h=(e,n=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,r.exports.Hash_Final(n),"binary"===e?s.slice(0,t):$t(l,s,t)},u=e=>"string"==typeof e?e.length<4096:e.byteLength<zt;let d=u;switch(e.name){case"argon2":case"scrypt":d=()=>!0;break;case"blake2b":case"blake2s":d=(e,t)=>t<=512&&u(e);break;case"blake3":d=(e,t)=>0===t&&u(e);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":d=()=>!1}return yield(()=>Mt(this,void 0,void 0,function*(){r||(yield o);const e=r.exports.Hash_GetBuffer(),t=r.exports.memory.buffer;s=new Uint8Array(t,e,zt)}))(),{getMemory:()=>s,writeMemory:(e,t=0)=>{s.set(e,t)},getExports:()=>r.exports,setMemorySize:e=>{r.exports.Hash_SetMemorySize(e);const t=r.exports.Hash_GetBuffer(),i=r.exports.memory.buffer;s=new Uint8Array(i,t,e)},init:a,update:c,digest:h,save:()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");const t=r.exports.Hash_GetState(),s=n(),o=r.exports.memory.buffer,a=new Uint8Array(o,t,s),c=new Uint8Array(4+s);return function(e,t){const r=t.length>>1;for(let s=0;s<r;s++){const r=s<<1;e[s]=Qt(t.charCodeAt(r),t.charCodeAt(r+1))}}(c,e.hash),c.set(a,4),c},load:t=>{if(!(t instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");const s=r.exports.Hash_GetState(),o=n(),a=4+o,c=r.exports.memory.buffer;if(t.length!==a)throw new Error(`Bad state length (expected ${a} bytes, got ${t.length})`);if(!function(e,t){if(e.length!==2*t.length)return!1;for(let r=0;r<t.length;r++){const s=r<<1;if(t[r]!==Qt(e.charCodeAt(s),e.charCodeAt(s+1)))return!1}return!0}(e.hash,t.subarray(0,4)))throw new Error("This state was written by an incompatible hash implementation");const l=t.subarray(4);new Uint8Array(c,s,o).set(l),i=!0},calculate:(e,i=null,n=null)=>{if(!d(e,i))return a(i),c(e),h("hex",n);const o=jt(e);return s.set(o),r.exports.Hash_Calculate(o.length,i,n),$t(l,s,t)},hashLength:t}})}new Pt,new Pt,new DataView(new ArrayBuffer(4)),new Pt,new Pt,new Pt,new Pt,new Uint8Array(8),new Pt,new Pt,new Pt;var Xt={name:"sha3",data:"AGFzbQEAAAABFARgAAF/YAF/AGACf38AYAN/f38AAwgHAAEBAgEAAwUEAQECAgYOAn8BQZCNBQt/AEGACAsHcAgGbWVtb3J5AgAOSGFzaF9HZXRCdWZmZXIAAAlIYXNoX0luaXQAAQtIYXNoX1VwZGF0ZQACCkhhc2hfRmluYWwABA1IYXNoX0dldFN0YXRlAAUOSGFzaF9DYWxjdWxhdGUABgpTVEFURV9TSVpFAwEKpBwHBQBBgAoL1wMAQQBCADcDgI0BQQBCADcD+IwBQQBCADcD8IwBQQBCADcD6IwBQQBCADcD4IwBQQBCADcD2IwBQQBCADcD0IwBQQBCADcDyIwBQQBCADcDwIwBQQBCADcDuIwBQQBCADcDsIwBQQBCADcDqIwBQQBCADcDoIwBQQBCADcDmIwBQQBCADcDkIwBQQBCADcDiIwBQQBCADcDgIwBQQBCADcD+IsBQQBCADcD8IsBQQBCADcD6IsBQQBCADcD4IsBQQBCADcD2IsBQQBCADcD0IsBQQBCADcDyIsBQQBCADcDwIsBQQBCADcDuIsBQQBCADcDsIsBQQBCADcDqIsBQQBCADcDoIsBQQBCADcDmIsBQQBCADcDkIsBQQBCADcDiIsBQQBCADcDgIsBQQBCADcD+IoBQQBCADcD8IoBQQBCADcD6IoBQQBCADcD4IoBQQBCADcD2IoBQQBCADcD0IoBQQBCADcDyIoBQQBCADcDwIoBQQBCADcDuIoBQQBCADcDsIoBQQBCADcDqIoBQQBCADcDoIoBQQBCADcDmIoBQQBCADcDkIoBQQBCADcDiIoBQQBCADcDgIoBQQBBwAwgAEEBdGtBA3Y2AoyNAUEAQQA2AoiNAQuMAwEIfwJAQQAoAoiNASIBQQBIDQBBACABIABqQQAoAoyNASICcDYCiI0BAkACQCABDQBBgAohAwwBCwJAIAIgAWsiBCAAIAQgAEkbIgNFDQAgA0EDcSEFQQAhBgJAIANBBEkNACABQYCKAWohByADQXxxIQhBACEGA0AgByAGaiIDQcgBaiAGQYAKai0AADoAACADQckBaiAGQYEKai0AADoAACADQcoBaiAGQYIKai0AADoAACADQcsBaiAGQYMKai0AADoAACAIIAZBBGoiBkcNAAsLIAVFDQAgAUHIiwFqIQMDQCADIAZqIAZBgApqLQAAOgAAIAZBAWohBiAFQX9qIgUNAAsLIAAgBEkNAUHIiwEgAhADIAAgBGshACAEQYAKaiEDCwJAIAAgAkkNAANAIAMgAhADIAMgAmohAyAAIAJrIgAgAk8NAAsLIABFDQBBACECQcgBIQYDQCAGQYCKAWogAyAGakG4fmotAAA6AAAgBkEBaiEGIAAgAkEBaiICQf8BcUsNAAsLC+ALAS1+IAApA0AhAkEAKQPAigEhAyAAKQM4IQRBACkDuIoBIQUgACkDMCEGQQApA7CKASEHIAApAyghCEEAKQOoigEhCSAAKQMgIQpBACkDoIoBIQsgACkDGCEMQQApA5iKASENIAApAxAhDkEAKQOQigEhDyAAKQMIIRBBACkDiIoBIREgACkDACESQQApA4CKASETQQApA8iKASEUAkACQCABQcgASw0AQQApA+iKASEVQQApA/iKASEWQQApA/CKASEXQQApA4CLASEYQQApA9CKASEZQQApA+CKASEaQQApA9iKASEbDAELQQApA+CKASAAKQNghSEaQQApA9iKASAAKQNYhSEbQQApA9CKASAAKQNQhSEZIBQgACkDSIUhFEEAKQPoigEhFUEAKQP4igEhFkEAKQPwigEhF0EAKQOAiwEhGCABQekASQ0AIBggACkDgAGFIRggFiAAKQN4hSEWIBcgACkDcIUhFyAVIAApA2iFIRUgAUGJAUkNAEEAQQApA4iLASAAKQOIAYU3A4iLAQsgAyAChSEcIAUgBIUhHSAHIAaFIQcgCSAIhSEIIAsgCoUhHiANIAyFIQkgDyAOhSEKIBEgEIUhCyATIBKFIQxBACkDuIsBIRBBACkDkIsBIRFBACkDoIsBIRJBACkDsIsBIRNBACkDiIsBIQ1BACkDwIsBIQ5BACkDmIsBIR9BACkDqIsBIQ9BwH4hAANAIB4gByALhSAbhSAYhSAPhUIBiYUgFIUgF4UgH4UgDoUhAiAMIB0gCoUgGoUgDYUgE4VCAYmFIAiFIBmFIBaFIBKFIgMgB4UhICAJIAggDIUgGYUgFoUgEoVCAYmFIByFIBWFIBGFIBCFIgQgDoUhISAcIAogFCAehSAXhSAfhSAOhUIBiYUgHYUgGoUgDYUgE4UiBYVCN4kiIiALIBwgCYUgFYUgEYUgEIVCAYmFIAeFIBuFIBiFIA+FIgYgCoVCPokiI0J/hYMgAyAPhUICiSIkhSEOIBYgAoVCKYkiJSAEIBeFQieJIiZCf4WDICKFIQ8gECAFhUI4iSIQIAYgDYVCD4kiJ0J/hYMgAyAbhUIKiSIohSENIAQgHoVCG4kiKSAoIAggAoVCJIkiKkJ/hYOFIRYgBiAdhUIGiSIrIAMgC4VCAYkiLEJ/hYMgEiAChUISiSIthSEXICsgBCAfhUIIiSIuIBUgBYVCGYkiFUJ/hYOFIRsgBiAThUI9iSIdIAQgFIVCFIkiBCAJIAWFQhyJIghCf4WDhSEUIAggHUJ/hYMgAyAYhUItiSIDhSEcIB0gA0J/hYMgGSAChUIDiSIJhSEdIAQgAyAJQn+Fg4UhByAJIARCf4WDIAiFIQggDCAChSICICFCDokiA0J/hYMgESAFhUIViSIEhSEJIAYgGoVCK4kiBSADIARCf4WDhSEKIAQgBUJ/hYMgIEIsiSIEhSELIABB0AlqKQMAIAUgBEJ/hYOFIAKFIQwgJyAoQn+FgyAqhSIFIRggAyAEIAJCf4WDhSICIR4gKiApQn+FgyAQhSIDIR8gLSAuQn+FgyAVhSIEIRogJiAkICVCf4WDhSIGIRMgFSArQn+FgyAshSIoIRkgIyAmICJCf4WDhSIiIRIgLiAsIC1Cf4WDhSImIRUgJyApIBBCf4WDhSInIREgIyAkQn+FgyAlhSIjIRAgAEEIaiIADQALQQAgDzcDqIsBQQAgBTcDgIsBQQAgGzcD2IoBQQAgBzcDsIoBQQAgCzcDiIoBQQAgDjcDwIsBQQAgAzcDmIsBQQAgFzcD8IoBQQAgFDcDyIoBQQAgAjcDoIoBQQAgBjcDsIsBQQAgDTcDiIsBQQAgBDcD4IoBQQAgHTcDuIoBQQAgCjcDkIoBQQAgIjcDoIsBQQAgFjcD+IoBQQAgKDcD0IoBQQAgCDcDqIoBQQAgDDcDgIoBQQAgIzcDuIsBQQAgJzcDkIsBQQAgJjcD6IoBQQAgHDcDwIoBQQAgCTcDmIoBC/gCAQV/QeQAQQAoAoyNASIBQQF2ayECAkBBACgCiI0BIgNBAEgNACABIQQCQCABIANGDQAgA0HIiwFqIQVBACEDA0AgBSADakEAOgAAIANBAWoiAyABQQAoAoiNASIEa0kNAAsLIARByIsBaiIDIAMtAAAgAHI6AAAgAUHHiwFqIgMgAy0AAEGAAXI6AABByIsBIAEQA0EAQYCAgIB4NgKIjQELAkAgAkEESQ0AIAJBAnYiA0EDcSEFQQAhBAJAIANBf2pBA0kNACADQfz///8DcSEBQQAhA0EAIQQDQCADQYAKaiADQYCKAWooAgA2AgAgA0GECmogA0GEigFqKAIANgIAIANBiApqIANBiIoBaigCADYCACADQYwKaiADQYyKAWooAgA2AgAgA0EQaiEDIAEgBEEEaiIERw0ACwsgBUUNACAFQQJ0IQEgBEECdCEDA0AgA0GACmogA0GAigFqKAIANgIAIANBBGohAyABQXxqIgENAAsLCwYAQYCKAQvRBgEDf0EAQgA3A4CNAUEAQgA3A/iMAUEAQgA3A/CMAUEAQgA3A+iMAUEAQgA3A+CMAUEAQgA3A9iMAUEAQgA3A9CMAUEAQgA3A8iMAUEAQgA3A8CMAUEAQgA3A7iMAUEAQgA3A7CMAUEAQgA3A6iMAUEAQgA3A6CMAUEAQgA3A5iMAUEAQgA3A5CMAUEAQgA3A4iMAUEAQgA3A4CMAUEAQgA3A/iLAUEAQgA3A/CLAUEAQgA3A+iLAUEAQgA3A+CLAUEAQgA3A9iLAUEAQgA3A9CLAUEAQgA3A8iLAUEAQgA3A8CLAUEAQgA3A7iLAUEAQgA3A7CLAUEAQgA3A6iLAUEAQgA3A6CLAUEAQgA3A5iLAUEAQgA3A5CLAUEAQgA3A4iLAUEAQgA3A4CLAUEAQgA3A/iKAUEAQgA3A/CKAUEAQgA3A+iKAUEAQgA3A+CKAUEAQgA3A9iKAUEAQgA3A9CKAUEAQgA3A8iKAUEAQgA3A8CKAUEAQgA3A7iKAUEAQgA3A7CKAUEAQgA3A6iKAUEAQgA3A6CKAUEAQgA3A5iKAUEAQgA3A5CKAUEAQgA3A4iKAUEAQgA3A4CKAUEAQcAMIAFBAXRrQQN2NgKMjQFBAEEANgKIjQEgABACQeQAQQAoAoyNASIAQQF2ayEDAkBBACgCiI0BIgFBAEgNACAAIQQCQCAAIAFGDQAgAUHIiwFqIQVBACEBA0AgBSABakEAOgAAIAFBAWoiASAAQQAoAoiNASIEa0kNAAsLIARByIsBaiIBIAEtAAAgAnI6AAAgAEHHiwFqIgEgAS0AAEGAAXI6AABByIsBIAAQA0EAQYCAgIB4NgKIjQELAkAgA0EESQ0AIANBAnYiAUEDcSEFQQAhBAJAIAFBf2pBA0kNACABQfz///8DcSEAQQAhAUEAIQQDQCABQYAKaiABQYCKAWooAgA2AgAgAUGECmogAUGEigFqKAIANgIAIAFBiApqIAFBiIoBaigCADYCACABQYwKaiABQYyKAWooAgA2AgAgAUEQaiEBIAAgBEEEaiIERw0ACwsgBUUNACAFQQJ0IQAgBEECdCEBA0AgAUGACmogAUGAigFqKAIANgIAIAFBBGohASAAQXxqIgANAAsLCwvYAQEAQYAIC9ABkAEAAAAAAAAAAAAAAAAAAAEAAAAAAAAAgoAAAAAAAACKgAAAAAAAgACAAIAAAACAi4AAAAAAAAABAACAAAAAAIGAAIAAAACACYAAAAAAAICKAAAAAAAAAIgAAAAAAAAACYAAgAAAAAAKAACAAAAAAIuAAIAAAAAAiwAAAAAAAICJgAAAAAAAgAOAAAAAAACAAoAAAAAAAICAAAAAAAAAgAqAAAAAAAAACgAAgAAAAICBgACAAAAAgICAAAAAAACAAQAAgAAAAAAIgACAAAAAgA==",hash:"fb24e536"};function Zt(e){return[224,256,384,512].includes(e)?null:new Error("Invalid variant! Valid values: 224, 256, 384, 512")}new Pt,new Pt,new Pt,new Pt,new Pt,new Pt,new Pt,new Pt,new Uint8Array(8),new Pt,new Uint8Array(8),new Pt,new Uint8Array(8),new Pt,new Pt,new Pt;class er{hasher;static async create(){return new er(await function(e=512){if(Zt(e))return Promise.reject(Zt(e));const t=e/8;return Yt(Xt,t).then(r=>{r.init(e);const s={init:()=>(r.init(e),s),update:e=>(r.update(e),s),digest:e=>r.digest(e,1),save:()=>r.save(),load:e=>(r.load(e),s),blockSize:200-2*t,digestSize:t};return s})}(256))}constructor(e){this.hasher=e}}function tr(e,t){e.hasher.init();for(const r of t)e.hasher.update(r.raw);return Y.fromBlob(e.hasher.digest("binary"),Ct)}class rr{map=new Map;constructor(){}static new(){return new rr}static fromEntries(e){const t=new rr;for(const[r,s]of e)t.set(r,s);return t}get size(){return this.map.size}has(e){return this.map.has(e.toString())}get(e){return this.map.get(e.toString())?.[1]}[Symbol.iterator](){return this.map.values()}entries(){return this.map.values()}*keys(){for(const e of this.map.values())yield e[0]}*values(){for(const e of this.map.values())yield e[1]}toSortedArray(e){const t=Array.from(this.map.values());return t.sort((t,r)=>e(t[0],r[0]).value),t.map(e=>e[1])}set(e,t){this.map.set(e.toString(),[e,t])}delete(e){return this.map.delete(e.toString())}}class sr{map;static viewDictionaryKeys(e){return new sr(e)}static from(e){const t=sr.new();return t.insertAll(e),t}static new(){return new sr}constructor(e=rr.new()){this.map=e}get size(){return this.map.size}has(e){return this.map.has(e)}*intersection(e){const t=this.size<e.size?this:e,r=t===this?e:this;for(const e of t)r.has(e)&&(yield e)}*[Symbol.iterator](){for(const e of this.map)yield e[0]}insert(e){return this.map.set(e,!0)}insertAll(e){for(const t of e)this.map.set(t,!0)}delete(e){return this.map.delete(e)}}function ir(e){return e}class nr extends Array{fixedLength;constructor(...e){super(...e),this.fixedLength=this.length}static new(e,t){M(e.length===t,`Expected an array of size: ${t}, got: ${e.length}`);const r=new nr(t);for(let s=0;s<t;s++)r[s]=e[s];return Object.seal(r),r}static fill(e,t){const r=[];for(let s=0;s<t;s++)r.push(e(s));return nr.new(r,t)}toString(){return H(Array.from(this))}}class or{array;comparator;static fromArray(e,t=[]){const r=t.slice();return r.sort((t,r)=>e(t,r).value),new or(r,e)}static fromSortedArray(e,t=[]){const r=t.length;if(0===r)return new or([],e);const s=t.slice();for(let t=1;t<r;t++)if(e(s[t-1],s[t]).isGreater())throw new Error(`Expected sorted array, got: ${s}`);return new or(s,e)}constructor(e,t){this.array=e,this.comparator=t}insert(e){const t=this.binarySearch(e);this.array.splice(t.idx,0,e)}pop(){return this.array.pop()}findIndex(e){const t=this.binarySearch(e);return t.isEqual?t.idx:-1}findExact(e){const t=this.binarySearch(e);if(t.isEqual)return this.array[t.idx]}removeOne(e){const t=this.binarySearch(e);t.isEqual&&this.array.splice(t.idx,1)}has(e){return this.binarySearch(e).isEqual}get length(){return this.array.length}slice(e,t){return this.array.slice(e,t)}binarySearch(e){const t=this.array,r=this.comparator;let s=0,i=t.length;for(;s<i;){const n=i+s>>1,o=r(t[n],e);if(o.isEqual())return{idx:n,isEqual:!0};o.isLess()?s=n+1:i=n}return{idx:s,isEqual:!1}}static fromTwoSortedCollections(e,t){M(e.comparator===t.comparator,"Cannot merge arrays if they do not use the same comparator");const r=e.comparator,s=e.array,i=s.length,n=t.array,o=n.length,a=new Array(i+o);let c=0,l=0,h=0;for(;c<i&&l<o;)r(s[c],n[l]).isLess()?a[h++]=s[c++]:(r(s[c],n[l]).isGreater()||(a[h++]=s[c++]),a[h++]=n[l++]);for(;c<i;)a[h++]=s[c++];for(;l<o;)a[h++]=n[l++];return or.fromSortedArray(r,a)}*[Symbol.iterator](){for(const e of this.array)yield e}}class ar extends or{static fromArray(e,t=[]){const r=t.slice();r.sort((t,r)=>e(t,r).value);const s=r.length;for(let i=1;i<s;i++)if(e(r[i-1],r[i]).isEqual())throw new Error(`Expected array without duplicates, got: ${t}`);return new ar(r,e)}static fromSortedArray(e,t=[]){if(0===t.length)return new ar([],e);const r=t.slice(),s=r.length;for(let t=1;t<s;t++)if(e(r[t-1],r[t]).isGreaterOrEqual())throw new Error(`Expected sorted array without duplicates, got: ${r}`);return new ar(r,e)}insert(e){const t=this.binarySearch(e);t.isEqual||this.array.splice(t.idx,0,e)}static fromTwoSortedCollections(e,t){M(e.comparator===t.comparator,"Cannot merge arrays if they do not use the same comparator");const r=e.comparator;if(0===e.length)return ar.fromSortedArray(r,t.array);if(0===t.length)return ar.fromSortedArray(r,e.array);const s=or.fromTwoSortedCollections(e,t).array,i=s.length;let n=1;for(let e=1;e<i;e++)r(s[e-1],s[e]).isNotEqual()&&(s[n++]=s[e]);return s.length=n,ar.fromSortedArray(r,s)}}class cr extends Q{validatorsCount;thirdOfValidators;validatorsSuperMajority;coresCount;slotDuration;epochLength;rotationPeriod;contestLength;ticketsPerValidator;maxTicketsPerExtrinsic;numberECPiecesPerSegment;constructor(e){super(),this.validatorsCount=e.validatorsCount,this.thirdOfValidators=Math.floor(e.validatorsCount/3),this.validatorsSuperMajority=2*Math.floor(e.validatorsCount/3)+1,this.coresCount=e.coresCount,this.slotDuration=e.slotDuration,this.epochLength=e.epochLength,this.rotationPeriod=e.rotationPeriod,this.contestLength=e.contestLength,this.ticketsPerValidator=e.ticketsPerValidator,this.maxTicketsPerExtrinsic=e.maxTicketsPerExtrinsic,this.numberECPiecesPerSegment=e.numberECPiecesPerSegment}}const lr=new cr({contestLength:10,coresCount:2,epochLength:12,maxTicketsPerExtrinsic:3,rotationPeriod:4,slotDuration:6,ticketsPerValidator:3,validatorsCount:6,numberECPiecesPerSegment:1026}),hr=new cr({contestLength:500,coresCount:341,epochLength:600,maxTicketsPerExtrinsic:16,rotationPeriod:10,slotDuration:6,ticketsPerValidator:2,validatorsCount:1023,numberECPiecesPerSegment:6});class ur{chainSpec;dbPath;omitSealVerification;static reInit(e){const{chainSpec:t,dbPath:r,omitSealVerification:s}=e;return new ur(new cr(t),r,s)}constructor(e,t,r=!1){this.chainSpec=e,this.dbPath=t,this.omitSealVerification=r}}function dr(e){const t=hr,{name:r,sizeHint:s}=e(t),i=new Map;return Pe.select({name:r,sizeHint:{bytes:s.bytes,isExact:!1}},s=>{if(s instanceof cr){const t=i.get(s);if(void 0!==t)return t;const r=e(s);return i.set(s,r),r}if(null===s)return e(t);if(null!==s)throw new Error(`[${r}] Unexpected context type ${typeof s} while encoding/decoding.`);throw new Error(`[${r}] Missing context while encoding/decoding!`)})}const fr=(e,t,r)=>"fixedLength"in t?De(Pe.sequenceFixLen(e,t.fixedLength)).convert(F,ir):De(Pe.sequenceVarLen(e,t)).convert(F,ir),pr=(e,t)=>{const r=r=>{if(t!==r)throw new Error(`[${e.name}] Invalid size of fixed-size array. Got ${r}, expected: ${t}`)};return Pe.sequenceFixLen(e,t).convert(e=>(r(e.length),e),e=>(r(e.length),nr.new(e,t)))},gr=(e,t,{typicalLength:r=32,compare:s=(e,r)=>t(e).compare(t(r))}={})=>Ne.new(`HashDictionary<${e.name}>[?]`,{bytes:r*e.sizeHint.bytes,isExact:!1},(t,r)=>{const i=Array.from(r.values());i.sort((e,t)=>s(e,t).value),t.varU32(pe(i.length));for(const r of i)e.encode(t,r)},r=>{const i=rr.new(),n=r.varU32();let o=null;for(let a=0;a<n;a+=1){const n=e.decode(r),a=t(n);if(i.has(a))throw new Error(`Duplicate item in the dictionary encoding: "${a}"!`);if(null!==o&&s(o,n).isGreaterOrEqual())throw new Error(`The keys in dictionary encoding are not sorted "${o}" >= "${n}"!`);i.set(a,n),o=n}return i},t=>{const r=t.decoder.varU32();t.sequenceFixLen(e,r)});class yr extends Q{anchor;bitfield;validatorIndex;signature;static Codec=Pe.Class(yr,{anchor:Pe.bytes(Ct).asOpaque(),bitfield:dr(e=>Pe.bitVecFixLen(e.coresCount)),validatorIndex:Pe.u16.asOpaque(),signature:Pe.bytes(At).asOpaque()});static create({anchor:e,bitfield:t,validatorIndex:r,signature:s}){return new yr(e,t,r,s)}constructor(e,t,r,s){super(),this.anchor=e,this.bitfield=t,this.validatorIndex=r,this.signature=s}}const mr=dr(e=>fr(yr.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2}));class br extends Q{workReportHash;wasConsideredValid;key;signature;static Codec=Pe.Class(br,{workReportHash:Pe.bytes(Ct).asOpaque(),wasConsideredValid:Pe.bool,key:Pe.bytes(bt).asOpaque(),signature:Pe.bytes(At).asOpaque()});static create({workReportHash:e,wasConsideredValid:t,key:r,signature:s}){return new br(e,t,r,s)}constructor(e,t,r,s){super(),this.workReportHash=e,this.wasConsideredValid=t,this.key=r,this.signature=s}}class Ar extends Q{workReportHash;key;signature;static Codec=Pe.Class(Ar,{workReportHash:Pe.bytes(Ct).asOpaque(),key:Pe.bytes(bt).asOpaque(),signature:Pe.bytes(At).asOpaque()});static create({workReportHash:e,key:t,signature:r}){return new Ar(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.key=t,this.signature=r}}class Ir extends Q{isWorkReportValid;index;signature;static Codec=Pe.Class(Ir,{isWorkReportValid:Pe.bool,index:Pe.u16.asOpaque(),signature:Pe.bytes(At).asOpaque()});static create({isWorkReportValid:e,index:t,signature:r}){return new Ir(e,t,r)}constructor(e,t,r){super(),this.isWorkReportValid=e,this.index=t,this.signature=r}}class vr extends Q{workReportHash;votesEpoch;votes;static Codec=Pe.Class(vr,{workReportHash:Pe.bytes(Ct).asOpaque(),votesEpoch:Pe.u32.asOpaque(),votes:dr(e=>De(Pe.sequenceFixLen(Ir.Codec,e.validatorsSuperMajority)).convert(F,ir))});static create({workReportHash:e,votesEpoch:t,votes:r}){return new vr(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.votesEpoch=t,this.votes=r}}class wr extends Q{verdicts;culprits;faults;static Codec=Pe.Class(wr,{verdicts:Pe.sequenceVarLen(vr.Codec),culprits:Pe.sequenceVarLen(Ar.Codec),faults:Pe.sequenceVarLen(br.Codec)});static create({verdicts:e,culprits:t,faults:r}){return new wr(e,t,r)}constructor(e,t,r){super(),this.verdicts=e,this.culprits=t,this.faults=r}}class Sr extends Q{anchor;stateRoot;beefyRoot;lookupAnchor;lookupAnchorSlot;prerequisites;static Codec=Pe.Class(Sr,{anchor:Pe.bytes(Ct).asOpaque(),stateRoot:Pe.bytes(Ct).asOpaque(),beefyRoot:Pe.bytes(Ct).asOpaque(),lookupAnchor:Pe.bytes(Ct).asOpaque(),lookupAnchorSlot:Pe.u32.asOpaque(),prerequisites:Pe.sequenceVarLen(Pe.bytes(Ct).asOpaque())});static create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n}){return new Sr(e,t,r,s,i,n)}constructor(e,t,r,s,i,n=[]){super(),this.anchor=e,this.stateRoot=t,this.beefyRoot=r,this.lookupAnchor=s,this.lookupAnchorSlot=i,this.prerequisites=n}}class Er extends Q{treeRoot;index;static Codec=Pe.Class(Er,{treeRoot:Pe.bytes(Ct),index:Pe.u16.asOpaque()});static create({treeRoot:e,index:t}){return new Er(e,t)}constructor(e,t){super(),this.treeRoot=e,this.index=t}}class Cr extends Q{hash;len;static Codec=Pe.Class(Cr,{hash:Pe.bytes(Ct).asOpaque(),len:Pe.u32});static create({hash:e,len:t}){return new Cr(e,t)}constructor(e,t){super(),this.hash=e,this.len=t}}class kr extends Q{service;codeHash;payload;refineGasLimit;accumulateGasLimit;importSegments;extrinsic;exportCount;static Codec=Pe.Class(kr,{service:Pe.u32.asOpaque(),codeHash:Pe.bytes(Ct).asOpaque(),payload:Pe.blob,refineGasLimit:Pe.u64.asOpaque(),accumulateGasLimit:Pe.u64.asOpaque(),importSegments:fr(Er.Codec,{minLength:0,maxLength:2048,typicalLength:2048}),extrinsic:Pe.sequenceVarLen(Cr.Codec),exportCount:Pe.u16});static create({service:e,codeHash:t,payload:r,refineGasLimit:s,accumulateGasLimit:i,importSegments:n,extrinsic:o,exportCount:a}){return new kr(e,t,r,s,i,n,o,a)}constructor(e,t,r,s,i,n,o,a){super(),this.service=e,this.codeHash=t,this.payload=r,this.refineGasLimit=s,this.accumulateGasLimit=i,this.importSegments=n,this.extrinsic=o,this.exportCount=a}}function xr(e){return P(e,e>=_r&&e<=Br,`WorkItemsCount: Expected '${_r} <= count <= ${Br}' got ${e}`)}const _r=1,Br=16;class Rr extends Q{authorization;authCodeHost;authCodeHash;parametrization;context;items;static Codec=Pe.Class(Rr,{authorization:Pe.blob,authCodeHost:Pe.u32.asOpaque(),authCodeHash:Pe.bytes(Ct).asOpaque(),parametrization:Pe.blob,context:Sr.Codec,items:Pe.sequenceVarLen(kr.Codec).convert(e=>e,e=>nr.new(e,xr(e.length)))});static create({authorization:e,authCodeHost:t,authCodeHash:r,parametrization:s,context:i,items:n}){return new Rr(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){super(),this.authorization=e,this.authCodeHost=t,this.authCodeHash=r,this.parametrization=s,this.context=i,this.items=n}}var Or,Ur;(Ur=Or||(Or={}))[Ur.ok=0]="ok",Ur[Ur.outOfGas=1]="outOfGas",Ur[Ur.panic=2]="panic",Ur[Ur.badCode=3]="badCode",Ur[Ur.codeOversize=4]="codeOversize";class Tr extends Q{kind;okBlob;static Codec=Pe.custom({name:"WorkExecResult",sizeHint:{bytes:1,isExact:!1}},(e,t)=>{e.varU32(pe(t.kind)),t.kind===Or.ok&&null!==t.okBlob&&e.bytesBlob(t.okBlob)},e=>{const t=e.varU32();if(t===Or.ok){const r=e.bytesBlob();return new Tr(t,r)}if(t>Or.codeOversize)throw new Error(`Invalid WorkExecResultKind: ${t}`);return new Tr(t)},e=>{e.decoder.varU32()===Or.ok&&e.bytesBlob()});constructor(e,t=null){super(),this.kind=e,this.okBlob=t}}class Nr extends Q{gasUsed;importedSegments;extrinsicCount;extrinsicSize;exportedSegments;static Codec=Pe.Class(Nr,{gasUsed:Pe.varU64.asOpaque(),importedSegments:Pe.varU32,extrinsicCount:Pe.varU32,extrinsicSize:Pe.varU32,exportedSegments:Pe.varU32});static create({gasUsed:e,importedSegments:t,extrinsicCount:r,extrinsicSize:s,exportedSegments:i}){return new Nr(e,t,r,s,i)}constructor(e,t,r,s,i){super(),this.gasUsed=e,this.importedSegments=t,this.extrinsicCount=r,this.extrinsicSize=s,this.exportedSegments=i}}class Dr{serviceId;codeHash;payloadHash;gas;result;load;static Codec=Pe.Class(Dr,{serviceId:Pe.u32.asOpaque(),codeHash:Pe.bytes(Ct).asOpaque(),payloadHash:Pe.bytes(Ct),gas:Pe.u64.asOpaque(),result:Tr.Codec,load:Nr.Codec});static create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n}){return new Dr(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.serviceId=e,this.codeHash=t,this.payloadHash=r,this.gas=s,this.result=i,this.load=n}}class Mr extends Q{hash;length;erasureRoot;exportsRoot;exportsCount;static Codec=Pe.Class(Mr,{hash:Pe.bytes(Ct).asOpaque(),length:Pe.u32,erasureRoot:Pe.bytes(Ct),exportsRoot:Pe.bytes(Ct).asOpaque(),exportsCount:Pe.u16});static create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i}){return new Mr(e,t,r,s,i)}constructor(e,t,r,s,i){super(),this.hash=e,this.length=t,this.erasureRoot=r,this.exportsRoot=s,this.exportsCount=i}}class Pr extends Q{workPackageHash;segmentTreeRoot;static Codec=Pe.Class(Pr,{workPackageHash:Pe.bytes(Ct).asOpaque(),segmentTreeRoot:Pe.bytes(Ct).asOpaque()});constructor(e,t){super(),this.workPackageHash=e,this.segmentTreeRoot=t}static create({workPackageHash:e,segmentTreeRoot:t}){return new Pr(e,t)}}class Lr extends Q{workPackageSpec;context;coreIndex;authorizerHash;authorizationOutput;segmentRootLookup;results;authorizationGasUsed;static Codec=Pe.Class(Lr,{workPackageSpec:Mr.Codec,context:Sr.Codec,coreIndex:Pe.u16.asOpaque(),authorizerHash:Pe.bytes(Ct).asOpaque(),authorizationOutput:Pe.blob,segmentRootLookup:De(Pe.sequenceVarLen(Pr.Codec)),results:Pe.sequenceVarLen(Dr.Codec).convert(e=>e,e=>nr.new(e,xr(e.length))),authorizationGasUsed:Pe.varU64.asOpaque()});static create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:n,results:o,authorizationGasUsed:a}){return new Lr(e,t,r,s,i,n,o,a)}constructor(e,t,r,s,i,n,o,a){super(),this.workPackageSpec=e,this.context=t,this.coreIndex=r,this.authorizerHash=s,this.authorizationOutput=i,this.segmentRootLookup=n,this.results=o,this.authorizationGasUsed=a}}const Hr=[2,3];class Kr extends Q{validatorIndex;signature;static Codec=Pe.Class(Kr,{validatorIndex:Pe.u16.asOpaque(),signature:Pe.bytes(At).asOpaque()});static create({validatorIndex:e,signature:t}){return new Kr(e,t)}constructor(e,t){super(),this.validatorIndex=e,this.signature=t}}class Qr extends Q{report;slot;credentials;static Codec=Pe.Class(Qr,{report:Lr.Codec,slot:Pe.u32.asOpaque(),credentials:fr(Kr.Codec,{minLength:Hr[0],maxLength:Hr[1],typicalLength:Hr[1]})});static create({report:e,slot:t,credentials:r}){return new Qr(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.credentials=r}}const Vr=dr(e=>fr(Qr.Codec,{minLength:0,maxLength:e.coresCount,typicalLength:e.coresCount})),Fr=e=>pe(e),$r=e=>de(e),jr=e=>pe(e),Gr=e=>ye(e),qr=e=>de(e),zr=e=>pe(e);function Wr(e,t){return M(e.length===t.validatorsCount,`Invalid per-validator array length. Expected ${t.validatorsCount}, got: ${e.length}`),e}const Jr=e=>dr(t=>fr(e,{fixedLength:t.validatorsCount}));function Yr(e,t){return M(e.length===t.epochLength,`Invalid per-epoch-block array length. Expected ${t.epochLength}, got: ${e.length}`),e}const Xr=e=>dr(t=>fr(e,{fixedLength:t.epochLength}));class Zr extends Q{attempt;signature;static Codec=Pe.Class(Zr,{attempt:Pe.u8.asOpaque(),signature:Pe.bytes(784).asOpaque()});static create({attempt:e,signature:t}){return new Zr(e,t)}constructor(e,t){super(),this.attempt=e,this.signature=t}}class es extends Q{id;attempt;static Codec=Pe.Class(es,{id:Pe.bytes(Ct),attempt:Pe.u8.asOpaque()});static create({id:e,attempt:t}){return new es(e,t)}constructor(e,t){super(),this.id=e,this.attempt=t}}const ts=fr(Zr.Codec,{minLength:0,maxLength:16,typicalLength:16});class rs extends Q{bandersnatch;ed25519;static Codec=Pe.Class(rs,{bandersnatch:Pe.bytes(wt).asOpaque(),ed25519:Pe.bytes(bt).asOpaque()});static create({bandersnatch:e,ed25519:t}){return new rs(e,t)}constructor(e,t){super(),this.bandersnatch=e,this.ed25519=t}}class ss extends Q{entropy;ticketsEntropy;validators;static Codec=Pe.Class(ss,{entropy:Pe.bytes(Ct).asOpaque(),ticketsEntropy:Pe.bytes(Ct).asOpaque(),validators:Jr(rs.Codec)});static create({entropy:e,ticketsEntropy:t,validators:r}){return new ss(e,t,r)}constructor(e,t,r){super(),this.entropy=e,this.ticketsEntropy=t,this.validators=r}}const is=e=>{const t=e.encoded().raw,r=t.length-96;return J.blobFrom(t.subarray(0,r))};class ns extends Q{static Codec=Pe.Class(ns,{parentHeaderHash:Pe.bytes(Ct).asOpaque(),priorStateRoot:Pe.bytes(Ct).asOpaque(),extrinsicHash:Pe.bytes(Ct).asOpaque(),timeSlotIndex:Pe.u32.asOpaque(),epochMarker:Pe.optional(ss.Codec),ticketsMarker:Pe.optional(Xr(es.Codec)),offendersMarker:Pe.sequenceVarLen(Pe.bytes(bt).asOpaque()),bandersnatchBlockAuthorIndex:Pe.u16.asOpaque(),entropySource:Pe.bytes(96).asOpaque(),seal:Pe.bytes(96).asOpaque()});static create(e){return Object.assign(ns.empty(),e)}parentHeaderHash=Y.zero(Ct).asOpaque();priorStateRoot=Y.zero(Ct).asOpaque();extrinsicHash=Y.zero(Ct).asOpaque();timeSlotIndex=Fr(0);epochMarker=null;ticketsMarker=null;offendersMarker=[];bandersnatchBlockAuthorIndex=$r(0);entropySource=Y.zero(96).asOpaque();seal=Y.zero(96).asOpaque();constructor(){super()}static empty(){return new ns}}class os extends kt{static Codec=Pe.Class(os,{hash:Pe.bytes(Ct).asOpaque(),data:ns.Codec.View});static create({hash:e,data:t}){return new kt(e,t)}}const as=os.Codec;class cs extends Q{requester;blob;static Codec=Pe.Class(cs,{requester:Pe.u32.asOpaque(),blob:Pe.blob});static create({requester:e,blob:t}){return new cs(e,t)}constructor(e,t){super(),this.requester=e,this.blob=t}}const ls=Pe.sequenceVarLen(cs.Codec);class hs extends Q{tickets;preimages;guarantees;assurances;disputes;static Codec=Pe.Class(hs,{tickets:ts,preimages:ls,guarantees:Vr,assurances:mr,disputes:wr.Codec});static create({tickets:e,preimages:t,assurances:r,disputes:s,guarantees:i}){return new hs(e,t,i,r,s)}constructor(e,t,r,s,i){super(),this.tickets=e,this.preimages=t,this.guarantees=r,this.assurances=s,this.disputes=i}}class us extends Q{header;extrinsic;static Codec=Pe.Class(us,{header:ns.Codec,extrinsic:hs.Codec});static create({header:e,extrinsic:t}){return new us(e,t)}constructor(e,t){super(),this.header=e,this.extrinsic=t}}const ds=Symbol("no key");function fs(e,t,r="<root>"){const s=typeof e;if("string"===t){if("string"===s)return e;throw new Error(`[${r}] Expected ${t} but got ${s}`)}if("number"===t){if("number"===s)return e;throw new Error(`[${r}] Expected ${t} but got ${s}`)}if("boolean"===t){if("boolean"===s)return e;throw new Error(`[${r}] Expected ${t} but got ${s}`)}if(Array.isArray(t)){const s=t[0];if("array"===s){const s=t[1];if("function"==typeof s)return s(e,r);if(!Array.isArray(e))throw new Error(`[${r}] Expected array, got ${e}`);const i=e,n=[];for(const[e,t]of i.entries())n[e]=fs(t,s,`${r}.${e}`);return n}if("optional"===s)return null==e?e:fs(e,t[1],r);if("object"===s)return ps(t[1],e,r);if("string"===s)return ps(t[1],fs(e,s,r),r);if("number"===s){const s=t[0];return ps(t[1],fs(e,s,r),r)}throw new Error(`[${r}] Invalid parser type: ${s}`)}if("object"!==s)throw new Error(`[${r}] Expected complex type but got ${s}`);if("object"!=typeof t)throw new Error(`[${r}] Unhandled type ${t}`);if(null===e)throw new Error(`[${r}] Unexpected 'null'`);const i={},n=e,o=t;for(const e of Object.keys(n))i[e]=void 0;for(const e of Object.keys(t))if(e in n){const t=n[e];i[e]=fs(t,o[e],`${r}.${e}`)}else Array.isArray(o[e])&&"optional"===o[e][0]&&(i[e]=ds);const a=function(e,t){const r=Object.keys(e),s=Object.keys(t);r.sort(),s.sort();const i={},n=Math.max(s.length,s.length);for(let e=0;e<n;e++)i[r[e]]=(i[r[e]]||0)+1,i[s[e]]=(i[s[e]]||0)+2;const o=[],a=e=>void 0!==e?`"${e}"`:"<missing>";for(const[e,t]of Object.entries(i))3!==t&&"undefined"!==e&&o.push(1===t?[a(e),a(void 0)]:[a(void 0),a(e)]);return o}(i,t);if(a.length>0)throw new Error(`[${r}] Unexpected or missing keys: ${a.join(" | ")}\n Data: ${Object.keys(i)}\n Schema: ${Object.keys(t)}`);for(const e of Object.keys(i))i[e]===ds&&delete i[e];return i}function ps(e,t,r){try{return e(t,r)}catch(e){throw new Error(`[${r}] Error while parsing the value: ${e}`)}}var gs,ys;!function(e){function t(e){return["number",e]}function r(e){return["object",e]}e.fromString=function(e){return["string",e]},e.fromNumber=t,e.castNumber=function(){return t(e=>e)},e.fromAny=r,e.optional=function(e){return["optional",e]},e.nullable=function(e){return["optional",e]},e.array=function(e){return["array",e]},e.record=function(e){return r((t,r)=>{if("object"!=typeof t||null===t)throw new Error("Expected object record for parsing");const s={};for(const[i,n]of Object.entries(t))s[i]=fs(n,e,`${r}.${i}`);return s})},e.map=function(e,t){return r((r,s)=>{if("object"!=typeof r||null===r)throw new Error("Expected map for parsing");const i=new Map;for(const[n,o]of Object.entries(r))i.set(fs(n,e,`${s}.key`),fs(o,t,`${s}.value`));return i})},e.object=function(e,t){return r((r,s)=>{const i=fs(r,e,s);return t(i)})}}(gs||(gs={})),function(e){e.bytes32=()=>gs.fromString(e=>Y.parseBytes(e,32).asOpaque()),e.bytes32NoPrefix=()=>gs.fromString(e=>Y.parseBytesNoPrefix(e,32).asOpaque()),e.bytesBlob=gs.fromString(J.parseBlobNoPrefix),e.ed25519Signature=gs.fromString(e=>Y.parseBytes(e,64).asOpaque()),e.ticketAttempt=gs.fromNumber(e=>{if(0!==e&&1!==e&&2!==e)throw new Error("Invalid TicketAttempt value.");return function(e){return he(e)}(e)}),e.uint8Array=gs.fromAny(e=>{if(Array.isArray(e))return new Uint8Array(e);if(null===e)return new Uint8Array;throw new Error(`Expected an array, got ${typeof e} instead. [uint8Array]`)}),e.bigUint64Array=gs.fromAny(e=>{if(Array.isArray(e))return new BigUint64Array(e.map(e=>BigInt(e)));if(null===e)return new BigUint64Array;throw new Error(`Expected an array, got ${typeof e} instead. [bigUint64Array]`)}),e.bigUint64=gs.fromAny(e=>BigInt(e))}(ys||(ys={}));const ms=e=>gs.array((e=>gs.object({anchor:ys.bytes32(),bitfield:gs.fromString(t=>{const r=Math.ceil(e.coresCount/8);return le.fromBytes(Y.parseBytes(t,r),e.coresCount)}),validator_index:"number",signature:ys.ed25519Signature},({anchor:e,bitfield:t,validator_index:r,signature:s})=>yr.create({anchor:e,bitfield:t,validatorIndex:r,signature:s})))(e)),bs=gs.object({target:ys.bytes32(),vote:"boolean",key:ys.bytes32(),signature:ys.ed25519Signature},({target:e,vote:t,key:r,signature:s})=>br.create({workReportHash:e,wasConsideredValid:t,key:r,signature:s})),As=gs.object({target:ys.bytes32(),key:ys.bytes32(),signature:ys.ed25519Signature},({target:e,key:t,signature:r})=>Ar.create({workReportHash:e,key:t,signature:r})),Is=gs.object({vote:"boolean",index:"number",signature:ys.ed25519Signature},({vote:e,index:t,signature:r})=>Ir.create({isWorkReportValid:e,index:t,signature:r})),vs=gs.object({target:ys.bytes32(),age:"number",votes:gs.array(Is)},({target:e,age:t,votes:r})=>vr.create({workReportHash:e,votesEpoch:t,votes:r})),ws=gs.object({verdicts:gs.array(vs),culprits:gs.array(As),faults:gs.array(bs)},({verdicts:e,culprits:t,faults:r})=>wr.create({verdicts:e,culprits:t,faults:r})),Ss=gs.object({anchor:ys.bytes32(),state_root:ys.bytes32(),beefy_root:ys.bytes32(),lookup_anchor:ys.bytes32(),lookup_anchor_slot:"number",prerequisites:gs.array(ys.bytes32())},({anchor:e,state_root:t,beefy_root:r,lookup_anchor:s,lookup_anchor_slot:i,prerequisites:n})=>Sr.create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n})),Es=gs.object({ok:gs.optional(gs.fromString(J.parseBlob)),out_of_gas:gs.optional(gs.fromAny(()=>null)),panic:gs.optional(gs.fromAny(()=>null)),bad_code:gs.optional(gs.fromAny(()=>null)),code_oversize:gs.optional(gs.fromAny(()=>null))},e=>{const{ok:t,out_of_gas:r,panic:s,bad_code:i,code_oversize:n}=e;if(void 0!==t)return new Tr(pe(Or.ok),t);if(null===r)return new Tr(pe(Or.outOfGas));if(null===s)return new Tr(pe(Or.panic));if(null===i)return new Tr(pe(Or.badCode));if(null===n)return new Tr(pe(Or.codeOversize));throw new Error("Invalid WorkExecResult")}),Cs=gs.object({gas_used:gs.fromNumber(e=>Gr(e)),imports:"number",extrinsic_count:"number",extrinsic_size:"number",exports:"number"},({gas_used:e,imports:t,extrinsic_count:r,extrinsic_size:s,exports:i})=>Nr.create({gasUsed:Gr(e),importedSegments:pe(t),extrinsicCount:pe(r),extrinsicSize:pe(s),exportedSegments:pe(i)})),ks=gs.object({service_id:"number",code_hash:ys.bytes32(),payload_hash:ys.bytes32(),accumulate_gas:gs.fromNumber(e=>Gr(e)),result:Es,refine_load:Cs},({service_id:e,code_hash:t,payload_hash:r,accumulate_gas:s,result:i,refine_load:n})=>Dr.create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n})),xs=gs.object({hash:ys.bytes32(),length:"number",erasure_root:ys.bytes32(),exports_root:ys.bytes32(),exports_count:"number"},({hash:e,length:t,erasure_root:r,exports_root:s,exports_count:i})=>Mr.create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i})),_s=gs.object({work_package_hash:ys.bytes32(),segment_tree_root:ys.bytes32()},({work_package_hash:e,segment_tree_root:t})=>Pr.create({workPackageHash:e,segmentTreeRoot:t})),Bs=gs.object({package_spec:xs,context:Ss,core_index:"number",authorizer_hash:ys.bytes32(),auth_output:gs.fromString(J.parseBlob),segment_root_lookup:gs.array(_s),results:gs.array(ks),auth_gas_used:gs.fromNumber(e=>Gr(e))},({package_spec:e,context:t,core_index:r,authorizer_hash:s,auth_output:i,results:n,segment_root_lookup:o,auth_gas_used:a})=>{const c=nr.new(n,xr(n.length));return Lr.create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:o,results:c,authorizationGasUsed:a})}),Rs=gs.object({validator_index:"number",signature:ys.ed25519Signature},({validator_index:e,signature:t})=>Kr.create({validatorIndex:e,signature:t})),Os=gs.object({report:Bs,slot:"number",signatures:gs.array(Rs)},({report:e,slot:t,signatures:r})=>Qr.create({report:e,slot:t,credentials:r})),Us=gs.array(Os),Ts=gs.object({requester:"number",blob:gs.fromString(J.parseBlob)},({requester:e,blob:t})=>cs.create({requester:e,blob:t})),Ns=gs.array(Ts),Ds=gs.object({attempt:ys.ticketAttempt,signature:gs.fromString(e=>Y.parseBytes(e,784).asOpaque())},e=>Zr.create({attempt:e.attempt,signature:e.signature})),Ms=gs.array(Ds),Ps=gs.fromString(e=>Y.parseBytes(e,96).asOpaque()),Ls=gs.object({bandersnatch:ys.bytes32(),ed25519:ys.bytes32()},rs.create),Hs=gs.object({entropy:ys.bytes32(),tickets_entropy:ys.bytes32(),validators:gs.array(Ls)},e=>ss.create({entropy:e.entropy,ticketsEntropy:e.tickets_entropy,validators:e.validators})),Ks=gs.object({id:ys.bytes32(),attempt:ys.ticketAttempt},e=>es.create({id:e.id,attempt:e.attempt})),Qs=gs.object({parent:ys.bytes32(),parent_state_root:ys.bytes32(),extrinsic_hash:ys.bytes32(),slot:"number",epoch_mark:gs.optional(Hs),tickets_mark:gs.optional(gs.array(Ks)),offenders_mark:gs.array(ys.bytes32()),author_index:"number",entropy_source:Ps,seal:Ps},({parent:e,parent_state_root:t,extrinsic_hash:r,slot:s,epoch_mark:i,tickets_mark:n,offenders_mark:o,author_index:a,entropy_source:c,seal:l})=>{const h=ns.empty();return h.parentHeaderHash=e,h.priorStateRoot=t,h.extrinsicHash=r,h.timeSlotIndex=s,h.epochMarker=i??null,h.ticketsMarker=n??null,h.offendersMarker=o,h.bandersnatchBlockAuthorIndex=a,h.entropySource=c,h.seal=l,h});class Vs extends Q{name;ip;port;static fromString(e){const[t,r]=e.split("@"),s=r.substring(0,r.lastIndexOf(":")),i=r.substring(r.lastIndexOf(":")+1);if(""===t||""===s||""===i)throw new Error(`Invalid bootnode format, expected: <name>@<ip>:<port>, got: "${e}"`);const n=Number.parseInt(i);if(!fe(n))throw new Error(`Invalid port number: "${i}"`);return new Vs(t,s,n)}constructor(e,t,r){super(),this.name=e,this.ip=t,this.port=r}}class Fs extends Q{bootnodes;id;genesisHeader;genesisState;static fromJson=gs.object({bootnodes:gs.optional(gs.array(gs.fromString(Vs.fromString))),id:"string",genesis_header:ys.bytesBlob,genesis_state:gs.map(gs.fromString(e=>Y.parseBytesNoPrefix(e,31).asOpaque()),ys.bytesBlob)},e=>Fs.create({bootnodes:e.bootnodes,id:e.id,genesisHeader:e.genesis_header,genesisState:e.genesis_state??new Map}));static create({bootnodes:e=[],id:t="",genesisHeader:r=J.empty(),genesisState:s=new Map}){return new Fs({bootnodes:e,id:t,genesisHeader:r,genesisState:s})}constructor(e){super(),this.bootnodes=e.bootnodes,this.id=e.id,this.genesisHeader=e.genesisHeader,this.genesisState=e.genesisState}}class $s{omitSealVerification;static fromJson=gs.object({omit_seal_verification:"boolean"},$s.new);static new({omit_seal_verification:e}){return new $s(e)}constructor(e){this.omitSealVerification=e}}var js;!function(e){e.Tiny="tiny",e.Full="full"}(js||(js={}));const Gs=gs.fromString((e,t)=>{switch(e){case js.Tiny:return js.Tiny;case js.Full:return js.Full;default:throw Error(`unknown network flavor: ${e} at ${t}`)}});class qs{$schema;version;flavor;chainSpec;databaseBasePath;authorship;static fromJson=gs.object({$schema:"string",version:"number",flavor:Gs,chain_spec:Fs.fromJson,database_base_path:"string",authorship:$s.fromJson},qs.new);static new({$schema:e,version:t,flavor:r,chain_spec:s,database_base_path:i,authorship:n}){if(1!==t)throw new Error("Only version=1 config is supported.");return new qs(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.$schema=e,this.version=t,this.flavor=r,this.chainSpec=s,this.databaseBasePath=i,this.authorship=n}}const zs=e=>Ne.withView(e.name,e.sizeHint,(t,r)=>e.encode(t,r.data),t=>{const r=t.clone(),s=Nt(e.skipEncoded(r));return new kt(s.asOpaque(),e.decode(t))},e.skip,e.View);class Ws extends Q{workReport;timeout;static Codec=Pe.Class(Ws,{workReport:zs(Lr.Codec),timeout:Pe.u32.asOpaque()});static create({workReport:e,timeout:t}){return new Ws(e,t)}constructor(e,t){super(),this.workReport=e,this.timeout=t}}class Js extends Q{headerHash;mmr;postStateRoot;reported;static Codec=Pe.Class(Js,{headerHash:Pe.bytes(Ct).asOpaque(),mmr:Pe.object({peaks:De(Pe.sequenceVarLen(Pe.optional(Pe.bytes(Ct))))}),postStateRoot:Pe.bytes(Ct).asOpaque(),reported:gr(Pr.Codec,e=>e.workPackageHash)});static create({headerHash:e,mmr:t,postStateRoot:r,reported:s}){return new Js(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.mmr=t,this.postStateRoot=r,this.reported=s}}function Ys(e,t){return M(e.length===t.coresCount,`Invalid per-core array length. Expected ${t.coresCount}, got: ${e.length}`),e}const Xs=e=>dr(t=>fr(e,{fixedLength:t.coresCount})),Zs=()=>De(Pe.sequenceVarLen(Pe.bytes(Ct))).convert(e=>e.array,e=>{const t=e.map(e=>e.asOpaque());return ar.fromSortedArray(ri,t)}),ei=Zs();class ti{goodSet;badSet;wonkySet;punishSet;static Codec=Pe.Class(ti,{goodSet:ei,badSet:ei,wonkySet:ei,punishSet:Zs()});static create({goodSet:e,badSet:t,wonkySet:r,punishSet:s}){return new ti(e,t,r,s)}constructor(e,t,r,s){this.goodSet=e,this.badSet=t,this.wonkySet=r,this.punishSet=s}static fromSortedArrays({goodSet:e,badSet:t,wonkySet:r,punishSet:s}){return new ti(ar.fromSortedArray(ri,e),ar.fromSortedArray(ri,t),ar.fromSortedArray(ri,r),ar.fromSortedArray(ri,s))}}function ri(e,t){return e.compare(t)}class si{service;gasLimit;static Codec=Pe.Class(si,{service:Pe.u32.asOpaque(),gasLimit:Pe.u64.asOpaque()});static create({service:e,gasLimit:t}){return new si(e,t)}constructor(e,t){this.service=e,this.gasLimit=t}}class ii{manager;authManager;validatorsManager;autoAccumulateServices;static Codec=Pe.Class(ii,{manager:Pe.u32.asOpaque(),authManager:Pe.u32.asOpaque(),validatorsManager:Pe.u32.asOpaque(),autoAccumulateServices:De(Pe.sequenceVarLen(si.Codec))});static create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s}){return new ii(e,t,r,s)}constructor(e,t,r,s){this.manager=e,this.authManager=t,this.validatorsManager=r,this.autoAccumulateServices=s}}const ni=128;class oi extends Q{bandersnatch;ed25519;bls;metadata;static Codec=Pe.Class(oi,{bandersnatch:Pe.bytes(wt).asOpaque(),ed25519:Pe.bytes(bt).asOpaque(),bls:Pe.bytes(Et).asOpaque(),metadata:Pe.bytes(ni)});static create({ed25519:e,bandersnatch:t,bls:r,metadata:s}){return new oi(t,e,r,s)}constructor(e,t,r,s){super(),this.bandersnatch=e,this.ed25519=t,this.bls=r,this.metadata=s}}var ai;!function(e){e[e.Tickets=0]="Tickets",e[e.Keys=1]="Keys"}(ai||(ai={}));const ci=Pe.bytes(wt).asOpaque();class li extends Q{kind;keys;tickets;static Codec=dr(e=>Pe.custom({name:"SafroleSealingKeys",sizeHint:{bytes:1+Ct*e.epochLength,isExact:!1}},(e,t)=>{e.varU32(pe(t.kind)),t.kind===ai.Keys?e.sequenceFixLen(ci,t.keys):e.sequenceFixLen(es.Codec,t.tickets)},t=>{const r=e.epochLength,s=t.varU32();if(s===ai.Keys){const s=t.sequenceFixLen(ci,r);return li.keys(Yr(s,e))}if(s===ai.Tickets){const s=t.sequenceFixLen(es.Codec,r);return li.tickets(Yr(s,e))}throw new Error(`Unexpected safrole sealing keys kind: ${s}`)},t=>{const r=t.decoder.varU32();if(r!==ai.Keys){if(r!==ai.Tickets)throw new Error(`Unexpected safrole sealing keys kind: ${r}`);t.sequenceFixLen(es.Codec,e.epochLength)}else t.sequenceFixLen(ci,e.epochLength)}));static keys(e){return new li(ai.Keys,e,void 0)}static tickets(e){return new li(ai.Tickets,void 0,e)}constructor(e,t,r){super(),this.kind=e,this.keys=t,this.tickets=r}}class hi{nextValidatorData;epochRoot;sealingKeySeries;ticketsAccumulator;static Codec=Pe.Class(hi,{nextValidatorData:Jr(oi.Codec),epochRoot:Pe.bytes(St).asOpaque(),sealingKeySeries:li.Codec,ticketsAccumulator:De(Pe.sequenceVarLen(es.Codec)).convert(F,ir)});static create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s}){return new hi(e,t,r,s)}constructor(e,t,r,s){this.nextValidatorData=e,this.epochRoot=t,this.sealingKeySeries=r,this.ticketsAccumulator=s}}class ui extends Q{codeHash;balance;accumulateMinGas;onTransferMinGas;storageUtilisationBytes;storageUtilisationCount;static Codec=Pe.Class(ui,{codeHash:Pe.bytes(Ct).asOpaque(),balance:Pe.u64,accumulateMinGas:Pe.u64.convert(e=>e,Gr),onTransferMinGas:Pe.u64.convert(e=>e,Gr),storageUtilisationBytes:Pe.u64,storageUtilisationCount:Pe.u32});static create(e){return new ui(e.codeHash,e.balance,e.accumulateMinGas,e.onTransferMinGas,e.storageUtilisationBytes,e.storageUtilisationCount)}static calculateThresholdBalance(e,t){const r=be(ye(100n),ye(10n*BigInt(e)),ye(1n*t));return r.overflow?ye(2n**64n-1n):r.value}constructor(e,t,r,s,i,n){super(),this.codeHash=e,this.balance=t,this.accumulateMinGas=r,this.onTransferMinGas=s,this.storageUtilisationBytes=i,this.storageUtilisationCount=n}}class di extends Q{hash;blob;static Codec=Pe.Class(di,{hash:Pe.bytes(Ct).asOpaque(),blob:Pe.blob});static create({hash:e,blob:t}){return new di(e,t)}constructor(e,t){super(),this.hash=e,this.blob=t}}class fi extends Q{hash;blob;static Codec=Pe.Class(fi,{hash:Pe.bytes(Ct).asOpaque(),blob:Pe.blob});static create({hash:e,blob:t}){return new fi(e,t)}constructor(e,t){super(),this.hash=e,this.blob=t}}function pi(e){const t=e;if(t.length>3)throw new Error("Lookup history items must contain 0-3 timeslots.");return t}class gi{hash;length;slots;constructor(e,t,r){this.hash=e,this.length=t,this.slots=r}static isRequested(e){return"slots"in e?0===e.slots.length:0===e.length}}var yi,mi,bi;!function(e){e[e.Provide=0]="Provide",e[e.Remove=1]="Remove",e[e.UpdateOrAdd=2]="UpdateOrAdd"}(yi||(yi={}));class Ai{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static provide({serviceId:e,preimage:t,slot:r}){return new Ai(e,{kind:yi.Provide,preimage:t,slot:r})}static remove({serviceId:e,hash:t,length:r}){return new Ai(e,{kind:yi.Remove,hash:t,length:r})}static updateOrAdd({serviceId:e,lookupHistory:t}){return new Ai(e,{kind:yi.UpdateOrAdd,item:t})}}!function(e){e[e.Update=0]="Update",e[e.Create=1]="Create"}(mi||(mi={}));class Ii{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static update({serviceId:e,serviceInfo:t}){return new Ii(e,{kind:mi.Update,account:t})}static create({serviceId:e,serviceInfo:t,lookupHistory:r}){return new Ii(e,{kind:mi.Create,account:t,lookupHistory:r})}}!function(e){e[e.Set=0]="Set",e[e.Remove=1]="Remove"}(bi||(bi={}));class vi{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static set({serviceId:e,storage:t}){return new vi(e,{kind:bi.Set,storage:t})}static remove({serviceId:e,key:t}){return new vi(e,{kind:bi.Remove,key:t})}get key(){return this.action.kind===bi.Remove?this.action.key:this.action.storage.hash}get value(){return this.action.kind===bi.Remove?null:this.action.storage.blob}}const wi=Pe.varU32.convert(e=>pe(e),e=>jr(e));class Si{blocks;tickets;preImages;preImagesSize;guarantees;assurances;static Codec=Pe.Class(Si,{blocks:Pe.u32,tickets:Pe.u32,preImages:Pe.u32,preImagesSize:Pe.u32,guarantees:Pe.u32,assurances:Pe.u32});static create({blocks:e,tickets:t,preImages:r,preImagesSize:s,guarantees:i,assurances:n}){return new Si(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.blocks=e,this.tickets=t,this.preImages=r,this.preImagesSize=s,this.guarantees=i,this.assurances=n}static empty(){const e=pe(0);return new Si(e,e,e,e,e,e)}}const Ei=Pe.varU32.convert(e=>pe(e),e=>de(e)),Ci=Pe.varU64.convert(e=>ye(e),e=>Gr(e));class ki{dataAvailabilityLoad;popularity;imports;exports;extrinsicSize;extrinsicCount;bundleSize;gasUsed;static Codec=Pe.Class(ki,{dataAvailabilityLoad:Pe.varU32,popularity:Ei,imports:Ei,exports:Ei,extrinsicSize:Pe.varU32,extrinsicCount:Ei,bundleSize:Pe.varU32,gasUsed:Ci});static create(e){return new ki(e.dataAvailabilityLoad,e.popularity,e.imports,e.exports,e.extrinsicSize,e.extrinsicCount,e.bundleSize,e.gasUsed)}constructor(e,t,r,s,i,n,o,a){this.dataAvailabilityLoad=e,this.popularity=t,this.imports=r,this.exports=s,this.extrinsicSize=i,this.extrinsicCount=n,this.bundleSize=o,this.gasUsed=a}static empty(){const e=pe(0),t=de(0),r=Gr(0);return new ki(e,t,t,t,e,t,e,r)}}class xi{providedCount;providedSize;refinementCount;refinementGasUsed;imports;exports;extrinsicSize;extrinsicCount;accumulateCount;accumulateGasUsed;onTransfersCount;onTransfersGasUsed;static Codec=Pe.Class(xi,{providedCount:Ei,providedSize:Pe.varU32,refinementCount:Pe.varU32,refinementGasUsed:Ci,imports:Ei,exports:Ei,extrinsicSize:Pe.varU32,extrinsicCount:Ei,accumulateCount:Pe.varU32,accumulateGasUsed:Ci,onTransfersCount:Pe.varU32,onTransfersGasUsed:Ci});static create(e){return new xi(e.providedCount,e.providedSize,e.refinementCount,e.refinementGasUsed,e.imports,e.exports,e.extrinsicSize,e.extrinsicCount,e.accumulateCount,e.accumulateGasUsed,e.onTransfersCount,e.onTransfersGasUsed)}constructor(e,t,r,s,i,n,o,a,c,l,h,u){this.providedCount=e,this.providedSize=t,this.refinementCount=r,this.refinementGasUsed=s,this.imports=i,this.exports=n,this.extrinsicSize=o,this.extrinsicCount=a,this.accumulateCount=c,this.accumulateGasUsed=l,this.onTransfersCount=h,this.onTransfersGasUsed=u}static empty(){const e=pe(0),t=de(0),r=Gr(0);return new xi(t,e,e,r,t,t,e,t,e,r,e,r)}}class _i{current;previous;cores;services;static Codec=Pe.Class(_i,{current:Jr(Si.Codec),previous:Jr(Si.Codec),cores:Xs(ki.Codec),services:Pe.dictionary(wi,xi.Codec,{sortKeys:(e,t)=>e-t})});static create(e){return new _i(e.current,e.previous,e.cores,e.services)}constructor(e,t,r,s){this.current=e,this.previous=t,this.cores=r,this.services=s}}var Bi,Ri;(Ri=Bi||(Bi={}))[Ri.DuplicateService=0]="DuplicateService",Ri[Ri.NoService=1]="NoService",Ri[Ri.PreimageExists=2]="PreimageExists";class Oi extends Q{serviceId;data;constructor(e,t){super(),this.serviceId=e,this.data=t}getInfo(){return this.data.info}getStorage(e){return this.data.storage.get(e)?.blob??null}hasPreimage(e){return this.data.preimages.has(e)}getPreimage(e){return this.data.preimages.get(e)?.blob??null}getLookupHistory(e,t){const r=this.data.lookupHistory.get(e);return void 0===r?null:r.find(e=>e.length===t)?.slots??null}getEntries(){return{storageKeys:Array.from(this.data.storage.keys()),preimages:Array.from(this.data.preimages.keys()),lookupHistory:Array.from(this.data.lookupHistory.entries()).map(([e,t])=>({hash:e,length:t[0].length}))}}static copyFrom(e,t){const r=e.getInfo(),s=rr.new(),i=rr.new(),n=rr.new();for(const r of t.preimages){const t=e.getPreimage(r);if(null===t)throw new Error(`Service ${e.serviceId} is missing expected preimage: ${r}`);s.set(r,di.create({hash:r,blob:t}))}for(const{hash:r,length:s}of t.lookupHistory){const t=e.getLookupHistory(r,s);if(null===t)throw new Error(`Service ${e.serviceId} is missing expected lookupHistory: ${r}, ${s}`);const i=n.get(r)??[];i.push(new gi(r,s,t)),n.set(r,i)}for(const r of t.storageKeys){const t=e.getStorage(r);if(null===t)throw new Error(`Service ${e.serviceId} is missing expected storage: ${r}`);i.set(r,fi.create({hash:r,blob:t}))}return new Oi(e.serviceId,{info:r,preimages:s,storage:i,lookupHistory:n})}}class Ui extends Q{static create(e){return new Ui(e)}static partial(e,t){const r=Ui.empty(e);return Object.assign(r,t),r}static copyFrom(e,t){const r=new Map;for(const[s,i]of t.entries()){const t=e.getService(s);if(null===t)throw new Error(`Expected service ${s} to be part of the state!`);const n=Oi.copyFrom(t,i);r.set(s,n)}return Ui.create({availabilityAssignment:e.availabilityAssignment,accumulationQueue:e.accumulationQueue,designatedValidatorData:e.designatedValidatorData,nextValidatorData:e.nextValidatorData,currentValidatorData:e.currentValidatorData,previousValidatorData:e.previousValidatorData,disputesRecords:e.disputesRecords,timeslot:e.timeslot,entropy:e.entropy,authPools:e.authPools,authQueues:e.authQueues,recentBlocks:e.recentBlocks,statistics:e.statistics,recentlyAccumulated:e.recentlyAccumulated,ticketsAccumulator:e.ticketsAccumulator,sealingKeySeries:e.sealingKeySeries,epochRoot:e.epochRoot,privilegedServices:e.privilegedServices,services:r})}intoServicesData(){const e=new Map;for(const[t,{data:r}]of this.services)e.set(t,{storageKeys:Array.from(r.storage.keys()),preimages:Array.from(r.preimages.keys()),lookupHistory:Array.from(r.lookupHistory).flatMap(([e,t])=>t.map(t=>({hash:e,length:t.length})))});return e}applyUpdate(e){const{servicesRemoved:t,servicesUpdates:r,preimages:s,storage:i,...n}=e;let o;return Object.assign(this,n),o=this.updateServices(r),o.isError?o:(o=this.updatePreimages(s),o.isError?o:(o=this.updateStorage(i),o.isError?o:(this.removeServices(t),z.ok($))))}removeServices(e){for(const t of e??[])M(this.services.has(t),`Attempting to remove non-existing service: ${t}`),this.services.delete(t)}updateStorage(e){for(const{serviceId:t,action:r}of e??[]){const{kind:e}=r,s=this.services.get(t);if(void 0===s)return z.error(Bi.NoService,`Attempting to update storage of non-existing service: ${t}`);e===bi.Set?s.data.storage.set(r.storage.hash,r.storage):e===bi.Remove?(M(!s.data.storage.has(r.key),`Attempting to remove non-existing storage item at ${t}: ${r.key}`),s.data.storage.delete(r.key)):L(e)}return z.ok($)}updatePreimages(e){for(const{serviceId:t,action:r}of e??[]){const e=this.services.get(t);if(void 0===e)return z.error(Bi.NoService,`Attempting to update preimage of non-existing service: ${t}`);const{kind:s}=r;if(s===yi.Provide){const{preimage:s,slot:i}=r;if(e.data.preimages.has(s.hash))return z.error(Bi.PreimageExists,`Overwriting existing preimage at ${t}: ${s}`);if(e.data.preimages.set(s.hash,s),null!==i){const t=e.data.lookupHistory.get(s.hash),r=pe(s.blob.length),n=new gi(s.hash,r,pi([i]));if(void 0===t)e.data.lookupHistory.set(s.hash,[n]);else{const e=t.map(e=>e.length).indexOf(r);t.splice(e,-1===e?0:1,n)}}}else if(s===yi.Remove){const{hash:t,length:s}=r;e.data.preimages.delete(t);const i=e.data.lookupHistory.get(t)??[],n=i.map(e=>e.length).indexOf(s);-1!==n&&i.splice(n,1)}else if(s===yi.UpdateOrAdd){const{item:t}=r,s=e.data.lookupHistory.get(t.hash)??[],i=s.map(e=>e.length).indexOf(t.length),n=-1===i?0:1;s.splice(i,n,t),e.data.lookupHistory.set(t.hash,s)}else L(s)}return z.ok($)}updateServices(e){for(const{serviceId:t,action:r}of e??[]){const{kind:e,account:s}=r;if(e===mi.Create){const{lookupHistory:e}=r;if(this.services.has(t))return z.error(Bi.DuplicateService,`${t} already exists!`);this.services.set(t,new Oi(t,{info:s,preimages:rr.new(),storage:rr.new(),lookupHistory:rr.fromEntries(null===e?[]:[[e.hash,[e]]])}))}else if(e===mi.Update){const e=this.services.get(t);if(void 0===e)return z.error(Bi.NoService,`Cannot update ${t} because it does not exist.`);e.data.info=s}else L(e)}return z.ok($)}availabilityAssignment;designatedValidatorData;nextValidatorData;currentValidatorData;previousValidatorData;disputesRecords;timeslot;entropy;authPools;authQueues;recentBlocks;statistics;accumulationQueue;recentlyAccumulated;ticketsAccumulator;sealingKeySeries;epochRoot;privilegedServices;services;recentServiceIds(){return Array.from(this.services.keys())}getService(e){return this.services.get(e)??null}constructor(e){super(),this.availabilityAssignment=e.availabilityAssignment,this.designatedValidatorData=e.designatedValidatorData,this.nextValidatorData=e.nextValidatorData,this.currentValidatorData=e.currentValidatorData,this.previousValidatorData=e.previousValidatorData,this.disputesRecords=e.disputesRecords,this.timeslot=e.timeslot,this.entropy=e.entropy,this.authPools=e.authPools,this.authQueues=e.authQueues,this.recentBlocks=e.recentBlocks,this.statistics=e.statistics,this.accumulationQueue=e.accumulationQueue,this.recentlyAccumulated=e.recentlyAccumulated,this.ticketsAccumulator=e.ticketsAccumulator,this.sealingKeySeries=e.sealingKeySeries,this.epochRoot=e.epochRoot,this.privilegedServices=e.privilegedServices,this.services=e.services}static empty(e){return new Ui({availabilityAssignment:Ys(Array.from({length:e.coresCount},()=>null),e),designatedValidatorData:Wr(Array.from({length:e.validatorsCount},()=>oi.create({bandersnatch:Y.zero(wt).asOpaque(),bls:Y.zero(Et).asOpaque(),ed25519:Y.zero(bt).asOpaque(),metadata:Y.zero(ni).asOpaque()})),e),nextValidatorData:Wr(Array.from({length:e.validatorsCount},()=>oi.create({bandersnatch:Y.zero(wt).asOpaque(),bls:Y.zero(Et).asOpaque(),ed25519:Y.zero(bt).asOpaque(),metadata:Y.zero(ni).asOpaque()})),e),currentValidatorData:Wr(Array.from({length:e.validatorsCount},()=>oi.create({bandersnatch:Y.zero(wt).asOpaque(),bls:Y.zero(Et).asOpaque(),ed25519:Y.zero(bt).asOpaque(),metadata:Y.zero(ni).asOpaque()})),e),previousValidatorData:Wr(Array.from({length:e.validatorsCount},()=>oi.create({bandersnatch:Y.zero(wt).asOpaque(),bls:Y.zero(Et).asOpaque(),ed25519:Y.zero(bt).asOpaque(),metadata:Y.zero(ni).asOpaque()})),e),disputesRecords:ti.create({goodSet:ar.fromSortedArray(ri,[]),badSet:ar.fromSortedArray(ri,[]),wonkySet:ar.fromSortedArray(ri,[]),punishSet:ar.fromSortedArray(ri,[])}),timeslot:Fr(0),entropy:nr.fill(()=>Y.zero(Ct).asOpaque(),4),authPools:Ys(Array.from({length:e.coresCount},()=>[]),e),authQueues:Ys(Array.from({length:e.coresCount},()=>nr.fill(()=>Y.zero(Ct).asOpaque(),80)),e),recentBlocks:[],statistics:_i.create({current:Wr(Array.from({length:e.validatorsCount},()=>Si.empty()),e),previous:Wr(Array.from({length:e.validatorsCount},()=>Si.empty()),e),cores:Ys(Array.from({length:e.coresCount},()=>ki.empty()),e),services:new Map}),accumulationQueue:Yr(Array.from({length:e.epochLength},()=>[]),e),recentlyAccumulated:Yr(Array.from({length:e.epochLength},()=>sr.new()),e),ticketsAccumulator:[],sealingKeySeries:li.keys(Yr(Array.from({length:e.epochLength},()=>Y.zero(wt).asOpaque()),e)),epochRoot:Y.zero(St).asOpaque(),privilegedServices:ii.create({manager:jr(0),authManager:jr(0),validatorsManager:jr(0),autoAccumulateServices:[]}),services:new Map})}}const Ti=Pe.object({storageKeys:Pe.sequenceVarLen(Pe.bytes(Ct).asOpaque()),preimages:Pe.sequenceVarLen(Pe.bytes(Ct).asOpaque()),lookupHistory:Pe.sequenceVarLen(Pe.object({hash:Pe.bytes(Ct).asOpaque(),length:Pe.u32}))});Pe.dictionary(Pe.u32.asOpaque(),Ti,{sortKeys:(e,t)=>e-t});class Ni extends Q{report;dependencies;static Codec=Pe.Class(Ni,{report:Lr.Codec,dependencies:fr(Pe.bytes(Ct).asOpaque(),{typicalLength:4,maxLength:8,minLength:0})});static create({report:e,dependencies:t}){return new Ni(e,t)}constructor(e,t){super(),this.report=e,this.dependencies=t}}var Di,Mi,Pi;!function(e){e[e.Unused=0]="Unused",e[e.Alpha=1]="Alpha",e[e.Phi=2]="Phi",e[e.Beta=3]="Beta",e[e.Gamma=4]="Gamma",e[e.Psi=5]="Psi",e[e.Eta=6]="Eta",e[e.Iota=7]="Iota",e[e.Kappa=8]="Kappa",e[e.Lambda=9]="Lambda",e[e.Rho=10]="Rho",e[e.Tau=11]="Tau",e[e.Chi=12]="Chi",e[e.Pi=13]="Pi",e[e.Theta=14]="Theta",e[e.Xi=15]="Xi",e[e.Delta=255]="Delta"}(Di||(Di={})),function(e){function t(e,t){const r=Y.zero(Ct);let s=0;for(const i of Ae(e))r.raw[s]=i,r.raw[s+1]=t.raw[s/2],s+=2;const i=s/2;return r.raw.set(t.raw.subarray(i,Ct-i),s),r.asOpaque()}e.index=function(e){const t=Y.zero(Ct);return t.raw[0]=e,t.asOpaque()},e.serviceInfo=function(e){const t=Y.zero(Ct);t.raw[0]=Di.Delta;let r=1;for(const s of Ae(e))t.raw[r]=s,r+=2;return t.asOpaque()},e.serviceStorage=function(e,r){const s=Y.zero(Ct);return s.raw.set(Ae(pe(2**32-1)),0),s.raw.set(r.raw.subarray(0,28),4),t(e,s)},e.servicePreimage=function(e,r){const s=Y.zero(Ct);return s.raw.set(Ae(pe(2**32-2)),0),s.raw.set(r.raw.subarray(1,29),4),t(e,s)},e.serviceLookupHistory=function(e,r,s){const i=Nt(r),n=Y.zero(Ct);return n.raw.set(Ae(s),0),n.raw.set(i.raw.subarray(2,30),4),t(e,n)},e.serviceNested=t}(Mi||(Mi={})),function(e){e.authPools={key:Mi.index(Di.Alpha),Codec:Xs(fr(Pe.bytes(Ct).asOpaque(),{minLength:0,maxLength:8,typicalLength:8})),extract:e=>e.authPools},e.authQueues={key:Mi.index(Di.Phi),Codec:Xs(pr(Pe.bytes(Ct).asOpaque(),80)),extract:e=>e.authQueues},e.recentBlocks={key:Mi.index(Di.Beta),Codec:fr(Js.Codec,{minLength:0,maxLength:8,typicalLength:8}),extract:e=>e.recentBlocks},e.safrole={key:Mi.index(Di.Gamma),Codec:hi.Codec,extract:e=>hi.create({nextValidatorData:e.nextValidatorData,epochRoot:e.epochRoot,sealingKeySeries:e.sealingKeySeries,ticketsAccumulator:e.ticketsAccumulator})},e.disputesRecords={key:Mi.index(Di.Psi),Codec:ti.Codec,extract:e=>e.disputesRecords},e.entropy={key:Mi.index(Di.Eta),Codec:pr(Pe.bytes(Ct).asOpaque(),4),extract:e=>e.entropy},e.designatedValidators={key:Mi.index(Di.Iota),Codec:Jr(oi.Codec),extract:e=>e.designatedValidatorData},e.currentValidators={key:Mi.index(Di.Kappa),Codec:Jr(oi.Codec),extract:e=>e.currentValidatorData},e.previousValidators={key:Mi.index(Di.Lambda),Codec:Jr(oi.Codec),extract:e=>e.previousValidatorData},e.availabilityAssignment={key:Mi.index(Di.Rho),Codec:Xs(Pe.optional(Ws.Codec)),extract:e=>e.availabilityAssignment},e.timeslot={key:Mi.index(Di.Tau),Codec:Pe.u32.asOpaque(),extract:e=>e.timeslot},e.privilegedServices={key:Mi.index(Di.Chi),Codec:ii.Codec,extract:e=>e.privilegedServices},e.statistics={key:Mi.index(Di.Pi),Codec:_i.Codec,extract:e=>e.statistics},e.accumulationQueue={key:Mi.index(Di.Theta),Codec:Xr(De(Pe.sequenceVarLen(Ni.Codec))),extract:e=>e.accumulationQueue},e.recentlyAccumulated={key:Mi.index(Di.Xi),Codec:Xr(Pe.sequenceVarLen(Pe.bytes(Ct).asOpaque()).convert(e=>Array.from(e),e=>sr.from(e))),extract:e=>e.recentlyAccumulated},e.serviceData=e=>({key:Mi.serviceInfo(e),Codec:ui.Codec}),e.serviceStorage=(e,t)=>({key:Mi.serviceStorage(e,t),Codec:Li}),e.servicePreimages=(e,t)=>({key:Mi.servicePreimage(e,t),Codec:Li}),e.serviceLookupHistory=(e,t,r)=>({key:Mi.serviceLookupHistory(e,t,r),Codec:De(Pe.sequenceVarLen(Pe.u32))})}(Pi||(Pi={}));const Li=Ne.new("Dump",{bytes:64,isExact:!1},(e,t)=>e.bytes(Y.fromBlob(t.raw,t.raw.length)),e=>J.blobFrom(e.bytes(e.source.length-e.bytesRead()).raw),e=>e.bytes(e.decoder.source.length-e.decoder.bytesRead()));var Hi;!function(e){e[e.Insert=0]="Insert",e[e.Remove=1]="Remove"}(Hi||(Hi={}));const Ki=J.empty();class Qi{serviceId;accountInfo;retrieveOptional;constructor(e,t,r){this.serviceId=e,this.accountInfo=t,this.retrieveOptional=r}getInfo(){return this.accountInfo}getStorage(e){return this.retrieveOptional(Pi.serviceStorage(this.serviceId,e))??null}hasPreimage(e){return void 0!==this.retrieveOptional(Pi.servicePreimages(this.serviceId,e))}getPreimage(e){return this.retrieveOptional(Pi.servicePreimages(this.serviceId,e))??null}getLookupHistory(e,t){const r=this.retrieveOptional(Pi.serviceLookupHistory(this.serviceId,e,t));return void 0===r?null:pi(r.map(Fr))}}class Vi{spec;backend;_recentServiceIds;static fromStateEntries(e,t,r=[]){return new Vi(e,function(e){const t=e.entries.data;return{get:e=>t.get(e)??null}}(t),r)}static new(e,t,r=[]){return new Vi(e,t,r)}constructor(e,t,r){this.spec=e,this.backend=t,this._recentServiceIds=r}updateBackend(e){this.backend=e}recentServiceIds(){return this._recentServiceIds}getService(e){const t=this.retrieveOptional(Pi.serviceData(e));return void 0===t?null:(this._recentServiceIds.includes(e)||this._recentServiceIds.push(e),new Qi(e,t,e=>this.retrieveOptional(e)))}retrieve({key:e,Codec:t},r){const s=this.backend.get(e);if(null===s)throw new Error(`Required state entry for ${r} is missing!. Accessing key: ${e}`);return we.decodeObject(t,s,this.spec)}retrieveOptional({key:e,Codec:t}){const r=this.backend.get(e);if(null!==r)return we.decodeObject(t,r,this.spec)}get availabilityAssignment(){return this.retrieve(Pi.availabilityAssignment,"availabilityAssignment")}get designatedValidatorData(){return this.retrieve(Pi.designatedValidators,"designatedValidatorData")}get nextValidatorData(){return this.retrieve(Pi.safrole,"safroleData.nextValidatorData").nextValidatorData}get currentValidatorData(){return this.retrieve(Pi.currentValidators,"currentValidators")}get previousValidatorData(){return this.retrieve(Pi.previousValidators,"previousValidators")}get disputesRecords(){return this.retrieve(Pi.disputesRecords,"disputesRecords")}get timeslot(){return this.retrieve(Pi.timeslot,"timeslot")}get entropy(){return this.retrieve(Pi.entropy,"entropy")}get authPools(){return this.retrieve(Pi.authPools,"authPools")}get authQueues(){return this.retrieve(Pi.authQueues,"authQueues")}get recentBlocks(){return this.retrieve(Pi.recentBlocks,"recentBlocks")}get statistics(){return this.retrieve(Pi.statistics,"statistics")}get accumulationQueue(){return this.retrieve(Pi.accumulationQueue,"accumulationQueue")}get recentlyAccumulated(){return this.retrieve(Pi.recentlyAccumulated,"recentlyAccumulated")}get ticketsAccumulator(){return this.retrieve(Pi.safrole,"safroleData.ticketsAccumulator").ticketsAccumulator}get sealingKeySeries(){return this.retrieve(Pi.safrole,"safrole.sealingKeySeries").sealingKeySeries}get epochRoot(){return this.retrieve(Pi.safrole,"safrole.epochRoot").epochRoot}get privilegedServices(){return this.retrieve(Pi.privilegedServices,"privilegedServices")}}const Fi=31;var $i;!function(e){e[e.Branch=0]="Branch",e[e.Leaf=1]="Leaf",e[e.EmbedLeaf=2]="EmbedLeaf"}($i||($i={}));class ji{raw;constructor(e=new Uint8Array(64)){this.raw=e}getNodeType(){return 128&this.raw[0]?192&~this.raw[0]?$i.EmbedLeaf:$i.Leaf:$i.Branch}asBranchNode(){return M(this.getNodeType()===$i.Branch),new Gi(this)}asLeafNode(){return M(this.getNodeType()!==$i.Branch),new qi(this)}toString(){return J.blobFrom(this.raw).toString()}}class Gi{node;constructor(e){this.node=e}static fromSubNodes(e,t){const r=new ji;return r.raw.set(e.raw,0),r.raw.set(t.raw,Ct),r.raw[0]&=127,new Gi(r)}getLeft(){return Y.fromBlob(this.node.raw.subarray(0,Ct),Ct).asOpaque()}getRight(){return Y.fromBlob(this.node.raw.subarray(Ct),Ct).asOpaque()}}class qi{node;constructor(e){this.node=e}static fromValue(e,t,r){const s=new ji;return t.length<=Ct?(s.raw[0]=128|t.length,s.raw.set(e.raw.subarray(0,Fi),1),s.raw.set(t.raw,32)):(s.raw[0]=192,s.raw.set(e.raw.subarray(0,Fi),1),s.raw.set(r().raw,32)),new qi(s)}getKey(){return Y.fromBlob(this.node.raw.subarray(1,32),Fi).asOpaque()}hasEmbeddedValue(){return this.node.getNodeType()===$i.EmbedLeaf}getValueLength(){return 63&this.node.raw[0]}getValue(){const e=this.getValueLength();return J.blobFrom(this.node.raw.subarray(Ct,Ct+e))}getValueHash(){return Y.fromBlob(this.node.raw.subarray(Ct),Ct).asOpaque()}toString(){return`LeafNode {\n key: ${this.getKey()},\n valueHash: ${this.getValueHash()}\n}`}}class zi{hasher;nodes=rr.new();constructor(e){this.hasher=e}get(e){return zi.withHashCompat(e,e=>this.nodes.get(e)??null)}hashNode(e){return this.hasher.hashConcat(e.raw)}*leaves(){for(const e of this.nodes.values())e.getNodeType()!==$i.Branch&&(yield e.asLeafNode())}static withHashCompat(e,t){const r=e.raw[0];e.raw[0]&=127;const s=t(e);return e.raw[0]=r,s}}class Wi extends zi{remove(e){return zi.withHashCompat(e,e=>{this.nodes.delete(e)})}insert(e,t){const r=t??this.hashNode(e);return zi.withHashCompat(r,t=>{this.nodes.set(t,e)}),r}}class Ji{nodes;root;static empty(e){return new Ji(new Wi(e))}static computeStateRoot(e,t){return Ji.fromLeaves(e,t).getRootHash()}static fromLeaves(e,t){let r=null;const s=new Wi(e);for(const e of t)r=Yi(r,s,e);return new Ji(s,r)}constructor(e,t=null){this.nodes=e,this.root=t}set(e,t,r){const s=qi.fromValue(e,t,()=>r??this.nodes.hasher.hashConcat(t.raw).asOpaque());return this.root=Yi(this.root,this.nodes,s),s}remove(e){throw new Error("Removing from the trie not implemented yet.")}getRootNode(){return this.root}getRootHash(){return null===this.root?Y.zero(Ct).asOpaque():this.nodes.hashNode(this.root)}toString(){return en(this.root,this.nodes)}}function Yi(e,t,r){if(null===e)return t.insert(r.node),r.node;const s=function(e,t,r){const s=new Xi;let i=e,n=t.hashNode(e);for(;;){if(i.getNodeType()!==$i.Branch){const e=i.asLeafNode();return s.leafToReplace=[e,n],s}const e=i.asBranchNode(),o=Zi(r,s.bitIndex),a=o?e.getRight():e.getLeft();s.branchingHistory.push([e,n,o]);const c=t.get(a);if(null===c){if(a.isEqualTo(Y.zero(Ct)))return s;throw new Error(`Missing trie node '${a}' with key prefix: ${r}[0..${s.bitIndex}]`)}i=c,n=a,s.bitIndex+=1}}(e,t,r.getKey()),i=void 0!==s.leafToReplace?function(e,t,r,s){const i=s.getKey();let[n,o]=r;const a=n.getKey(),c=t.insert(s.node);if(a.isEqualTo(i))return n.getValueHash().isEqualTo(s.getValueHash())||t.remove(o),[s.node,c];const l=[];let h=Zi(i,e.bitIndex);for(;e.bitIndex<248;){h=Zi(i,e.bitIndex);const t=Zi(a,e.bitIndex);if(h!==t)break;l.push(t),e.bitIndex+=1}const u=Y.zero(Ct).asOpaque();(()=>{const t=e.branchingHistory.length;return t>0&&!1===e.branchingHistory[t-1][2]})()&&!h&&(o=t.hashNode(n.node));let d=h?Gi.fromSubNodes(o,c):Gi.fromSubNodes(c,o),f=t.insert(d.node),p=l.pop();for(;void 0!==p;)d=p?Gi.fromSubNodes(u,f):Gi.fromSubNodes(f,u),f=t.insert(d.node),p=l.pop();return[d.node,f]}(s,t,s.leafToReplace,r):[r.node,t.insert(r.node)];let n=s.branchingHistory.pop(),[o,a]=i;for(;void 0!==n;){const[e,r,i]=n;t.remove(r);const c=i?Gi.fromSubNodes(e.getLeft(),a):Gi.fromSubNodes(a,e.getRight());a=t.insert(c.node),o=c.node,n=s.branchingHistory.pop()}return o}class Xi{branchingHistory=[];bitIndex=0;leafToReplace}function Zi(e,t){M(t<248);const r=t>>>3,s=128>>>t-(r<<3);return 0!==(e.raw[r]&s)}function en(e,t){if(null===e)return"<empty tree>";if(e.getNodeType()===$i.Branch){const r=e.asBranchNode(),s=r.getLeft(),i=r.getRight(),n=e=>e.split("\n").map(e=>`\t\t${e}`).join("\n"),o=en(t.get(s),t),a=en(t.get(i),t);return`<branch>\n\t-- ${s}: ${n(o)}\n\t-- ${i}: ${n(a)}\n`}const r=e.asLeafNode(),s=r.getValueLength(),i=s>0?`'${r.getValue()}'(len:${s})`:`'<hash>${r.getValueHash()}'`;return`\nLeaf('${r.getKey().toString()}',${i})`}const tn={hashConcat:(e,t=[])=>Tt([e,...t])};class rn{entries;static serializeInMemory(e,t){return new rn({full:!0,data:sn(e,t)})}static fromDictionaryUnsafe(e){return new rn({full:!0,data:e})}static fromTruncatedDictionaryUnsafe(e){return new rn({full:!1,data:e})}trieCache=null;constructor(e){this.entries=e}getTrie(){if(null===this.trieCache){const e=Ji.empty(tn);for(const[t,r]of this.entries.data)e.set(t.asOpaque(),r);this.trieCache=e}return this.trieCache}getRootHash(){return this.getTrie().getRootHash().asOpaque()}}function sn(e,t){const r=rr.new();function s(s){r.set(s.key,_e.encodeObject(s.Codec,s.extract(t),e))}s(Pi.authPools),s(Pi.authQueues),s(Pi.recentBlocks),s(Pi.safrole),s(Pi.disputesRecords),s(Pi.entropy),s(Pi.designatedValidators),s(Pi.currentValidators),s(Pi.previousValidators),s(Pi.availabilityAssignment),s(Pi.timeslot),s(Pi.privilegedServices),s(Pi.statistics),s(Pi.accumulationQueue),s(Pi.recentlyAccumulated);for(const[e,s]of t.services.entries()){const{key:t,Codec:i}=Pi.serviceData(e);r.set(t,_e.encodeObject(i,s.getInfo()));for(const t of s.data.preimages.values()){const{key:s,Codec:i}=Pi.servicePreimages(e,t.hash);r.set(s,_e.encodeObject(i,t.blob))}for(const t of s.data.storage.values()){const{key:s,Codec:i}=Pi.serviceStorage(e,t.hash);r.set(s,_e.encodeObject(i,t.blob))}for(const t of s.data.lookupHistory.values())for(const s of t){const{key:t,Codec:i}=Pi.serviceLookupHistory(e,s.hash,s.length);r.set(t,_e.encodeObject(i,s.slots.slice()))}}return r}const nn=Pe.object({hash:Pe.bytes(Ct).asOpaque(),length:Pe.u32,slots:De(Pe.sequenceVarLen(Pe.u32.asOpaque())).convert(F,pi)},"LookupHistoryItem",({hash:e,length:t,slots:r})=>new gi(e,t,r)),on=Pe.object({key:Pe.bytes(Ct).asOpaque(),data:Pe.sequenceVarLen(nn)}),an=Pe.sequenceVarLen(on).convert(e=>{const t=[];for(const[r,s]of e)t.push({key:r,data:s});return t},e=>{const t=rr.new();for(const{key:r,data:s}of e){const e=t.get(r)??[];e.push(...s),t.set(r,e)}return t});class cn extends Oi{static Codec=Pe.Class(cn,{serviceId:Pe.u32.asOpaque(),data:Pe.object({info:ui.Codec,preimages:gr(di.Codec,e=>e.hash),lookupHistory:an,storage:gr(fi.Codec,e=>e.hash)})});constructor(e,t){super(e,t)}static create({serviceId:e,data:t}){return new cn(e,t)}}var ln,hn,un;Pe.Class(Ui,{authPools:Pi.authPools.Codec,authQueues:Pi.authQueues.Codec,recentBlocks:Pi.recentBlocks.Codec,nextValidatorData:Jr(oi.Codec),epochRoot:Pe.bytes(St).asOpaque(),sealingKeySeries:li.Codec,ticketsAccumulator:De(Pe.sequenceVarLen(es.Codec)).convert(e=>e,ir),disputesRecords:Pi.disputesRecords.Codec,entropy:Pi.entropy.Codec,designatedValidatorData:Pi.designatedValidators.Codec,currentValidatorData:Pi.currentValidators.Codec,previousValidatorData:Pi.previousValidators.Codec,availabilityAssignment:Pi.availabilityAssignment.Codec,timeslot:Pi.timeslot.Codec,privilegedServices:Pi.privilegedServices.Codec,statistics:Pi.statistics.Codec,accumulationQueue:Pi.accumulationQueue.Codec,recentlyAccumulated:Pi.recentlyAccumulated.Codec,services:Pe.dictionary(Pe.u32.asOpaque(),cn.Codec,{sortKeys:(e,t)=>e-t})}),function(e){e[e.Conflict=0]="Conflict",e[e.Commit=1]="Commit"}(ln||(ln={}));class dn{dict;static fromEntries(e){const t=e.map(([e,t])=>{const r=Y.zero(Ct).asOpaque();return r.raw.set(e.raw.subarray(0,Fi)),[r,t]});return new dn(rr.fromEntries(t))}truncatedKey=Y.zero(Ct).asOpaque();constructor(e){this.dict=e}get(e){return this.truncatedKey.raw.set(e.raw.subarray(0,Fi)),this.dict.get(this.truncatedKey)}[Symbol.iterator](){return this.dict[Symbol.iterator]()}}!function(e){e[e.InvalidLeafData=0]="InvalidLeafData"}(hn||(hn={})),function(e){e[e.EmbeddedValue=0]="EmbeddedValue",e[e.DbKey=1]="DbKey"}(un||(un={}));class fn{leaves;db;static fromLeavesBlob(e,t){if(e.length%64!=0)return z.error(hn.InvalidLeafData,`${e.length} is not a multiply of 64: ${e}`);const r=[];for(const t of e.chunks(64)){const e=new ji(t.raw);if(e.getNodeType()===$i.Branch)return z.error(hn.InvalidLeafData,`Branch node detected: ${t}`);r.push(e.asLeafNode())}return z.ok(new fn(r,t))}lookup;constructor(e,t){this.leaves=e,this.db=t,this.lookup=dn.fromEntries(e.map(e=>[e.getKey().asOpaque(),e.hasEmbeddedValue()?{kind:un.EmbeddedValue,value:e.getValue()}:{kind:un.DbKey,key:e.getValueHash().raw}]))}get(e){const t=this.lookup.get(e);return void 0===t?null:t.kind===un.EmbeddedValue?t.value:t.kind===un.DbKey?J.blobFrom(this.db.get(t.key)):void L(t)}getStateRoot(){return Ji.computeStateRoot(tn,this.leaves).asOpaque()}}const pn="best hash and posterior state root";class gn{chainSpec;root;extrinsics;headers;postStateRoots;constructor(e,t){this.chainSpec=e,this.root=t,this.extrinsics=this.root.subDb("extrinsics"),this.headers=this.root.subDb("headers"),this.postStateRoots=this.root.subDb("postStateRoots")}async setPostStateRoot(e,t){await this.postStateRoots.put(e.raw,t.raw)}getPostStateRoot(e){const t=this.postStateRoots.get(e.raw);return void 0===t?null:Y.fromBlob(t,Ct).asOpaque()}async insertBlock(e){const t=e.data.header.view().encoded(),r=e.data.extrinsic.view().encoded();await this.root.db.transaction(()=>{this.headers.put(e.hash.raw,t.raw),this.extrinsics.put(e.hash.raw,r.raw)})}async setBestHeaderHash(e){await this.root.db.put(pn,e.raw)}getBestHeaderHash(){const e=this.root.db.get(pn);return void 0===e?Y.zero(Ct).asOpaque():Y.fromBlob(e,Ct).asOpaque()}getHeader(e){const t=this.headers.get(e.raw);return void 0===t?null:we.decodeObject(ns.Codec.View,t,this.chainSpec)}getExtrinsic(e){const t=this.extrinsics.get(e.raw);return void 0===t?null:we.decodeObject(hs.Codec.View,t,this.chainSpec)}}const yn=(e=>{var t={};return o.d(t,e),t})({open:()=>s.open});class mn{db;constructor(e,t=!1){this.db=yn.open(e,{compression:!0,keyEncoding:"binary",encoding:"binary",readOnly:t})}subDb(e){return this.db.openDB({name:e})}}class bn{spec;root;states;values;constructor(e,t){this.spec=e,this.root=t,this.states=this.root.subDb("states"),this.values=this.root.subDb("values")}async insertState(e,t){const r=Ji.empty(tn);return await this.updateAndCommit(e,r,Array.from(t.entries.data).map(e=>[Hi.Insert,e[0],e[1]]))}async updateAndCommit(e,t,r){const s=[];for(const[e,i,n]of r)if(e===Hi.Insert){const e=t.set(i.asOpaque(),n);e.hasEmbeddedValue()||s.push([e.getValueHash(),n])}else e===Hi.Remove?t.remove(i.asOpaque()):L(e);const i=J.blobFromParts(Array.from(t.nodes.leaves()).map(e=>e.node.raw)),n=this.states.put(e.raw,i.raw),o=this.values.transaction(()=>{for(const[e,t]of s)this.values.put(e.raw,t.raw)});try{await Promise.all([o,n])}catch(e){return console.error(e),z.error(ln.Commit)}return z.ok($)}async updateAndSetState(e,t,r){const s=Ji.fromLeaves(tn,t.backend.leaves),i=function*(e,t){yield*function*(e,t){function r(t,r){return[Hi.Insert,r.key,_e.encodeObject(r.Codec,t,e)]}void 0!==t.authPools&&(yield r(t.authPools,Pi.authPools)),void 0!==t.authQueues&&(yield r(t.authQueues,Pi.authQueues)),void 0!==t.recentBlocks&&(yield r(t.recentBlocks,Pi.recentBlocks));const s=function(e,t,r,s){if(void 0!==e&&void 0!==t&&void 0!==r&&void 0!==s)return hi.create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s});if([e,t,r,s].some(e=>void 0!==e))throw new Error("SafroleData needs to be updated all at once!")}(t.nextValidatorData,t.epochRoot,t.sealingKeySeries,t.ticketsAccumulator);void 0!==s&&(yield r(s,Pi.safrole)),void 0!==t.disputesRecords&&(yield r(t.disputesRecords,Pi.disputesRecords)),void 0!==t.entropy&&(yield r(t.entropy,Pi.entropy)),void 0!==t.designatedValidatorData&&(yield r(t.designatedValidatorData,Pi.designatedValidators)),void 0!==t.currentValidatorData&&(yield r(t.currentValidatorData,Pi.currentValidators)),void 0!==t.previousValidatorData&&(yield r(t.previousValidatorData,Pi.previousValidators)),void 0!==t.availabilityAssignment&&(yield r(t.availabilityAssignment,Pi.availabilityAssignment)),void 0!==t.timeslot&&(yield r(t.timeslot,Pi.timeslot)),void 0!==t.privilegedServices&&(yield r(t.privilegedServices,Pi.privilegedServices)),void 0!==t.statistics&&(yield r(t.statistics,Pi.statistics)),void 0!==t.accumulationQueue&&(yield r(t.accumulationQueue,Pi.accumulationQueue)),void 0!==t.recentlyAccumulated&&(yield r(t.recentlyAccumulated,Pi.recentlyAccumulated))}(e,t);const r=(t,r)=>_e.encodeObject(t,r,e);yield*function*(e,t){for(const{action:r,serviceId:s}of e??[]){const e=Pi.serviceData(s);if(yield[Hi.Insert,e.key,t(e.Codec,r.account)],r.kind===mi.Create&&null!==r.lookupHistory){const{lookupHistory:e}=r,i=Pi.serviceLookupHistory(s,e.hash,e.length);yield[Hi.Insert,i.key,t(i.Codec,e.slots)]}}}(t.servicesUpdates,r),yield*function*(e,t){for(const{action:r,serviceId:s}of e??[])switch(r.kind){case yi.Provide:{const{hash:e,blob:i}=r.preimage,n=Pi.servicePreimages(s,e);if(yield[Hi.Insert,n.key,i],null!==r.slot){const n=Pi.serviceLookupHistory(s,e,pe(i.length));yield[Hi.Insert,n.key,t(n.Codec,pi([r.slot]))]}break}case yi.UpdateOrAdd:{const{hash:e,length:i,slots:n}=r.item,o=Pi.serviceLookupHistory(s,e,i);yield[Hi.Insert,o.key,t(o.Codec,n)];break}case yi.Remove:{const{hash:e,length:t}=r,i=Pi.servicePreimages(s,e);yield[Hi.Remove,i.key,Ki];const n=Pi.serviceLookupHistory(s,e,t);yield[Hi.Remove,n.key,Ki];break}default:L(r)}}(t.preimages,r),yield*function*(e){for(const{action:t,serviceId:r}of e??[])switch(t.kind){case bi.Set:{const e=Pi.serviceStorage(r,t.storage.hash);yield[Hi.Insert,e.key,t.storage.blob];break}case bi.Remove:{const e=Pi.serviceStorage(r,t.key);yield[Hi.Remove,e.key,Ki];break}default:L(t)}}(t.storage),yield*function*(e){for(const t of e??[]){const e=Pi.serviceData(t);yield[Hi.Remove,e.key,Ki]}}(t.servicesRemoved)}(this.spec,r);return await this.updateAndCommit(e,s,i)}async getStateRoot(e){return e.backend.getStateRoot()}getState(e){const t=this.states.get(e.raw);if(void 0===t)return null;const r=this.values,s=fn.fromLeavesBlob(J.blobFrom(t),{get(e){const t=r.get(e);if(void 0===t)throw new Error(`Missing required value: ${J.blobFrom(e)} in the DB`);return t}});if(s.isError)throw new Error(`Inconsistent DB. Invalid leaf nodes for ${e}: ${q(s)}`);return Vi.new(this.spec,s.ok)}}const An=t(import.meta.url)("node:events"),In=2**32,vn=m.new(void 0,"state-machine/port");class wn{port;listeners=new An.EventEmitter;responseListeners=new An.EventEmitter;messageId=0;constructor(e){this.port=e,e.on("message",e=>{try{this.dispatchPortMessage(e)}catch(t){throw vn.error(`[${this.constructor.name}] Failed to dispatch a message: ${t}: ${JSON.stringify(e)}`),t}})}async sendRequest(e,t,r,s){const[i,n]=this.prepareRequest(e,t,r);return this.postMessage(i,s),n}sendSignal(e,t,r,s){this.messageId=(this.messageId+1)%In,this.messageId>>>=0,this.postMessage({kind:"signal",name:t,id:this.messageId,localState:e,data:r},s)}prepareRequest(e,t,r){this.messageId+=1;const s=new Promise((e,t)=>{this.responseListeners.once(Sn(this.messageId),(r,s)=>null!==r?t(r):e(s))});return[{kind:"request",id:this.messageId,name:t,localState:e,data:r},s]}respond(e,t,r){M("request"===t.kind),this.postMessage({kind:"response",id:t.id,name:t.name,data:r,localState:e})}close(){this.cleanup("closing"),this.listeners.removeAllListeners(),this.port.close()}postMessage(e,t){try{this.port.postMessage(e,t)}catch(t){throw vn.error(`[${this.constructor.name}] Failed to post a message: ${t}: ${JSON.stringify(e)}`),t}}dispatchPortMessage(e){if(!function(e){return null!==e&&"object"==typeof e&&"kind"in e&&"string"==typeof e.kind&&"id"in e&&"number"==typeof e.id&&"name"in e&&"string"==typeof e.name&&"data"in e&&"localState"in e&&"string"==typeof e.localState}(e))throw new Error(`Invalid message: ${JSON.stringify(e)}.`);switch(e.kind){case"response":M(-1!==this.responseListeners.eventNames().indexOf(Sn(e.id))),this.responseListeners.emit(Sn(e.id),null,e.data,e.name,e.localState,e);break;case"signal":this.listeners.emit("signal",e.name,e.data,e.localState,e);break;case"request":this.listeners.emit("request",e.name,e.data,e.localState,e);break;case"subscription":case"subscribe":throw new Error("unimplemented");default:throw new Error(`Unexpected message: "${e.kind}"`)}}cleanup(e){const t=this.responseListeners.eventNames();for(const r in t)this.responseListeners.emit(r,new Error(`port is ${e}`))}}function Sn(e){return`req:${e}`}const En=m.new(void 0,"state-machine"),Cn="channel";class kn{machine;port;constructor(e,t){this.machine=e,this.port=t,t.listeners.on("signal",(e,t,r)=>{try{this.dispatchSignal(e,t)}catch(t){throw En.error(`[${this.constructor.name}] Unable to dispatch signal (${e}): ${t}. ${this.stateInfo(r)}`),t}}),t.listeners.on("request",async(e,t,r,s)=>{try{await this.dispatchRequest(e,t,s)}catch(t){throw En.error(`[${this.constructor.name}] Unable to dispatch request (${e}): ${t}. ${this.stateInfo(r)}`),t}})}sendSignal(e,t){this.port.sendSignal(this.currentState().stateName,e,t)}async sendRequest(e,t){return this.port.sendRequest(this.currentState().stateName,e,t)}close(){this.port.close()}getState(e){return this.machine.getState(e)}currentState(){return this.machine.currentState()}async waitForState(e){return await this.machine.waitForState(e),this.transitionTo()}async doUntil(e,t){const r={isDone:!1},s=this.waitForState(e).then(()=>{r.isDone=!0});return await t(this.currentState(),this,()=>r.isDone),await s,this.transitionTo()}transition(e){const t=e(this.currentState(),this);return this.machine.transition(t.state,t.data),this.transitionTo()}stateInfo(e){return` (local state: "${this.currentState()}", remote state: "${e}")`}async dispatchRequest(e,t,r){const s=this.currentState(),i=s.requestHandlers.get(e);if(void 0===i)throw new Error(`Missing request handler for "${e}"`);const n=await i(t),o=this.currentState()!==s;if(void 0!==n.transitionTo&&this.machine.transition(n.transitionTo.state,n.transitionTo.data),!o)return this.port.respond(s.stateName,r,n.response);En.warn(`Ignoring obsolete response for an old request: "${e}"`)}dispatchSignal(e,t){const r=this.currentState().signalListeners.get(e);if(void 0===r)throw new Error(`Unexpected signal "${e}"`);const s=r(t);void 0!==s&&this.machine.transition(s.state,s.data)}transitionTo(){return En.trace(`[${this.machine.name}] transitioned to ${this.currentState()}`),this}static async createAndTransferChannel(e,t){const r=new T.MessageChannel,s=new wn(r.port2),i=e.currentState().stateName,[n,o]=s.prepareRequest(i,Cn,r.port1);t.postMessage(n,[r.port1]);try{await o}catch(e){En.error(JSON.stringify(e))}return new kn(e,s)}static async receiveChannel(e,t){if(null===t)throw new Error("This code is expected to be run in a worker.");const r=new Promise((r,s)=>{t.once("message",t=>{try{M("request"===t.kind,"The initial message should be a request with channel."),M(t.name===Cn),M(t.data instanceof T.MessagePort);const s=new wn(t.data);s.respond(e.currentState().stateName,t,"OK"),r(s)}catch(e){s(e)}})}),s=await r;return new kn(e,s)}}const xn=Symbol(),_n=Symbol();class Bn{emitter=new An.EventEmitter;emit(e){this.emitter.emit(xn,e)}on(e){return this.emitter.on(xn,e),this}once(e){return this.emitter.once(xn,e),this}onceDone(e){return this.emitter.once(_n,e),this}markDone(){this.emitter.emit(_n),this.emitter.removeAllListeners(xn),this.emitter.removeAllListeners(_n)}}class Rn{name;state;allStates;stateListeners=new An.EventEmitter;constructor(e,t,r){this.name=e,this.state=t,this.allStates=new Map;for(const e of r)this.allStates.set(e.stateName,e)}getState(e){const t=this.allStates.get(e);return M(void 0!==t,`Unable to retrieve state object for ${e}.`),t}currentState(){return this.state}waitForState(e){if(this.state.stateName===e)throw new Error(`Attempting to await a state that is already active: ${e}`);return new Promise(t=>{this.stateListeners.once(e,t)})}transition(e,t){if(this.state.stateName===e)throw new Error("Attempting transition to already active state!");if(!this.state.canTransitionTo(e))throw new Error(`Unallowed transition from ${this.state} to ${e}`);const r=this.allStates.get(e);if(void 0===r)throw new Error(`Unavailable state: ${e}`);r.onActivation(t);const s=this.transitionTo(r);return s.stateListeners.emit(e,s),s}transitionTo(e){return this.state=e,this}}const On=m.new(void 0,"state-machine/state");class Un{stateName;signalListeners;requestHandlers;allowedTransitions;data=null;constructor({name:e,signalListeners:t={},requestHandlers:r={},allowedTransitions:s=[]}){this.stateName=e,this.allowedTransitions=s,this.signalListeners=new Map(Object.entries(t)),this.requestHandlers=new Map(Object.entries(r))}onActivation(e){On.trace(`[${this.constructor.name}] Changing state to: ${this}`),this.data=e}canTransitionTo(e){return-1!==this.allowedTransitions.indexOf(e)}toString(){return`<State ${this.stateName}>`}}class Tn extends Un{constructor(){super({name:"finished"})}close(e){e.close()}async waitForWorkerToFinish(){return this.data}}class Nn extends Un{readyName;constructor(e){super({name:"init(main)",allowedTransitions:[e]}),this.readyName=e}sendConfig(e,t){return e.sendSignal("config",t),{state:this.readyName,data:t}}}class Dn extends Un{workerReadyName;handleConfig;constructor(e,t){super({name:"init(worker)",allowedTransitions:[e],signalListeners:{config:e=>this.onConfig(e)}}),this.workerReadyName=e,this.handleConfig=t}onConfig(e){return{state:this.workerReadyName,data:this.handleConfig(e)}}}async function Mn(e,t,r,s){const i=new T.Worker(e),n=function(e,t,r){const s=new Nn(t),i=new Tn;return new Rn(e,s,[s,r,i])}(`main->${r}`,r,s),o=await kn.createAndTransferChannel(n,i);return t.trace(`[${n.name}] Worker spawned ${o.currentState()}`),o}const Pn=4294967295,Ln=4294967296,Hn=4096,Kn=(M(!0,"incorrect minimal allocation shift"),7),Qn=Hn>>Kn,Vn=1048575,Fn=1048576,$n=e=>P(e,e>=0&&e<=Pn,`Incorrect memory index: ${e}!`),jn=e=>P(e,e>=0&&e<=4294967296,`Incorrect sbrk index: ${e}!`);var Gn,qn;(qn=Gn||(Gn={}))[qn.OK=255]="OK",qn[qn.HALT=0]="HALT",qn[qn.PANIC=1]="PANIC",qn[qn.FAULT=2]="FAULT",qn[qn.HOST=3]="HOST",qn[qn.OOG=4]="OOG";const zn=e=>pe(e);var Wn,Jn;!function(e){e[e.Halt=0]="Halt",e[e.Panic=1]="Panic"}(Wn||(Wn={}));class Yn{lookupTableForward;constructor(e){this.lookupTableForward=this.buildLookupTableForward(e)}isInstruction(e){return 0===this.lookupTableForward[e]}getNoOfBytesToNextInstruction(e){return M(e>=0,`index (${e}) cannot be a negative number`),Math.min(this.lookupTableForward[e]??0,25)}buildLookupTableForward(e){const t=new Uint8Array(e.bitLength);let r=0;for(let s=e.bitLength-1;s>=0;s--)e.isSet(s)?r=0:r++,t[s]=r;return t}static empty(){return new Yn(le.empty(0))}}!function(e){e[e.NO_ARGUMENTS=0]="NO_ARGUMENTS",e[e.ONE_IMMEDIATE=1]="ONE_IMMEDIATE",e[e.TWO_IMMEDIATES=2]="TWO_IMMEDIATES",e[e.ONE_OFFSET=3]="ONE_OFFSET",e[e.ONE_REGISTER_ONE_IMMEDIATE=4]="ONE_REGISTER_ONE_IMMEDIATE",e[e.ONE_REGISTER_TWO_IMMEDIATES=5]="ONE_REGISTER_TWO_IMMEDIATES",e[e.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET=6]="ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET",e[e.TWO_REGISTERS=7]="TWO_REGISTERS",e[e.TWO_REGISTERS_ONE_IMMEDIATE=8]="TWO_REGISTERS_ONE_IMMEDIATE",e[e.TWO_REGISTERS_ONE_OFFSET=9]="TWO_REGISTERS_ONE_OFFSET",e[e.TWO_REGISTERS_TWO_IMMEDIATES=10]="TWO_REGISTERS_TWO_IMMEDIATES",e[e.THREE_REGISTERS=11]="THREE_REGISTERS",e[e.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE=12]="ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE"}(Jn||(Jn={}));class Xn{u32;i32;u64;i64;view;bytes;constructor(){const e=new ArrayBuffer(8);this.u32=new Uint32Array(e),this.i32=new Int32Array(e),this.u64=new BigUint64Array(e),this.i64=new BigInt64Array(e),this.view=new DataView(e),this.bytes=new Uint8Array(e)}setBytes(e){const t=e.length,r=t>0?128&e[t-1]:0,s=Math.min(t,8),i=0!==r?255:0;for(let t=0;t<s;t++)this.view.setUint8(t,e[t]);for(let e=t;e<8;e++)this.view.setUint8(e,i)}getUnsigned(){return this.u32[0]}getSigned(){return this.i32[0]}getU32(){return this.u32[0]}getI32(){return this.i32[0]}getU64(){return this.u64[0]}getI64(){return this.i64[0]}getBytesAsLittleEndian(){return this.bytes.subarray(0,4)}getExtendedBytesAsLittleEndian(){return this.bytes}}class Zn{bytes;asSigned;asUnsigned;constructor(e=new Uint8Array(104)){this.bytes=e,M(104===e.length,"Invalid size of registers array."),this.asSigned=new BigInt64Array(e.buffer,e.byteOffset),this.asUnsigned=new BigUint64Array(e.buffer,e.byteOffset)}static fromBytes(e){return M(104===e.length,"Invalid size of registers array."),new Zn(e)}getBytesAsLittleEndian(e,t){const r=e<<3;return this.bytes.subarray(r,r+t)}getAllBytesAsLittleEndian(){return this.bytes}copyFrom(e){const t=e instanceof BigUint64Array?e:e.asUnsigned;this.asUnsigned.set(t)}reset(){for(let e=0;e<13;e++)this.asUnsigned[e]=0n}getLowerU32(e){return Number(0xffffffffn&this.asUnsigned[e])}getLowerI32(e){return 0|Number(this.getLowerU32(e))}setU32(e,t){this.asUnsigned[e]=eo(t)}setI32(e,t){this.asSigned[e]=eo(t)}getU64(e){return this.asUnsigned[e]}getI64(e){return this.asSigned[e]}setU64(e,t){this.asUnsigned[e]=t}setI64(e,t){this.asSigned[e]=t}getAllU64(){return this.asUnsigned}}function eo(e){const t="number"==typeof e?BigInt(e):e,r=BigInt(4294967295),s=t&r;return(s&BigInt(2147483648))!==BigInt(0)?s|~r:s}class to{byte=new Int8Array(1);setByte(e){this.byte[0]=e}getHighNibble(){return(240&this.byte[0])>>>4}getLowNibble(){return 15&this.byte[0]}getHighNibbleAsRegisterIndex(){return Math.min(this.getHighNibble(),12)}getLowNibbleAsRegisterIndex(){return Math.min(this.getLowNibble(),12)}getHighNibbleAsLength(){return Math.min(this.getHighNibble(),4)}getLowNibbleAsLength(){return Math.min(this.getLowNibble(),4)}}class ro{nibblesDecoder=new to;offsetDecoder=new Xn;code=new Uint8Array;mask=Yn.empty();reset(e,t){this.code=e,this.mask=t}fillArgs(e,t){const r=1+this.mask.getNoOfBytesToNextInstruction(e+1);switch(t.noOfBytesToSkip=r,t.type){case Jn.NO_ARGUMENTS:break;case Jn.ONE_IMMEDIATE:{const s=Math.min(4,r-1),i=e+1;t.immediateDecoder.setBytes(this.code.subarray(i,i+s));break}case Jn.THREE_REGISTERS:{const r=this.code[e+1],s=this.code[e+2];this.nibblesDecoder.setByte(r),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex(),this.nibblesDecoder.setByte(s),t.thirdRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();break}case Jn.TWO_REGISTERS_ONE_IMMEDIATE:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex();const i=e+2,n=i+Math.min(4,Math.max(0,r-2));t.immediateDecoder.setBytes(this.code.subarray(i,n));break}case Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const i=this.nibblesDecoder.getHighNibbleAsLength(),n=e+2,o=n+i;t.immediateDecoder.setBytes(this.code.subarray(n,o));const a=e+2+i,c=a+Math.min(4,Math.max(0,r-2-i));this.offsetDecoder.setBytes(this.code.subarray(a,c)),t.nextPc=e+this.offsetDecoder.getSigned();break}case Jn.TWO_REGISTERS_ONE_OFFSET:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex();const i=e+2,n=i+Math.min(4,Math.max(0,r-2));this.offsetDecoder.setBytes(this.code.subarray(i,n)),t.nextPc=e+this.offsetDecoder.getSigned();break}case Jn.TWO_REGISTERS:{const r=this.code[e+1];this.nibblesDecoder.setByte(r),t.firstRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();break}case Jn.ONE_OFFSET:{const s=e+1,i=s+Math.min(4,r-1),n=this.code.subarray(s,i);this.offsetDecoder.setBytes(n);const o=this.offsetDecoder.getSigned();t.nextPc=e+o;break}case Jn.ONE_REGISTER_ONE_IMMEDIATE:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const i=e+2,n=i+Math.min(4,Math.max(0,r-2)),o=this.code.subarray(i,n);t.immediateDecoder.setBytes(o);break}case Jn.TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s);const i=this.nibblesDecoder.getLowNibbleAsLength(),n=e+2,o=n+i,a=this.code.subarray(n,o);t.firstImmediateDecoder.setBytes(a);const c=o,l=c+Math.min(4,Math.max(0,r-2-i)),h=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(h);break}case Jn.ONE_REGISTER_TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const i=this.nibblesDecoder.getHighNibbleAsLength(),n=e+2,o=n+i,a=this.code.subarray(n,o);t.firstImmediateDecoder.setBytes(a);const c=o,l=c+Math.min(4,Math.max(0,r-2-i)),h=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(h);break}case Jn.TWO_REGISTERS_TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex();const i=this.code[e+2];this.nibblesDecoder.setByte(i);const n=this.nibblesDecoder.getLowNibbleAsLength(),o=e+3,a=o+n,c=this.code.subarray(o,a);t.firstImmediateDecoder.setBytes(c);const l=a,h=l+Math.min(4,Math.max(0,r-3-n)),u=this.code.subarray(l,h);t.secondImmediateDecoder.setBytes(u);break}case Jn.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE:{const r=this.code[e+1];this.nibblesDecoder.setByte(r),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const s=e+2,i=s+8,n=this.code.subarray(s,i);t.immediateDecoder.setBytes(n);break}}}}class so{unsignedImmediate;bytes;constructor(){const e=new ArrayBuffer(8);this.unsignedImmediate=new BigUint64Array(e),this.bytes=new Uint8Array(e)}setBytes(e){let t=0;for(;t<e.length;t++)this.bytes[t]=e[t];for(;t<8;t++)this.bytes[t]=0}getValue(){return this.unsignedImmediate[0]}getBytesAsLittleEndian(){return this.bytes.subarray(0,8)}}const io=Object.keys(Jn).length/2;var no;!function(e){e[e.TRAP=0]="TRAP",e[e.FALLTHROUGH=1]="FALLTHROUGH",e[e.ECALLI=10]="ECALLI",e[e.LOAD_IMM_64=20]="LOAD_IMM_64",e[e.STORE_IMM_U8=30]="STORE_IMM_U8",e[e.STORE_IMM_U16=31]="STORE_IMM_U16",e[e.STORE_IMM_U32=32]="STORE_IMM_U32",e[e.STORE_IMM_U64=33]="STORE_IMM_U64",e[e.JUMP=40]="JUMP",e[e.JUMP_IND=50]="JUMP_IND",e[e.LOAD_IMM=51]="LOAD_IMM",e[e.LOAD_U8=52]="LOAD_U8",e[e.LOAD_I8=53]="LOAD_I8",e[e.LOAD_U16=54]="LOAD_U16",e[e.LOAD_I16=55]="LOAD_I16",e[e.LOAD_U32=56]="LOAD_U32",e[e.LOAD_I32=57]="LOAD_I32",e[e.LOAD_U64=58]="LOAD_U64",e[e.STORE_U8=59]="STORE_U8",e[e.STORE_U16=60]="STORE_U16",e[e.STORE_U32=61]="STORE_U32",e[e.STORE_U64=62]="STORE_U64",e[e.STORE_IMM_IND_U8=70]="STORE_IMM_IND_U8",e[e.STORE_IMM_IND_U16=71]="STORE_IMM_IND_U16",e[e.STORE_IMM_IND_U32=72]="STORE_IMM_IND_U32",e[e.STORE_IMM_IND_U64=73]="STORE_IMM_IND_U64",e[e.LOAD_IMM_JUMP=80]="LOAD_IMM_JUMP",e[e.BRANCH_EQ_IMM=81]="BRANCH_EQ_IMM",e[e.BRANCH_NE_IMM=82]="BRANCH_NE_IMM",e[e.BRANCH_LT_U_IMM=83]="BRANCH_LT_U_IMM",e[e.BRANCH_LE_U_IMM=84]="BRANCH_LE_U_IMM",e[e.BRANCH_GE_U_IMM=85]="BRANCH_GE_U_IMM",e[e.BRANCH_GT_U_IMM=86]="BRANCH_GT_U_IMM",e[e.BRANCH_LT_S_IMM=87]="BRANCH_LT_S_IMM",e[e.BRANCH_LE_S_IMM=88]="BRANCH_LE_S_IMM",e[e.BRANCH_GE_S_IMM=89]="BRANCH_GE_S_IMM",e[e.BRANCH_GT_S_IMM=90]="BRANCH_GT_S_IMM",e[e.MOVE_REG=100]="MOVE_REG",e[e.SBRK=101]="SBRK",e[e.COUNT_SET_BITS_64=102]="COUNT_SET_BITS_64",e[e.COUNT_SET_BITS_32=103]="COUNT_SET_BITS_32",e[e.LEADING_ZERO_BITS_64=104]="LEADING_ZERO_BITS_64",e[e.LEADING_ZERO_BITS_32=105]="LEADING_ZERO_BITS_32",e[e.TRAILING_ZERO_BITS_64=106]="TRAILING_ZERO_BITS_64",e[e.TRAILING_ZERO_BITS_32=107]="TRAILING_ZERO_BITS_32",e[e.SIGN_EXTEND_8=108]="SIGN_EXTEND_8",e[e.SIGN_EXTEND_16=109]="SIGN_EXTEND_16",e[e.ZERO_EXTEND_16=110]="ZERO_EXTEND_16",e[e.REVERSE_BYTES=111]="REVERSE_BYTES",e[e.STORE_IND_U8=120]="STORE_IND_U8",e[e.STORE_IND_U16=121]="STORE_IND_U16",e[e.STORE_IND_U32=122]="STORE_IND_U32",e[e.STORE_IND_U64=123]="STORE_IND_U64",e[e.LOAD_IND_U8=124]="LOAD_IND_U8",e[e.LOAD_IND_I8=125]="LOAD_IND_I8",e[e.LOAD_IND_U16=126]="LOAD_IND_U16",e[e.LOAD_IND_I16=127]="LOAD_IND_I16",e[e.LOAD_IND_U32=128]="LOAD_IND_U32",e[e.LOAD_IND_I32=129]="LOAD_IND_I32",e[e.LOAD_IND_U64=130]="LOAD_IND_U64",e[e.ADD_IMM_32=131]="ADD_IMM_32",e[e.AND_IMM=132]="AND_IMM",e[e.XOR_IMM=133]="XOR_IMM",e[e.OR_IMM=134]="OR_IMM",e[e.MUL_IMM_32=135]="MUL_IMM_32",e[e.SET_LT_U_IMM=136]="SET_LT_U_IMM",e[e.SET_LT_S_IMM=137]="SET_LT_S_IMM",e[e.SHLO_L_IMM_32=138]="SHLO_L_IMM_32",e[e.SHLO_R_IMM_32=139]="SHLO_R_IMM_32",e[e.SHAR_R_IMM_32=140]="SHAR_R_IMM_32",e[e.NEG_ADD_IMM_32=141]="NEG_ADD_IMM_32",e[e.SET_GT_U_IMM=142]="SET_GT_U_IMM",e[e.SET_GT_S_IMM=143]="SET_GT_S_IMM",e[e.SHLO_L_IMM_ALT_32=144]="SHLO_L_IMM_ALT_32",e[e.SHLO_R_IMM_ALT_32=145]="SHLO_R_IMM_ALT_32",e[e.SHAR_R_IMM_ALT_32=146]="SHAR_R_IMM_ALT_32",e[e.CMOV_IZ_IMM=147]="CMOV_IZ_IMM",e[e.CMOV_NZ_IMM=148]="CMOV_NZ_IMM",e[e.ADD_IMM_64=149]="ADD_IMM_64",e[e.MUL_IMM_64=150]="MUL_IMM_64",e[e.SHLO_L_IMM_64=151]="SHLO_L_IMM_64",e[e.SHLO_R_IMM_64=152]="SHLO_R_IMM_64",e[e.SHAR_R_IMM_64=153]="SHAR_R_IMM_64",e[e.NEG_ADD_IMM_64=154]="NEG_ADD_IMM_64",e[e.SHLO_L_IMM_ALT_64=155]="SHLO_L_IMM_ALT_64",e[e.SHLO_R_IMM_ALT_64=156]="SHLO_R_IMM_ALT_64",e[e.SHAR_R_IMM_ALT_64=157]="SHAR_R_IMM_ALT_64",e[e.ROT_R_64_IMM=158]="ROT_R_64_IMM",e[e.ROT_R_64_IMM_ALT=159]="ROT_R_64_IMM_ALT",e[e.ROT_R_32_IMM=160]="ROT_R_32_IMM",e[e.ROT_R_32_IMM_ALT=161]="ROT_R_32_IMM_ALT",e[e.BRANCH_EQ=170]="BRANCH_EQ",e[e.BRANCH_NE=171]="BRANCH_NE",e[e.BRANCH_LT_U=172]="BRANCH_LT_U",e[e.BRANCH_LT_S=173]="BRANCH_LT_S",e[e.BRANCH_GE_U=174]="BRANCH_GE_U",e[e.BRANCH_GE_S=175]="BRANCH_GE_S",e[e.LOAD_IMM_JUMP_IND=180]="LOAD_IMM_JUMP_IND",e[e.ADD_32=190]="ADD_32",e[e.SUB_32=191]="SUB_32",e[e.MUL_32=192]="MUL_32",e[e.DIV_U_32=193]="DIV_U_32",e[e.DIV_S_32=194]="DIV_S_32",e[e.REM_U_32=195]="REM_U_32",e[e.REM_S_32=196]="REM_S_32",e[e.SHLO_L_32=197]="SHLO_L_32",e[e.SHLO_R_32=198]="SHLO_R_32",e[e.SHAR_R_32=199]="SHAR_R_32",e[e.ADD_64=200]="ADD_64",e[e.SUB_64=201]="SUB_64",e[e.MUL_64=202]="MUL_64",e[e.DIV_U_64=203]="DIV_U_64",e[e.DIV_S_64=204]="DIV_S_64",e[e.REM_U_64=205]="REM_U_64",e[e.REM_S_64=206]="REM_S_64",e[e.SHLO_L_64=207]="SHLO_L_64",e[e.SHLO_R_64=208]="SHLO_R_64",e[e.SHAR_R_64=209]="SHAR_R_64",e[e.AND=210]="AND",e[e.XOR=211]="XOR",e[e.OR=212]="OR",e[e.MUL_UPPER_S_S=213]="MUL_UPPER_S_S",e[e.MUL_UPPER_U_U=214]="MUL_UPPER_U_U",e[e.MUL_UPPER_S_U=215]="MUL_UPPER_S_U",e[e.SET_LT_U=216]="SET_LT_U",e[e.SET_LT_S=217]="SET_LT_S",e[e.CMOV_IZ=218]="CMOV_IZ",e[e.CMOV_NZ=219]="CMOV_NZ",e[e.ROT_L_64=220]="ROT_L_64",e[e.ROT_L_32=221]="ROT_L_32",e[e.ROT_R_64=222]="ROT_R_64",e[e.ROT_R_32=223]="ROT_R_32",e[e.AND_INV=224]="AND_INV",e[e.OR_INV=225]="OR_INV",e[e.XNOR=226]="XNOR",e[e.MAX=227]="MAX",e[e.MAX_U=228]="MAX_U",e[e.MIN=229]="MIN",e[e.MIN_U=230]="MIN_U"}(no||(no={}));const oo=no.MIN_U,ao=(()=>{const e=new Array(oo+1);return e[no.TRAP]=Jn.NO_ARGUMENTS,e[no.FALLTHROUGH]=Jn.NO_ARGUMENTS,e[no.ECALLI]=Jn.ONE_IMMEDIATE,e[no.LOAD_IMM_64]=Jn.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,e[no.STORE_IMM_U8]=Jn.TWO_IMMEDIATES,e[no.STORE_IMM_U16]=Jn.TWO_IMMEDIATES,e[no.STORE_IMM_U32]=Jn.TWO_IMMEDIATES,e[no.STORE_IMM_U64]=Jn.TWO_IMMEDIATES,e[no.JUMP]=Jn.ONE_OFFSET,e[no.JUMP_IND]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_U8]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_I8]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_U16]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_I16]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_U32]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_I32]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.LOAD_U64]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.STORE_U8]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.STORE_U16]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.STORE_U32]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.STORE_U64]=Jn.ONE_REGISTER_ONE_IMMEDIATE,e[no.STORE_IMM_IND_U8]=Jn.ONE_REGISTER_TWO_IMMEDIATES,e[no.STORE_IMM_IND_U16]=Jn.ONE_REGISTER_TWO_IMMEDIATES,e[no.STORE_IMM_IND_U32]=Jn.ONE_REGISTER_TWO_IMMEDIATES,e[no.STORE_IMM_IND_U64]=Jn.ONE_REGISTER_TWO_IMMEDIATES,e[no.LOAD_IMM_JUMP]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_EQ_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_NE_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_LT_U_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_LE_U_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_GE_U_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_GT_U_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_LT_S_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_LE_S_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_GE_S_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.BRANCH_GT_S_IMM]=Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[no.MOVE_REG]=Jn.TWO_REGISTERS,e[no.SBRK]=Jn.TWO_REGISTERS,e[no.COUNT_SET_BITS_64]=Jn.TWO_REGISTERS,e[no.COUNT_SET_BITS_32]=Jn.TWO_REGISTERS,e[no.LEADING_ZERO_BITS_64]=Jn.TWO_REGISTERS,e[no.LEADING_ZERO_BITS_32]=Jn.TWO_REGISTERS,e[no.TRAILING_ZERO_BITS_64]=Jn.TWO_REGISTERS,e[no.TRAILING_ZERO_BITS_32]=Jn.TWO_REGISTERS,e[no.SIGN_EXTEND_8]=Jn.TWO_REGISTERS,e[no.SIGN_EXTEND_16]=Jn.TWO_REGISTERS,e[no.ZERO_EXTEND_16]=Jn.TWO_REGISTERS,e[no.REVERSE_BYTES]=Jn.TWO_REGISTERS,e[no.STORE_IND_U8]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.STORE_IND_U16]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.STORE_IND_U32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.STORE_IND_U64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_U8]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_I8]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_U16]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_I16]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_U32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_I32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.LOAD_IND_U64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.ADD_IMM_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.ADD_IMM_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.AND_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.XOR_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.OR_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.MUL_IMM_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.MUL_IMM_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SET_LT_U_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SET_LT_S_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_L_IMM_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_R_IMM_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHAR_R_IMM_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.NEG_ADD_IMM_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_L_IMM_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_R_IMM_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHAR_R_IMM_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.NEG_ADD_IMM_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SET_GT_U_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SET_GT_S_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_L_IMM_ALT_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_R_IMM_ALT_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHAR_R_IMM_ALT_32]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_L_IMM_ALT_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHLO_R_IMM_ALT_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.SHAR_R_IMM_ALT_64]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.CMOV_IZ_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.CMOV_NZ_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.ROT_R_64_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.ROT_R_64_IMM_ALT]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.ROT_R_32_IMM]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.ROT_R_32_IMM_ALT]=Jn.TWO_REGISTERS_ONE_IMMEDIATE,e[no.BRANCH_EQ]=Jn.TWO_REGISTERS_ONE_OFFSET,e[no.BRANCH_NE]=Jn.TWO_REGISTERS_ONE_OFFSET,e[no.BRANCH_LT_U]=Jn.TWO_REGISTERS_ONE_OFFSET,e[no.BRANCH_LT_S]=Jn.TWO_REGISTERS_ONE_OFFSET,e[no.BRANCH_GE_U]=Jn.TWO_REGISTERS_ONE_OFFSET,e[no.BRANCH_GE_S]=Jn.TWO_REGISTERS_ONE_OFFSET,e[no.LOAD_IMM_JUMP_IND]=Jn.TWO_REGISTERS_TWO_IMMEDIATES,e[no.ADD_32]=Jn.THREE_REGISTERS,e[no.ADD_64]=Jn.THREE_REGISTERS,e[no.SUB_32]=Jn.THREE_REGISTERS,e[no.SUB_64]=Jn.THREE_REGISTERS,e[no.AND]=Jn.THREE_REGISTERS,e[no.XOR]=Jn.THREE_REGISTERS,e[no.OR]=Jn.THREE_REGISTERS,e[no.MUL_32]=Jn.THREE_REGISTERS,e[no.MUL_64]=Jn.THREE_REGISTERS,e[no.MUL_UPPER_S_S]=Jn.THREE_REGISTERS,e[no.MUL_UPPER_U_U]=Jn.THREE_REGISTERS,e[no.MUL_UPPER_S_U]=Jn.THREE_REGISTERS,e[no.DIV_U_32]=Jn.THREE_REGISTERS,e[no.DIV_S_32]=Jn.THREE_REGISTERS,e[no.REM_U_32]=Jn.THREE_REGISTERS,e[no.REM_S_32]=Jn.THREE_REGISTERS,e[no.DIV_U_64]=Jn.THREE_REGISTERS,e[no.DIV_S_64]=Jn.THREE_REGISTERS,e[no.REM_U_64]=Jn.THREE_REGISTERS,e[no.REM_S_64]=Jn.THREE_REGISTERS,e[no.SET_LT_U]=Jn.THREE_REGISTERS,e[no.SET_LT_S]=Jn.THREE_REGISTERS,e[no.SHLO_L_32]=Jn.THREE_REGISTERS,e[no.SHLO_R_32]=Jn.THREE_REGISTERS,e[no.SHAR_R_32]=Jn.THREE_REGISTERS,e[no.SHLO_L_64]=Jn.THREE_REGISTERS,e[no.SHLO_R_64]=Jn.THREE_REGISTERS,e[no.SHAR_R_64]=Jn.THREE_REGISTERS,e[no.CMOV_IZ]=Jn.THREE_REGISTERS,e[no.CMOV_NZ]=Jn.THREE_REGISTERS,e[no.ROT_L_64]=Jn.THREE_REGISTERS,e[no.ROT_L_32]=Jn.THREE_REGISTERS,e[no.ROT_R_64]=Jn.THREE_REGISTERS,e[no.ROT_R_32]=Jn.THREE_REGISTERS,e[no.AND_INV]=Jn.THREE_REGISTERS,e[no.OR_INV]=Jn.THREE_REGISTERS,e[no.XNOR]=Jn.THREE_REGISTERS,e[no.MAX]=Jn.THREE_REGISTERS,e[no.MAX_U]=Jn.THREE_REGISTERS,e[no.MIN]=Jn.THREE_REGISTERS,e[no.MIN_U]=Jn.THREE_REGISTERS,e})(),co=e=>pe(e),lo=e=>ye(e),ho=e=>"number"==typeof e&&e<2**32?co(e):lo(e);function uo(e){return new fo(ye(e))}class fo{gas;constructor(e){this.gas=e}set(e){this.gas=ye(e)}get(){return ho(this.gas)}sub(e){return this.gas=ye(this.gas-ye(e)),this.gas<0n}}const po=[[no.TRAP,1],[no.FALLTHROUGH,1],[no.ECALLI,1],[no.LOAD_IMM_64,1],[no.STORE_IMM_U8,1],[no.STORE_IMM_U16,1],[no.STORE_IMM_U32,1],[no.STORE_IMM_U64,1],[no.JUMP,1],[no.JUMP_IND,1],[no.LOAD_IMM,1],[no.LOAD_U8,1],[no.LOAD_I8,1],[no.LOAD_U16,1],[no.LOAD_I16,1],[no.LOAD_U32,1],[no.LOAD_I32,1],[no.LOAD_U64,1],[no.STORE_U8,1],[no.STORE_U16,1],[no.STORE_U32,1],[no.STORE_U64,1],[no.STORE_IMM_IND_U8,1],[no.STORE_IMM_IND_U16,1],[no.STORE_IMM_IND_U32,1],[no.STORE_IMM_IND_U64,1],[no.LOAD_IMM_JUMP,1],[no.BRANCH_EQ_IMM,1],[no.BRANCH_NE_IMM,1],[no.BRANCH_LT_U_IMM,1],[no.BRANCH_LE_U_IMM,1],[no.BRANCH_GE_U_IMM,1],[no.BRANCH_GT_U_IMM,1],[no.BRANCH_LT_S_IMM,1],[no.BRANCH_LE_S_IMM,1],[no.BRANCH_GE_S_IMM,1],[no.BRANCH_GT_S_IMM,1],[no.MOVE_REG,1],[no.SBRK,1],[no.COUNT_SET_BITS_64,1],[no.COUNT_SET_BITS_32,1],[no.LEADING_ZERO_BITS_64,1],[no.LEADING_ZERO_BITS_32,1],[no.TRAILING_ZERO_BITS_64,1],[no.TRAILING_ZERO_BITS_32,1],[no.SIGN_EXTEND_8,1],[no.SIGN_EXTEND_16,1],[no.ZERO_EXTEND_16,1],[no.REVERSE_BYTES,1],[no.STORE_IND_U8,1],[no.STORE_IND_U16,1],[no.STORE_IND_U32,1],[no.STORE_IND_U64,1],[no.LOAD_IND_U8,1],[no.LOAD_IND_I8,1],[no.LOAD_IND_U16,1],[no.LOAD_IND_I16,1],[no.LOAD_IND_U32,1],[no.LOAD_IND_I32,1],[no.LOAD_IND_U64,1],[no.ADD_IMM_32,1],[no.AND_IMM,1],[no.XOR_IMM,1],[no.OR_IMM,1],[no.MUL_IMM_32,1],[no.SET_LT_U_IMM,1],[no.SET_LT_S_IMM,1],[no.SHLO_L_IMM_32,1],[no.SHLO_R_IMM_32,1],[no.SHAR_R_IMM_32,1],[no.NEG_ADD_IMM_32,1],[no.SET_GT_U_IMM,1],[no.SET_GT_S_IMM,1],[no.SHLO_L_IMM_ALT_32,1],[no.SHLO_R_IMM_ALT_32,1],[no.SHAR_R_IMM_ALT_32,1],[no.CMOV_IZ_IMM,1],[no.CMOV_NZ_IMM,1],[no.ADD_IMM_64,1],[no.MUL_IMM_64,1],[no.SHLO_L_IMM_64,1],[no.SHLO_R_IMM_64,1],[no.SHAR_R_IMM_64,1],[no.NEG_ADD_IMM_64,1],[no.SHLO_L_IMM_ALT_64,1],[no.SHLO_R_IMM_ALT_64,1],[no.SHAR_R_IMM_ALT_64,1],[no.ROT_R_64_IMM,1],[no.ROT_R_64_IMM_ALT,1],[no.ROT_R_32_IMM,1],[no.ROT_R_32_IMM_ALT,1],[no.BRANCH_EQ,1],[no.BRANCH_NE,1],[no.BRANCH_LT_U,1],[no.BRANCH_LT_S,1],[no.BRANCH_GE_U,1],[no.BRANCH_GE_S,1],[no.LOAD_IMM_JUMP_IND,1],[no.ADD_32,1],[no.SUB_32,1],[no.MUL_32,1],[no.DIV_U_32,1],[no.DIV_S_32,1],[no.REM_U_32,1],[no.REM_S_32,1],[no.SHLO_L_32,1],[no.SHLO_R_32,1],[no.SHAR_R_32,1],[no.ADD_64,1],[no.SUB_64,1],[no.MUL_64,1],[no.DIV_U_64,1],[no.DIV_S_64,1],[no.REM_U_64,1],[no.REM_S_64,1],[no.SHLO_L_64,1],[no.SHLO_R_64,1],[no.SHAR_R_64,1],[no.AND,1],[no.XOR,1],[no.OR,1],[no.MUL_UPPER_S_S,1],[no.MUL_UPPER_U_U,1],[no.MUL_UPPER_S_U,1],[no.SET_LT_U,1],[no.SET_LT_S,1],[no.CMOV_IZ,1],[no.CMOV_NZ,1],[no.ROT_L_64,1],[no.ROT_L_32,1],[no.ROT_R_64,1],[no.ROT_R_32,1],[no.AND_INV,1],[no.OR_INV,1],[no.XNOR,1],[no.MAX,1],[no.MAX_U,1],[no.MIN,1],[no.MIN_U,1]].reduce((e,t)=>{const[r,s]=(([e,t])=>[e,{gas:co(t)}])(t);return e[r]=s,e},{}),go=(()=>{const e=new Array(oo+1);return e.fill(!1),e[no.TRAP]=!0,e[no.FALLTHROUGH]=!0,e[no.JUMP]=!0,e[no.JUMP_IND]=!0,e[no.LOAD_IMM_JUMP]=!0,e[no.LOAD_IMM_JUMP_IND]=!0,e[no.BRANCH_EQ]=!0,e[no.BRANCH_NE]=!0,e[no.BRANCH_GE_U]=!0,e[no.BRANCH_GE_S]=!0,e[no.BRANCH_LT_U]=!0,e[no.BRANCH_LT_S]=!0,e[no.BRANCH_EQ_IMM]=!0,e[no.BRANCH_NE_IMM]=!0,e[no.BRANCH_LT_U_IMM]=!0,e[no.BRANCH_LT_S_IMM]=!0,e[no.BRANCH_LE_U_IMM]=!0,e[no.BRANCH_LE_S_IMM]=!0,e[no.BRANCH_GE_U_IMM]=!0,e[no.BRANCH_GE_S_IMM]=!0,e[no.BRANCH_GT_U_IMM]=!0,e[no.BRANCH_GT_S_IMM]=!0,e})();class yo{basicBlocks=new Set;reset(e,t){this.basicBlocks.clear(),this.basicBlocks.add(0);const r=e.length,s=r=>t.isInstruction(r)&&go[e[r]];for(let e=0;e<r;e++)t.isInstruction(e)&&s(e)&&this.basicBlocks.add(e+1+t.getNoOfBytesToNextInstruction(e+1))}isBeginningOfBasicBlock(e){return this.basicBlocks.has(e)}}const mo=(()=>{const e=new Array(oo+1);for(let t=0;t<oo+1;t++){const r=po[t]?.gas;e[t]=r}return e})();class bo{nextPc=0;status=null;exitParam=null;reset(){this.nextPc=0,this.status=null,this.exitParam=null}}const Ao=e=>P(e,e>=0&&e<Hn,`Incorect page index: ${e}!`),Io=e=>P(e,e>=0&&e<=Vn,`Incorrect page number: ${e}!`);function vo(e){return Io(e===Vn?0:e+1)}function wo(e){return Hn*Math.ceil(e/Hn)}function So(e){return Io(e>>>12)}function Eo(e){return $n(e>>>12<<12)}function Co(e){return $n(e<<12>>>0)}class ko{address;isAccessFault;constructor(e,t=!0){this.address=e,this.isAccessFault=t}static fromPageNumber(e,t=!1){const r=Co(Io(e));return new ko(r,t)}static fromMemoryIndex(e,t=!1){const r=Eo($n(e%Ln));return new ko(r,t)}}class xo extends Error{constructor(){super("Out of bounds")}}Error,Error;class _o extends Error{constructor(){super("Space between sbrk index and max heap index should be empty!")}}class Bo extends Error{constructor(){super("MemoryBuilder was finalized and cannot be changed!")}}class Ro extends Error{constructor(){super("You are trying to access reserved memory!")}}class Oo extends Error{constructor(){super("You try to fill data on memory page that does not exist!")}}Error;class Uo extends Error{constructor(){super("Out of memory")}}class To{start;length;end;lastIndex=null;constructor(e,t){this.start=e,this.length=t,this.end=$n((this.start+this.length)%Ln),t>0&&(this.lastIndex=$n((this.end-1+Ln)%Ln))}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>Ln)throw new TypeError(`length must be a non-negative integer and less than 4294967296, got ${t}`);return new To(e,t)}isEmpty(){return 0===this.length}isWrapped(){return this.start>=this.end&&!this.isEmpty()}isInRange(e){return this.isWrapped()?e>=this.start||e<this.end:e>=this.start&&e<this.end}overlapsWith(e){return null!==this.lastIndex&&null!==e.lastIndex&&(this.isInRange(e.start)||this.isInRange(e.lastIndex)||e.isInRange(this.start)||e.isInRange(this.lastIndex))}}const No=To.fromStartAndLength($n(0),65536);class Do{start;length;end;constructor(e,t){this.start=e,this.length=t,this.end=Io((this.start+this.length)%Fn)}static fromMemoryRange(e){const t=So(e.start);if(e.isEmpty())return new Do(t,0);const r=So(e.lastIndex??e.end),s=vo(r);if((t===s||t===r)&&e.length>Hn)return new Do(t,Fn);const i=t<s?s-t:Fn-t+s;return Do.fromStartAndLength(t,i)}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>Fn)throw new TypeError(`length must be a non-negative integer and less than 1048576, got ${t}`);return new Do(e,t)}isEmpty(){return 0===this.length}*[Symbol.iterator](){if(this.isEmpty())return;const e=this.end;let t=this.start;do{yield t,t=vo(t)}while(t!==e)}}class Mo{start;constructor(e){this.start=Co(e)}}class Po extends Mo{data;constructor(e,t){super(e),this.data=t}loadInto(e,t,r){const s=t+r;if(s>Hn)return z.error(ko.fromMemoryIndex(this.start+Hn));const i=this.data.subarray(t,s);return e.fill(0,i.length,r),e.set(i),z.ok($)}storeFrom(e,t){return z.error(ko.fromMemoryIndex(this.start,!0))}setData(e,t){this.data.set(t,e)}isWriteable(){return!1}getPageDump(){return this.data}}class Lo extends Mo{buffer;view;constructor(e,t){super(e);const r=t?.length??0,s=Math.min(Hn,Math.max(r,Qn));this.buffer=new ArrayBuffer(s,{maxByteLength:Hn}),this.view=new Uint8Array(this.buffer),void 0!==t&&this.view.set(t)}loadInto(e,t,r){const s=t+r;if(s>Hn)return z.error(ko.fromMemoryIndex(this.start+Hn));const i=this.view.subarray(t,s);return e.fill(0,i.length,r),e.set(i),z.ok($)}storeFrom(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Hn){const r=Math.min(Hn,Math.max(Qn,e+t.length));this.buffer.resize(r)}return this.view.set(t,e),z.ok($)}setData(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Hn){const r=Math.min(Hn,Math.max(Qn,e+t.length));this.buffer.resize(r)}this.view.set(t,e)}isWriteable(){return!0}getPageDump(){return this.view}}var Ho;!function(e){e[e.READ=0]="READ",e[e.WRITE=1]="WRITE"}(Ho||(Ho={}));class Ko{sbrkIndex;virtualSbrkIndex;endHeapIndex;memory;static fromInitialMemory(e){return new Ko(e?.sbrkIndex,e?.sbrkIndex,e?.endHeapIndex,e?.memory)}constructor(e=jn(No.end),t=jn(No.end),r=jn(Pn),s=new Map){this.sbrkIndex=e,this.virtualSbrkIndex=t,this.endHeapIndex=r,this.memory=s}reset(){this.sbrkIndex=jn(No.end),this.virtualSbrkIndex=jn(No.end),this.endHeapIndex=jn(Pn),this.memory=new Map}copyFrom(e){this.sbrkIndex=e.sbrkIndex,this.virtualSbrkIndex=e.virtualSbrkIndex,this.endHeapIndex=e.endHeapIndex,this.memory=e.memory}storeFrom(e,t){if(0===t.length)return z.ok($);const r=this.getPages(e,t.length,Ho.WRITE);if(r.isError)return z.error(r.error);const s=r.ok;let i=e,n=t.length;for(const r of s){const s=Ao(i%Hn),o=Math.min(Hn-s,n),a=i-e,c=t.subarray(a,a+o);r.storeFrom(s,c),i+=o,n-=o}return z.ok($)}getPages(e,t,r){if(0===t)return z.ok([]);const s=To.fromStartAndLength(e,t),i=Do.fromMemoryRange(s),n=[];for(const e of i){if(e<16)return z.error(ko.fromPageNumber(e,!0));const t=this.memory.get(e);if(void 0===t)return z.error(ko.fromPageNumber(e));if(r===Ho.WRITE&&!t.isWriteable())return z.error(ko.fromPageNumber(e,!0));n.push(t)}return z.ok(n)}loadInto(e,t){if(0===e.length)return z.ok($);const r=this.getPages(t,e.length,Ho.READ);if(r.isError)return z.error(r.error);const s=r.ok;let i=t,n=e.length;for(const r of s){const s=Ao(i%Hn),o=Math.min(Hn-s,n),a=i-t,c=e.subarray(a);r.loadInto(c,s,o),i+=o,n-=o}return z.ok($)}sbrk(e){const t=this.sbrkIndex,r=this.virtualSbrkIndex;if(Pn<r+e||r+e>this.endHeapIndex)throw new Uo;const s=jn(this.virtualSbrkIndex+e);if(s<=t)return this.virtualSbrkIndex=s,r;const i=jn(wo(s)),n=So(t),o=(i-t)/Hn,a=Do.fromStartAndLength(n,o);for(const e of a){const t=new Lo(e);this.memory.set(e,t)}return this.virtualSbrkIndex=s,this.sbrkIndex=i,r}getPageDump(e){const t=this.memory.get(e);return t?.getPageDump()??null}getDirtyPages(){return this.memory.keys()}}class Qo{initialMemory=new Map;isFinalized=!1;ensureNotFinalized(){if(this.isFinalized)throw new Bo}ensureNoReservedMemoryUsage(e){if(e.overlapsWith(No))throw new Ro}setReadablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),M(e<t,"end has to be bigger than start"),M(e%Hn===0,"start needs to be a multiple of page size (4096)"),M(t%Hn===0,"end needs to be a multiple of page size (4096)"),M(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=To.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(Do.fromMemoryRange(i)),o=n.length;for(let e=0;e<o;e++){const t=n[e],s=r.subarray(e*Hn,(e+1)*Hn),i=new Po(t,s);this.initialMemory.set(t,i)}return this}setWriteablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),M(e<t,"end has to be bigger than start"),M(e%Hn===0,"start needs to be a multiple of page size (4096)"),M(t%Hn===0,"end needs to be a multiple of page size (4096)"),M(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=To.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(Do.fromMemoryRange(i)),o=n.length;for(let e=0;e<o;e++){const t=n[e],s=r.subarray(e*Hn,(e+1)*Hn),i=new Lo(t,s);this.initialMemory.set(t,i)}return this}setData(e,t){this.ensureNotFinalized();const r=Hn-e%Hn;M(t.length<=r,"The data has to fit into a single page.");const s=t.length,i=To.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=So(e),o=this.initialMemory.get(n);if(void 0===o)throw new Oo;const a=Ao(e-o.start);return o.setData(a,t),this}finalize(e,t){M(e<=t,`startHeapIndex (${e}) has to be less than or equal to endHeapIndex (${t})`),this.ensureNotFinalized();const r=To.fromStartAndLength(e,t-e),s=Do.fromMemoryRange(r);for(const e of s)if(this.initialMemory.has(e))throw new _o;const i=Ko.fromInitialMemory({memory:this.initialMemory,sbrkIndex:jn(e),endHeapIndex:t});return this.isFinalized=!0,i}}class Vo{mathOps;shiftOps;bitOps;booleanOps;moveOps;bitRotationOps;constructor(e,t,r,s,i,n){this.mathOps=e,this.shiftOps=t,this.bitOps=r,this.booleanOps=s,this.moveOps=i,this.bitRotationOps=n}dispatch(e,t){switch(e){case no.ADD_32:this.mathOps.addU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.ADD_64:this.mathOps.addU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MUL_32:this.mathOps.mulU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MUL_64:this.mathOps.mulU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MUL_UPPER_U_U:this.mathOps.mulUpperUU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MUL_UPPER_S_S:this.mathOps.mulUpperSS(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MUL_UPPER_S_U:this.mathOps.mulUpperSU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SUB_32:this.mathOps.subU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SUB_64:this.mathOps.subU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.DIV_S_32:this.mathOps.divSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.DIV_S_64:this.mathOps.divSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.DIV_U_32:this.mathOps.divUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.DIV_U_64:this.mathOps.divUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.REM_S_32:this.mathOps.remSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.REM_S_64:this.mathOps.remSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.REM_U_32:this.mathOps.remUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.REM_U_64:this.mathOps.remUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SHLO_L_32:this.shiftOps.shiftLogicalLeftU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SHLO_L_64:this.shiftOps.shiftLogicalLeftU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SHLO_R_32:this.shiftOps.shiftLogicalRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SHLO_R_64:this.shiftOps.shiftLogicalRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SHAR_R_32:this.shiftOps.shiftArithmeticRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SHAR_R_64:this.shiftOps.shiftArithmeticRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.OR:this.bitOps.or(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.AND:this.bitOps.and(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.XOR:this.bitOps.xor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SET_LT_S:this.booleanOps.setLessThanSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.SET_LT_U:this.booleanOps.setLessThanUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.CMOV_IZ:this.moveOps.cmovIfZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.CMOV_NZ:this.moveOps.cmovIfNotZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.ROT_L_64:this.bitRotationOps.rotL64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.ROT_L_32:this.bitRotationOps.rotL32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.ROT_R_64:this.bitRotationOps.rotR64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.ROT_R_32:this.bitRotationOps.rotR32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.AND_INV:this.bitOps.andInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.OR_INV:this.bitOps.orInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.XNOR:this.bitOps.xnor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MAX:this.mathOps.max(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MAX_U:this.mathOps.maxU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MIN:this.mathOps.min(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case no.MIN_U:this.mathOps.minU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex)}}}class Fo{mathOps;shiftOps;bitOps;booleanOps;moveOps;storeOps;loadOps;bitRotationOps;constructor(e,t,r,s,i,n,o,a){this.mathOps=e,this.shiftOps=t,this.bitOps=r,this.booleanOps=s,this.moveOps=i,this.storeOps=n,this.loadOps=o,this.bitRotationOps=a}dispatch(e,t){switch(e){case no.ADD_IMM_32:this.mathOps.addImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.ADD_IMM_64:this.mathOps.addImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.MUL_IMM_32:this.mathOps.mulImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.MUL_IMM_64:this.mathOps.mulImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.NEG_ADD_IMM_32:this.mathOps.negAddImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.NEG_ADD_IMM_64:this.mathOps.negAddImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_L_IMM_32:this.shiftOps.shiftLogicalLeftImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_L_IMM_64:this.shiftOps.shiftLogicalLeftImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_L_IMM_ALT_32:this.shiftOps.shiftLogicalLeftImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_L_IMM_ALT_64:this.shiftOps.shiftLogicalLeftImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_R_IMM_32:this.shiftOps.shiftLogicalRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_R_IMM_64:this.shiftOps.shiftLogicalRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_R_IMM_ALT_32:this.shiftOps.shiftLogicalRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHLO_R_IMM_ALT_64:this.shiftOps.shiftLogicalRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHAR_R_IMM_32:this.shiftOps.shiftArithmeticRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHAR_R_IMM_64:this.shiftOps.shiftArithmeticRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHAR_R_IMM_ALT_32:this.shiftOps.shiftArithmeticRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SHAR_R_IMM_ALT_64:this.shiftOps.shiftArithmeticRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.OR_IMM:this.bitOps.orImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.AND_IMM:this.bitOps.andImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.XOR_IMM:this.bitOps.xorImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SET_LT_S_IMM:this.booleanOps.setLessThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SET_LT_U_IMM:this.booleanOps.setLessThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SET_GT_S_IMM:this.booleanOps.setGreaterThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.SET_GT_U_IMM:this.booleanOps.setGreaterThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.CMOV_IZ_IMM:this.moveOps.cmovIfZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.CMOV_NZ_IMM:this.moveOps.cmovIfNotZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.STORE_IND_U8:this.storeOps.storeIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.STORE_IND_U16:this.storeOps.storeIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.STORE_IND_U32:this.storeOps.storeIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.STORE_IND_U64:this.storeOps.storeIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_U8:this.loadOps.loadIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_U16:this.loadOps.loadIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_U32:this.loadOps.loadIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_U64:this.loadOps.loadIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_I8:this.loadOps.loadIndI8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_I16:this.loadOps.loadIndI16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.LOAD_IND_I32:this.loadOps.loadIndI32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case no.ROT_R_64_IMM:this.bitRotationOps.rotR64Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.ROT_R_64_IMM_ALT:this.bitRotationOps.rotR64ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.ROT_R_32_IMM:this.bitRotationOps.rotR32Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case no.ROT_R_32_IMM_ALT:this.bitRotationOps.rotR32ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex)}}}class $o{moveOps;memoryOps;bitOps;bitRotationOps;constructor(e,t,r,s){this.moveOps=e,this.memoryOps=t,this.bitOps=r,this.bitRotationOps=s}dispatch(e,t){switch(e){case no.MOVE_REG:this.moveOps.moveRegister(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.SBRK:this.memoryOps.sbrk(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.COUNT_SET_BITS_64:this.bitOps.countSetBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.COUNT_SET_BITS_32:this.bitOps.countSetBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.LEADING_ZERO_BITS_64:this.bitOps.leadingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.LEADING_ZERO_BITS_32:this.bitOps.leadingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.TRAILING_ZERO_BITS_64:this.bitOps.trailingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.TRAILING_ZERO_BITS_32:this.bitOps.trailingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.SIGN_EXTEND_8:this.bitOps.signExtend8(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.SIGN_EXTEND_16:this.bitOps.signExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.ZERO_EXTEND_16:this.bitOps.zeroExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case no.REVERSE_BYTES:this.bitRotationOps.reverseBytes(t.firstRegisterIndex,t.secondRegisterIndex)}}}class jo{branchOps;loadOps;constructor(e,t){this.branchOps=e,this.loadOps=t}dispatch(e,t){switch(e){case no.LOAD_IMM_JUMP:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder),this.branchOps.jump(t.nextPc);break;case no.BRANCH_EQ_IMM:this.branchOps.branchEqImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_NE_IMM:this.branchOps.branchNeImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_LT_U_IMM:this.branchOps.branchLtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_LE_U_IMM:this.branchOps.branchLeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_GE_U_IMM:this.branchOps.branchGeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_GT_U_IMM:this.branchOps.branchGtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_LT_S_IMM:this.branchOps.branchLtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_LE_S_IMM:this.branchOps.branchLeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_GE_S_IMM:this.branchOps.branchGeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case no.BRANCH_GT_S_IMM:this.branchOps.branchGtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc)}}}class Go{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){switch(e){case no.BRANCH_EQ:this.branchOps.branchEq(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case no.BRANCH_NE:this.branchOps.branchNe(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case no.BRANCH_LT_U:this.branchOps.branchLtUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case no.BRANCH_LT_S:this.branchOps.branchLtSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case no.BRANCH_GE_U:this.branchOps.branchGeUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case no.BRANCH_GE_S:this.branchOps.branchGeSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc)}}}class qo{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){e===no.JUMP&&this.branchOps.jump(t.nextPc)}}class zo{loadOps;storeOps;dynamicJumpOps;constructor(e,t,r){this.loadOps=e,this.storeOps=t,this.dynamicJumpOps=r}dispatch(e,t){switch(e){case no.LOAD_IMM:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder);break;case no.STORE_U8:this.storeOps.storeU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.STORE_U16:this.storeOps.storeU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.STORE_U32:this.storeOps.storeU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.STORE_U64:this.storeOps.storeU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_U8:this.loadOps.loadU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_U16:this.loadOps.loadU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_U32:this.loadOps.loadU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_U64:this.loadOps.loadU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_I8:this.loadOps.loadI8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_I16:this.loadOps.loadI16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.LOAD_I32:this.loadOps.loadI32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case no.JUMP_IND:{const e=this.dynamicJumpOps.caluclateJumpAddress(t.immediateDecoder,t.registerIndex);this.dynamicJumpOps.jumpInd(e);break}}}}class Wo{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case no.STORE_IMM_IND_U8:this.storeOps.storeImmediateIndU8(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case no.STORE_IMM_IND_U16:this.storeOps.storeImmediateIndU16(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case no.STORE_IMM_IND_U32:this.storeOps.storeImmediateIndU32(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case no.STORE_IMM_IND_U64:this.storeOps.storeImmediateIndU64(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder)}}}class Jo{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case no.STORE_IMM_U8:this.storeOps.storeImmediateU8(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case no.STORE_IMM_U16:this.storeOps.storeImmediateU16(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case no.STORE_IMM_U32:this.storeOps.storeImmediateU32(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case no.STORE_IMM_U64:this.storeOps.storeImmediateU64(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder)}}}class Yo{noArgsOps;constructor(e){this.noArgsOps=e}dispatch(e){switch(e){case no.TRAP:this.noArgsOps.trap();break;case no.FALLTHROUGH:this.noArgsOps.fallthrough()}}}class Xo{loadOps;dynamicJumpOps;constructor(e,t){this.loadOps=e,this.dynamicJumpOps=t}dispatch(e,t){switch(e){case no.LOAD_IMM_JUMP_IND:{const e=this.dynamicJumpOps.caluclateJumpAddress(t.secondImmediateDecoder,t.secondRegisterIndex);this.loadOps.loadImmediate(t.firstRegisterIndex,t.firstImmediateDecoder),this.dynamicJumpOps.jumpInd(e);break}}}}class Zo{hostCallOps;constructor(e){this.hostCallOps=e}dispatch(e,t){e===no.ECALLI&&this.hostCallOps.hostCall(t.immediateDecoder)}}class ea{loadOps;constructor(e){this.loadOps=e}dispatch(e,t){e===no.LOAD_IMM_64&&this.loadOps.loadImmediateU64(t.registerIndex,t.immediateDecoder)}}class ta{regs;constructor(e){this.regs=e}or(e,t,r){this.regs.setU64(r,this.regs.getU64(e)|this.regs.getU64(t))}orImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)|t.getU64())}and(e,t,r){this.regs.setU64(r,this.regs.getU64(e)&this.regs.getU64(t))}andImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)&t.getU64())}xor(e,t,r){this.regs.setU64(r,this.regs.getU64(e)^this.regs.getU64(t))}xorImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)^t.getU64())}andInv(e,t,r){this.regs.setU64(r,this.regs.getU64(e)&~this.regs.getU64(t))}orInv(e,t,r){this.regs.setU64(r,this.regs.getU64(e)|~this.regs.getU64(t))}xnor(e,t,r){this.regs.setU64(r,this.regs.getU64(e)^~this.regs.getU64(t))}countSetBits64(e,t){this.regs.setU32(t,function(e){let t=e;return t-=t>>1n&0x5555555555555555n,t=(0x3333333333333333n&t)+(t>>2n&0x3333333333333333n),t=t+(t>>4n)&0x0f0f0f0f0f0f0f0fn,t+=t>>8n,t+=t>>16n,t+=t>>32n,Number(0x7fn&t)}(this.regs.getU64(e)))}countSetBits32(e,t){this.regs.setU32(t,function(e){let t=e;return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,63&t}(this.regs.getLowerU32(e)))}leadingZeroBits64(e,t){this.regs.setU32(t,function(e){const t=Number(e>>32n),r=Number(0xffffffffn&e),s=Math.clz32(t);return s<32?s:s+Math.clz32(r)}(this.regs.getU64(e)))}leadingZeroBits32(e,t){this.regs.setU32(t,Math.clz32(this.regs.getLowerU32(e)))}trailingZeroBits64(e,t){this.regs.setU32(t,function(e){if(0n===e)return 64;let t=e,r=0;for(;0n==(1n&t);)r++,t>>=1n;return r}(this.regs.getU64(e)))}trailingZeroBits32(e,t){this.regs.setU32(t,function(e){if(0===e)return 32;let t=e,r=0;for(;!(1&t);)r++,t>>>=1;return r}(this.regs.getLowerU32(e)))}signExtend(e,t){const r=2**t-1,s=e&r;return(s&1<<t-1)>0?~BigInt(r)|BigInt(s):BigInt(s)}signExtend8(e,t){const r=this.signExtend(this.regs.getLowerU32(e),8);this.regs.setU64(t,r)}signExtend16(e,t){const r=this.signExtend(this.regs.getLowerU32(e),16);this.regs.setU64(t,r)}zeroExtend16(e,t){const r=0x000000000000ffffn&this.regs.getU64(e);this.regs.setU64(t,r)}}const ra=4294967295,sa=-(2**31),ia=32,na=64n;function oa(e,t){return e>ra-t?ra-(ra-e+(ra-t))-1:e+t}function aa(e,t){return(e+t)%2n**64n}function ca(e,t){return t>e?ra-t+e+1:e-t}function la(e,t){return(2n**64n+e-t)%2n**64n}function ha(e,t){if(e>65536||t>65536){const r=65535&e,s=65535&t,i=r*s;return 65535&i|(i>>16)+(65535&r*(t>>16))+(65535&(e>>16)*s)<<16}return e*t}function ua(e,t){return e*t%2n**64n}function da(e){return e>=1n<<63n?e-(1n<<64n):e}function fa(e,t){return(0xffffffffffffffffn&e)*(0xffffffffffffffffn&t)>>64n&0xffffffffffffffffn}function pa(e,t){return da(0xffffffffffffffffn&e*t>>64n)}function ga(e,t){M(t>=0,"Shift count must be non-negative");const r=e<0?"1":"0",s=e.toString(2).padStart(64,r);return(e<0n?(1n<<BigInt(s.length))+e:e)>>t}function ya(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t>e?t:e)}function ma(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t<e?t:e)}class ba{regs;constructor(e){this.regs=e}shiftLogicalLeftU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<this.regs.getLowerU32(t)%ia)}shiftLogicalLeftU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<this.regs.getU64(t)%na)}shiftLogicalRightU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>this.regs.getLowerU32(t)%ia)}shiftLogicalRightU64(e,t,r){this.regs.setU64(r,ga(this.regs.getU64(e),this.regs.getU64(t)%na))}shiftArithmeticRightU32(e,t,r){this.regs.setI32(r,this.regs.getLowerI32(e)>>this.regs.getLowerU32(t)%ia)}shiftArithmeticRightU64(e,t,r){this.regs.setI64(r,this.regs.getI64(e)>>this.regs.getU64(t)%na)}shiftLogicalLeftImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<t.getU32()%ia)}shiftLogicalLeftImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<t.getU64()%na)}shiftLogicalRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>t.getU32()%ia)}shiftLogicalRightImmediateU64(e,t,r){this.regs.setU64(r,ga(this.regs.getU64(e),t.getU64()%na))}shiftArithmeticRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerI32(e)>>t.getU32()%ia)}shiftArithmeticRightImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getI64(e)>>t.getU64()%na)}shiftLogicalLeftImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()<<this.regs.getLowerU32(e)%ia)}shiftLogicalLeftImmediateAlternativeU64(e,t,r){this.regs.setU64(r,t.getU64()<<this.regs.getU64(e)%na)}shiftLogicalRightImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()>>>this.regs.getLowerU32(e)%ia)}shiftLogicalRightImmediateAlternativeU64(e,t,r){this.regs.setU64(r,ga(t.getU64(),this.regs.getU64(e)%na))}shiftArithmeticRightImmediateAlternativeU32(e,t,r){this.regs.setI32(r,t.getU32()>>this.regs.getLowerU32(e)%ia)}shiftArithmeticRightImmediateAlternativeU64(e,t,r){this.regs.setI64(r,t.getI64()>>this.regs.getU64(e)%na)}}class Aa{regs;constructor(e){this.regs=e}addU32(e,t,r){this.regs.setU64(r,eo(oa(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}addU64(e,t,r){this.regs.setU64(r,aa(this.regs.getU64(e),this.regs.getU64(t)))}addImmediateU32(e,t,r){this.regs.setU64(r,eo(oa(this.regs.getLowerU32(e),t.getU32())))}addImmediateU64(e,t,r){this.regs.setU64(r,aa(this.regs.getU64(e),t.getU64()))}mulU32(e,t,r){this.regs.setU64(r,eo(ha(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}mulU64(e,t,r){this.regs.setU64(r,ua(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperUU(e,t,r){this.regs.setU64(r,fa(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperSS(e,t,r){this.regs.setI64(r,pa(this.regs.getI64(e),this.regs.getI64(t)))}mulUpperSU(e,t,r){this.regs.setI64(r,da(0xffffffffffffffffn&this.regs.getI64(e)*(0xffffffffffffffffn&this.regs.getU64(t))>>64n))}mulImmediateU32(e,t,r){this.regs.setU64(r,eo(ha(this.regs.getLowerU32(e),t.getU32())))}mulImmediateU64(e,t,r){this.regs.setU64(r,ua(this.regs.getU64(e),t.getU64()))}mulUpperSSImmediate(e,t,r){this.regs.setI64(r,pa(this.regs.getI64(e),t.getI64()))}mulUpperUUImmediate(e,t,r){this.regs.setU64(r,fa(this.regs.getU64(e),t.getU64()))}subU32(e,t,r){this.regs.setU64(r,eo(ca(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}subU64(e,t,r){this.regs.setU64(r,la(this.regs.getU64(e),this.regs.getU64(t)))}negAddImmediateU32(e,t,r){this.regs.setU64(r,eo(ca(t.getU32(),this.regs.getLowerU32(e))))}negAddImmediateU64(e,t,r){this.regs.setU64(r,la(t.getU64(),this.regs.getU64(e)))}divSignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,2n**64n-1n):-1===this.regs.getLowerI32(t)&&this.regs.getLowerI32(e)===sa?this.regs.setU64(r,eo(this.regs.getLowerU32(e))):this.regs.setI64(r,eo(~~(this.regs.getLowerI32(e)/this.regs.getLowerI32(t))))}divSignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,2n**64n-1n):-1n===this.regs.getI64(t)&&this.regs.getI64(e)===-(2n**63n)?this.regs.setU64(r,this.regs.getU64(e)):this.regs.setI64(r,~~(this.regs.getI64(e)/this.regs.getI64(t)))}divUnsignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,2n**64n-1n):this.regs.setU64(r,eo(~~(this.regs.getLowerU32(e)/this.regs.getLowerU32(t))))}divUnsignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,2n**64n-1n):this.regs.setU64(r,~~(this.regs.getU64(e)/this.regs.getU64(t)))}remSignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,BigInt(this.regs.getLowerI32(e))):-1===this.regs.getLowerI32(t)&&this.regs.getLowerI32(e)===sa?this.regs.setU64(r,0n):this.regs.setI64(r,eo(this.regs.getLowerI32(e)%this.regs.getLowerI32(t)))}remSignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,this.regs.getU64(e)):-1n===this.regs.getI64(t)&&this.regs.getI64(e)===-(2n**63n)?this.regs.setU64(r,0n):this.regs.setI64(r,this.regs.getI64(e)%this.regs.getI64(t))}remUnsignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,eo(this.regs.getLowerU32(e))):this.regs.setU64(r,eo(this.regs.getLowerU32(e)%this.regs.getLowerU32(t)))}remUnsignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,this.regs.getU64(e)):this.regs.setU64(r,this.regs.getU64(e)%this.regs.getU64(t))}max(e,t,r){this.regs.setI64(r,ya(this.regs.getI64(e),this.regs.getI64(t)))}maxU(e,t,r){this.regs.setU64(r,ya(this.regs.getU64(e),this.regs.getU64(t)))}min(e,t,r){this.regs.setI64(r,ma(this.regs.getI64(e),this.regs.getI64(t)))}minU(e,t,r){this.regs.setU64(r,ma(this.regs.getU64(e),this.regs.getU64(t)))}}class Ia{regs;constructor(e){this.regs=e}setLessThanSignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getI64(e)<t.getI64()?1n:0n)}setLessThanUnsignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<t.getU64()?1n:0n)}setLessThanSigned(e,t,r){this.regs.setU64(r,this.regs.getI64(e)<this.regs.getI64(t)?1n:0n)}setLessThanUnsigned(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<this.regs.getU64(t)?1n:0n)}setGreaterThanSignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getI64(e)>t.getI64()?1n:0n)}setGreaterThanUnsignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)>t.getU64()?1n:0n)}}class va{regs;constructor(e){this.regs=e}cmovIfZeroImmediate(e,t,r){0n===this.regs.getU64(e)&&this.regs.setU64(r,t.getU64())}cmovIfNotZeroImmediate(e,t,r){0n!==this.regs.getU64(e)&&this.regs.setU64(r,t.getU64())}cmovIfZero(e,t,r){0n===this.regs.getU64(t)&&this.regs.setU64(r,this.regs.getU64(e))}cmovIfNotZero(e,t,r){0n!==this.regs.getU64(t)&&this.regs.setU64(r,this.regs.getU64(e))}moveRegister(e,t){this.regs.setU64(t,this.regs.getU64(e))}}var wa,Sa;(Sa=wa||(wa={}))[Sa.HALT=0]="HALT",Sa[Sa.PANIC=1]="PANIC",Sa[Sa.FAULT_ACCESS=2]="FAULT_ACCESS",Sa[Sa.FAULT=3]="FAULT",Sa[Sa.HOST=4]="HOST";class Ea{regs;instructionResult;basicBlocks;constructor(e,t,r){this.regs=e,this.instructionResult=t,this.basicBlocks=r}setBasicBlocks(e){this.basicBlocks=e}branch(e,t){t&&(this.basicBlocks.isBeginningOfBasicBlock(e)?this.instructionResult.nextPc=e:this.instructionResult.status=wa.PANIC)}jump(e){this.branch(e,!0)}branchEqImmediate(e,t,r){this.branch(r,this.regs.getU64(e)===t.getU64())}branchEq(e,t,r){this.branch(r,this.regs.getU64(e)===this.regs.getU64(t))}branchNeImmediate(e,t,r){this.branch(r,this.regs.getU64(e)!==t.getU64())}branchNe(e,t,r){this.branch(r,this.regs.getU64(e)!==this.regs.getU64(t))}branchLtUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)<t.getU64())}branchLtUnsigned(e,t,r){this.branch(r,this.regs.getU64(e)<this.regs.getU64(t))}branchLeUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)<=t.getU64())}branchGtUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)>t.getU64())}branchGeUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)>=t.getU64())}branchGeUnsigned(e,t,r){this.branch(r,this.regs.getU64(e)>=this.regs.getU64(t))}branchLtSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)<t.getI64())}branchLtSigned(e,t,r){this.branch(r,this.regs.getI64(e)<this.regs.getI64(t))}branchLeSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)<=t.getI64())}branchGtSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)>t.getI64())}branchGeSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)>=t.getI64())}branchGeSigned(e,t,r){this.branch(r,this.regs.getI64(e)>=this.regs.getI64(t))}}class Ca{regs;memory;instructionResult;constructor(e,t,r){this.regs=e,this.memory=t,this.instructionResult=r}loadImmediate(e,t){this.regs.setU64(e,t.getU64())}loadImmediateU64(e,t){this.regs.setU64(e,t.getValue())}loadNumber(e,t,r){const s=this.regs.getBytesAsLittleEndian(t,8),i=this.memory.loadInto(s.subarray(0,r),$n(e));i.isError?i.error.isAccessFault?this.instructionResult.status=wa.FAULT_ACCESS:(this.instructionResult.status=wa.FAULT,this.instructionResult.exitParam=e):s.fill(0,r)}loadSignedNumber(e,t,r){const s=this.regs.getBytesAsLittleEndian(t,8),i=this.memory.loadInto(s.subarray(0,r),$n(e));i.isError?i.error.isAccessFault?this.instructionResult.status=wa.FAULT_ACCESS:(this.instructionResult.status=wa.FAULT,this.instructionResult.exitParam=e):(128&s[r-1])>0?s.fill(255,r):s.fill(0,r)}loadU8(e,t){this.loadNumber(e,t,1)}loadU16(e,t){this.loadNumber(e,t,2)}loadU32(e,t){this.loadNumber(e,t,4)}loadU64(e,t){this.loadNumber(e,t,8)}loadI8(e,t){this.loadSignedNumber(e,t,1)}loadI16(e,t){this.loadSignedNumber(e,t,2)}loadI32(e,t){this.loadSignedNumber(e,t,4)}loadIndU8(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,1)}loadIndU16(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,2)}loadIndU32(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,4)}loadIndU64(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,8)}loadIndI8(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,1)}loadIndI16(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,2)}loadIndI32(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,4)}}class ka{regs;memory;instructionResult;constructor(e,t,r){this.regs=e,this.memory=t,this.instructionResult=r}storeU8(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,1))}storeU16(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,2))}storeU32(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,4))}storeU64(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,8))}storeIndU8(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,1))}storeIndU16(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,2))}storeIndU32(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,4))}storeIndU64(e,t,r){const s=oa(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,8))}storeImmediateU8(e,t){this.store(e,t.getBytesAsLittleEndian().subarray(0,1))}storeImmediateU16(e,t){this.store(e,t.getBytesAsLittleEndian().subarray(0,2))}storeImmediateU32(e,t){this.store(e,t.getBytesAsLittleEndian().subarray(0,4))}storeImmediateU64(e,t){this.store(e,t.getExtendedBytesAsLittleEndian())}storeImmediateIndU8(e,t,r){const s=oa(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,1))}storeImmediateIndU16(e,t,r){const s=oa(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,2))}storeImmediateIndU32(e,t,r){const s=oa(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,4))}storeImmediateIndU64(e,t,r){const s=oa(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getExtendedBytesAsLittleEndian())}store(e,t){const r=this.memory.storeFrom($n(e),t);r.isOk||(r.error.isAccessFault?this.instructionResult.status=wa.FAULT_ACCESS:(this.instructionResult.status=wa.FAULT,this.instructionResult.exitParam=Eo(r.error.address)))}}class xa{instructionResult;constructor(e){this.instructionResult=e}trap(){this.instructionResult.status=wa.PANIC}fallthrough(){}}class _a{regs;jumpTable;instructionResult;basicBlocks;constructor(e,t,r,s){this.regs=e,this.jumpTable=t,this.instructionResult=r,this.basicBlocks=s}djump(e){if(4294901760===e)return void(this.instructionResult.status=wa.HALT);if(0===e||e%2!=0)return void(this.instructionResult.status=wa.PANIC);const t=e/2-1;if(!this.jumpTable.hasIndex(t))return void(this.instructionResult.status=wa.PANIC);const r=this.jumpTable.getDestination(t);this.basicBlocks.isBeginningOfBasicBlock(r)?this.instructionResult.nextPc=r:this.instructionResult.status=wa.PANIC}caluclateJumpAddress(e,t){return oa(this.regs.getLowerU32(t),e.getU32())}jumpInd(e){this.djump(e)}}class Ba{instructionResult;constructor(e){this.instructionResult=e}hostCall(e){this.instructionResult.status=wa.HOST,this.instructionResult.exitParam=e.getUnsigned()}}class Ra{regs;memory;instructionResult;constructor(e,t,r){this.regs=e,this.memory=t,this.instructionResult=r}sbrk(e,t){try{this.regs.setU32(t,this.memory.sbrk(this.regs.getLowerU32(e)))}catch{this.instructionResult.status=wa.FAULT}}}class Oa{regs;constructor(e){this.regs=e}reverseBytes(e,t){const r=this.regs.getU64(e);let s=0n;for(let e=0;e<8;e++)s=s<<8n|r>>BigInt(8*e)&0xffn;this.regs.setU64(t,s)}rotate32Left(e,t){const r=t%32,s=2**32-1;return(e<<r&s|e>>>32-r)>>>0&s}rotate64Left(e,t){const r=t%64,s=(1n<<64n)-1n;return(e<<BigInt(r)&s|ga(e,BigInt(64-r)))&s}rotate32Right(e,t){const r=t%32,s=2**32-1;return(e>>>r|e<<32-r&s)&s}rotate64Right(e,t){const r=t%64,s=(1n<<64n)-1n;return(ga(e,BigInt(r))|e<<BigInt(64-r)&s)&s}rotR64Imm(e,t,r){const s=t.getU32(),i=this.regs.getU64(e);this.regs.setU64(r,this.rotate64Right(i,s))}rotR64ImmAlt(e,t,r){const s=this.regs.getLowerU32(e),i=t.getU64();this.regs.setU64(r,this.rotate64Right(i,s))}rotR32Imm(e,t,r){const s=t.getU32(),i=this.regs.getLowerU32(e);this.regs.setU32(r,this.rotate32Right(i,s))}rotR32ImmAlt(e,t,r){const s=this.regs.getLowerU32(e),i=t.getU32();this.regs.setU32(r,this.rotate32Right(i,s))}rotL64(e,t,r){const s=this.regs.getU64(e),i=this.regs.getLowerU32(t);this.regs.setU64(r,this.rotate64Left(s,i))}rotL32(e,t,r){const s=this.regs.getLowerU32(e),i=this.regs.getLowerU32(t);this.regs.setU32(r,this.rotate32Left(s,i))}rotR64(e,t,r){const s=this.regs.getU64(e),i=this.regs.getLowerU32(t);this.regs.setU64(r,this.rotate64Right(s,i))}rotR32(e,t,r){const s=this.regs.getLowerU32(e),i=this.regs.getLowerU32(t);this.regs.setU32(r,this.rotate32Right(s,i))}}class Ua{indices;constructor(e,t){M(0===e||t.length%e===0,`Length of jump table (${t.length}) should be a multiple of item lenght (${e})!`);const r=0===e?0:t.length/e;this.indices=new Uint32Array(r);for(let s=0;s<r;s++)this.indices[s]=this.decodeNext(t.subarray(s*e,(s+1)*e))}decodeNext(e){const t=e.length;let r=0;for(let s=0;s<t;s++){if((4278190080&r)>0)return 2**32-1;r<<=8,r|=e[t-s-1]}return r}hasIndex(e){return e<this.indices.length&&e>=0}getDestination(e){return this.indices[e]}static empty(){return new Ua(0,new Uint8Array)}copyFrom(e){this.indices=e.indices}}const Ta=m.new(void 0,"pvm-interpreter");var Na;!function(e){e[e.InvalidProgramError=0]="InvalidProgramError"}(Na||(Na={}));class Da{code;mask;jumpTable;constructor(e){const{code:t,mask:r,jumpTable:s,jumpTableItemLength:i}=this.decodeProgram(e);this.code=new Uint8Array(t),this.mask=new Yn(r),this.jumpTable=new Ua(i,s)}decodeProgram(e){const t=we.fromBlob(e),r=t.varU32(),s=t.u8(),i=t.varU32(),n=r*s,o=t.bytes(n).raw,a=t.bytes(i).raw,c=t.bitVecFixLen(i);return t.finish(),{mask:c,code:a,jumpTableItemLength:s,jumpTable:o}}getMask(){return this.mask}getCode(){return this.code}getJumpTable(){return this.jumpTable}static deblob(e){try{return z.ok(new Da(e))}catch(e){return Ta.error(`Invalid program: ${e}`),z.error(Na.InvalidProgramError)}}}class Ma{useSbrkGas;registers=new Zn;code=new Uint8Array;mask=Yn.empty();pc=0;gas=uo(ho(0));initialGas=uo(ho(0));argsDecoder;threeRegsDispatcher;twoRegsOneImmDispatcher;twoRegsDispatcher;oneRegOneImmOneOffsetDispatcher;twoRegsOneOffsetDispatcher;oneOffsetDispatcher;oneRegOneImmDispatcher;instructionResult=new bo;memory=new Ko;twoImmsDispatcher;oneRegTwoImmsDispatcher;noArgsDispatcher;twoRegsTwoImmsDispatcher;oneImmDispatcher;oneRegOneExtImmDispatcher;status=Gn.OK;argsDecodingResults=(()=>{const e=new Array(io);return e[Jn.NO_ARGUMENTS]={type:Jn.NO_ARGUMENTS,noOfBytesToSkip:1},e[Jn.ONE_IMMEDIATE]={type:Jn.ONE_IMMEDIATE,noOfBytesToSkip:1,immediateDecoder:new Xn},e[Jn.TWO_REGISTERS]={type:Jn.TWO_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0},e[Jn.THREE_REGISTERS]={type:Jn.THREE_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,thirdRegisterIndex:0},e[Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET]={type:Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new Xn,nextPc:0},e[Jn.TWO_REGISTERS_ONE_OFFSET]={type:Jn.TWO_REGISTERS_ONE_OFFSET,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,nextPc:0},e[Jn.TWO_REGISTERS_ONE_IMMEDIATE]={type:Jn.TWO_REGISTERS_ONE_IMMEDIATE,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,immediateDecoder:new Xn},e[Jn.ONE_REGISTER_ONE_IMMEDIATE]={type:Jn.ONE_REGISTER_ONE_IMMEDIATE,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new Xn},e[Jn.ONE_REGISTER_TWO_IMMEDIATES]={type:Jn.ONE_REGISTER_TWO_IMMEDIATES,noOfBytesToSkip:1,registerIndex:0,firstImmediateDecoder:new Xn,secondImmediateDecoder:new Xn},e[Jn.ONE_OFFSET]={type:Jn.ONE_OFFSET,noOfBytesToSkip:1,nextPc:0},e[Jn.TWO_IMMEDIATES]={type:Jn.TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new Xn,secondImmediateDecoder:new Xn},e[Jn.TWO_REGISTERS_TWO_IMMEDIATES]={type:Jn.TWO_REGISTERS_TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new Xn,secondImmediateDecoder:new Xn,firstRegisterIndex:0,secondRegisterIndex:0},e[Jn.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE]={type:Jn.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,noOfBytesToSkip:9,registerIndex:0,immediateDecoder:new so},e})();basicBlocks;jumpTable=Ua.empty();constructor(e=!1){this.useSbrkGas=e,this.argsDecoder=new ro,this.basicBlocks=new yo;const t=new Aa(this.registers),r=new ba(this.registers),s=new ta(this.registers),i=new Ia(this.registers),n=new va(this.registers),o=new Ea(this.registers,this.instructionResult,this.basicBlocks),a=new Ca(this.registers,this.memory,this.instructionResult),c=new ka(this.registers,this.memory,this.instructionResult),l=new xa(this.instructionResult),h=new _a(this.registers,this.jumpTable,this.instructionResult,this.basicBlocks),u=new Ba(this.instructionResult),d=new Ra(this.registers,this.memory,this.instructionResult),f=new Oa(this.registers);this.threeRegsDispatcher=new Vo(t,r,s,i,n,f),this.twoRegsOneImmDispatcher=new Fo(t,r,s,i,n,c,a,f),this.twoRegsDispatcher=new $o(n,d,s,f),this.oneRegOneImmOneOffsetDispatcher=new jo(o,a),this.twoRegsOneOffsetDispatcher=new Go(o),this.oneOffsetDispatcher=new qo(o),this.oneRegOneImmDispatcher=new zo(a,c,h),this.twoImmsDispatcher=new Jo(c),this.oneRegTwoImmsDispatcher=new Wo(c),this.noArgsDispatcher=new Yo(l),this.twoRegsTwoImmsDispatcher=new Xo(a,h),this.oneImmDispatcher=new Zo(u),this.oneRegOneExtImmDispatcher=new ea(a)}reset(e,t,r,s,i){const n=new Da(e);this.code=n.getCode(),this.mask=n.getMask(),this.jumpTable.copyFrom(n.getJumpTable()),this.pc=t,this.gas=uo(r),this.initialGas=uo(r),this.status=Gn.OK,this.argsDecoder.reset(this.code,this.mask),this.basicBlocks.reset(this.code,this.mask),this.instructionResult.reset(),void 0!==s?this.registers.copyFrom(s):this.registers.reset(),void 0!==i?this.memory.copyFrom(i):this.memory.reset()}printProgram(){const e=(t=this.code,r=this.mask,t.reduce((e,t,s)=>(r.isInstruction(s)?e.push([no[t]]):e[e.length-1].push(t),e),[]));var t,r;return console.table(e),e}runProgram(){for(;this.nextStep()===Gn.OK;);}nextStep(){this.status===Gn.HOST&&(this.status=Gn.OK,this.pc=this.instructionResult.nextPc,this.instructionResult.reset());const e=this.code[this.pc]??no.TRAP,t=void 0!==no[e],r=mo[e]??mo[no.TRAP];if(this.gas.sub(r))return this.status=Gn.OOG,this.status;const s=ao[e]??Jn.NO_ARGUMENTS,i=this.argsDecodingResults[s];if(this.argsDecoder.fillArgs(this.pc,i),t)switch(this.instructionResult.nextPc=this.pc+i.noOfBytesToSkip,i.type){case Jn.NO_ARGUMENTS:this.noArgsDispatcher.dispatch(e);break;case Jn.ONE_IMMEDIATE:this.oneImmDispatcher.dispatch(e,i);break;case Jn.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET:this.oneRegOneImmOneOffsetDispatcher.dispatch(e,i);break;case Jn.TWO_REGISTERS:if(this.useSbrkGas&&e===no.SBRK){const e=e=>wo(e)/Hn*16;if(this.gas.sub(ho(e(this.registers.getLowerU32(i.firstRegisterIndex)))))return this.status=Gn.OOG,this.status}this.twoRegsDispatcher.dispatch(e,i);break;case Jn.THREE_REGISTERS:this.threeRegsDispatcher.dispatch(e,i);break;case Jn.TWO_REGISTERS_ONE_IMMEDIATE:this.twoRegsOneImmDispatcher.dispatch(e,i);break;case Jn.TWO_REGISTERS_ONE_OFFSET:this.twoRegsOneOffsetDispatcher.dispatch(e,i);break;case Jn.ONE_OFFSET:this.oneOffsetDispatcher.dispatch(e,i);break;case Jn.ONE_REGISTER_ONE_IMMEDIATE:this.oneRegOneImmDispatcher.dispatch(e,i);break;case Jn.TWO_IMMEDIATES:this.twoImmsDispatcher.dispatch(e,i);break;case Jn.ONE_REGISTER_TWO_IMMEDIATES:this.oneRegTwoImmsDispatcher.dispatch(e,i);break;case Jn.TWO_REGISTERS_TWO_IMMEDIATES:this.twoRegsTwoImmsDispatcher.dispatch(e,i);break;case Jn.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE:this.oneRegOneExtImmDispatcher.dispatch(e,i)}else this.instructionResult.status=wa.PANIC;if(null!==this.instructionResult.status){switch(this.instructionResult.status!==wa.FAULT&&this.instructionResult.status!==wa.FAULT_ACCESS||this.gas.sub(mo[no.TRAP]),this.instructionResult.status){case wa.FAULT:this.status=Gn.FAULT;break;case wa.HALT:this.status=Gn.HALT;break;case wa.PANIC:case wa.FAULT_ACCESS:this.status=Gn.PANIC;break;case wa.HOST:this.status=Gn.HOST}return this.status}return this.pc=this.instructionResult.nextPc,this.status}getRegisters(){return this.registers}getPC(){return this.pc}setNextPC(e){this.pc=e}getGas(){return this.gas.get()}getGasConsumed(){const e=lo(this.initialGas.get())-lo(this.gas.get());return e<0?this.initialGas.get():lo(e)}getGasCounter(){return this.gas}getStatus(){return this.status}getExitParam(){const e=this.instructionResult.exitParam;return null!==e?pe(e):e}getMemory(){return this.memory}getMemoryPage(e){return this.memory.getPageDump(Io(e))}}class Pa{memory;constructor(e){this.memory=e}storeFrom(e,t){return 0===t.length?z.ok($):e+ye(t.length)>Ln?z.error(new xo):this.memory.storeFrom($n(Number(e)),t)}loadInto(e,t){return 0===e.length?z.ok($):t+ye(e.length)>Ln?z.error(new xo):this.memory.loadInto(e,$n(Number(t)))}getMemory(){return this.memory}}class La{registers;constructor(e){this.registers=e}get(e){return ye(this.registers.getU64(e))}set(e,t){this.registers.setU64(e,t)}}class Ha{consumedGas;status;memorySlice;constructor(e,t,r){this.consumedGas=e,this.status=t,this.memorySlice=r,M(null===t&&null!==r||null!==t&&null===r,"`status` and `memorySlice` must not both be null or both be non-null — exactly one must be provided")}static fromStatus(e,t){return new Ha(e,t,null)}static fromMemorySlice(e,t){return new Ha(e,null,t)}hasMemorySlice(){return this.memorySlice instanceof Uint8Array&&null===this.status}hasStatus(){return!this.hasMemorySlice()}}class Ka{pvmInstanceManager;hostCalls;constructor(e,t){this.pvmInstanceManager=e,this.hostCalls=t}getReturnValue(e,t){const r=t.getGasConsumed();if(e===Gn.OOG)return Ha.fromStatus(r,e);if(e===Gn.HALT){const e=t.getMemory(),s=t.getRegisters(),i=s.getLowerU32(10),n=s.getLowerU32(11),o=new Uint8Array(n),a=$n(i);return null!==e.loadInto(o,a)?Ha.fromMemorySlice(r,new Uint8Array):Ha.fromMemorySlice(r,o)}return Ha.fromStatus(r,Gn.PANIC)}async execute(e){for(e.runProgram();;){let t=e.getStatus();if(t!==Gn.HOST)return this.getReturnValue(t,e);M(null!==e.getExitParam(),"We know that the exit param is not null, because the status is `Status.HOST`");const r=e.getExitParam()??-1,s=e.getGasCounter(),i=new La(e.getRegisters()),n=new Pa(e.getMemory()),o=this.hostCalls.get(zn(r)),a="number"==typeof o.gasCost?o.gasCost:o.gasCost(i);if(s.sub(a))return Ha.fromStatus(e.getGasConsumed(),Gn.OOG);if(await o.execute(s,i,n)===Wn.Halt)return t=Gn.HALT,this.getReturnValue(t,e);e.runProgram(),t=e.getStatus()}}async runProgram(e,t,r,s,i){const n=await this.pvmInstanceManager.getInstance();n.reset(e,t,r,s,i);try{return await this.execute(n)}finally{this.pvmInstanceManager.releaseInstance(n)}}}class Qa{instances=[];waitingQueue=[];constructor(e){for(let t=0;t<e;t++)this.instances.push(new Ma)}async getInstance(){const e=this.instances.pop();return void 0!==e?Promise.resolve(e):new Promise(e=>{this.waitingQueue.push(e)})}releaseInstance(e){const t=this.waitingQueue.shift();if(void 0!==t)return t(e);this.instances.push(e)}}const Va={NONE:ye(0xffffffffffffffffn),WHAT:ye(0xfffffffffffffffen),OOB:ye(0xfffffffffffffffdn),WHO:ye(0xfffffffffffffffcn),FULL:ye(0xfffffffffffffffbn),CORE:ye(0xfffffffffffffffan),CASH:ye(0xfffffffffffffff9n),LOW:ye(0xfffffffffffffff8n),HUH:ye(0xfffffffffffffff7n),OK:ye(0n)},Fa=pe(2**32-1),$a=ye(Fa),ja=jr(2**32-1);function Ga(e,t,r){const s=t.get(e);return s===2n**64n-1n?r:qa(s)}function qa(e){const{lower:t,upper:r}=(e=>{const t=e>>32n;return{lower:Number(e&2n**32n-1n),upper:Number(t)}})(e);return 0===r?jr(t):null}function za(e,t){M(t.length>=4,"Not enough space in the destination."),t.set(Ae(e))}function Wa(e){return e>$a?Fa:pe(Number(e))}class Ja{hostCalls=new Map;missing=new Ya;constructor(...e){for(const t of e)M(void 0===this.hostCalls.get(t.index),`Overwriting host call handler at index ${t.index}`),this.hostCalls.set(t.index,t)}get(e){return this.hostCalls.get(e)??this.missing}}class Ya{index=zn(2**32-1);gasCost=co(10);currentServiceId=ja;execute(e,t,r){return t.set(7,Va.WHAT),Promise.resolve(void 0)}}const Xa=4096,Za=65536,ec=2**24,tc=4278059008,rc=4278124544;function sc(e){return Xa*Math.ceil(e/Xa)}class ic extends Q{start;end;data;static from({start:e,end:t,data:r}){return new ic(e,t,r)}constructor(e,t,r){super(),this.start=e,this.end=t,this.data=r}}class nc extends Q{readable;writeable;sbrkIndex;heapEnd;constructor(e,t,r,s){super(),this.readable=e,this.writeable=t,this.sbrkIndex=r,this.heapEnd=s}}class oc extends Q{code;memory;registers;constructor(e,t,r){super(),this.code=e,this.memory=t,this.registers=r}}function ac(e,t,r=null){return new ic(e,t,r)}class cc{code;registers;memory;metadata;static fromSpi(e,t,r){const{code:s,metadata:i}=r?lc(e):{code:e},{code:n,memory:o,registers:a}=function(e,t){const r=we.fromBlob(e),s=r.u24(),i=r.u24(),n=P(t.length,t.length<=ec,"Incorrect arguments length"),o=P(s,s<=ec,"Incorrect readonly segment length"),a=P(i,i<=ec,"Incorrect heap segment length"),c=r.u16(),l=r.u24(),h=r.bytes(o).raw,u=r.bytes(a).raw,d=r.u32(),f=r.bytes(d).raw;r.finish();const p=Za+sc(o),g=131072+(y=o,Za*Math.ceil(y/Za));var y;const m=g+sc(a),b=g+sc(a)+c*Xa,A=tc-sc(l),I=tc,v=rc,w=v+sc(n),S=w+sc(n);function E(e){return!1!==e}const C=[o>0&&ac(65536,p,h),n>0&&ac(v,w,t),w<S&&ac(w,S)].filter(E),k=[a>0&&ac(g,m,u),m<b&&ac(m,b),A<I&&ac(A,I)].filter(E);return new oc(f,new nc(C,k,b,A),function(e){const t=new BigUint64Array(13);return t[0]=BigInt(4294901760),t[1]=BigInt(tc),t[7]=BigInt(rc),t[8]=BigInt(e),t}(t.length))}(s,t),c=new Zn;c.copyFrom(a);const l=new Qo;for(const{start:e,end:t,data:r}of o.readable){const s=$n(e),i=$n(t);l.setReadablePages(s,i,r??new Uint8Array)}for(const{start:e,end:t,data:r}of o.writeable){const s=$n(e),i=$n(t);l.setWriteablePages(s,i,r??new Uint8Array)}const h=$n(o.sbrkIndex),u=jn(o.heapEnd),d=l.finalize(h,u);return new cc(n,c,d,i)}static fromGeneric(e,t){const{code:r,metadata:s}=t?lc(e):{code:e},i=new Zn,n=new Ko;return new cc(r,i,n,s)}constructor(e,t,r,s=new Uint8Array){this.code=e,this.registers=t,this.memory=r,this.metadata=s}}function lc(e){const t=we.fromBlob(e);return{metadata:t.bytesBlob().raw,code:t.remainingBytes().raw}}var hc,uc,dc;!function(e){e[e.NoLookup=0]="NoLookup",e[e.NoState=1]="NoState",e[e.NoServiceCode=2]="NoServiceCode",e[e.ServiceCodeMismatch=3]="ServiceCodeMismatch"}(hc||(hc={}));class fc{context;keccakHasher;allocator;constructor(e,t,r){this.context=e,this.keccakHasher=t,this.allocator=r}hashConcat(e,t){return tr(this.keccakHasher,[e,t])}hashConcatPrepend(e,t,r){return tr(this.keccakHasher,[e,t,r])}header(e){return new kt(Nt(e.encoded(),this.allocator).asOpaque(),e)}extrinsic(e){const t=e.guarantees.view().map(e=>e.view()).map(e=>{const t=Nt(e.report.encoded(),this.allocator).asOpaque();return J.blobFromParts([t.raw,e.slot.encoded().raw,e.credentials.encoded().raw])}),r=_e.encodeObject(Pe.sequenceVarLen(Li),t,this.context),s=Nt(e.tickets.encoded(),this.allocator).asOpaque(),i=Nt(e.preimages.encoded(),this.allocator).asOpaque(),n=Nt(r,this.allocator).asOpaque(),o=Nt(e.assurances.encoded(),this.allocator).asOpaque(),a=Nt(e.disputes.encoded(),this.allocator).asOpaque(),c=J.blobFromParts([s.raw,i.raw,n.raw,o.raw,a.raw]);return new xt(Nt(c,this.allocator).asOpaque(),e,c)}workPackage(e){return this.encode(Rr.Codec,e)}encode(e,t){const r=_e.encodeObject(e,t,this.context);return new xt(Nt(r,this.allocator).asOpaque(),t,r)}}!function(e){e.PreimageUnneeded="preimage_unneeded",e.PreimagesNotSortedUnique="preimages_not_sorted_unique",e.AccountNotFound="account_not_found"}(uc||(uc={}));class pc{state;constructor(e){this.state=e}integrate(e){for(let t=1;t<e.preimages.length;t++){const r=e.preimages[t-1],s=e.preimages[t];if(!(r.requester<s.requester)&&(r.requester>s.requester||s.blob.compare(r.blob).isLessOrEqual()))return z.error(uc.PreimagesNotSortedUnique)}const{preimages:t,slot:r}=e,s=[];for(const e of t){const{requester:t,blob:i}=e,n=Nt(i).asOpaque(),o=this.state.getService(t);if(null===o)return z.error(uc.AccountNotFound);const a=o.hasPreimage(n),c=o.getLookupHistory(n,pe(i.length));if(a||null===c||!gi.isRequested(c))return z.error(uc.PreimageUnneeded);s.push(Ai.provide({serviceId:t,preimage:di.create({hash:n,blob:i}),slot:r}))}return z.ok({preimages:s})}}class gc{spec;importer;toImport=or.fromSortedArray((e,t)=>{const r=e.timeSlot-t.timeSlot;return r<0?D.Greater:r>0?D.Less:D.Equal});lastEpoch=zr(2**32-1);constructor(e,t){this.spec=e,this.importer=t}tryToReadTimeSlot(e){try{return e.header.view().timeSlotIndex.materialize()}catch{return null}}isCurrentEpoch(e){const t=Math.floor(e/this.spec.epochLength);return this.lastEpoch===t}startPreverification(){for(const e of this.toImport)this.isCurrentEpoch(e.timeSlot)&&(e.seal=this.importer.preverifySeal(e.timeSlot,e.block))}push(e){const t=this.tryToReadTimeSlot(e);if(null===t)return null;const r={timeSlot:t,block:e,seal:this.isCurrentEpoch(t)?this.importer.preverifySeal(t,e):Promise.resolve(null)};return this.toImport.insert(r),t}shift(){const e=this.toImport.pop();if(void 0!==e){const t=Math.floor(e.timeSlot/this.spec.epochLength),r=this.lastEpoch!==t;this.lastEpoch=zr(t),r&&this.startPreverification()}return e}}!function(e){e[e.ParentNotFound=0]="ParentNotFound",e[e.InvalidTimeSlot=1]="InvalidTimeSlot",e[e.InvalidExtrinsic=2]="InvalidExtrinsic",e[e.StateRootNotFound=3]="StateRootNotFound",e[e.InvalidStateRoot=4]="InvalidStateRoot",e[e.AlreadyImported=5]="AlreadyImported"}(dc||(dc={}));const yc=Y.zero(Ct).asOpaque();class mc{hasher;blocks;constructor(e,t){this.hasher=e,this.blocks=t}async verifyBlock(e){const t=e.header.view(),r=this.hasher.header(t);if(null!==this.blocks.getHeader(r.hash))return z.error(dc.AlreadyImported,`Block ${r.hash} is already imported.`);const s=t.parentHeaderHash.materialize();if(!s.isEqualTo(yc)){const e=this.blocks.getHeader(s);if(null===e)return z.error(dc.ParentNotFound,`Parent ${s.toString()} not found`);const r=t.timeSlotIndex.materialize(),i=e.timeSlotIndex.materialize();if(r<=i)return z.error(dc.InvalidTimeSlot,`Invalid time slot index: ${r}, expected > ${i}`)}const i=t.extrinsicHash.materialize(),n=this.hasher.extrinsic(e.extrinsic.view());if(!i.isEqualTo(n.hash))return z.error(dc.InvalidExtrinsic,`Invalid extrinsic hash: ${i.toString()}, expected ${n.hash.toString()}`);const o=t.priorStateRoot.materialize(),a=this.blocks.getPostStateRoot(s);return null===a?z.error(dc.StateRootNotFound,`Posterior state root ${s.toString()} not found`):o.isEqualTo(a)?z.ok(r.hash):z.error(dc.InvalidStateRoot,`Invalid prior state root: ${o.toString()}, expected ${a.toString()} (ours)`)}hashHeader(e){return this.hasher.header(e.header.view())}}var bc;function Ac(e,t){for(let r=1;r<e.length;r++)if(e[r-1][t].compare(e[r][t]).isGreaterOrEqual())return!1;return!0}!function(e){e.AlreadyJudged="already_judged",e.BadVoteSplit="bad_vote_split",e.VerdictsNotSortedUnique="verdicts_not_sorted_unique",e.JudgementsNotSortedUnique="judgements_not_sorted_unique",e.CulpritsNotSortedUnique="culprits_not_sorted_unique",e.FaultsNotSortedUnique="faults_not_sorted_unique",e.NotEnoughCulprits="not_enough_culprits",e.NotEnoughFaults="not_enough_faults",e.CulpritsVerdictNotBad="culprits_verdict_not_bad",e.FaultVerdictWrong="fault_verdict_wrong",e.OffenderAlreadyReported="offender_already_reported",e.BadJudgementAge="bad_judgement_age",e.BadValidatorIndex="bad_validator_index",e.BadSignature="bad_signature",e.BadGuarantorKey="bad_guarantor_key",e.BadAuditorKey="bad_auditor_key"}(bc||(bc={}));const Ic=J.blobFromString("jam_valid").raw,vc=J.blobFromString("jam_invalid").raw,wc=J.blobFromString("jam_guarantee").raw;function Sc({key:e,signature:t,workReportHash:r}){return{key:e,signature:t,message:J.blobFromParts(wc,r.raw)}}function Ec({workReportHash:e,wasConsideredValid:t,signature:r,key:s}){const i=t?Ic:vc;return{key:s,signature:r,message:J.blobFromParts(i,e.raw)}}function Cc(e,t,r){const{isWorkReportValid:s,signature:i}=e,n=s?Ic:vc;return{key:r,signature:i,message:J.blobFromParts(n,t.raw)}}class kc{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}verifyCulprits(e,t,r,s){if(!Ac(e.culprits,"key"))return z.error(bc.CulpritsNotSortedUnique);const i=e.culprits.length;for(let n=0;n<i;n++){const{key:i,workReportHash:o}=e.culprits[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return z.error(bc.OffenderAlreadyReported);if(!s.has(i))return z.error(bc.BadGuarantorKey);if(void 0===t.toAddToBadSet.findExact(o))return z.error(bc.CulpritsVerdictNotBad);const a=r.culprits[n];if(!a?.isValid)return z.error(bc.BadSignature)}return z.ok(null)}verifyFaults(e,t,r,s){if(!Ac(e.faults,"key"))return z.error(bc.FaultsNotSortedUnique);const i=e.faults.length;for(let n=0;n<i;n++){const{key:i,workReportHash:o,wasConsideredValid:a}=e.faults[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return z.error(bc.OffenderAlreadyReported);if(!s.has(i))return z.error(bc.BadAuditorKey);if(a){const e=t.toAddToGoodSet.findExact(o),r=t.toAddToBadSet.findExact(o);if(void 0!==e||void 0===r)return z.error(bc.FaultVerdictWrong)}if(!r.faults[n].isValid)return z.error(bc.BadSignature)}return z.ok(null)}verifyVerdicts(e,t){if(!Ac(e.verdicts,"workReportHash"))return z.error(bc.VerdictsNotSortedUnique);if(e.verdicts.some(e=>!function(e){for(let t=1;t<e.length;t++)if(e[t-1].index>=e[t].index)return!1;return!0}(e.votes)))return z.error(bc.JudgementsNotSortedUnique);const r=Math.floor(this.state.timeslot/this.chainSpec.epochLength);let s=0;for(const{votesEpoch:i,votes:n}of e.verdicts){if(i!==r&&i+1!==r)return z.error(bc.BadJudgementAge);const e=i===r?this.state.currentValidatorData:this.state.previousValidatorData;for(const{index:r}of n){const i=e[r]?.ed25519;if(void 0===i)return z.error(bc.BadValidatorIndex);if(!t.judgements[s].isValid)return z.error(bc.BadSignature);s+=1}}return z.ok(null)}verifyIfAlreadyJudged(e){for(const t of e.verdicts){const e=this.state.disputesRecords.goodSet.findExact(t.workReportHash),r=this.state.disputesRecords.badSet.findExact(t.workReportHash),s=this.state.disputesRecords.wonkySet.findExact(t.workReportHash);if(void 0!==e||void 0!==r||void 0!==s)return z.error(bc.AlreadyJudged)}return z.ok(null)}calculateVotesForWorkReports(e){const t=rr.new();for(const r of e.verdicts){const e=r.votes,s=r.workReportHash;let i=0;for(const{isWorkReportValid:t}of e)t&&(i+=1);t.set(s,i)}return t}verifyVotesForWorkReports(e,t){for(const[r,s]of e)if(s===this.chainSpec.validatorsSuperMajority){const e=t.faults.find(e=>e.workReportHash.isEqualTo(r));if(void 0===e)return z.error(bc.NotEnoughFaults)}else if(0===s){const e=t.culprits.find(e=>e.workReportHash.isEqualTo(r)),s=t.culprits.findLast(e=>e.workReportHash.isEqualTo(r));if(e===s)return z.error(bc.NotEnoughCulprits)}else if(s!==this.chainSpec.thirdOfValidators)return z.error(bc.BadVoteSplit);return z.ok(null)}getDisputesRecordsNewItems(e){const t=[],r=[],s=[];for(const[i,n]of e)n>=this.chainSpec.validatorsSuperMajority?t.push(i):0===n?r.push(i):n>=this.chainSpec.thirdOfValidators&&s.push(i);return{toAddToGoodSet:ar.fromArray(ri,t),toAddToBadSet:ar.fromArray(ri,r),toAddToWonkySet:ar.fromArray(ri,s)}}getClearedCoreAssignment(e){const t=this.state.availabilityAssignment.slice();for(let r=0;r<t.length;r++){const s=t[r];if(null!==s){const i=e.get(s.workReport.hash);void 0!==i&&i<this.chainSpec.validatorsSuperMajority&&(t[r]=null)}}return Ys(t,this.chainSpec)}getOffenders(e){const t=[];for(const{key:r}of e.culprits)t.push(r);for(const{key:r}of e.faults)t.push(r);return t}getUpdatedDisputesRecords(e,t){const r=or.fromArray(ri,t);return ti.create({goodSet:ar.fromTwoSortedCollections(this.state.disputesRecords.goodSet,e.toAddToGoodSet),badSet:ar.fromTwoSortedCollections(this.state.disputesRecords.badSet,e.toAddToBadSet),wonkySet:ar.fromTwoSortedCollections(this.state.disputesRecords.wonkySet,e.toAddToWonkySet),punishSet:ar.fromTwoSortedCollections(this.state.disputesRecords.punishSet,r)})}prepareSignaturesToVerification(e){const t={culprits:[],judgements:[],faults:[]},r=Math.floor(this.state.timeslot/this.chainSpec.epochLength);for(const{votesEpoch:s,votes:i,workReportHash:n}of e.verdicts){const e=s===r?this.state.currentValidatorData:this.state.previousValidatorData;for(const r of i){const s=e[r.index];if(void 0===s)return z.error(bc.BadValidatorIndex);const i=s.ed25519;t.judgements.push(Cc(r,n,i))}}return t.culprits=e.culprits.map(Sc),t.faults=e.faults.map(Ec),z.ok(t)}getValidatorKeys(){const e=this.state.disputesRecords.punishSet,t=this.state.currentValidatorData.map(e=>e.ed25519),r=this.state.previousValidatorData.map(e=>e.ed25519),s=t.concat(r).filter(t=>!e.has(t));return sr.from(s)}async transition(e){const t=this.prepareSignaturesToVerification(e);if(t.isError)return z.error(t.error);const r=async function(e){const t={culprits:[],faults:[],judgements:[]},r=Object.entries(e);for(const[e,s]of r)t[e]=(await It(s)).map((e,t)=>({isValid:e,signature:s[t].signature}));return Promise.resolve(t)}(t.ok),s=this.calculateVotesForWorkReports(e),i=this.getDisputesRecordsNewItems(s),n=await r,o=this.getValidatorKeys(),a=[this.verifyVerdicts(e,n),this.verifyVotesForWorkReports(s,e),this.verifyCulprits(e,i,n,o),this.verifyFaults(e,i,n,o),this.verifyIfAlreadyJudged(e)].find(e=>e.isError);if(a?.isError)return z.error(a.error);const c=this.getOffenders(e),l=this.getUpdatedDisputesRecords(i,c),h=this.getClearedCoreAssignment(s);return z.ok({offendersMark:c,stateUpdate:{disputesRecords:l,availabilityAssignment:h}})}}const xc=J.blobFromString("jam_entropy").raw,_c=J.blobFromString("jam_fallback_seal").raw,Bc=J.blobFromString("jam_ticket_seal").raw;var Rc;!function(e){e[e.Ok=0]="Ok",e[e.Error=1]="Error"}(Rc||(Rc={}));const Oc=async function(e,t,r,s,i,n){const o=J.blobFromParts(t.map(e=>e.raw)).raw,a=await e.verifySeal(o,r,s.raw,i.raw,n.raw);return a[0]===Rc.Error?z.error(null):z.ok(Y.fromBlob(a.subarray(1),Ct).asOpaque())},Uc=async function(e,t,r,s){const i=s.length+Bc.length+1,n=J.blobFromParts(r.map(e=>J.blobFromParts([e.signature.raw,Bc,s.raw,Uint8Array.of(e.attempt)]).raw)).raw,o=J.blobFromParts(t.map(e=>e.raw)).raw;try{const t=await e.batchVerifyTicket(o,n,i);return Array.from(J.blobFrom(t).chunks(33)).map(e=>({isValid:e.raw[0]===Rc.Ok,entropyHash:Y.fromBlob(e.raw.subarray(1,33),Ct).asOpaque()}))}catch(e){if("RuntimeError: unreachable"==`${e}`)return Array.from({length:r.length},()=>({isValid:!1,entropyHash:Y.zero(Ct).asOpaque()}));throw e}},Tc=async function(e,t){const r=J.blobFromParts(t.map(e=>e.raw)).raw,s=await e.getRingCommitment(r);return s[0]===Rc.Error?z.error(null):z.ok(Y.fromBlob(s.subarray(1),St).asOpaque())};class Nc{runInternal;state;static new(e,t){return new Nc(e,t)}constructor(e,t){this.runInternal=e,this.state=t}listenToParentPort(){if(null===T.parentPort)throw new Error("This method is meant to be run inside a worker thread!");T.parentPort.once("close",()=>{process.exit(0)}),T.parentPort.once("message",e=>{this.listenTo(e),T.parentPort?.postMessage("ready")})}listenTo(e){e.once("close",()=>{e.removeAllListeners(),process.exit(0)}),e.on("message",t=>{const{params:r}=t;this.run(r).then(t=>{const r=z.ok(t);e.postMessage(r,t.getTransferList())}).catch(t=>{const r=z.error(`${t}`);e.postMessage(r,[])})})}async run(e){return await this.runInternal(e,this.state)}async destroy(){}}class Dc{workers;maxWorkers;workerPath;static async initialize(e,t){M(t.maxWorkers>0,"Max workers has to be positive."),M(t.minWorkers<=t.maxWorkers,"Min workers has to be lower or equal to max workers.");const r=[];for(let s=0;s<t.minWorkers;s++)r.push(await Mc(e));return new Dc(r,t.maxWorkers,e)}freeWorkerIndices=[];taskQueue=[];isDestroyed=!1;isWorkerInitializing=!1;constructor(e,t,r){this.workers=e,this.maxWorkers=t,this.workerPath=r;for(let t=0;t<e.length;t++)this.freeWorkerIndices.push(t)}async initNewWorker(e=()=>{}){this.workers.length>=this.maxWorkers?console.warn(`Task queue has ${this.taskQueue.length} pending items and we can't init any more workers.`):this.isWorkerInitializing||(this.isWorkerInitializing=!0,this.workers.push(await Mc(this.workerPath)),this.freeWorkerIndices.push(this.workers.length-1),this.isWorkerInitializing=!1,e())}async destroy(){for(const e of this.workers)e.port.close(),await e.worker.terminate();this.workers.length=0,this.isDestroyed=!0}async run(e){return new Promise((t,r)=>{this.isDestroyed?r("pool destroyed"):(this.taskQueue.push({params:e,resolve:t,reject:r}),this.processEntryFromTaskQueue())})}processEntryFromTaskQueue(){const e=this.freeWorkerIndices.pop();if(void 0===e)return void(this.taskQueue.length>5&&this.initNewWorker(()=>{this.processEntryFromTaskQueue()}));const t=this.taskQueue.pop();void 0!==t?this.workers[e].runTask(t,()=>{this.freeWorkerIndices.push(e),this.processEntryFromTaskQueue()}):this.freeWorkerIndices.push(e)}}async function Mc(e){const{port1:t,port2:r}=new MessageChannel,s=new T.Worker(e,{});return s.postMessage(t,[t]),await new Promise((e,t)=>{s.once("message",e),s.once("error",t)}),s.unref(),new Pc(s,r)}class Pc{worker;port;constructor(e,t){this.worker=e,this.port=t}runTask(e,t){const r={params:e.params};this.port.once("message",r=>{r.isOk?e.resolve(r.ok):e.reject(new Error(r.error)),t()}),this.port.postMessage(r,r.params.getTransferList())}}var Lc;!function(e){e[e.RingCommitment=0]="RingCommitment",e[e.BatchVerifyTickets=1]="BatchVerifyTickets",e[e.VerifySeal=2]="VerifySeal"}(Lc||(Lc={}));class Hc{data;constructor(e){this.data=e}getTransferList(){return[]}}class Kc{params;constructor(e){this.params=e}getTransferList(){return[]}}const Qc=Nc.new(e=>{const t=e.params,r=t.method;return r===Lc.RingCommitment?Promise.resolve(new Hc((0,vt.hc)(t.keys))):r===Lc.BatchVerifyTickets?Promise.resolve(new Hc((0,vt.ZJ)(t.keys,t.ticketsData,t.contextLength))):r===Lc.VerifySeal?Promise.resolve(new Hc((0,vt.KG)(t.keys,t.authorIndex,t.signature,t.payload,t.auxData))):void L(r)},null);class Vc{executor;constructor(e){this.executor=e}destroy(){return this.executor.destroy()}static async new({synchronous:e}){const t=A().cpus().length;return new Vc(e?Qc:await Dc.initialize(new URL(o(884),o.b),{minWorkers:Math.max(1,Math.floor(t/2)),maxWorkers:t}))}async verifySeal(e,t,r,s,i){return(await this.executor.run(new Kc({method:Lc.VerifySeal,keys:e,authorIndex:t,signature:r,payload:s,auxData:i}))).data}async getRingCommitment(e){return(await this.executor.run(new Kc({method:Lc.RingCommitment,keys:e}))).data}async batchVerifyTicket(e,t,r){return(await this.executor.run(new Kc({method:Lc.BatchVerifyTickets,keys:e,ticketsData:t,contextLength:r}))).data}}const Fc=(e,t)=>ce(e.id,t.id);var $c,jc,Gc,qc,zc,Wc,Jc;!function(e){e[e.IncorrectData=1]="IncorrectData",e[e.BadSlot=2]="BadSlot",e[e.UnexpectedTicket=3]="UnexpectedTicket",e[e.BadTicketOrder=4]="BadTicketOrder",e[e.BadTicketProof=5]="BadTicketProof",e[e.BadTicketAttempt=6]="BadTicketAttempt",e[e.DuplicateTicket=7]="DuplicateTicket"}($c||($c={}));class Yc{chainSpec;state;bandersnatch;constructor(e,t,r=Vc.new({synchronous:!0})){this.chainSpec=e,this.state=t,this.bandersnatch=r}isEpochChanged(e){const t=Math.floor(this.state.timeslot/this.chainSpec.epochLength);return Math.floor(e/this.chainSpec.epochLength)>t}isSameEpoch(e){const t=Math.floor(this.state.timeslot/this.chainSpec.epochLength);return Math.floor(e/this.chainSpec.epochLength)===t}isNextEpoch(e){const t=Math.floor(this.state.timeslot/this.chainSpec.epochLength);return Math.floor(e/this.chainSpec.epochLength)===t+1}getSlotPhaseIndex(e){return e%this.chainSpec.epochLength}getEntropy(e,t){const[r,...s]=this.state.entropy,i=Tt([r.raw,t]).asOpaque();return this.isEpochChanged(e)?nr.new([i,r,s[0],s[1]],4):nr.new([i,...s],4)}async getValidatorKeys(e){if(!this.isEpochChanged(e)){const{nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s}=this.state;return z.ok({nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s})}const t=this.state.disputesRecords.punishSet,r=this.state.designatedValidatorData.map(e=>!1!==t.has(e.ed25519)?oi.create({bandersnatch:Y.zero(wt).asOpaque(),ed25519:Y.zero(bt).asOpaque(),bls:e.bls,metadata:e.metadata}):e),{nextValidatorData:s,currentValidatorData:i}=this.state,n=await Tc(await this.bandersnatch,r.map(e=>e.bandersnatch));return n.isOk?z.ok({nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n.ok}):z.error($c.IncorrectData)}outsideInSequencer(e){const t=e.length,r=new Array(t),s=Math.floor(t/2);t%2==1&&(r[s]=e[s]);for(let i=0;i<s;i+=1)r[2*i]=e[i],r[2*i+1]=e[t-i-1];return Yr(r,this.chainSpec)}fallbackKeySequencer(e,t){const r=this.chainSpec.epochLength,s=[],i=t.length;for(let n=pe(0);n<r;n++){const r=Ae(n),o=Tt([e.raw,r]).raw,a=we.fromBlob(o).u32()%i;s.push(t[a].bandersnatch)}return Yr(s,this.chainSpec)}getSlotKeySequence(e,t,r){const s=this.getSlotPhaseIndex(this.state.timeslot);return this.isNextEpoch(e)&&s>=this.chainSpec.contestLength&&this.state.ticketsAccumulator.length===this.chainSpec.epochLength?li.tickets(this.outsideInSequencer(this.state.ticketsAccumulator)):this.isSameEpoch(e)?this.state.sealingKeySeries:li.keys(this.fallbackKeySequencer(r,t))}getEpochMark(e,t){if(!this.isEpochChanged(e))return null;const r=this.state.entropy;return ss.create({entropy:r[0],ticketsEntropy:r[1],validators:t.map(e=>rs.create(e))})}verifyTickets(e){const t=e.length;for(let r=1;r<t;r++){const t=e[r-1].id.compare(e[r].id);if(t.isEqual())return z.error($c.DuplicateTicket);if(t.isGreater())return z.error($c.BadTicketOrder)}return z.ok(null)}async getNewTicketAccumulator(e,t,r,s){const i=0===t.length?[]:await Uc(await this.bandersnatch,r.map(e=>e.bandersnatch),t,s),n=t.map((e,t)=>({id:i[t].entropyHash,attempt:e.attempt}));if(!i.every(e=>e.isValid))return z.error($c.BadTicketProof);const o=this.verifyTickets(n);if(o.isError)return z.error(o.error);if(this.isEpochChanged(e))return z.ok(n);const a=ar.fromSortedArray(Fc,this.state.ticketsAccumulator),c=ar.fromSortedArray(Fc,n),l=ar.fromTwoSortedCollections(a,c);return a.length+c.length!==l.length?z.error($c.DuplicateTicket):z.ok(l.array.slice(0,this.chainSpec.epochLength))}getTicketsMark(e){const t=this.getSlotPhaseIndex(this.state.timeslot),r=this.getSlotPhaseIndex(e);return this.isSameEpoch(e)&&t<this.chainSpec.contestLength&&this.chainSpec.contestLength<=r&&this.state.ticketsAccumulator.length===this.chainSpec.epochLength?this.outsideInSequencer(this.state.ticketsAccumulator):null}isExtrinsicLengthValid(e,t){return this.getSlotPhaseIndex(e)<this.chainSpec.contestLength?t.length<=this.chainSpec.maxTicketsPerExtrinsic:0===t.length}areTicketAttemptsValid(e){const t=e.length;for(let r=0;r<t;r++)if(e[r].attempt>=this.chainSpec.ticketsPerValidator)return!1;return!0}getSafroleSealState(e){const t=this.isEpochChanged(e),r=t?this.state.nextValidatorData:this.state.currentValidatorData,s=this.state.entropy[t?1:2];return{currentValidatorData:r,currentEntropy:this.state.entropy[t?2:3],sealingKeySeries:this.getSlotKeySequence(e,r,s)}}async transition(e){if(this.state.timeslot>=e.slot)return z.error($c.BadSlot);if(!this.isExtrinsicLengthValid(e.slot,e.extrinsic))return z.error($c.UnexpectedTicket);if(!this.areTicketAttemptsValid(e.extrinsic))return z.error($c.BadTicketAttempt);const t=await this.getValidatorKeys(e.slot);if(t.isError)return z.error(t.error);const{nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n}=t.ok,o=this.getEntropy(e.slot,e.entropy),a=this.getSlotKeySequence(e.slot,s,o[2]),c=await this.getNewTicketAccumulator(e.slot,e.extrinsic,this.state.nextValidatorData,o[2]);if(c.isError)return z.error(c.error);const l={nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n,timeslot:e.slot,entropy:o,sealingKeySeries:a,ticketsAccumulator:c.ok},h={epochMark:this.getEpochMark(e.slot,r),ticketsMark:this.getTicketsMark(e.slot),stateUpdate:l};return z.ok(h)}}!function(e){e[e.InvalidValidatorIndex=0]="InvalidValidatorIndex",e[e.InvalidValidator=1]="InvalidValidator",e[e.InvalidTicket=2]="InvalidTicket",e[e.IncorrectSeal=3]="IncorrectSeal",e[e.IncorrectEntropySource=4]="IncorrectEntropySource"}(jc||(jc={}));class Xc{bandersnatch;constructor(e=Vc.new({synchronous:!0})){this.bandersnatch=e}async verifyHeaderSeal(e,t){const r=await this.verifySeal(e,t);if(r.isError)return r;const s=J.blobFromParts(xc,r.ok.raw),i=await Oc(await this.bandersnatch,t.currentValidatorData.map(e=>e.bandersnatch),e.bandersnatchBlockAuthorIndex.materialize(),e.entropySource.materialize(),s,J.blobFromNumbers([]));return i.isError?z.error(jc.IncorrectEntropySource):z.ok(i.ok)}async verifySeal(e,t){const r=t.currentValidatorData,s=e.bandersnatchBlockAuthorIndex.materialize(),i=r[s];if(void 0===i)return z.error(jc.InvalidValidatorIndex);const n=e.timeSlotIndex.materialize(),o=t.sealingKeySeries,a=t.currentEntropy;return o.kind===ai.Tickets?await this.verifySealWithTicket(o.tickets,n,a,r,s,e):await this.verifySealWithKeys(o.keys,i,n,a,r,s,e)}async verifySealWithTicket(e,t,r,s,i,n){const o=t%e.length,{id:a,attempt:c}=e[o],l=J.blobFromParts(Bc,r.raw,new Uint8Array([c])),h=await Oc(await this.bandersnatch,s.map(e=>e.bandersnatch),i,n.seal.materialize(),l,is(n));return h.isError?z.error(jc.IncorrectSeal):a.isEqualTo(h.ok)?z.ok(h.ok):z.error(jc.InvalidTicket)}async verifySealWithKeys(e,t,r,s,i,n,o){if(!e[r%e.length].isEqualTo(t.bandersnatch))return z.error(jc.InvalidValidator);const a=J.blobFromParts(_c,s.raw),c=await Oc(await this.bandersnatch,i.map(e=>e.bandersnatch),n,o.seal.materialize(),a,is(o));return c.isError?z.error(jc.IncorrectSeal):z.ok(c.ok)}}function Zc(e){if(e.length===Gc.Requested)return{status:Gc.Requested};if(e.length===Gc.Available)return{status:Gc.Available,data:[e[0]]};if(e.length===Gc.Unavailable)return{status:Gc.Unavailable,data:[e[0],e[1]]};if(e.length===Gc.Reavailable)return{status:Gc.Reavailable,data:[e[0],e[1],e[2]]};throw new Error(`Invalid slots length: ${e.length}`)}!function(e){e[e.Requested=0]="Requested",e[e.Available=1]="Available",e[e.Unavailable=2]="Unavailable",e[e.Reavailable=3]="Reavailable"}(Gc||(Gc={})),function(e){e[e.AlreadyRequested=0]="AlreadyRequested",e[e.AlreadyAvailable=1]="AlreadyAvailable",e[e.InsufficientFunds=2]="InsufficientFunds"}(qc||(qc={})),function(e){e[e.DestinationNotFound=0]="DestinationNotFound",e[e.GasTooLow=1]="GasTooLow",e[e.BalanceBelowThreshold=2]="BalanceBelowThreshold"}(zc||(zc={})),function(e){e[e.InvalidService=0]="InvalidService",e[e.InvalidPreimage=1]="InvalidPreimage"}(Wc||(Wc={})),function(e){e[e.ServiceNotFound=0]="ServiceNotFound",e[e.WasNotRequested=1]="WasNotRequested",e[e.AlreadyProvided=2]="AlreadyProvided"}(Jc||(Jc={}));class el{source;destination;amount;memo;gas;constructor(e,t,r,s,i){this.source=e,this.destination=t,this.amount=r,this.memo=s,this.gas=i}static create({source:e,destination:t,amount:r,memo:s,gas:i}){return new el(e,t,r,s,i)}}class tl{serviceId;static copyFrom(e){const t=new tl(e.serviceId);t.newServices.push(...e.newServices),t.ejectedServices.push(...e.ejectedServices),t.transfers.push(...e.transfers),t.lookupHistory.push(...e.lookupHistory),t.providedPreimages.push(...e.providedPreimages);for(const[r,s]of e.authorizationQueues)t.authorizationQueues.set(r,s);return t.storage.push(...e.storage),t.updatedServiceInfo=null===e.updatedServiceInfo?null:ui.create(e.updatedServiceInfo),t.validatorsData=null===e.validatorsData?null:[...e.validatorsData],t.yieldedRoot=e.yieldedRoot,t.privilegedServices=null===e.privilegedServices?null:{...e.privilegedServices},t}intoServicesUpdate(e){return{servicesRemoved:this.ejectedServices,servicesUpdates:this.newServices.map(e=>Ii.create({serviceId:e.serviceId,serviceInfo:e.data.info,lookupHistory:e.data.lookupHistory.values().next().value?.[0]??null})).concat(null===this.updatedServiceInfo?[]:[Ii.update({serviceId:this.serviceId,serviceInfo:this.updatedServiceInfo})]),preimages:this.providedPreimages.map(t=>Ai.provide({serviceId:t.serviceId,preimage:t.item,slot:e})).concat(this.lookupHistory.map(e=>e.forgotten?Ai.remove({serviceId:this.serviceId,hash:e.hash,length:e.length}):Ai.updateOrAdd({serviceId:this.serviceId,lookupHistory:e}))),storage:this.storage}}newServices=[];ejectedServices=[];transfers=[];lookupHistory=[];providedPreimages=[];authorizationQueues=new Map;updatedServiceInfo=null;yieldedRoot=null;validatorsData=null;privilegedServices=null;storage=[];constructor(e){this.serviceId=e}}class rl extends gi{forgotten;constructor(e,t){super(e.hash,e.length,e.slots),this.forgotten=t}static forget(e){return new rl(e,!0)}static update(e){return new rl(e,!1)}}class sl{serviceId;item;static create({serviceId:e,item:t}){return new sl(e,t)}constructor(e,t){this.serviceId=e,this.item=t}}const il=19200;class nl{state;currentServiceId;updatedState;checkpointedState=null;nextNewServiceId;constructor(e,t,r){if(this.state=e,this.currentServiceId=t,this.updatedState=new tl(t),this.nextNewServiceId=this.getNextAvailableServiceId(r),null===this.state.getService(this.currentServiceId))throw new Error(`Invalid state initialization. Service info missing for ${this.currentServiceId}.`)}getStateUpdates(){return[this.updatedState,this.checkpointedState]}getNextNewServiceId(){return this.nextNewServiceId}getCurrentServiceInfo(){if(null!==this.updatedState.updatedServiceInfo)return this.updatedState.updatedServiceInfo;const e=this.state.getService(this.currentServiceId);return P(e,null!==e,"Service existence in state validated in constructor.").getInfo()}getServiceInfo(e){if(null===e)return null;if(e===this.currentServiceId)return this.getCurrentServiceInfo();const t=this.updatedState.ejectedServices.some(t=>t===e);if(t)return null;const r=this.updatedState.newServices.find(({serviceId:t})=>t===e);if(void 0!==r)return r.data.info;const s=this.state.getService(e);return null===s?null:s.getInfo()}getPreimageStatus(e,t){const r=this.updatedState.lookupHistory.find(r=>r.hash.isEqualTo(e)&&BigInt(r.length)===t);if(void 0!==r)return r;const s=this.state.getService(this.currentServiceId),i=ol(t);if(null===i||null===s)return null;const n=s.getLookupHistory(e,i);return null===n?null:rl.update(new gi(e,i,n))}isPreviousCodeExpired(e,t,r){const s=this.state.getService(e),i=ol(r),n=null===s||null===i?null:s.getLookupHistory(t,i),o=null===n?null:Zc(n);if(o?.status!==Gc.Unavailable)return[!1,"wrong status"];const a=this.state.timeslot,c=o.data[1]<a-il;return[c,c?"":"not expired"]}hasExistingPreimage(e,t){if(null===e)return!1;if(void 0!==this.updatedState.providedPreimages.find(r=>r.serviceId===e&&r.item.hash.isEqualTo(t)))return!0;const r=this.state.getService(e);return void 0!==r&&(r?.hasPreimage(t)??!1)}replaceOrAddPreimageUpdate(e,t){const r=this.updatedState.lookupHistory.indexOf(e),s=-1===r?0:1;this.updatedState.lookupHistory.splice(r,s,t)}getNextAvailableServiceId(e){let t=e;const r=2**32-512;for(;;){if(null===this.getServiceInfo(t))return t;t=jr((t-256+1+r)%r+256)}}checkPreimageStatus(e,t){const r=this.getPreimageStatus(e,t);return null===r||r.forgotten?null:Zc(r.slots)}requestPreimage(e,t){const r=this.getPreimageStatus(e,t);if(null!==r&&!r.forgotten){const e=r.slots.length;if(e===Gc.Requested)return z.error(qc.AlreadyRequested);if(e===Gc.Available||e===Gc.Reavailable)return z.error(qc.AlreadyAvailable);M(e===Gc.Unavailable)}const s=this.getCurrentServiceInfo(),i=function(...e){let t=0,r=!1;for(const s of e){const e=t;t=t+s>>>0,r||=e>t}return{overflow:r,value:pe(t)}}(s.storageUtilisationCount,pe(1)),n=be(s.storageUtilisationBytes,t),o=this.updateServiceStorageUtilisation(i,n,s);if(o.isError)return z.error(qc.InsufficientFunds,o.details);const a=Wa(t);return null===r||r.forgotten?this.updatedState.lookupHistory.push(rl.update(new gi(e,a,pi([])))):this.replaceOrAddPreimageUpdate(r,rl.update(new gi(e,a,pi([...r.slots,this.state.timeslot])))),z.ok($)}updateServiceStorageUtilisation(e,t,r){if(e.overflow||t.overflow)return z.error("insufficient funds");const s=ui.calculateThresholdBalance(e.value,t.value);return r.balance<s?z.error("insufficient funds"):(this.updatedState.updatedServiceInfo=ui.create({...r,storageUtilisationBytes:t.value,storageUtilisationCount:e.value}),z.ok($))}forgetPreimage(e,t){const r=this.getPreimageStatus(e,t);if(null===r||r.forgotten)return z.error(null);const s=Zc(r.slots);if(s.status===Gc.Requested)return this.replaceOrAddPreimageUpdate(r,rl.forget(r)),z.ok($);const i=this.state.timeslot;return s.status===Gc.Unavailable?s.data[1]<i-il?(this.replaceOrAddPreimageUpdate(r,rl.forget(r)),z.ok($)):z.error(null):s.status===Gc.Available?(this.replaceOrAddPreimageUpdate(r,rl.update(new gi(r.hash,r.length,pi([s.data[0],i])))),z.ok($)):s.status===Gc.Reavailable?s.data[1]<i-il?(this.replaceOrAddPreimageUpdate(r,rl.update(new gi(r.hash,r.length,pi([s.data[2],i])))),z.ok($)):z.error(null):void L(s)}transfer(e,t,r,s){const i=this.getCurrentServiceInfo(),n=this.getServiceInfo(e);if(null===n||null===e)return z.error(zc.DestinationNotFound);if(r<n.onTransferMinGas)return z.error(zc.GasTooLow);const o=i.balance-t;return o<ui.calculateThresholdBalance(i.storageUtilisationCount,i.storageUtilisationBytes)?z.error(zc.BalanceBelowThreshold):(this.updatedState.transfers.push(el.create({source:this.currentServiceId,destination:e,amount:t,memo:s,gas:r})),this.updatedState.updatedServiceInfo=ui.create({...i,balance:ye(o)}),z.ok($))}newService(e,t,r,s){const i=this.nextNewServiceId,n=pe(2),o=be(ye(81),t),a=Wa(t),c=ui.calculateThresholdBalance(n,o.value),l=this.getCurrentServiceInfo(),h=ui.calculateThresholdBalance(l.storageUtilisationCount,l.storageUtilisationBytes),u=l.balance-c;if(u<h||o.overflow)return z.error("insufficient funds");const d=new Oi(i,{info:ui.create({codeHash:e,balance:c,accumulateMinGas:r,onTransferMinGas:s,storageUtilisationBytes:o.value,storageUtilisationCount:n}),preimages:rr.new(),lookupHistory:rr.fromEntries([[e.asOpaque(),[new gi(e.asOpaque(),a,pi([]))]]]),storage:rr.new()});return this.updatedState.newServices.push(d),this.updatedState.updatedServiceInfo=ui.create({...l,balance:ye(u)}),this.nextNewServiceId=this.getNextAvailableServiceId(function(e){const t=2**32-512;return jr(256+(e-256+42+t)%t)}(i)),z.ok(i)}upgradeService(e,t,r){const s=this.getCurrentServiceInfo();this.updatedState.updatedServiceInfo=ui.create({...s,codeHash:e,accumulateMinGas:Gr(t),onTransferMinGas:Gr(r)})}updateValidatorsData(e){this.updatedState.validatorsData=e}checkpoint(){this.checkpointedState=tl.copyFrom(this.updatedState)}updateAuthorizationQueue(e,t){this.updatedState.authorizationQueues.set(e,t)}updatePrivilegedServices(e,t,r,s){this.updatedState.privilegedServices={manager:e,authorizer:t,validators:r,autoAccumulate:s}}yield(e){this.updatedState.yieldedRoot=e}providePreimage(e,t){const r=null===e?null:this.state.getService(e);if(null===r||null===e)return z.error(Jc.ServiceNotFound);const s=Nt(t).asOpaque();if(e===this.currentServiceId){const e=this.getPreimageStatus(s,ye(t.length));if(null===e||!gi.isRequested(e)||e.forgotten)return z.error(Jc.WasNotRequested)}else{const e=r.getLookupHistory(s,pe(t.length));if(null===e||!gi.isRequested(e))return z.error(Jc.WasNotRequested)}return this.hasExistingPreimage(e,s)?z.error(Jc.AlreadyProvided):(this.updatedState.providedPreimages.push(sl.create({serviceId:e,item:di.create({hash:s,blob:t})})),z.ok($))}eject(e,t){const r=this.getServiceInfo(e);if(null===r||null===e)return z.error(Wc.InvalidService,"Service missing");const s=this.getCurrentServiceInfo(),i=Y.zero(Ct).asOpaque();if(za(this.currentServiceId,i.raw),!r.codeHash.isEqualTo(i))return z.error(Wc.InvalidService,"Invalid code hash");if(2!==r.storageUtilisationCount)return z.error(Wc.InvalidPreimage,"Too many storage items");const n=ye(81),o=ye(((e,...t)=>t.reduce((e,t)=>t<e?e:t,e))(r.storageUtilisationBytes,n)-n),[a,c]=this.isPreviousCodeExpired(e,t,o);if(!a)return z.error(Wc.InvalidPreimage,`Previous code available: ${c}`);const l=be(s.balance,r.balance);return l.overflow?z.error(Wc.InvalidService,"Balance overflow"):(this.updatedState.updatedServiceInfo=ui.create({...s,balance:l.value}),this.updatedState.ejectedServices.push(e),z.ok($))}replaceOrAddStorageUpdate(e,t){const r=null===t?vi.remove({serviceId:this.currentServiceId,key:e}):vi.set({serviceId:this.currentServiceId,storage:fi.create({hash:e,blob:t})}),s=this.updatedState.storage.findIndex(t=>t.serviceId===r.serviceId&&t.key.isEqualTo(e)),i=-1===s?0:1;this.updatedState.storage.splice(s,i,r)}read(e,t){if(null===e)return null;if(this.currentServiceId===e){const r=this.updatedState.storage.find(r=>r.serviceId===e&&r.key.isEqualTo(t));if(void 0!==r)return r.value}const r=this.state.getService(e);return r?.getStorage(t)??null}write(e,t){const r=this.read(this.currentServiceId,e),s=null===r&&null!==t?1:null!==r&&null===t?-1:0,i=(t?.length??0)-(r?.length??0),n=this.getCurrentServiceInfo(),o=n.storageUtilisationCount+s,a=n.storageUtilisationBytes+BigInt(i);M(o>=0,`storageUtilisationCount has to be a positive number, got: ${o}`),M(a>=0,`storageUtilisationBytes has to be a positive number, got: ${a}`);const c=!ge(o),l=!me(a),h=this.updateServiceStorageUtilisation({overflow:c,value:c?pe(0):o},{overflow:l,value:l?ye(0):a},n);return h.isError?z.error("full",h.details):(this.replaceOrAddStorageUpdate(e,t),z.ok($))}readSnapshotLength(e){const t=this.state.getService(this.currentServiceId);return t?.getStorage(e)?.length??null}lookup(e,t){if(null===e)return null;const r=this.updatedState.providedPreimages.find(r=>r.serviceId===e&&r.item.hash.isEqualTo(t));if(void 0!==r)return r.item.blob;const s=this.state.getService(e);return s?.getPreimage(t)??null}}function ol(e){return e>=2n**32n?null:pe(Number(e))}function al(e){const t=e.map(e=>e.workPackageSpec.hash);return sr.from(t)}const cl=Pe.object({serviceId:Pe.u32.asOpaque(),entropy:Pe.bytes(Ct).asOpaque(),timeslot:Pe.u32.asOpaque()});class ll{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}getWorkReportsToAccumulateImmediately(e){return e.filter(e=>0===e.context.prerequisites.length&&0===e.segmentRootLookup.length)}getWorkReportDependencies(e){return Array.from(sr.from(e.context.prerequisites.concat(e.segmentRootLookup.map(e=>e.workPackageHash))))}getWorkReportsToAccumulateLater(e){const t=this.state.recentlyAccumulated.flatMap(e=>Array.from(e));return hl(e.filter(e=>e.context.prerequisites.length>0||e.segmentRootLookup.length>0).map(e=>Ni.create({report:e,dependencies:this.getWorkReportDependencies(e)})),sr.from(t))}enqueueReports(e){const t=[];let r=[...e];for(;r.length>0;){const e=r.filter(({dependencies:e})=>0===e.length).map(({report:e})=>e);if(0===e.length)return t;t.push(...e),r=hl(r,al(e))}return t}getQueueFromState(e){const t=e%this.chainSpec.epochLength,r=this.state.accumulationQueue.slice(t),s=this.state.accumulationQueue.slice(0,t);return r.concat(s).flat()}}function hl(e,t){return e.filter(({report:e})=>!t.has(e.workPackageSpec.hash)).map(e=>{const{report:r,dependencies:s}=e;return Ni.create({report:r,dependencies:s.filter(e=>!t.has(e))})})}var ul;!function(e){e[e.InvalidAnchor=0]="InvalidAnchor",e[e.InvalidOrder=1]="InvalidOrder",e[e.InvalidSignature=2]="InvalidSignature",e[e.NoReportPending=3]="NoReportPending",e[e.InvalidValidatorIndex=4]="InvalidValidatorIndex"}(ul||(ul={}));class dl{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}async transition(e){const t=this.chainSpec.coresCount,r=this.verifySignatures(e.assurances),s=e.assurances.map(e=>e.materialize()),i=nr.new(Array(t).fill(0),t);let n=-1;for(const r of s){const{anchor:s,validatorIndex:o,bitfield:a}=r;if(!s.isEqualTo(e.parentHash))return z.error(ul.InvalidAnchor,`anchor: expected: ${e.parentHash}, got ${s}`);if(n>=o)return z.error(ul.InvalidOrder,`order: expected: ${n+1}, got: ${o}`);n=r.validatorIndex,M(a.bitLength===t,`Invalid bitfield length of ${a.bitLength}`);const c=a.indicesOfSetBits();for(const e of c)i[e]+=1}const o=[],a=[],c=this.chainSpec.validatorsSuperMajority;for(let r=0;r<t;r++){const t=i[r],s=this.state.availabilityAssignment[r],n=null!==s;if(t>0&&!n)return z.error(ul.NoReportPending,`no report pending for core ${r} yet we got an assurance`);n&&(e.slot>=s.timeout+5&&a.push(r),t>=c&&(o.push(s.workReport.data),a.push(r)))}const l=await r;if(l.isError)return l;const h=this.state.availabilityAssignment.slice();for(const e of a)h[e]=null;return z.ok({availableReports:o,stateUpdate:{availabilityAssignment:h}})}async verifySignatures(e){const t=this.state.currentValidatorData,r=[];for(const s of e){const e=s.view(),i=t[e.validatorIndex.materialize()];if(void 0===i)return z.error(ul.InvalidValidatorIndex);r.push({signature:e.signature.materialize(),key:i.ed25519,message:pl(e.anchor.encoded(),e.bitfield.encoded())})}const s=await It(r),i=s.every(e=>e);if(!i){const e=s.reduce((e,t,r)=>t?e:e.concat(r),[]);return z.error(ul.InvalidSignature,`invalid signatures at ${e.join(", ")}`)}return z.ok($)}}const fl=J.blobFromString("jam_available").raw;function pl(e,t){return J.blobFromParts(fl,Nt(J.blobFromParts(e.raw,t.raw)).raw)}const gl=J.blobFromString("peak");class yl{hasher;mountains;static empty(e){return new yl(e)}static fromPeaks(e,t){return new yl(e,t.peaks.reduce((e,t,r)=>(null!==t&&e.push(ml.fromPeak(t,2**r)),e),[]).reverse())}constructor(e,t=[]){this.hasher=e,this.mountains=t}append(e){let t=ml.fromPeak(e,1);for(;;){const e=this.mountains.pop();if(void 0===e)return void this.mountains.push(t);if(e.size!==t.size)return this.mountains.push(e),void this.mountains.push(t);t=e.mergeWith(this.hasher,t)}}getSuperPeakHash(){if(0===this.mountains.length)return Y.zero(Ct).asOpaque();const e=this.mountains.slice().reverse(),t=e.length;let r=e[0].peak;for(let s=1;s<t;s++){const t=e[s];r=this.hasher.hashConcatPrepend(gl,r,t.peak)}return r}getPeaks(){const e=[],t=this.mountains;let r=1,s=t.length-1;for(;s>=0;){const i=t[s];i.size>=r&&i.size<2*r?(e.push(i.peak),s-=1):e.push(null),r<<=1}return{peaks:e}}}class ml{peak;size;constructor(e,t){this.peak=e,this.size=t}static fromPeak(e,t){return new ml(e,t)}static fromChildren(e,t){const[r,s]=t,i=e.hashConcat(r.peak,s.peak),n=r.size+s.size;return new ml(i,n)}mergeWith(e,t){return ml.fromChildren(e,[this,t])}toString(){return`${this.size} @ ${this.peak}`}}var bl;!function(e){e[e.BadCoreIndex=0]="BadCoreIndex",e[e.FutureReportSlot=1]="FutureReportSlot",e[e.ReportEpochBeforeLast=2]="ReportEpochBeforeLast",e[e.InsufficientGuarantees=3]="InsufficientGuarantees",e[e.OutOfOrderGuarantee=4]="OutOfOrderGuarantee",e[e.NotSortedOrUniqueGuarantors=5]="NotSortedOrUniqueGuarantors",e[e.WrongAssignment=6]="WrongAssignment",e[e.CoreEngaged=7]="CoreEngaged",e[e.AnchorNotRecent=8]="AnchorNotRecent",e[e.BadServiceId=9]="BadServiceId",e[e.BadCodeHash=10]="BadCodeHash",e[e.DependencyMissing=11]="DependencyMissing",e[e.DuplicatePackage=12]="DuplicatePackage",e[e.BadStateRoot=13]="BadStateRoot",e[e.BadBeefyMmrRoot=14]="BadBeefyMmrRoot",e[e.CoreUnauthorized=15]="CoreUnauthorized",e[e.BadValidatorIndex=16]="BadValidatorIndex",e[e.WorkReportGasTooHigh=17]="WorkReportGasTooHigh",e[e.ServiceItemGasTooLow=18]="ServiceItemGasTooLow",e[e.TooManyDependencies=19]="TooManyDependencies",e[e.SegmentRootLookupInvalid=20]="SegmentRootLookupInvalid",e[e.BadSignature=21]="BadSignature",e[e.WorkReportTooBig=22]="WorkReportTooBig"}(bl||(bl={}));class Al{static Codec=Pe.Class(Al,{gas:Pe.u64.asOpaque(),payloadHash:Pe.bytes(Ct),result:Tr.Codec,authorizationOutput:Pe.blob,exportsRoot:Pe.bytes(Ct).asOpaque(),hash:Pe.bytes(Ct).asOpaque(),authorizerHash:Pe.bytes(Ct).asOpaque()});gas;payloadHash;result;authorizationOutput;exportsRoot;hash;authorizerHash;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,gas:s,hash:i,payloadHash:n,result:o}){return new Al({gas:Gr(s),payloadHash:n.asOpaque(),result:o,authorizationOutput:J.blobFrom(e.raw),exportsRoot:r.asOpaque(),hash:i.asOpaque(),authorizerHash:t.asOpaque()})}constructor(e){this.gas=e.gas,this.payloadHash=e.payloadHash,this.result=e.result,this.authorizationOutput=e.authorizationOutput,this.exportsRoot=e.exportsRoot,this.hash=e.hash,this.authorizerHash=e.authorizerHash}static new(e){return new Al(e)}}class Il{static Codec=Pe.Class(Il,{hash:Pe.bytes(Ct).asOpaque(),exportsRoot:Pe.bytes(Ct).asOpaque(),authorizerHash:Pe.bytes(Ct).asOpaque(),authorizationOutput:Pe.blob,payloadHash:Pe.bytes(Ct),result:Tr.Codec});hash;exportsRoot;authorizerHash;authorizationOutput;payloadHash;result;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,hash:s,payloadHash:i,result:n}){return new Il({payloadHash:i,result:n,authorizationOutput:e,exportsRoot:r,hash:s,authorizerHash:t})}constructor(e){this.payloadHash=e.payloadHash,this.result=e.result,this.authorizationOutput=e.authorizationOutput,this.exportsRoot=e.exportsRoot,this.hash=e.hash,this.authorizerHash=e.authorizerHash}static new(e){return new Il(e)}}const vl=Pe.object({B_I:Pe.u64,B_L:Pe.u64,B_S:Pe.u64,C:Pe.u16,D:Pe.u32,E:Pe.u32,G_A:Pe.u64,G_I:Pe.u64,G_R:Pe.u64,G_T:Pe.u64,H:Pe.u16,I:Pe.u16,J:Pe.u16,L:Pe.u32,O:Pe.u16,P:Pe.u16,Q:Pe.u16,R:Pe.u16,S:Pe.u16,T:Pe.u16,U:Pe.u16,V:Pe.u16,W_A:Pe.u32,W_B:Pe.u32,W_C:Pe.u32,W_E:Pe.u32,W_G:Pe.u32,W_M:Pe.u32,W_P:Pe.u32,W_R:Pe.u32,W_T:Pe.u32,W_X:Pe.u32,Y:Pe.u32}),wl=new Map;class Sl{entropyHash;operands;chainSpec;constructor(e,t,r){this.entropyHash=e,this.operands=t,this.chainSpec=r}constants(){return function(e){const t=wl.get(e);if(void 0!==t)return t;const r=_e.encodeObject(vl,{B_I:ye(10n),B_L:ye(1n),B_S:ye(100n),C:de(e.coresCount),D:pe(il),E:pe(e.epochLength),G_A:ye(Ql),G_I:ye(5e7),G_R:ye(5e9),G_T:ye(Vl),H:de(8),I:de(Br),J:de(8),L:pe(14400),O:de(8),P:de(e.slotDuration),Q:de(80),R:de(e.rotationPeriod),S:de(1024),T:de(128),U:de(5),V:de(e.validatorsCount),W_A:pe(64e3),W_B:pe(13794305),W_C:pe(4e6),W_E:pe(684),W_G:pe(4104),W_M:pe(3072),W_P:pe(6),W_R:pe(49152),W_T:pe(128),W_X:pe(3072),Y:pe(500)});return wl.set(e,r),r}(this.chainSpec)}entropy(){return this.entropyHash.asOpaque()}authorizerTrace(){return null}workItemExtrinsic(e,t){return null}workItemImport(e,t){return null}workPackage(){return null}authorizer(){return null}authorizationToken(){return null}refineContext(){return null}allWorkItems(){return null}oneWorkItem(e){return null}workItemPayload(e){return null}allOperands(){return _e.encodeObject(Pe.sequenceVarLen(Il.Codec),this.operands,this.chainSpec)}oneOperand(e){if(e>=2n**32n)return null;const t=this.operands[Number(e)];return void 0===t?null:_e.encodeObject(Il.Codec,t,this.chainSpec)}allTransfers(){return null}oneTransfer(e){return null}}const El=Pe.object({serviceId:Pe.u32.convert(e=>e,e=>e),gas:Pe.u64.convert(e=>ye(e),e=>Gr(e))});class Cl{currentServiceId;index=zn(0);gasCost=co(10);constructor(e){this.currentServiceId=e}execute(e,t){return t.set(7,ye(e.get())),Promise.resolve(void 0)}}const kl=Ce(oi.Codec.sizeHint),xl=e=>ye(e);var _l,Bl,Rl;!function(e){e[e.SourcePageFault=0]="SourcePageFault",e[e.DestinationPageFault=1]="DestinationPageFault",e[e.NoMachine=2]="NoMachine"}(_l||(_l={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidPage=1]="InvalidPage"}(Bl||(Bl={})),Symbol("Machine index not found."),Symbol("Too many segments already exported.");class Ol{currentServiceId;fetch;index=zn(18);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.fetch=t}async execute(e,t,r){const s=this.getValue(t),i=t.get(7),n=ye(s?.length??0),o=ve(t.get(8),n),a=ve(t.get(9),ye(n-o)),c=null===s?new Uint8Array:s.raw.subarray(Number(o),Number(o+a));if(r.storeFrom(i,c).isError)return Wn.Panic;t.set(7,null===s?Va.NONE:n)}getValue(e){const t=Wa(e.get(10));if(t===Rl.Constants)return this.fetch.constants();if(t===Rl.Entropy)return this.fetch.entropy();if(t===Rl.AuthorizerTrace)return this.fetch.authorizerTrace();if(t===Rl.OtherWorkItemExtrinsics){const t=e.get(11),r=e.get(12);return this.fetch.workItemExtrinsic(t,r)}if(t===Rl.MyExtrinsics){const t=e.get(11);return this.fetch.workItemExtrinsic(null,t)}if(t===Rl.OtherWorkItemImports){const t=e.get(11),r=e.get(12);return this.fetch.workItemImport(t,r)}if(t===Rl.MyImports){const t=e.get(11);return this.fetch.workItemImport(null,t)}if(t===Rl.WorkPackage)return this.fetch.workPackage();if(t===Rl.Authorizer)return this.fetch.authorizer();if(t===Rl.AuthorizationToken)return this.fetch.authorizationToken();if(t===Rl.RefineContext)return this.fetch.refineContext();if(t===Rl.AllWorkItems)return this.fetch.allWorkItems();if(t===Rl.OneWorkItem){const t=e.get(11);return this.fetch.oneWorkItem(t)}if(t===Rl.WorkItemPayload){const t=e.get(11);return this.fetch.workItemPayload(t)}if(t===Rl.AllOperands)return this.fetch.allOperands();if(t===Rl.OneOperand){const t=e.get(11);return this.fetch.oneOperand(t)}if(t===Rl.AllTransfers)return this.fetch.allTransfers();if(t===Rl.OneTransfer){const t=e.get(11);return this.fetch.oneTransfer(t)}return null}}!function(e){e[e.Constants=0]="Constants",e[e.Entropy=1]="Entropy",e[e.AuthorizerTrace=2]="AuthorizerTrace",e[e.OtherWorkItemExtrinsics=3]="OtherWorkItemExtrinsics",e[e.MyExtrinsics=4]="MyExtrinsics",e[e.OtherWorkItemImports=5]="OtherWorkItemImports",e[e.MyImports=6]="MyImports",e[e.WorkPackage=7]="WorkPackage",e[e.Authorizer=8]="Authorizer",e[e.AuthorizationToken=9]="AuthorizationToken",e[e.RefineContext=10]="RefineContext",e[e.AllWorkItems=11]="AllWorkItems",e[e.OneWorkItem=12]="OneWorkItem",e[e.WorkItemPayload=13]="WorkItemPayload",e[e.AllOperands=14]="AllOperands",e[e.OneOperand=15]="OneOperand",e[e.AllTransfers=16]="AllTransfers",e[e.OneTransfer=17]="OneTransfer"}(Rl||(Rl={}));class Ul{currentServiceId;account;index=zn(4);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=Ga(7,t,this.currentServiceId),i=t.get(8),n=this.account.getServiceInfo(s),o=null===n?J.empty():_e.encodeObject(Tl,{...n,thresholdBalance:ui.calculateThresholdBalance(n.storageUtilisationCount,n.storageUtilisationBytes)});if(r.storeFrom(i,o.raw).isError)return Wn.Panic;null!==n?t.set(7,Va.OK):t.set(7,Va.NONE)}}const Tl=Pe.object({codeHash:Pe.bytes(Ct),balance:Pe.u64,thresholdBalance:Pe.u64,accumulateMinGas:Pe.u64.convert(e=>e,Gr),onTransferMinGas:Pe.u64.convert(e=>e,Gr),storageUtilisationBytes:Pe.u64,storageUtilisationCount:Pe.u32},"ServiceAccountInfoWithThresholdBalance");class Nl{currentServiceId;account;index=zn(1);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=Ga(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),o=Y.zero(Ct);if(r.loadInto(o.raw,i).isError)return Wn.Panic;const a=this.account.lookup(s,o),c=ye(null===a?0:a.raw.length),l=t.get(10),h=t.get(11),u=ve(l,c),d=ve(h,ye(c-u)),f=null===a?new Uint8Array(0):a.raw.subarray(Number(u),Number(u+d));if(r.storeFrom(n,f).isError)return Wn.Panic;null!==a?t.set(7,c):t.set(7,Va.NONE)}}class Dl{currentServiceId;account;index=zn(2);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=Ga(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),o=t.get(10),a=Wa(n),c=new Uint8Array(4+a);if(null!==s&&za(s,c),r.loadInto(c.subarray(4),i).isError)return Wn.Panic;const l=Nt(c),h=this.account.read(s,l),u=ye(null===h?0:h.raw.length),d=t.get(11),f=t.get(12),p=ve(d,u),g=ve(f,ye(u-p)),y=null===h?new Uint8Array(0):h.raw.subarray(Number(p),Number(p+g));if(r.storeFrom(o,y).isError)return Wn.Panic;null!==h?t.set(7,u):t.set(7,Va.NONE)}}class Ml{currentServiceId;account;index=zn(3);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),o=t.get(10),a=Wa(i),c=new Uint8Array(4+a);if(za(this.currentServiceId,c),r.loadInto(c.subarray(4),s).isError)return Wn.Panic;const l=Nt(c),h=Wa(o),u=new Uint8Array(h);if(r.loadInto(u,n).isError)return Wn.Panic;const d=0n===o?null:J.blobFrom(u);if(this.account.write(l,d).isError)return void t.set(7,Va.FULL);const f=this.account.readSnapshotLength(l);t.set(7,null===f?Va.NONE:ye(f))}}const Pl=[class{currentServiceId;partialState;index=zn(5);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=qa(t.get(7)),i=qa(t.get(8)),n=qa(t.get(9)),o=t.get(10),a=t.get(11),c=new Array,l=new Uint8Array(Ce(El.sizeHint)),h=we.fromBlob(l);let u=o;for(let e=0n;e<a;e+=1n){if(h.resetTo(0),r.loadInto(l,u).isError)return Wn.Panic;const{serviceId:e,gas:t}=h.object(El);c.push([e,t]),u=ye(u+ye(h.bytesRead()))}null!==s&&null!==i&&null!==n?(this.partialState.updatePrivilegedServices(s,i,n,c),t.set(7,Va.OK)):t.set(7,Va.WHO)}},class{currentServiceId;partialState;chainSpec;index=zn(6);gasCost=co(10);constructor(e,t,r){this.currentServiceId=e,this.partialState=t,this.chainSpec=r}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=new Uint8Array(2560);if(r.loadInto(n,i).isError)return Wn.Panic;if(s>=this.chainSpec.coresCount)return void t.set(7,Va.CORE);const o=we.fromBlob(n).sequenceFixLen(Pe.bytes(Ct),80),a=nr.new(o,80);t.set(7,Va.OK),this.partialState.updateAuthorizationQueue(qr(Number(s)),a)}},class{currentServiceId;partialState;chainSpec;index=zn(7);gasCost=co(10);constructor(e,t,r){this.currentServiceId=e,this.partialState=t,this.chainSpec=r}async execute(e,t,r){const s=t.get(7),i=new Uint8Array(kl*this.chainSpec.validatorsCount);if(r.loadInto(i,s).isError)return Wn.Panic;const n=we.fromBlob(i).sequenceFixLen(oi.Codec,this.chainSpec.validatorsCount);t.set(7,Va.OK),this.partialState.updateValidatorsData(Wr(n,this.chainSpec))}},class{currentServiceId;partialState;index=zn(8);gasCost=co(10);gasHostCall;constructor(e,t){this.currentServiceId=e,this.partialState=t,this.gasHostCall=new Cl(e)}async execute(e,t){await this.gasHostCall.execute(e,t),this.partialState.checkpoint()}},class{currentServiceId;partialState;index=zn(9);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=Gr(t.get(9)),o=Gr(t.get(10)),a=Y.zero(Ct);if(r.loadInto(a.raw,s).isError)return Wn.Panic;const c=this.partialState.newService(a.asOpaque(),i,n,o);c.isOk?t.set(7,ye(c.ok)):t.set(7,Va.CASH)}},class{currentServiceId;partialState;index=zn(10);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),o=Y.zero(Ct);if(r.loadInto(o.raw,s).isError)return Wn.Panic;this.partialState.upgradeService(o.asOpaque(),i,n),t.set(7,Va.OK)}},class{currentServiceId;partialState;index=zn(11);gasCost=e=>{const t=10n+e.get(9);return ho(t)};constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=qa(t.get(7)),i=t.get(8),n=Gr(t.get(9)),o=t.get(10),a=Y.zero(128);if(r.loadInto(a.raw,o).isError)return Wn.Panic;const c=this.partialState.transfer(s,i,n,a);if(c.isOk)return void t.set(7,Va.OK);const l=c.error;l!==zc.DestinationNotFound?l!==zc.GasTooLow?l!==zc.BalanceBelowThreshold?L(l):t.set(7,Va.CASH):t.set(7,Va.LOW):t.set(7,Va.WHO)}},class{currentServiceId;partialState;index=zn(12);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=qa(t.get(7)),i=t.get(8),n=Y.zero(Ct).asOpaque();if(r.loadInto(n.raw,i).isError)return Wn.Panic;if(s===this.currentServiceId)return void t.set(7,Va.WHO);const o=this.partialState.eject(s,n);if(o.isOk)return void t.set(7,Va.OK);const a=o.error;a===Wc.InvalidService?t.set(7,Va.WHO):a===Wc.InvalidPreimage?t.set(7,Va.HUH):L(a)}},class{currentServiceId;partialState;index=zn(13);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=Y.zero(Ct);if(r.loadInto(n.raw,s).isError)return Wn.Panic;const o=this.partialState.checkPreimageStatus(n.asOpaque(),i),a=ye(0n);if(null===o)return t.set(7,Va.NONE),void t.set(8,a);switch(o.status){case Gc.Requested:return t.set(7,a),void t.set(8,a);case Gc.Available:return t.set(7,ye(1n+(BigInt(o.data[0])<<32n))),void t.set(8,a);case Gc.Unavailable:return t.set(7,ye(2n+(BigInt(o.data[0])<<32n))),void t.set(8,ye(o.data[1]));case Gc.Reavailable:return t.set(7,ye(3n+(BigInt(o.data[0])<<32n))),void t.set(8,ye((BigInt(o.data[2])<<32n)+BigInt(o.data[1])))}}},class{currentServiceId;partialState;index=zn(14);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=Y.zero(Ct);if(r.loadInto(n.raw,s).isError)return Wn.Panic;const o=this.partialState.requestPreimage(n.asOpaque(),i);if(o.isOk)return void t.set(7,Va.OK);const a=o.error;a!==qc.AlreadyAvailable&&a!==qc.AlreadyRequested?a!==qc.InsufficientFunds?L(a):t.set(7,Va.FULL):t.set(7,Va.HUH)}},class{currentServiceId;partialState;index=zn(15);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=Y.zero(Ct);if(r.loadInto(n.raw,s).isError)return Wn.Panic;this.partialState.forgetPreimage(n.asOpaque(),i).isOk?t.set(7,Va.OK):t.set(7,Va.HUH)}},class{currentServiceId;partialState;index=zn(16);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=Y.zero(Ct);if(r.loadInto(i.raw,s).isError)return Wn.Panic;this.partialState.yield(i),t.set(7,Va.OK)}},class{currentServiceId;partialState;index=zn(27);gasCost=co(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=Ga(7,t,this.currentServiceId),i=t.get(8),n=Wa(t.get(9)),o=J.blobFrom(new Uint8Array(n));if(r.loadInto(o.raw,i).isError)return Wn.Panic;const a=this.partialState.providePreimage(s,o);if(a.isOk)return void t.set(7,Va.OK);const c=a.error;c!==Jc.ServiceNotFound?c!==Jc.WasNotRequested&&c!==Jc.AlreadyProvided?L(c):t.set(7,Va.HUH):t.set(7,Va.WHO)}}];var Ll,Hl;!function(e){e.IS_AUTHORIZED=xl(0),e.REFINE=xl(0),e.ACCUMULATE=xl(5),e.ON_TRANSFER=xl(10)}(Ll||(Ll={}));class Kl{serviceCode;entrypoint;pvm;hostCalls;pvmInstanceManager=new Qa(4);constructor(e,t,r){this.serviceCode=e,this.entrypoint=r,this.hostCalls=new Ja(...t),this.pvm=new Ka(this.pvmInstanceManager,this.hostCalls)}static prepareAccumulateHostCalls(e,t,r){const s=Pl.map(s=>new s(e,t.partialState,r)),i=[new Cl(e),new Dl(e,t.serviceExternalities),new Ml(e,t.serviceExternalities),new Ol(e,t.fetchExternalities),new Nl(e,t.serviceExternalities),new Ul(e,t.serviceExternalities)];return s.concat(i)}async run(e,t){const r=cc.fromSpi(this.serviceCode.raw,e.raw,!0);return this.pvm.runProgram(r.code,Number(this.entrypoint),t,r.registers,r.memory)}static createAccumulateExecutor(e,t,r,s){const i=Kl.prepareAccumulateHostCalls(e,r,s);return new Kl(t,i,Ll.ACCUMULATE)}}!function(e){e[e.NoService=0]="NoService",e[e.NoPreimage=1]="NoPreimage"}(Hl||(Hl={}));const Ql=10000000n,Vl=3500000000n,Fl=m.new(void 0,"accumulate"),$l=Pe.object({slot:Pe.u32.asOpaque(),serviceId:Pe.u32.asOpaque(),operands:Pe.sequenceVarLen(Il.Codec)});class jl{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}findReportCutoffIndex(e,t){const r=t.length;let s=0n;for(let i=0;i<r;i++){const r=t[i].results.map(e=>e.gas).reduce((e,t)=>e+t,0n);if(s+r>e)return i;s+=r}return r}async pvmAccumulateInvocation(e,t,r,s,i){const n=this.state.getService(t);if(null===n)return Fl.log(`Service with id ${t} not found.`),z.error(Hl.NoService);const o=n.getInfo().codeHash,a=n.getPreimage(o.asOpaque());if(null===a)return Fl.log(`Code with hash ${o} not found for service ${t}.`),z.error(Hl.NoPreimage);const c=function({serviceId:e,entropy:t,timeslot:r},s){const i=Ie(Nt(_e.encodeObject(cl,{serviceId:e,entropy:t,timeslot:r},s)).raw.subarray(0,4))>>>0;return jr(i%(2**32-512)+256)}({serviceId:t,entropy:i,timeslot:e},this.chainSpec),l=new nl(this.state,t,c),h={partialState:l,serviceExternalities:l,fetchExternalities:new Sl(i,r,this.chainSpec)},u=Kl.createAccumulateExecutor(t,a,h,this.chainSpec),d=_e.encodeObject($l,{slot:e,serviceId:t,operands:r},this.chainSpec),f=await u.run(d,ho(s)),[p,g]=l.getStateUpdates();if(f.hasStatus()){const e=f.status;if(e===Gn.OOG||e===Gn.PANIC)return z.ok({stateUpdate:g,consumedGas:Gr(f.consumedGas)})}if(f.hasMemorySlice()&&f.memorySlice.length===Ct){const e=Y.fromBlob(f.memorySlice,Ct);p.yieldedRoot=e.asOpaque()}return z.ok({stateUpdate:p,consumedGas:Gr(f.consumedGas)})}getOperandsAndGasCost(e,t){let r=this.state.privilegedServices.autoAccumulateServices.find(t=>t.service===e)?.gasLimit??Gr(0n);const s=[];for(const i of t){const t=i.results.filter(t=>t.serviceId===e);for(const e of t)r=Gr(r+e.gas),s.push(Il.new({payloadHash:e.payloadHash,result:e.result,authorizationOutput:i.authorizationOutput,exportsRoot:i.workPackageSpec.exportsRoot,hash:i.workPackageSpec.hash,authorizerHash:i.authorizerHash}))}return{operands:s,gasCost:r}}async accumulateSingleService(e,t,r,s){const{operands:i,gasCost:n}=this.getOperandsAndGasCost(e,t),o=await this.pvmAccumulateInvocation(r,e,i,n,s);return o.isError?{stateUpdate:null,consumedGas:n}:o.ok}async accumulateSequentially(e,t,r,s){const i=this.findReportCutoffIndex(e,t);if(0===i)return{accumulatedReports:pe(0),gasCosts:[],yieldedRoots:[],pendingTransfers:[],stateUpdates:[]};const n=t.slice(0,i),o=t.slice(i),{gasCosts:a,yieldedRoots:c,pendingTransfers:l,stateUpdates:h,...u}=await this.accumulateInParallel(n,r,s),d=a.reduce((e,[t,r])=>e+r,0n),{accumulatedReports:f,gasCosts:p,yieldedRoots:g,pendingTransfers:y,stateUpdates:m,...b}=await this.accumulateSequentially(Gr(e-d),o,r,s);return{accumulatedReports:pe(i+f),gasCosts:a.concat(p),yieldedRoots:c.concat(g),pendingTransfers:l.concat(y),stateUpdates:h.concat(m)}}async accumulateInParallel(e,t,r){const s=this.state.privilegedServices.autoAccumulateServices.map(({service:e})=>e),i=e.flatMap(e=>e.results.map(e=>e.serviceId)).concat(Array.from(s)),n=function(e){const t=new Set;for(const r of e)t.add(r);return Array.from(t)}(s.concat(i)),o=[],a=[],c=[],l=[];for(const s of n){const{consumedGas:i,stateUpdate:n}=await this.accumulateSingleService(s,e,t,r);a.push([s,Gr(i)]),null!==n&&(o.push([s,n]),l.push([s,n.transfers]),null!==n.yieldedRoot&&c.push([s,n.yieldedRoot]))}return{stateUpdates:o,pendingTransfers:l,yieldedRoots:c,gasCosts:a}}mergeServiceStateUpdates(e,t){const{authManager:r,manager:s,validatorsManager:i}=this.state.privilegedServices;let n=null;const o=this.state.authQueues.slice();let a=!1,c=null;const l=[];for(const[h,u]of e){if(h===s&&null!==u.privilegedServices){const{manager:e,authorizer:t,validators:r,autoAccumulate:s}=u.privilegedServices;M(null===n,"Only one service can update privileged services!"),n=ii.create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s.map(([e,t])=>si.create({gasLimit:t,service:e}))})}if(h===r&&null!==u.authorizationQueues)for(const[e,t]of u.authorizationQueues)o[e]=t,a=!0;h===i&&null!==u.validatorsData&&(M(null===c,"Only one service can update designated validators!"),c=u.validatorsData),l.push(u.intoServicesUpdate(t))}const h=l.reduce((e,t)=>(e.servicesRemoved.push(...t.servicesRemoved),e.servicesUpdates.push(...t.servicesUpdates),e.preimages.push(...t.preimages),e.storage.push(...t.storage),e),{servicesRemoved:[],servicesUpdates:[],preimages:[],storage:[]}),u=new Set;for(const e of h.servicesUpdates)if(e.action.kind===mi.Create){if(u.has(e.serviceId))return z.error("duplicate service created",`duplicate service ${e.serviceId} has been created!`);u.add(e.serviceId)}return z.ok({...h,...null!==n?{privilegedServices:n}:{},...a?{authQueues:o}:{},...null!==c?{designatedValidatorData:c}:{}})}getAccumulationStateUpdate(e,t,r){const s=this.chainSpec.epochLength,i=r%s,n=al(e),o=Array.from(n).sort((e,t)=>ri(e,t).value),a=Yr(this.state.recentlyAccumulated.slice(1).concat(sr.from(o)),this.chainSpec),c=this.state.accumulationQueue.slice();c[i]=hl(t,n);for(let e=1;e<s;e++)if(e<r-this.state.timeslot)c[(i+s-e)%s]=[];else{const t=(i+s-e)%s;c[t]=hl(c[t],n)}return{recentlyAccumulated:a,accumulationQueue:Yr(c,this.chainSpec),timeslot:r}}getGasLimit(){const e=Ql*BigInt(this.chainSpec.coresCount)+this.state.privilegedServices.autoAccumulateServices.reduce((e,{gasLimit:t})=>e+t,0n),t=Gr(Vl>e?Vl:e);return Gr(t)}async transition({reports:e,slot:t,entropy:r}){const s=new ll(this.chainSpec,this.state),i=s.getWorkReportsToAccumulateImmediately(e),n=s.getWorkReportsToAccumulateLater(e),o=hl(s.getQueueFromState(t).concat(n),al(i)),a=s.enqueueReports(o),c=i.concat(a),l=this.getGasLimit(),{accumulatedReports:h,yieldedRoots:u,gasCosts:d,pendingTransfers:f,stateUpdates:p,...g}=await this.accumulateSequentially(l,c,t,r),y=c.slice(0,h),m=this.getAccumulationStateUpdate(y,n,t),b=this.mergeServiceStateUpdates(p,t);if(b.isError)return b;const A=await async function(e){const t=await er.create(),r=(n=t,{hashConcat:(e,t=[])=>tr(n,[e,...t].map(J.blobFrom)).asOpaque()}),s=Ji.empty(r),i=e.sort((e,t)=>e[0]-t[0]);var n;for(const[e,t]of i){const r=J.blobFromParts([Ae(e),t.raw]);s.set(Y.fromBlob(r.raw,36).asOpaque(),r)}return s.getRootHash().asOpaque()}(u);return z.ok({root:A,stateUpdate:{...m,...b.ok}})}}class Gl{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}transition(e){const t=this.state.authPools.slice();for(let r=qr(0);r<this.chainSpec.coresCount;r++){let s=t[r].slice();const i=this.state.authQueues[r],n=e.used.get(r);for(void 0!==n&&(s=s.filter(e=>!n.delete(e))),s.push(i[e.slot%80]);s.length>8;)s.shift();t[r]=ir(s)}return{authPools:Ys(t,this.chainSpec)}}}class ql{hasher;state;constructor(e,t){this.hasher=e,this.state=t}transition(e){const t=this.state.recentBlocks.slice(),r=t.length>0?t[t.length-1]:null;null!==r&&(r.postStateRoot=e.priorStateRoot);const s=null!==r?yl.fromPeaks(this.hasher,r.mmr):yl.empty(this.hasher);return s.append(e.accumulateRoot),t.push({headerHash:e.headerHash,mmr:s.getPeaks(),postStateRoot:Y.zero(Ct).asOpaque(),reported:e.workPackages}),t.length>8&&t.shift(),{recentBlocks:t}}}function zl(e,t,r){return function(e,t,r){const s=Wl(Fr(t%r.epochLength),r.rotationPeriod),i=(n=function(e,t){M(32===t.length,`Expected entropy of length 32, got ${t.length}`);const r=e.length,s=function(e,t){const r=new Array(t),s=new Uint8Array(36);s.set(e.raw);for(let e=0;e<t;e++){s.set(Ae(pe(Math.floor(e/8))),32);const t=4*e%32,i=t+4,n=Ie(Nt(s).raw.subarray(t,i))>>>0;r[e]=n}return r}(t,e.length),i=new Array(r);let n=r;for(let t=0;t<r;t++){const r=s[t]%n;i[t]=e[r],n--,e[r]=e[n],e.length=n}return i}(Array(r.validatorsCount).fill(0).map((e,t)=>qr(Math.floor(t*r.coresCount/r.validatorsCount))),e),o=s,a=r.coresCount,n.map(e=>(e+o)%a));var n,o,a;return i}(t,r,e)}function Wl(e,t){return Math.floor(e/t)}const Jl=J.blobFromString("jam_guarantee").raw;function Yl(e){return J.blobFromParts(Jl,e.raw)}const Xl=1e7;class Zl{chainSpec;state;mmrHasher;headerChain;constructor(e,t,r,s){this.chainSpec=e,this.state=t,this.mmrHasher=r,this.headerChain=s}async transition(e){const t=function(e,t){const r=t.coresCount;let s=-1;for(const t of e){const e=t.view().report.view().coreIndex.materialize();if(s>=e)return z.error(bl.OutOfOrderGuarantee,`Core indices of work reports are not unique or in order. Got: ${e}, expected at least: ${s+1}`);if(e>=r)return z.error(bl.BadCoreIndex,`Invalid core index. Got: ${e}, max: ${r}`);s=e}return z.ok($)}(e.guarantees,this.chainSpec);if(t.isError)return t;const r=function(e){for(const t of e){const e=t.view().report.view(),r=e.context.view().prerequisites.view().length,s=e.segmentRootLookup.view().length;if(r+s>8)return z.error(bl.TooManyDependencies,`Report at ${e.coreIndex.materialize()} has too many dependencies. Got ${r} + ${s}, max: 8`);const i=e.authorizationOutput.view().length;let n=0;for(const t of e.results.view())n+=t.view().result.view().okBlob?.raw.length??0;if(i+n>49152)return z.error(bl.WorkReportTooBig,`Work report at ${e.coreIndex.materialize()} too big. Got ${i} + ${n}, max: 49152`)}return z.ok($)}(e.guarantees);if(r.isError)return r;const s=this.workReportHashes(e.guarantees),i=this.verifyCredentials(e,s);if(i.isError)return i;const n=It(i.ok),o=this.verifyPostSignatureChecks(e.guarantees);if(o.isError)return o;const a=this.verifyContextualValidity(e);if(a.isError)return a;const c=this.checkSignatures(i.ok,await n);if(c.isError)return c;let l=0;const h=this.state.availabilityAssignment.slice();for(const t of e.guarantees){const r=t.view().report.materialize(),i=s[l];h[r.coreIndex]=Ws.create({workReport:new kt(i,r),timeout:e.slot}),l+=1}return z.ok({stateUpdate:{availabilityAssignment:Ys(h,this.chainSpec)},reported:a.ok,reporters:ar.fromArray(ce,i.ok.map(e=>e.key)).slice()})}workReportHashes(e){const t=[];for(const r of e)t.push(V(Nt(r.view().report.encoded())));return t}verifyCredentials(e,t){return function(e,t,r,s){const i=[],n=r;let o=0;for(const r of e){const e=r.view(),a=e.report.view().coreIndex.materialize(),c=t[o];o+=1;const l=e.credentials.view();if(l.length<Hr[0]||l.length>Hr[1])return z.error(bl.InsufficientGuarantees,`Invalid number of credentials. Expected ${Hr}, got ${l.length}`);const h=s(n,e.slot.materialize());if(h.isError)return h;const u=h.ok;let d=-1;for(const e of l){const t=e.view(),r=t.validatorIndex.materialize();if(d>=r)return z.error(bl.NotSortedOrUniqueGuarantors,`Credentials must be sorted by validator index. Got ${r}, expected at least ${d+1}`);d=r;const s=t.signature.materialize(),n=u[r];if(void 0===n)return z.error(bl.BadValidatorIndex,`Invalid validator index: ${r}`);if(n.core!==a)return z.error(bl.WrongAssignment,`Invalid core assignment for validator ${r}. Expected: ${n.core}, got: ${a}`);i.push({signature:s,key:n.ed25519,message:Yl(c)})}}return z.ok(i)}(e.guarantees,t,e.slot,(e,t)=>this.getGuarantorAssignment(e,t))}verifyPostSignatureChecks(e){return function(e,t,r,s){for(const i of e){const e=i.materialize().report,n=e.coreIndex;if(null!==t[n])return z.error(bl.CoreEngaged,`Report pending availability at core: ${n}`);const o=e.authorizerHash;if(void 0===r[n].find(e=>e.isEqualTo(o)))return z.error(bl.CoreUnauthorized,`Authorizer hash not found in the pool of core ${n}: ${o}`);for(const t of e.results){const e=s(t.serviceId);if(null===e)return z.error(bl.BadServiceId,`No service with id: ${t.serviceId}`);const r=e.getInfo();if(t.gas<r.accumulateMinGas)return z.error(bl.ServiceItemGasTooLow,`Service (${t.serviceId}) gas is less than minimal. Got: ${t.gas}, expected at least: ${r.accumulateMinGas}`)}const a=be(...e.results.map(e=>e.gas));if(a.overflow||a.value>Xl)return z.error(bl.WorkReportGasTooHigh,`Total gas too high. Got: ${a.value} (ovfl: ${a.overflow}), maximal: ${Xl}`)}return z.ok($)}(e,this.state.availabilityAssignment,this.state.authPools,e=>this.state.getService(e))}verifyContextualValidity(e){return function(e,t,r,s){const i=[],n=rr.new(),o=sr.new(),a=sr.new();for(const r of e.guarantees){const e=r.materialize();i.push(e.report.context);const s=Pr.create({workPackageHash:e.report.workPackageSpec.hash,segmentTreeRoot:e.report.workPackageSpec.exportsRoot});n.set(s.workPackageHash,s),o.insertAll(e.report.context.prerequisites),a.insertAll(e.report.segmentRootLookup.map(e=>e.workPackageHash));for(const r of e.report.results){const e=t.getService(r.serviceId);if(null===e)return z.error(bl.BadServiceId,`No service with id: ${r.serviceId}`);if(!r.codeHash.isEqualTo(e.getInfo().codeHash))return z.error(bl.BadCodeHash,`Service (${r.serviceId}) code hash mismatch. Got: ${r.codeHash}, expected: ${e.getInfo().codeHash}`)}}if(n.size!==e.guarantees.length)return z.error(bl.DuplicatePackage,"Duplicate work package detected.");const c=function(e,t,r,s,i){const n=rr.new();for(const e of r.recentBlocks)n.set(e.headerHash,e);for(const r of t){const t=n.get(r.anchor);if(void 0===t)return z.error(bl.AnchorNotRecent,`Anchor block ${r.anchor} not found in recent blocks.`);if(!t.postStateRoot.isEqualTo(r.stateRoot))return z.error(bl.BadStateRoot,`Anchor state root mismatch. Got: ${r.stateRoot}, expected: ${t.postStateRoot}.`);const o=yl.fromPeaks(s,t.mmr).getSuperPeakHash();if(!o.isEqualTo(r.beefyRoot))return z.error(bl.BadBeefyMmrRoot,`Invalid BEEFY super peak hash. Got: ${r.beefyRoot}, expected: ${o}. Anchor: ${t.headerHash}`);if(r.lookupAnchorSlot<e)return z.error(bl.SegmentRootLookupInvalid,`Lookup anchor slot's too old. Got: ${r.lookupAnchorSlot}, minimal: ${e}`);if(!i.isInChain(r.lookupAnchor))return z.error(bl.SegmentRootLookupInvalid,`Lookup anchor is not found in chain. Hash: ${r.lookupAnchor} (slot: ${r.lookupAnchorSlot})`)}return z.ok($)}(Math.max(0,e.slot-14400),i,t,r,s);if(c.isError)return c;const l=function(e,t){const r=sr.new();for(const e of t.recentBlocks)r.insertAll(Array.from(e.reported.keys()));for(const e of t.recentlyAccumulated)r.insertAll(Array.from(e));for(const e of t.accumulationQueue)r.insertAll(e.map(e=>e.report.workPackageSpec.hash));for(const e of t.availabilityAssignment)null!==e&&r.insert(e.workReport.data.workPackageSpec.hash);const s=r.intersection(e);for(const e of s)return z.error(bl.DuplicatePackage,`The same work package hash found in the pipeline (workPackageHash: ${e})`);return z.ok($)}(sr.viewDictionaryKeys(n),t);if(l.isError)return l;const h=rr.new();for(const e of t.recentBlocks)for(const t of e.reported.values())h.set(t.workPackageHash,t.segmentTreeRoot);const u=function({currentWorkPackages:e,recentlyReported:t,prerequisiteHashes:r,segmentRootLookupHashes:s}){const i=(r,s=!1)=>{for(const i of r)if(!e.has(i)&&!t.has(i))return z.error(s?bl.SegmentRootLookupInvalid:bl.DependencyMissing,`Missing work package ${i} in current extrinsic or recent history.`);return z.ok($)},n=i(r);if(n.isError)return n;const o=i(s,!0);return o.isError?o:z.ok($)}({currentWorkPackages:n,recentlyReported:h,prerequisiteHashes:o,segmentRootLookupHashes:a});if(u.isError)return u;for(const t of e.guarantees){const e=t.materialize().report;for(const t of e.segmentRootLookup){let e=n.get(t.workPackageHash);if(void 0===e){const r=h.get(t.workPackageHash);e=void 0!==r?Pr.create({workPackageHash:t.workPackageHash,segmentTreeRoot:r}):void 0}if(void 0===e||!e.segmentTreeRoot.isEqualTo(t.segmentTreeRoot))return z.error(bl.SegmentRootLookupInvalid,`Mismatching segment tree root for package ${t.workPackageHash}. Got: ${t.segmentTreeRoot}, expected: ${e?.segmentTreeRoot}`)}}return z.ok(n)}(e,this.state,this.mmrHasher,this.headerChain)}checkSignatures(e,t){if(t.every(e=>e))return z.ok($);const r=t.map((t,r)=>t?null:e[r].key).filter(e=>null!==e);return z.error(bl.BadSignature,`Invalid signatures for validators with keys: ${r.join(", ")}`)}getGuarantorAssignment(e,t){const r=this.chainSpec.epochLength,s=this.chainSpec.rotationPeriod,i=Wl(e,s),n=Wl(t,s),o=Math.max(0,i-1)*s;if(t>e)return z.error(bl.FutureReportSlot,`Report slot is in future. Block ${e}, Report: ${t}`);if(t<o)return z.error(bl.ReportEpochBeforeLast,`Report slot is too old. Block ${e}, Report: ${t}`);let a=this.state.entropy[2],c=this.state.currentValidatorData,l=e;i>n&&(l=Fr(e-s),function(e,t,r){const s=Math.floor(t/r);return Math.floor(e/r)!==s}(l,e,r)&&(a=this.state.entropy[3],c=this.state.previousValidatorData));const h=zl(this.chainSpec,a,l);return z.ok((u=c,d=(e,t)=>({core:e,ed25519:t.ed25519}),h.map((e,t)=>d(e,u[t]))));var u,d}}class eh{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}getStatistics(e){if(Math.floor(this.state.timeslot/this.chainSpec.epochLength)===Math.floor(e/this.chainSpec.epochLength))return this.state.statistics;const t=Wr(Array.from({length:this.chainSpec.validatorsCount},()=>Si.empty()),this.chainSpec);return _i.create({...this.state.statistics,current:t,previous:this.state.statistics.current})}calculateDAScoreCore(e){if(void 0===e)return pe(0);let t=0;return t+=e.workPackageSpec.length+4104*Math.ceil(65*e.workPackageSpec.exportsCount/64),pe(t)}calculateRefineScore(e){const t={gasUsed:0n,imported:0,extrinsicCount:0,extrinsicSize:0,exported:0};for(const r of e)t.gasUsed+=r.load.gasUsed,t.imported+=r.load.importedSegments,t.extrinsicCount+=r.load.extrinsicCount,t.extrinsicSize+=r.load.extrinsicSize,t.exported+=r.load.exportedSegments;return{gasUsed:Gr(t.gasUsed),exported:de(t.exported),imported:de(t.imported),extrinsicCount:de(t.extrinsicCount),extrinsicSize:pe(t.extrinsicSize)}}calculateProvidedScoreService(e){const t={count:0,size:0};for(const r of e)t.count+=1,t.size+=r.blob.length;return{count:de(t.count),size:pe(t.size)}}collectServiceIds(e,t,r,s){const i=new Set;for(const t of e)i.add(t.requester);for(const e of t)i.add(e.serviceId);for(const e of r)i.add(e);for(const e of s)i.add(e);return i}transition(e){const{slot:t,authorIndex:r,extrinsic:s,incomingReports:i,availableReports:n}=e,o=this.getStatistics(t),{current:a,cores:c,services:l}=o;M(void 0!==a[r],"authorIndex is out of bounds");const h=a[r].blocks+1;a[r].blocks=pe(h);const u=a[r].tickets+s.tickets.length;a[r].tickets=pe(u);const d=a[r].preImages+s.preimages.length;a[r].preImages=pe(d);const f=s.preimages.reduce((e,t)=>e+t.blob.length,0),p=a[r].preImagesSize+f;a[r].preImagesSize=pe(p);for(const{credentials:e}of s.guarantees)for(const{validatorIndex:t}of e){const e=a[t].guarantees+1;a[t].guarantees=pe(e)}for(const{validatorIndex:e}of s.assurances){const t=a[e].assurances+1;a[e].assurances=pe(t)}for(let e=0;e<this.chainSpec.coresCount;e++){const t=qr(e),r=i.find(e=>e.coreIndex===t),{imported:o,extrinsicCount:a,extrinsicSize:l,exported:h,gasUsed:u}=void 0!==r?this.calculateRefineScore(r.results.map(e=>e)):{imported:de(0),extrinsicCount:de(0),extrinsicSize:pe(0),exported:de(0),gasUsed:Gr(0n)},d=n.find(e=>e.coreIndex===t),f=s.assurances.reduce((t,{bitfield:r})=>t+(r.isSet(e)?1:0),0);c[t].imports=o,c[t].extrinsicCount=a,c[t].extrinsicSize=l,c[t].exports=h,c[t].gasUsed=u,c[t].bundleSize=pe(r?.workPackageSpec.length??0),c[t].dataAvailabilityLoad=this.calculateDAScoreCore(d),c[t].popularity=de(f)}l.clear();const g=this.collectServiceIds(s.preimages,i.flatMap(e=>e.results),e.accumulationStatistics.keys(),e.transferStatistics.keys());for(const t of g){const r=i.flatMap(e=>e.results.filter(e=>e.serviceId===t)),{gasUsed:n,imported:o,extrinsicCount:a,extrinsicSize:c,exported:h}=this.calculateRefineScore(r),u=s.preimages.filter(e=>e.requester===t),{count:d,size:f}=this.calculateProvidedScoreService(u),{count:p,gasUsed:g}=e.accumulationStatistics.get(t)??{count:pe(0),gasUsed:Gr(0n)},{count:y,gasUsed:m}=e.transferStatistics.get(t)??{count:pe(0),gasUsed:Gr(0n)},b=xi.empty();b.refinementCount=pe(r.length),b.refinementGasUsed=n,b.imports=o,b.extrinsicCount=a,b.extrinsicSize=c,b.exports=h,b.providedCount=d,b.providedSize=f,b.providedCount=d,b.providedSize=f,b.accumulateCount=p,b.accumulateGasUsed=g,b.onTransfersCount=y,b.onTransfersGasUsed=m,l.set(t,b)}return{statistics:o}}}class th{blocks;constructor(e){this.blocks=e}isInChain(e){return null!==this.blocks.getHeader(e)}}var rh;!function(e){e[e.Assurances=0]="Assurances",e[e.Disputes=1]="Disputes",e[e.Safrole=2]="Safrole",e[e.Reports=3]="Reports",e[e.Preimages=4]="Preimages",e[e.SafroleSeal=5]="SafroleSeal",e[e.Accumulate=6]="Accumulate"}(rh||(rh={}));const sh=(e,t)=>z.taggedError(rh,e,t);class ih{chainSpec;state;hasher;safrole;safroleSeal;disputes;reports;assurances;accumulate;preimages;recentHistory;authorization;statistics;constructor(e,t,r,s,{enableParallelSealVerification:i}){this.chainSpec=e,this.state=t,this.hasher=s;const n=Vc.new({synchronous:!i});this.statistics=new eh(e,t),this.safrole=new Yc(e,t,n),this.safroleSeal=new Xc(n),this.recentHistory=new ql(s,t),this.disputes=new kc(e,t),this.reports=new Zl(e,t,s,new th(r)),this.assurances=new dl(e,t),this.accumulate=new jl(e,t),this.preimages=new pc(t),this.authorization=new Gl(e,t)}async verifySeal(e,t){const r=this.safrole.getSafroleSealState(e);return await this.safroleSeal.verifyHeaderSeal(t.header.view(),r)}async transition(e,t,r=null,s=!1){const i=e.header.materialize(),n=i.timeSlotIndex;let o=r;if(s&&(o=Nt(i.seal).asOpaque()),null===o){const t=await this.verifySeal(n,e);if(t.isError)return sh(rh.SafroleSeal,t);o=t.ok}const a=await this.disputes.transition(e.extrinsic.view().disputes.materialize());if(a.isError)return sh(rh.Disputes,a);const{disputesRecords:c,availabilityAssignment:l,...h}=a.ok.stateUpdate,u=await this.reports.transition({slot:n,guarantees:e.extrinsic.view().guarantees.view(),knownPackages:[]});if(u.isError)return sh(rh.Reports,u);const{availabilityAssignment:d,...f}=u.ok.stateUpdate,p=await this.assurances.transition({assurances:e.extrinsic.view().assurances.view(),slot:n,parentHash:i.parentHeaderHash});if(p.isError)return sh(rh.Assurances,p);const{availabilityAssignment:g,...y}=p.ok.stateUpdate,m=await this.safrole.transition({slot:n,entropy:o,extrinsic:e.extrinsic.view().tickets.materialize()});if(m.isError)return sh(rh.Safrole,m);const{timeslot:b,ticketsAccumulator:A,sealingKeySeries:I,epochRoot:v,entropy:w,nextValidatorData:S,currentValidatorData:E,previousValidatorData:C,...k}=m.ok.stateUpdate,x=this.preimages.integrate({slot:n,preimages:e.extrinsic.view().preimages.materialize()});if(x.isError)return sh(rh.Preimages,x);const{preimages:_,...B}=x.ok,R=await this.accumulate.transition({slot:n,reports:p.ok.availableReports,entropy:w[0]});if(R.isError)return sh(rh.Accumulate,R);const{root:O,stateUpdate:U,...T}=R.ok,{privilegedServices:N,authQueues:D,designatedValidatorData:M,timeslot:P,preimages:L,...H}=U,K=this.recentHistory.transition({headerHash:t,priorStateRoot:i.priorStateRoot,accumulateRoot:O,workPackages:u.ok.reported}),{recentBlocks:Q,...V}=K,F=this.authorization.transition({slot:n,used:this.getUsedAuthorizerHashes(e.extrinsic.view().guarantees.view())}),{authPools:$,...j}=F,G=e.extrinsic.materialize(),q=this.statistics.transition({slot:n,authorIndex:i.bandersnatchBlockAuthorIndex,extrinsic:G,incomingReports:G.guarantees.map(e=>e.report),availableReports:p.ok.availableReports,accumulationStatistics:new Map,transferStatistics:new Map}),{statistics:W,...J}=q;return z.ok({...void 0!==D?{authQueues:D}:{},...void 0!==M?{designatedValidatorData:M}:{},...void 0!==N?{privilegedServices:N}:{},authPools:$,preimages:_.concat(L),disputesRecords:c,availabilityAssignment:nh(this.state.availabilityAssignment,d,l,g),recentBlocks:Q,statistics:W,timeslot:b,epochRoot:v,entropy:w,currentValidatorData:E,nextValidatorData:S,previousValidatorData:C,sealingKeySeries:I,ticketsAccumulator:A,...H})}getUsedAuthorizerHashes(e){const t=new Map;for(const r of e){const e=r.view().report.view(),s=e.coreIndex.materialize(),i=t.get(s)??sr.new();i.insert(e.authorizerHash.materialize()),t.set(s,i)}return t}}function nh(e,t,r,s){const i=e.slice();for(const n of t.keys())null!==r[n]&&null!==s[n]||(i[n]=null),null!==t[n]&&e[n]!==t[n]&&(i[n]=t[n]);return i}var oh;!function(e){e[e.Verifier=0]="Verifier",e[e.Stf=1]="Stf",e[e.Update=2]="Update"}(oh||(oh={}));const ah=(e,t)=>z.taggedError(oh,e,t);class ch{logger;blocks;states;verifier;stf;state;constructor(e,t,r,s,i){this.logger=r,this.blocks=s,this.states=i;const n=this.blocks.getBestHeaderHash(),o=i.getState(n);if(null===o)throw new Error(`Unable to load best state from header hash: ${n}.`);this.verifier=new mc(t,s),this.stf=new ih(e,o,s,t,{enableParallelSealVerification:!0}),this.state=o,r.info(`😎 Best time slot: ${o.timeslot} (header hash: ${n})`)}async preverifySeal(e,t){try{const r=await this.stf.verifySeal(e,t);return r.isOk?r.ok:(this.logger.warn(`Unable to pre-verify the seal: ${q(r)}`),null)}catch(e){return this.logger.warn(`Error while trying to pre-verify the seal: ${e}`),null}}async importBlock(e,t,r=!1){const s=this.logger;s.log("🧱 Attempting to import a new block "+(null!==t?"(seal preverified)":""));const i=K("import:verify"),n=await this.verifier.verifyBlock(e);if(s.log(i()),n.isError)return ah(oh.Verifier,n);const o=e.header.view().timeSlotIndex.materialize(),a=n.ok;s.log(`🧱 Verified block: Got hash ${a} for block at slot ${o}.`);const c=K("import:stf"),l=await this.stf.transition(e,a,t,r);if(s.log(c()),l.isError)return ah(oh.Stf,l);const h=l.ok,u=K("import:state"),d=await this.states.updateAndSetState(a,this.state,h);if(d.isError)return s.error(`🧱 Unable to update state: ${q(d)}`),ah(oh.Update,d);const f=this.states.getState(a);if(null===f)throw new Error("Freshly updated state not in the DB?");this.state.updateBackend(f.backend),s.log(u());const p=K("import:db"),g=this.blocks.insertBlock(new kt(a,e)),y=await this.states.getStateRoot(f);s.log(`🧱 Storing post-state-root for ${a}: ${y}.`);const m=this.blocks.setPostStateRoot(a,y);return await Promise.all([g,m]),s.log(p()),await this.blocks.setBestHeaderHash(a),z.ok(new kt(a,e.header.view()))}bestBlockHash(){return this.blocks.getBestHeaderHash()}}const lh=m.new(void 0,"importer");class hh extends Un{onBestBlock=new Bn;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{bestBlock:e=>this.triggerBestBlock(e)}})}getConfig(){if(null===this.data)throw new Error("Did not receive chain spec config!");return this.data}triggerBestBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=we.decodeObject(as,e,t.chainSpec);this.onBestBlock.emit(r)}}sendBlock(e,t){e.sendSignal("block",t,[t.buffer])}finish(e){return this.onBestBlock.markDone(),{state:"finished",data:e.sendRequest("finish",null)}}}class uh extends Un{onBlock=new Bn;constructor(){super({name:"ready(importer)",allowedTransitions:["finished"],requestHandlers:{finish:async()=>this.endWork()},signalListeners:{block:e=>this.triggerOnBlock(e)}})}getConfig(){if(null===this.data)throw new Error("Did not receive chain spec config!");return this.data}announce(e,t){const r=this.getConfig(),s=_e.encodeObject(as,t,r.chainSpec).raw;e.sendSignal("bestBlock",s,[s.buffer])}triggerOnBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=we.decodeObject(us.Codec.View,e,t.chainSpec);this.onBlock.emit(r)}else lh.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}async endWork(){return this.onBlock.markDone(),{response:null,transitionTo:{state:"finished",data:Promise.resolve(null)}}}}const dh=m.new(void 0,"importer");if(!T.isMainThread){m.configureAll(process.env.JAM_LOG??"",l.LOG);const e=function(){const e=new Dn("ready(importer)",ur.reInit),t=new uh,r=new Tn;return new Rn("importer",e,[e,t,r])}();kn.receiveChannel(e,T.parentPort).then(e=>async function(e){dh.info(`📥 Importer starting ${e.currentState()}`);const t=await e.waitForState("ready(importer)"),r=await t.doUntil("finished",async(e,t)=>{dh.info("📥 Importer waiting for blocks.");const r=e.getConfig(),s=new mn(r.dbPath),i=new gn(r.chainSpec,s),n=new bn(r.chainSpec,s),o=new ch(r.chainSpec,new fc(r.chainSpec,await fh,new _t),dh,i,n);let a=!1;const c=new gc(r.chainSpec,o);e.onBlock.on(async s=>{const i=c.push(s)??Fr(0);if(dh.log(`🧊 Got block: #${i}`),!a){a=!0;try{for(;;){const s=c.shift();if(void 0===s)return;const{block:i,seal:n,timeSlot:a}=s,l=K("importBlock"),h=await o.importBlock(i,await n,r.omitSealVerification);if(h.isOk){const r=h.ok;e.announce(t,r),dh.info(`🧊 Best block: #${r.data.timeSlotIndex.materialize()} (${r.hash})`)}else dh.log(`❌ Rejected block #${a}: ${q(h)}`);dh.log(l())}}finally{a=!1}}})});dh.info("📥 Importer finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>dh.error(e))}const fh=er.create(),ph=t(import.meta.url)("node:timers/promises");class gh{chainSpec;keccakHasher;blocks;states;hashAllocator=new _t;lastHeaderHash;lastHeader;lastState;constructor(e,t,r,s){this.chainSpec=e,this.keccakHasher=t,this.blocks=r,this.states=s;const{lastHeaderHash:i,lastHeader:n,lastState:o}=gh.getLastHeaderAndState(r,s);this.lastHeaderHash=i,this.lastHeader=n,this.lastState=o}refreshLastHeaderAndState(){const{lastHeaderHash:e,lastHeader:t,lastState:r}=gh.getLastHeaderAndState(this.blocks,this.states);this.lastHeaderHash=e,this.lastHeader=t,this.lastState=r}static getLastHeaderAndState(e,t){const r=e.getBestHeaderHash(),s=e.getHeader(r)?.materialize()??null,i=t.getState(r);if(null===s)throw new Error(`Missing best header: ${r}! Make sure DB is initialized.`);if(null===i)throw new Error(`Missing last state at ${r}! Make sure DB is initialized.`);return{lastHeaderHash:r,lastHeader:s,lastState:i}}async nextEncodedBlock(){const e=await this.nextBlock();return _e.encodeObject(us.Codec,e,this.chainSpec)}async nextBlock(){this.refreshLastHeaderAndState();const e=this.lastHeader.timeSlotIndex+1,t=$r(e%6),r=new fc(this.chainSpec,this.keccakHasher,this.hashAllocator),s=this.lastHeaderHash,i=this.states.getStateRoot(this.lastState),n=hs.create({tickets:[],preimages:[],guarantees:[],assurances:[],disputes:wr.create({verdicts:[],culprits:[],faults:[]})}),o=_e.encodeObject(hs.Codec,n,this.chainSpec),a=we.decodeObject(hs.Codec.View,o,this.chainSpec),c=r.extrinsic(a).hash,l=_e.create();l.i32(e),l.i16(t),l.bytes(Y.fill(90,0));const h=Y.fromBlob(l.viewResult().raw,96),u=ns.create({parentHeaderHash:s,priorStateRoot:await i,extrinsicHash:c,timeSlotIndex:Fr(e),epochMarker:null,ticketsMarker:null,offendersMarker:[],bandersnatchBlockAuthorIndex:t,entropySource:Y.fill(96,42*e%256).asOpaque(),seal:h.asOpaque()}),d=_e.encodeObject(ns.Codec,u,this.chainSpec),f=we.decodeObject(ns.Codec.View,d,this.chainSpec);return this.lastHeaderHash=r.header(f).hash,this.lastHeader=u,us.create({header:u,extrinsic:n})}}const yh=m.new(void 0,"block-generator");class mh extends Un{onBlock=new Bn;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{block:e=>this.triggerOnBlock(e)}})}triggerOnBlock(e){e instanceof Uint8Array?this.onBlock.emit(e):yh.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}finish(e){return this.onBlock.markDone(),{state:"finished",data:e.sendRequest("finish",null)}}}class bh extends Un{constructor(){super({name:"ready(generator)",allowedTransitions:["finished"],requestHandlers:{finish:async()=>this.endWork()}})}sendBlock(e,t){e.sendSignal("block",t.raw,[t.raw.buffer])}getConfig(){if(null===this.data)throw new Error("Config not received.");return this.data}async endWork(){return{response:null,transitionTo:{state:"finished",data:Promise.resolve(null)}}}}const Ah=m.new(void 0,"block-generator");if(!T.isMainThread){m.configureAll(process.env.JAM_LOG??"",l.LOG);const e=function(){const e=new Dn("ready(generator)",ur.reInit),t=new bh,r=new Tn;return new Rn("block-generator",e,[e,t,r])}();kn.receiveChannel(e,T.parentPort).then(e=>async function(e){Ah.info(`🎁 Block Generator running ${e.currentState()}`);const t=await e.waitForState("ready(generator)"),r=t.currentState().getConfig(),s=new mn(r.dbPath),i=new gn(r.chainSpec,s),n=new bn(r.chainSpec,s),o=await t.doUntil("finished",async(e,t,s)=>{let o=0;const a=new gh(r.chainSpec,await er.create(),i,n);for(;!s();){o+=1;const r=await a.nextEncodedBlock();Ah.trace(`Sending block ${o}`),e.sendBlock(t,r),await(0,ph.setTimeout)(3e3)}});Ah.info("Block Generator finished. Closing channel."),o.currentState().close(e)}(e)).catch(e=>{Ah.error(e),void 0!==e.stack&&Ah.error(e.stack),void 0!==e.cause&&Ah.error(e.cause)})}const Ih=t(import.meta.url)("dgram");var vh,wh;(wh=vh||(vh={}))[wh.NOTSET=0]="NOTSET",wh[wh.DEBUG=1]="DEBUG",wh[wh.INFO=2]="INFO",wh[wh.WARN=3]="WARN",wh[wh.ERROR=4]="ERROR",wh[wh.SILENT=100]="SILENT";const Sh="captureStackTrace"in Error,Eh="stackTraceLimit"in Error;function Ch(e){switch(e){case vh.NOTSET:return"NOTSET";case vh.DEBUG:return"DEBUG";case vh.INFO:return"INFO";case vh.WARN:return"WARN";case vh.ERROR:return"ERROR";case vh.SILENT:return"SILENT"}}function kh(e,t){return"function"==typeof t?t():t}function xh(e){return JSON.stringify(e,kh)}const _h=Symbol("level"),Bh=Symbol("key"),Rh=Symbol("keys"),Oh=Symbol("date"),Uh=Symbol("msg"),Th=Symbol("stack"),Nh=Symbol("data"),Dh=(function(e,...t){return r=>{let s=e[0];for(let i=0;i<t.length;i++){const n=t[i];if(n===Bh)s+=r.key;else if(n===Rh)s+=r.keys;else if(n===Oh)s+=r.date().toISOString();else if(n===Uh)null!=r.msg&&(s+=r.msg);else if(n===_h)s+=Ch(r.level);else if(n===Nh)s+=xh(r.data);else if(n===Th){const e=r.stack();""!==e&&(s+="\n"+e)}else s+=n.toString();s+=e[i+1]}return s}})`${_h}:${Bh}:${Uh}`,Mh=class{formatter;constructor(e=Dh){this.formatter=e}setFormatter(e){this.formatter=e}handle(e,t){const r=null!=t?t(e):this.format(e);this.emit(r)}format(e){return this.formatter(e)}},Ph=class extends Mh{emit(e){console.error(e)}};class Lh{key;level;filter;keys;handlers;parent;_loggers=new Map;loggersRegistry;constructor(e="root",t=vh.NOTSET,r=[new Ph],s){this.key=e,this.level=t,this.handlers=new Set(r),this.parent=s,this.keys=null!=s?`${s.keys}.${e}`:e,this.loggersRegistry=new FinalizationRegistry(e=>{this._loggers.delete(e)})}get loggers(){return new Map([...this._loggers.entries()].map(([e,t])=>{const r=t.deref();return null!=r?[e,r]:void 0}).filter(e=>null!=e))}getChild(e){let t=this._loggers.get(e),r=t?.deref();return null!=r||(r=new Lh(e,vh.NOTSET,[],this),t=new WeakRef(r),this._loggers.set(e,t),this.loggersRegistry.register(r,e)),r}getParent(){return this.parent}setLevel(e){this.level=e}getEffectiveLevel(){return this.level!==vh.NOTSET?this.level:this.parent?this.parent.getEffectiveLevel():this.level}isEnabledFor(e){return e>=this.level}addHandler(e){this.handlers.add(e)}removeHandler(e){this.handlers.delete(e)}clearHandlers(){this.handlers.clear()}hasHandlers(){return!!this.handlers.size||(this.parent?.hasHandlers()??!1)}setFilter(e){this.filter=e}unsetFilter(){delete this.filter}debug(e,t,r){return null==t||"function"==typeof t?this.log(e,{},vh.DEBUG,t):this.log(e,t,vh.DEBUG,r)}info(e,t,r){return null==t||"function"==typeof t?this.log(e,{},vh.INFO,t):this.log(e,t,vh.INFO,r)}warn(e,t,r){return null==t||"function"==typeof t?this.log(e,{},vh.WARN,t):this.log(e,t,vh.WARN,r)}error(e,t,r){return null==t||"function"==typeof t?this.log(e,{},vh.ERROR,t):this.log(e,t,vh.ERROR,r)}log(e,t,r,s){if(r<this.getEffectiveLevel())return;const i=this.makeRecord(e,t,r);this.callHandlers(i,r,s)}makeRecord(e,t,r){return{logger:this,key:this.key,keys:this.keys,level:r,msg:e?.toString(),data:t,date:()=>new Date,stack:()=>{let e;if(Sh&&Eh){Error.stackTraceLimit++;const t={};Error.captureStackTrace(t,Lh.prototype.log),Error.stackTraceLimit--,e=t.stack,e=e.slice(e.indexOf("\n",e.indexOf("\n")+1)+1)}else e=(new Error).stack??"",e=e.slice(e.indexOf("\n")+1);return e}}}callHandlers(e,t,r,s=""){if(!(t<this.getEffectiveLevel())&&(s=`${this.key}.${s}`,null==this.filter||this.filter.test(s))){for(const t of this.handlers)t.handle(e,r);this.parent&&this.parent.callHandlers(e,t,r,s)}}}const Hh=Lh;t(import.meta.url)("node:process");class Kh extends Event{detail;constructorParams;constructor(e=new.target.name,t,r){"string"==typeof e?(super(e,t),this.detail=t?.detail):(super(new.target.name,e),this.detail=e.detail,r=t),this.constructorParams=r??arguments}clone(){try{return new this.constructor(...this.constructorParams)}catch(e){if("TypeError"===e.name)throw new TypeError(`Cloning ${this.constructor.name} requires the original constructor arguments to be passed into super`);throw e}}}const Qh=Kh;class Vh extends Qh{constructor(e){super(Vh.name,e,arguments)}}const Fh=Vh;class $h extends Qh{constructor(e){super($h.name,e,arguments)}}const jh=$h;class Gh extends Qh{constructor(e){super(Gh.name,e,arguments)}}const qh=Gh,zh=Symbol("_eventTarget"),Wh=Symbol("eventTarget"),Jh=Symbol("_eventHandlers"),Yh=Symbol("eventHandlers"),Xh=Symbol("_eventHandled"),Zh=Symbol("eventHandled"),eu=Symbol("_handleEventError"),tu=Symbol("handleEventError");function ru(e){return{capture:!1,once:!1,passive:!1,..."boolean"==typeof e?{capture:e}:"object"==typeof e?e:void 0}}function su(e,t){return e.capture===t.capture}function iu(){return e=>{const t=class extends e{[zh]=new EventTarget;[Jh]=new Map;[Xh]=new WeakSet;[eu]=e=>{throw e.detail};constructor(...e){super(...e),this[zh].addEventListener(qh.name,this[eu])}get[Wh](){return this[zh]}get[Yh](){return this[Jh]}get[Zh](){return this[Xh]}get[tu](){return this[eu]}addEventListener(e,t,r){r=ru(r);const s=this;let i,n,o=!1;if("function"==typeof t||"function"==typeof t?.handleEvent){n=this[Jh].get(e),void 0===n&&(n=new Set,this[Jh].set(e,n));for(const e of n)if(e.callback===t&&(i=e.handler,su(e.options,r))){o=!0;break}}"function"==typeof t?null==i?(i=async function(e){let r;s[Xh].add(e);try{r=t.call(s,e)}catch(e){this.dispatchEvent(new qh({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new qh({detail:e}))}},n.add({callback:t,options:r,handler:i})):o||n.add({callback:t,options:r,handler:i}):"function"==typeof t?.handleEvent?null==i?(i=async function(e){let r;s[Xh].add(e);try{r=t.handleEvent(e)}catch(e){this.dispatchEvent(new qh({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new qh({detail:e}))}return r},n.add({callback:t,options:r,handler:i})):o||n.add({callback:t,options:r,handler:i}):i=t,this[zh].addEventListener(e,i,r),e===qh.name&&1===n?.size&&this[zh].removeEventListener(qh.name,this[eu])}removeEventListener(e,t,r){let s,i,n;if(r=ru(r),null!=t){if(i=this[Jh].get(e),void 0===i)return;for(const e of i)if(e.callback===t&&su(e.options,r)){s=e.handler,n=e;break}if(null==s)return}else s=t;this[zh].removeEventListener(e,s,r),null!=i&&null!=n&&(i.delete(n),e===qh.name&&0===i.size&&this[zh].addEventListener(qh.name,this[eu]))}dispatchEvent(e){if(Object.defineProperties(e,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),e instanceof qh)return this[zh].dispatchEvent(e);{let t=this[zh].dispatchEvent(e);if(t&&!this[Xh].has(e)){const r=new Fh({bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed,detail:e});Object.defineProperties(r,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),t=this[zh].dispatchEvent(r)}if(t){const r=new jh({bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed,detail:e});Object.defineProperties(r,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),t=this[zh].dispatchEvent(r)}return t}}};return Object.defineProperty(t,"name",Object.getOwnPropertyDescriptor(e,"name")),t}}async function nu(e,t){const r=[],s=[];let i;try{for(const t of e){const[e,i]=await t(s);r.push(e),s.push(i)}return await t(s)}catch(e){throw i=e,e}finally{r.reverse();for(const e of r)await e(i)}}async function*ou(e,t){const r=[],s=[];let i;try{for(const t of e){const[e,i]=await t(s);r.push(e),s.push(i)}return yield*t(s)}catch(e){throw i=e,e}finally{r.reverse();for(const e of r)await e(i)}}class au extends Promise{static get[Symbol.species](){return Promise}static resolve(e){return e instanceof au?e:super.resolve(e)}static reject(e){return super.reject(e)}static all(e,t){const r=super.all(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static allSettled(e,t){const r=super.allSettled(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static race(e,t){const r=super.race(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static any(e,t){const r=super.any(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static from(e,t){return new this((t,r)=>{e.then(t,r)},t)}reject;abortController;constructor(e,t){let r,s,i,n;"function"==typeof t?(r=new AbortController,t(r.signal),s=r.signal,i=!0):null!=t?(r=t,s=t.signal,i=!0):(r=new AbortController,s=new Proxy(r.signal,{get:(e,t,r)=>"addEventListener"===t?function(...r){return i=!0,e[t].apply(this,r)}:Reflect.get(e,t,r),set:(e,t,r)=>("onabort"===t&&(i=!0),Reflect.set(e,t,r)),deleteProperty:(e,t)=>("onabort"===t&&(i=!0),Reflect.deleteProperty(e,t))}),i=!1),super((t,r)=>{n=e=>{e instanceof DOMException&&"AbortError"===e.name&&(e=void 0),r(e)},e(t,n,s)}),i||r.signal.addEventListener("abort",()=>{n(r.signal.reason)},{once:!0}),this.reject=n,this.abortController=r}get[Symbol.toStringTag](){return this.constructor.name}cancel(e){this.abortController.abort(e)}then(e,t,r){let s,i,n;"function"==typeof e&&(i=t=>e(t,s)),"function"==typeof t&&(n=e=>t(e,s));const o=super.then(i,n),a=au.from(o,r);return s=a.abortController.signal,a}catch(e,t){let r,s;"function"==typeof e&&(s=t=>e(t,r));const i=super.catch(s);return"function"==typeof t?(i.abortController=new AbortController,t(i.abortController.signal)):null!=t&&(i.abortController=t),r=i.abortController.signal,i}finally(e,t){let r,s;"function"==typeof e&&(s=()=>e(r));const i=super.finally(s);return"function"==typeof t?(i.abortController=new AbortController,t(i.abortController.signal)):null!=t&&(i.abortController=t),r=i.abortController.signal,i}}const cu=au,lu=t(import.meta.url)("node:perf_hooks");var hu,uu=(hu=function(e,t){return hu=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},hu(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}hu(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),du=function(e){function t(t){var r,s,i,n=this.constructor,o=e.call(this,t)||this;return Object.defineProperty(o,"name",{value:n.name,enumerable:!1,configurable:!0}),r=o,s=n.prototype,(i=Object.setPrototypeOf)?i(r,s):r.__proto__=s,function(e,t){void 0===t&&(t=e.constructor);var r=Error.captureStackTrace;r&&r(e,t)}(o),o}return uu(t,e),t}(Error);const fu=class extends du{static description="";static fromJSON(e){if("object"!=typeof e||e.type!==this.name||"object"!=typeof e.data||"string"!=typeof e.data.message||isNaN(Date.parse(e.data.timestamp))||"object"!=typeof e.data.data||"stack"in e.data&&"string"!=typeof e.data.stack)throw new TypeError(`Cannot decode JSON to ${this.name}`);const t=new this(e.data.message,{timestamp:new Date(e.data.timestamp),data:e.data.data,cause:e.data.cause});return t.stack=e.data.stack,t}data;cause;timestamp;constructor(e="",t={}){super(e),this.timestamp=t.timestamp??new Date(lu.performance.timeOrigin+lu.performance.now()),this.data=t.data??{},this.cause=t.cause}get description(){return this.constructor.description}toJSON(){return{type:this.constructor.name,description:this.description,data:{message:this.message,timestamp:this.timestamp,data:this.data,cause:this.cause,stack:this.stack}}}};function pu(e,t,r=new Set){if(r.has(e))return!1;if(r.add(e),t(e))return!0;if(e instanceof AggregateError){for(const s of e.errors){const e=pu(s,t,r);if(e)return e}return pu(e.cause,t,r)}return e instanceof Error&&pu(e.cause,t,r)}class gu extends fu{static description="Timer error"}class yu extends gu{static description="The timer has already ended"}class mu{_delay;lazy;timestamp;_scheduled;handler;p;resolveP;rejectP;abortController;timeoutRef;_status=null;constructor(e,t=0,r=!1,s){let i,n;"function"==typeof e?i=e:"object"==typeof e&&null!==e&&(i=e.handler,t=e.delay??t,r=e.lazy??r,s=e.controller??s),isNaN(t)?t=0:(t=Math.max(t,0),isFinite(t)&&(t=Math.min(t,2**31-1))),this.handler=i,this._delay=t,this.lazy=r,"function"==typeof s?(n=new AbortController,s(n.signal)):null!=s?n=s:(n=new AbortController,n.signal.addEventListener("abort",()=>{this.reject(n.signal.reason)})),this.p=new cu((e,t)=>{this.resolveP=e.bind(this.p),this.rejectP=t.bind(this.p)},n),this.abortController=n,isFinite(t)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},t),this.timestamp=new Date(lu.performance.timeOrigin+lu.performance.now()),this._scheduled=new Date(this.timestamp.getTime()+t)):(this.timeoutRef=setInterval(()=>{},2**31-1),this.timestamp=new Date(lu.performance.timeOrigin+lu.performance.now()))}get[Symbol.toStringTag](){return this.constructor.name}get status(){return this._status}get scheduled(){return this._scheduled}get delay(){return this._delay}getTimeout(){return null!==this._status?0:null==this._scheduled?1/0:Math.max(Math.trunc(this._scheduled.getTime()-(lu.performance.timeOrigin+lu.performance.now())),0)}toString(){return this.getTimeout().toString()}valueOf(){return this.getTimeout()}cancel(e){this.p.catch(()=>{}),this.p.cancel(e)}then(e,t,r){return this.p.then(e,t,r)}catch(e,t){return this.p.catch(e,t)}finally(e,t){return this.p.finally(e,t)}refresh(){if(null!=this._status)throw new yu;return this.reset(this._delay)}reset(e){if(null!=this._status)throw new yu;clearTimeout(this.timeoutRef),this._delay=e,isFinite(e)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},e),this._scheduled=new Date(lu.performance.timeOrigin+lu.performance.now()+e)):(this.timeoutRef=setInterval(()=>{},2**31-1),delete this._scheduled)}async fulfill(){if(this._status="settling",clearTimeout(this.timeoutRef),delete this.timeoutRef,null!=this.handler)try{const e=await this.handler(this.abortController.signal);this.resolveP(e)}catch(e){this.rejectP(e)}else this.resolveP();delete this.handler,this._status="settled"}async reject(e){this.lazy&&"settling"===this._status||"settled"===this._status||(this._status="settling",clearTimeout(this.timeoutRef),delete this.timeoutRef,this.rejectP(e),delete this.handler,this._status="settled")}}const bu=mu;function Au(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Iu(e,t,r,s,i,n){let o,a;if(void 0!==i.timer&&"number"!=typeof i.timer||void 0!==i.signal)if((void 0===i.timer||"number"==typeof i.timer)&&i.signal instanceof AbortSignal){o=new AbortController;const e=new s,t=new bu(()=>{o.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),o.abort(n.reason)};n.aborted?(t.cancel(),o.abort(n.reason)):n.addEventListener("abort",c),i.signal=o.signal,i.timer=t,a=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof bu&&void 0===i.signal){o=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||o.abort(e),r),()=>{}),i.signal=o.signal,a=()=>{t=!0}}else{o=new AbortController;const e=i.signal,t=()=>{o.abort(e.reason)};e.aborted?o.abort(e.reason):e.addEventListener("abort",t),i.signal=o.signal,a=()=>{e.removeEventListener("abort",t)}}else{o=new AbortController;const e=new s,t=new bu(()=>{o.abort(e)},i.timer??r);o.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=o.signal,i.timer=t,a=()=>{t.cancel()}}const c=e(i,...n);return new cu((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},o).finally(()=>{a()},o)}class vu extends fu{static description="Async locks error"}class wu extends vu{static description="Async locks timeout"}const Su=class{limit;priority;_count=0;currentWeight=0;queue=[];abortQueueMap=new WeakMap;constructor(e,t=!1){if(e<1)throw new RangeError("Semaphore must be constructed with `limit` >= 1");this.limit=e,this.priority=t}get count(){return this._count}isLocked(){return this._count>0}lock(...e){const t=(2===e.length||"number"==typeof e[0]?e[0]:void 0)??1;let r=2===e.length?e[1]:"number"!=typeof e[0]?e[0]:void 0;if(t<1)throw new RangeError("Semaphore must be locked with `weight` >= 1");return r=null!=r?{...r}:{},()=>Iu((e,t)=>{this._count++;const{p:r,resolveP:s,rejectP:i}=Au();if(e.signal.aborted)return this._count--,i(e.signal.reason),r;const n=()=>{this._count--;const t=this.abortQueueMap.get(n);null!=t&&(t.aborted=!0),i(e.signal.reason)};let o=!1;const a={task:()=>{this.currentWeight+=t,e.signal.removeEventListener("abort",n),s([async()=>{o||(o=!0,this._count--,this.currentWeight-=t,this.processQueue())},this])},weight:t,abortHandler:n,aborted:!1};return e.signal.addEventListener("abort",n,{once:!0}),this.abortQueueMap.set(n,a),this.insertQueue(a),this.processQueue(),r},!0,1/0,wu,r,[t])}waitForUnlock(...e){const t=(2===e.length||"number"==typeof e[0]?e[0]:void 0)??1;let r=2===e.length?e[1]:"number"!=typeof e[0]?e[0]:void 0;if(t<1)throw new RangeError("Semaphore must be locked with `weight` >= 1");return r=null!=r?{...r}:{},Iu((e,t)=>{const{p:r,resolveP:s,rejectP:i}=Au();if(e.signal.aborted)return i(e.signal.reason),r;const n=()=>{const t=this.abortQueueMap.get(n);null!=t&&(t.aborted=!0),i(e.signal.reason)},o={task:()=>{e.signal.removeEventListener("abort",n),s()},weight:t,abortHandler:n,aborted:!1};return e.signal.addEventListener("abort",n,{once:!0}),this.abortQueueMap.set(n,o),this.insertQueue(o),this.processQueue(),r},!0,1/0,wu,r,[t])}withF(...e){const t=e.pop();return nu([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return ou([this.lock(...e)],([e])=>t(e))}insertQueue(e){if(this.priority){let t=this.queue.length;for(;t>0&&this.queue[t-1].weight<e.weight;)t--;this.queue.splice(t,0,e)}else this.queue.unshift(e)}processQueue(){for(;this.queue.length>0&&this.currentWeight+this.queue[this.queue.length-1].weight<=this.limit;){const e=this.queue.pop();e.aborted||e.task()}}},Eu=class{semaphore=new Su(1);get count(){return this.semaphore.count}isLocked(){return this.semaphore.isLocked()}lock(e){const t=this.semaphore.lock(1,e);return()=>{const e=t();return e.then(([e])=>[e,this],void 0,t=>{t.addEventListener("abort",()=>{e.cancel(t.reason)},{once:!0})})}}waitForUnlock(e){return this.semaphore.waitForUnlock(1,e)}withF(...e){const t=e.pop();return nu([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return ou([this.lock(...e)],([e])=>t(e))}},Cu=class{readersLock=new Eu;writersLock=new Eu;readersRelease;readerCountBlocked=0;acquireReadersLockP;_readerCount=0;_writerCount=0;get count(){return this.readerCount+this.writerCount}get readerCount(){return this._readerCount+this.readerCountBlocked}get writerCount(){return this._writerCount}isLocked(e){return"read"===e?0===this._writerCount&&this.readersLock.isLocked():"write"===e?this.writersLock.isLocked():this.readersLock.isLocked()||this.writersLock.isLocked()}lock(...e){const t=(2===e.length||"string"==typeof e[0]?e[0]:void 0)??"write",r=2===e.length?e[1]:"string"!=typeof e[0]?e[0]:void 0;switch(t){case"read":return this.read(r);case"write":return this.write(r)}}read(e){return e=null!=e?{...e}:{},()=>Iu(async e=>{if(this._writerCount>0){++this.readerCountBlocked;const t=this.writersLock.waitForUnlock(e);try{await t}finally{--this.readerCountBlocked}}if(1===++this._readerCount){const t=this.readersLock.lock(e);this.acquireReadersLockP=t();try{[this.readersRelease]=await this.acquireReadersLockP}catch(e){throw--this._readerCount,e}}else await this.acquireReadersLockP.catch(()=>{});let t=!1;return[async()=>{t||(t=!0,0===--this._readerCount&&await this.readersRelease())},this]},!0,1/0,wu,e,[])}write(e){return e=null!=e?{...e}:{},()=>Iu(async e=>{++this._writerCount;const t=this.writersLock.lock(e)();let r;try{[r]=await t}catch(e){throw--this._writerCount,e}const s=this.readersLock.lock(e)();try{[this.readersRelease]=await s}catch(e){throw await r(),--this._writerCount,e}let i=!1;return[async()=>{i||(i=!0,await this.readersRelease(),await r(),--this._writerCount)},this]},!0,1/0,wu,e,[])}waitForUnlock(e){const t=this.readersLock.waitForUnlock(e),r=this.writersLock.waitForUnlock(e);return cu.all([t,r]).then(()=>{},void 0,e=>{e.addEventListener("abort",()=>{t.cancel(e.reason),r.cancel(e.reason)},{once:!0})})}withF(...e){let t;switch(2===e.length||"string"==typeof e[0]?t=e.shift():null==typeof e[0]&&e.shift(),t=t??"write",t){case"read":return this.withReadF(...e);case"write":return this.withWriteF(...e)}}withReadF(...e){const t=e.pop();return nu([this.read(...e)],([e])=>t(e))}withWriteF(...e){const t=e.pop();return nu([this.write(...e)],([e])=>t(e))}withG(...e){let t;switch(2===e.length||"string"==typeof e[0]?t=e.shift():null==typeof e[0]&&e.shift(),t=t??"write",t){case"read":return this.withReadG(...e);case"write":return this.withWriteG(...e)}}withReadG(...e){const t=e.pop();return ou([this.read(...e)],([e])=>t(e))}withWriteG(...e){const t=e.pop();return ou([this.write(...e)],([e])=>t(e))}},ku=Symbol("_running"),xu=Symbol("running"),_u=Symbol("_destroyed"),Bu=Symbol("destroyed"),Ru=Symbol("_status"),Ou=Symbol("status"),Uu=Symbol("_statusP"),Tu=Symbol("statusP"),Nu=Symbol("resolveStatusP"),Du=Symbol("initLock"),Mu=(async()=>{}).constructor,Pu=function*(){}.constructor,Lu=async function*(){}.constructor,Hu="captureStackTrace"in Error;function Ku(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Qu(e,t){if(null!=e.stack){const r=e.stack.slice(0,e.stack.indexOf("\n")+1);Hu?Error.captureStackTrace(e,t):e.stack=(new Error).stack??"",e.stack=e.stack.replace(/[^\n]+\n/,r)}}class Vu extends Qh{}class Fu extends Vu{}class $u extends Vu{}class ju extends Vu{}class Gu extends Vu{}class qu extends Vu{}class zu extends Vu{}class Wu extends fu{static description="Async init error"}class Ju extends Wu{static description="Async init is not running"}class Yu extends Wu{static description="Async init is destroyed"}function Xu({eventDestroy:e=qu,eventDestroyed:t=zu}={}){return r=>{const{p:s,resolveP:i}=Ku(),n=class extends(iu()(r)){[_u]=!1;[Ru]=null;[Uu]=s;[Nu]=i;[Du]=new Cu;get[Bu](){return this[_u]}get[Ou](){return this[Ru]}get[Tu](){return this[Uu]}async destroy(...r){return this[Du].withWriteF(async()=>{if(this[_u])return;this[Ru]="destroying",this[Nu]("destroying");const{p:s,resolveP:i}=Ku();let n;return this[Uu]=s,this[Nu]=i,this.dispatchEvent(new e),"function"==typeof super.destroy&&(n=await super.destroy(...r)),this[_u]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[Ru]=null,this[Nu](null);const{p:e,resolveP:t}=Ku();this[Uu]=e,this[Nu]=t})}};return Object.defineProperty(n,"name",Object.getOwnPropertyDescriptor(r,"name")),n}}function Zu(e=new Yu,t=!1,r=[]){return(s,i,n)=>{let o;null!=n.value?o="value":null!=n.get?o="get":null!=n.set&&(o="set");const a=n[o];if("function"!=typeof a)throw new TypeError(`${i} is not a function`);return n[o]=a instanceof Mu?async function(...s){if(this[Du].isLocked("write")&&null===this[Ru]&&await this[Uu],r.includes(this[Ru]))return a.apply(this,s);if(t)return this[Du].withReadF(async()=>{if(this[_u])throw Qu(e,n[o]),e;return a.apply(this,s)});if(this[Du].isLocked("write")||this[_u])throw Qu(e,n[o]),e;return a.apply(this,s)}:a instanceof Pu?function*(...t){if(r.includes(this[Ru]))return yield*a.apply(this,t);if(this[Du].isLocked("write")&&null!==this[Ou]||this[_u])throw Qu(e,n[o]),e;return yield*a.apply(this,t)}:a instanceof Lu?async function*(...s){if(this[Du].isLocked("write")&&null===this[Ru]&&await this[Uu],r.includes(this[Ru]))return yield*a.apply(this,s);if(t)return yield*this[Du].withReadG(()=>{if(this[_u])throw Qu(e,n[o]),e;return a.apply(this,s)});if(this[Du].isLocked("write")||this[_u])throw Qu(e,n[o]),e;return yield*a.apply(this,s)}:function(...t){if(r.includes(this[Ru]))return a.apply(this,t);if(this[Du].isLocked("write")&&null!==this[Ou]||this[_u])throw Qu(e,n[o]),e;return a.apply(this,t)},Object.defineProperty(n[o],"name",{value:i}),n}}function ed({eventStart:e=Fu,eventStarted:t=$u,eventStop:r=ju,eventStopped:s=Gu}={}){return i=>{const{p:n,resolveP:o}=Ku(),a=class extends(iu()(i)){[ku]=!1;[Ru]=null;[Uu]=n;[Nu]=o;[Du]=new Cu;get[xu](){return this[ku]}get[Ou](){return this[Ru]}get[Tu](){return this[Uu]}async start(...r){return this[Du].withWriteF(async()=>{if(this[ku])return;this[Ru]="starting",this[Nu]("starting");const{p:s,resolveP:i}=Ku();let n;return this[Uu]=s,this[Nu]=i,this.dispatchEvent(new e),"function"==typeof super.start&&(n=await super.start(...r)),this[ku]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[Ru]=null,this[Nu](null);const{p:e,resolveP:t}=Ku();this[Uu]=e,this[Nu]=t})}async stop(...e){return this[Du].withWriteF(async()=>{if(!this[ku])return;this[Ru]="stopping",this[Nu]("stopping");const{p:t,resolveP:i}=Ku();let n;return this[Uu]=t,this[Nu]=i,this.dispatchEvent(new r),"function"==typeof super.stop&&(n=await super.stop(...e)),this[ku]=!1,this.dispatchEvent(new s),n}).finally(()=>{this[Ru]=null,this[Nu](null);const{p:e,resolveP:t}=Ku();this[Uu]=e,this[Nu]=t})}};return Object.defineProperty(a,"name",Object.getOwnPropertyDescriptor(i,"name")),a}}function td(e=new Ju,t=!1,r=[]){return(s,i,n)=>{let o;null!=n.value?o="value":null!=n.get?o="get":null!=n.set&&(o="set");const a=n[o];if("function"!=typeof a)throw new TypeError(`${i} is not a function`);return n[o]=a instanceof Mu?async function(...s){if(this[Du].isLocked("write")&&null===this[Ru]&&await this[Uu],r.includes(this[Ru]))return a.apply(this,s);if(t)return this[Du].withReadF(async()=>{if(!this[ku])throw Qu(e,n[o]),e;return a.apply(this,s)});if(this[Du].isLocked("write")||!this[ku])throw Qu(e,n[o]),e;return a.apply(this,s)}:a instanceof Pu?function*(...t){if(r.includes(this[Ru]))return yield*a.apply(this,t);if(this[Du].isLocked("write")&&null!==this[Ou]||!this[ku])throw Qu(e,n[o]),e;return yield*a.apply(this,t)}:a instanceof Lu?async function*(...s){if(this[Du].isLocked("write")&&null===this[Ru]&&await this[Uu],r.includes(this[Ru]))return yield*a.apply(this,s);if(t)return yield*this[Du].withReadG(()=>{if(!this[ku])throw Qu(e,n[o]),e;return a.apply(this,s)});if(this[Du].isLocked("write")||!this[ku])throw Qu(e,n[o]),e;return yield*a.apply(this,s)}:function(...t){if(r.includes(this[Ru]))return a.apply(this,t);if(this[Du].isLocked("write")&&null!==this[Ou]||!this[ku])throw Qu(e,n[o]),e;return a.apply(this,t)},Object.defineProperty(n[o],"name",{value:i}),n}}class rd extends Uint8Array{string;static fromString(e){const t=Buffer.from(e,"hex");return new this(t.buffer,t.byteOffset,t.byteLength)}static fromBuffer(e){return new this(e.buffer,e.byteOffset,e.byteLength)}constructor(...e){super(...e),this.string=this.toBuffer().toString("hex")}toString(){return this.string}toBuffer(){return Buffer.from(this.buffer,this.byteOffset,this.byteLength)}[Symbol.toPrimitive](e){return this.toString()}}const sd=rd;class id{[Symbol.toStringTag]="QUICConnectionMap";_serverConnections=new Map;_clientConnections=new Map;constructor(e){if(null!=e)for(const[t,r]of e)this.set(t,r)}get size(){return this._serverConnections.size+this._clientConnections.size}get serverConnections(){return this._serverConnections}get clientConnections(){return this._clientConnections}has(e){return this._serverConnections.has(e.toString())||this._clientConnections.has(e.toString())}get(e){return this._serverConnections.get(e.toString())??this._clientConnections.get(e.toString())}set(e,t){return"server"===t.type?this._serverConnections.set(e.toString(),t):"client"===t.type&&this._clientConnections.set(e.toString(),t),this}delete(e){return this._serverConnections.delete(e.toString())||this._clientConnections.delete(e.toString())}clear(){this._serverConnections.clear(),this._clientConnections.clear()}forEach(e,t){this._serverConnections.forEach((r,s)=>{e.bind(t)(r,sd.fromString(s),this)}),this._clientConnections.forEach((r,s)=>{e.bind(t)(r,sd.fromString(s),this)})}[Symbol.iterator](){const e=this._serverConnections[Symbol.iterator](),t=this._clientConnections[Symbol.iterator](),r={next:()=>{const r=e.next();if(!r.done){const[e,t]=r.value;return{done:!1,value:[sd.fromString(e),t]}}const s=t.next();if(!s.done){const[e,t]=s.value;return{done:!1,value:[sd.fromString(e),t]}}return{done:!0,value:void 0}},[Symbol.iterator]:()=>r};return r}entries(){return this[Symbol.iterator]()}keys(){const e={next:()=>{const e=this[Symbol.iterator]().next();return e.done?{done:!0,value:void 0}:{done:!1,value:e.value[0]}},[Symbol.iterator]:()=>e};return e}values(){const e={next:()=>{const e=this[Symbol.iterator]().next();return e.done?{done:!0,value:void 0}:{done:!1,value:e.value[1]}},[Symbol.iterator]:()=>e};return e}}const nd=id,od=t(import.meta.url)("process");var ad=o(928);const cd=t(import.meta.url)("url"),ld=t(import.meta.url)("node:module").createRequire("file:///home/runner/work/typeberry/typeberry/node_modules/@matrixai/quic/dist/native/quiche.js"),hd=cd.fileURLToPath(new URL(o(810),o.b)),ud=ad.join(hd,"../../"),dd=ad.join(ud,"prebuild");function fd(e){const t=e.map(e=>ad.join(dd,`quic-${e}.node`));for(const e of t){try{return ld(e)}catch(e){if("MODULE_NOT_FOUND"!==e.code)throw e}try{return ld(cd.pathToFileURL(e).href)}catch(e){if("MODULE_NOT_FOUND"!==e.code)throw e}}const r=e.map(e=>`@matrixai/quic-${e}`);for(const e of r){try{return ld(e)}catch(e){if("MODULE_NOT_FOUND"!==e.code)throw e}try{return ld(cd.pathToFileURL(e).href)}catch(e){if("MODULE_NOT_FOUND"!==e.code)throw e}}throw new Error(`Failed requiring possible native bindings: ${t.concat(r)}`)}let pd;switch(od.platform){case"win32":switch(od.arch){case"x64":pd=fd(["win32-x64"]);break;case"ia32":pd=fd(["win32-ia32"]);break;case"arm64":pd=fd(["win32-arm64"]);break;default:throw new Error(`Unsupported architecture on Windows: ${od.arch}`)}break;case"darwin":switch(od.arch){case"x64":pd=fd(["darwin-x64","darwin-x64+arm64","darwin-arm64+x64","darwin-universal"]);break;case"arm64":pd=fd(["darwin-arm64","darwin-arm64+x64","darwin-x64+arm64","darwin-universal"]);break;default:throw new Error(`Unsupported architecture on macOS: ${od.arch}`)}break;case"linux":switch(od.arch){case"x64":pd=fd(["linux-x64"]);break;case"arm64":pd=fd(["linux-arm64"]);break;case"arm":pd=fd(["linux-arm"]);break;default:throw new Error(`Unsupported architecture on Linux: ${od.arch}`)}break;default:throw new Error(`Unsupported OS: ${od.platform}, architecture: ${od.arch}`)}const gd=pd,yd=t(import.meta.url)("dns");var md=o(618);class bd extends fu{static description="QUIC error"}class Ad extends fu{static description="You should never see this error"}class Id extends fu{static description="Host provided was not valid"}class vd extends fu{static description="Port provided was not valid"}class wd extends bd{static description="QUIC config error"}class Sd extends bd{static description="QUIC Socket error"}class Ed extends Sd{static description="QUIC Socket is not running"}class Cd extends Sd{static description="QUIC Socket has active connections"}class kd extends Sd{static description="QUIC Socket cannot bind to the specified address"}class xd extends Sd{static description="QUIC Socket cannot send to the specified address"}class _d extends Sd{static description="QUIC Socket internal error"}class Bd extends bd{static description="QUIC Client error"}class Rd extends Bd{static description="QUIC Client is destroyed"}class Od extends Bd{static description="QUIC Client cannot be created with an unstarted shared QUIC socket"}class Ud extends Bd{static description="QUIC Client had a failure relating to an invalid argument"}class Td extends Bd{static description="QUIC Client cannot be created with the specified host"}class Nd extends Bd{static description="QUIC Client internal error"}class Dd extends bd{static description="QUIC Server error"}class Md extends Dd{static description="QUIC Server is not running"}class Pd extends Dd{static description="QUIC Server cannot start with an unstarted shared QUIC socket"}class Ld extends Dd{static description="QUIC Server creating a new connection"}class Hd extends Dd{static description="QUIC Server internal error"}class Kd extends Dd{static description="QUIC Server is stopping"}class Qd extends bd{static description="QUIC Connection error"}class Vd extends Qd{static description="QUIC Connection is stopping"}class Fd extends Qd{static description="QUIC Connection is not running"}class $d extends Qd{static description="QUIC Connection cannot be restarted because it has already been closed"}class jd extends bd{static description="QUIC Connection start requires data when it is a server connection"}class Gd extends Qd{static description="QUIC connection invalid configuration"}class qd extends Qd{static description="QUIC Connection local error";constructor(e="",t){super(e,t)}}class zd extends qd{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class Wd extends Qd{static description="QUIC Connection peer error";constructor(e="",t){super(e,t)}}class Jd extends qd{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class Yd extends Qd{static description="QUIC Connection max idle timeout exhausted"}class Xd extends Qd{static description="QUIC Connection internal error"}class Zd extends bd{static description="QUIC Stream error"}class ef extends Zd{static description="QUIC Stream is destroyed"}class tf extends Zd{static description="QUIC Stream locally closed readable side";constructor(e="",t){super(e,t)}}class rf extends Zd{static description="QUIC Stream locally closed writable side";constructor(e="",t){super(e,t)}}class sf extends Zd{static description="QUIC Stream peer closed readable side";constructor(e="",t){super(e,t)}}class nf extends Zd{static description="QUIC Stream peer closed writable side";constructor(e="",t){super(e,t)}}class of extends Zd{static description="QUIC Stream internal error"}class af extends Zd{static description="QUIC Stream limit has been reached"}const cf=new TextEncoder,lf=new TextDecoder("utf-8");function hf(e){throw new Ad(e)}function uf(e){return function(...t){return new Promise((r,s)=>{t.push((e,...t)=>{if(null!=e)return s(e);0===t.length?r():1===t.length?r(t[0]):r(t)}),e.apply(this,t)})}}function df(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function ff(e){const[t]=md.Validator.isValidIPv4String(e);return t}function pf(e){const[t]=md.Validator.isValidIPv6String(e);return!!t||gf(e)}function gf(e){if(e.startsWith("::ffff:"))try{return md.IPv6.fromString(e),!0}catch{if(ff(e.slice(7)))return!0}return!1}function yf(e){if(!ff(e))throw new TypeError("Invalid IPv4 address");return"::ffff:"+e}function mf(e){const t=e.slice(7);if(ff(t))return t;const r=t.match(/^([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/);if(null==r)throw new TypeError("Invalid IPv4 mapped IPv6 address");return(r[1].padStart(4,"0")+r[2].padStart(4,"0")).match(/.{1,2}/g).map(e=>parseInt(e,16)).join(".")}function bf(e){const t=new md.IPv4("0.0.0.0"),r=new md.IPv6("::");if(gf(e)){const r=mf(e);return new md.IPv4(r).isEquals(t)?yf("127.0.0.1"):e}return ff(e)&&new md.IPv4(e).isEquals(t)?"127.0.0.1":pf(e)&&new md.IPv6(e).isEquals(r)?"::1":e}async function Af(e){return(await yd.promises.lookup(e,{family:0,all:!1,verbatim:!0})).address}async function If(e,t){if(ff(e))return[e,"udp4"];if(pf(e))return[e,"udp6"];try{return If(e=await t(e),t)}catch{throw new Id}}function vf(e){if(!function(e){return"number"==typeof e&&e>=0&&e<=65535}(e))throw new vd;return e}function wf(e,t=0){let r;return r=ff(e)?`${e}:${t}`:pf(e)?`[${e}]:${t}`:`${e}:${t}`,r}function Sf(e,t,r,s,i){if("0.0.0.0"===(n=r)||"::"===n||"::0"===n||"::ffff:0.0.0.0"===n||"::ffff:0:0"===n)throw new i(`Invalid wildcard target host ${r}`);var n;const o=gf(e),a=gf(r);if("ipv4&ipv6"===t&&"udp4"===s)return yf(r);if("ipv4"===t){if(o){if("udp4"===s)return yf(r);if("udp6"===s&&!a)throw new i(`Invalid target host ${r} from an IPv4 socket`)}else if("udp6"===s){if(a)return mf(r);throw new i(`Invalid target host ${r} from an IPv4 socket`)}return r}if("ipv6"===t){if("udp4"===s||a)throw new i(`Invalid target host ${r} from an IPv6 socket`);return r}return r}function Ef(e){const t=[];if("string"==typeof e)t.push(e.trim()+"\n");else if(e instanceof Uint8Array)t.push(lf.decode(e).trim()+"\n");else if(Array.isArray(e))for(const r of e)"string"==typeof r?t.push(r.trim()+"\n"):t.push(lf.decode(r).trim()+"\n");return t}function Cf(e){const t=e.replace(/-----BEGIN .*-----/,"").replace(/-----END .*-----/,"").replace(/\s+/g,""),r=Buffer.from(t,"base64");return new Uint8Array(r)}function kf(e){return`${e.name}${"description"in e?`: ${e.description}`:""}${void 0!==e.message?` - ${e.message}`:""}`}function xf(e){let t;return null!=(t=e.message.match(/StreamStopped\((\d{1,16})\)/))&&parseInt(t[1])}function _f(e){let t;return null!=(t=e.message.match(/StreamReset\((\d{1,16})\)/))&&parseInt(t[1])}function Bf(e,t=1e5){An.setMaxListeners(t,e)}class Rf extends Qh{}class Of extends Rf{}class Uf extends Of{}class Tf extends Of{}class Nf extends Of{}class Df extends Rf{}class Mf extends Df{}class Pf extends Of{}class Lf extends Df{}class Hf extends Rf{}class Kf extends Hf{}class Qf extends Hf{}class Vf extends Hf{}class Ff extends Rf{}class $f extends Ff{}class jf extends Ff{}class Gf extends Ff{}class qf extends Ff{}class zf extends Ff{}class Wf extends Rf{}class Jf extends Wf{}class Yf extends Wf{}class Xf extends Wf{}class Zf extends Wf{}class ep extends Wf{}var tp=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let rp=class{connectionMap=new nd;logger;server;resolveHostname;_host;_port;_type;_closed=!1;_closedP;resolveClosedP;socket;socketBind;socketClose;socketSend;handleEventQUICSocketError=e=>{const t=e.detail;this.logger.debug(kf(t))};handleEventQUICSocketClose=async()=>{await this.socketClose(),this._closed=!0,this.resolveClosedP(),this[xu]&&await this.stop({force:!0})};handleSocketMessage=async(e,t)=>{let r;try{r=gd.Header.fromSlice(e,gd.MAX_CONN_ID_LEN)}catch(e){if("BufferTooShort"===e.message||"InvalidPacket"===e.message)return;throw e}const s=new sd(r.dcid),i={host:t.address,port:t.port},n=this.connectionMap.get(s);if(null!=n)await n.recv(e,i);else{if(null==this.server)return;try{await this.server.acceptConnection(i,r,s,e)}catch(e){if(pu(e,e=>e instanceof Sd)){const t=new _d("Failed to call accept connection due to socket send",{cause:e});return this.dispatchEvent(new Tf({detail:t})),void this.dispatchEvent(new Nf)}if(e instanceof Ld)return;throw e}}};constructor({resolveHostname:e=Af,logger:t}){this.logger=t??new Hh(this.constructor.name),this.resolveHostname=e;const{p:r,resolveP:s}=df();this._closedP=r,this.resolveClosedP=s}get host(){return this._host}get port(){return this._port}get type(){return this._type}get closed(){return this._closed}get closedP(){return this._closedP}async start({host:e="::",port:t=0,reuseAddr:r=!1,ipv6Only:s=!1}={}){Bf(this[zh]);let i=wf(e,t);this.logger.info(`Start ${this.constructor.name} on ${i}`);const[n,o]=await If(e,this.resolveHostname),a=vf(t);this.socket=Ih.createSocket({type:o,reuseAddr:r,ipv6Only:s}),this.socketBind=uf(this.socket.bind).bind(this.socket),this.socketClose=uf(this.socket.close).bind(this.socket),this.socketSend=uf(this.socket.send).bind(this.socket);const{p:c,rejectP:l}=df();c.catch(()=>{}),this.socket.once("error",l);const h=this.socketBind(a,n);try{await Promise.race([h,c])}catch(t){throw new kd(e!==n?`Could not bind to resolved ${e} -> ${n}`:`Could not bind to ${e}`,{cause:t})}this.socket.removeListener("error",l);const u=this.socket.address();this._host=u.address,this._port=u.port,"::"!==n||s?"udp4"===o||gf(n)?this._type="ipv4":"udp6"===o&&(this._type="ipv6"):this._type="ipv4&ipv6",this.socket.on("message",this.handleSocketMessage),this.addEventListener(Tf.name,this.handleEventQUICSocketError),this.addEventListener(Nf.name,this.handleEventQUICSocketClose,{once:!0}),this._closed=!1,i=wf(this._host,this._port),this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({force:e=!1}={}){const t=wf(this._host,this._port);if(this.logger.info(`Stop ${this.constructor.name} on ${t}`),!e&&this.connectionMap.size>0)throw new Cd(`Cannot stop QUICSocket with ${this.connectionMap.size} active connection(s)`);this._closed||this.dispatchEvent(new Nf),await this._closedP;const{p:r,resolveP:s}=df();this._closedP=r,this.resolveClosedP=s,this.removeEventListener(Tf.name,this.handleEventQUICSocketError),this.removeEventListener(Nf.name,this.handleEventQUICSocketClose),this.socket.off("message",this.handleSocketMessage),this.logger.info(`Stopped ${this.constructor.name} on ${t}`)}async send(...e){let t;if(3===e.length&&"string"==typeof e[2])t=2;else{if(5!==e.length||"string"!=typeof e[4])throw new TypeError("QUICSocket.send requires `port` and `address` parameters");t=4}const r=e[t];let[s,i]=await If(r,this.resolveHostname);return s=bf(s),s=Sf(this._host,this._type,s,i,xd),e[t]=s,this.socketSend(...e)}async send_(...e){return this.socketSend(...e)}setServer(e){this.server=e}unsetServer(){delete this.server}};tp([td(new Ed)],rp.prototype,"host",null),tp([td(new Ed)],rp.prototype,"port",null),tp([td(new Ed)],rp.prototype,"type",null),tp([td(new Ed)],rp.prototype,"send",null),tp([td(new Ed)],rp.prototype,"send_",null),rp=tp([ed({eventStart:class extends Of{},eventStarted:class extends Of{},eventStop:class extends Of{},eventStopped:Uf})],rp);const sp=rp,ip=new WeakMap;const np=function(e,t,r){const s=e.name??e.constructor.name,i=e[t];if(ip.has(i))throw new TypeError(`\`${s}.${t.toString()}\` redeclares \`@context\` decorator`);ip.set(i,r)};class op extends fu{static description="Contexts error"}class ap extends op{static description="Aborted due to timer expiration"}const cp=function(e=!1,t=1/0,r=ap){return(s,i,n)=>{const o=s.name??s.constructor.name,a=n.value;if("function"!=typeof a)throw new TypeError(`\`${o}.${i.toString()}\` is not a function`);const c=function(e,t,r){const s=ip.get(e[t]);if(null==s)throw new TypeError(`\`${r}.${t.toString()}\` does not have a \`@context\` parameter decorator`);return s}(s,i,o);return n.value=function(...s){let n=s[c];return n=void 0===n?{}:{...n},s[c]=n,function(e,t,r){if("object"!=typeof e||null===e)throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter is not a context object`);if(void 0!==e.signal&&!(e.signal instanceof AbortSignal))throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter's \`signal\` property is not an instance of \`AbortSignal\``);if(void 0!==e.timer&&!("number"==typeof e.timer||e.timer instanceof bu))throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter's \`timer\` property is not a number nor an instance of \`Timer\``)}(n,i,o),function(e,t,r,s,i,n){let o,a;if(void 0!==i.timer&&"number"!=typeof i.timer||void 0!==i.signal)if((void 0===i.timer||"number"==typeof i.timer)&&i.signal instanceof AbortSignal){o=new AbortController;const e=new s,t=new bu(()=>{o.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),o.abort(n.reason)};n.aborted?(t.cancel(),o.abort(n.reason)):n.addEventListener("abort",c),i.signal=o.signal,i.timer=t,a=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof bu&&void 0===i.signal){o=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||o.abort(e),r),()=>{}),i.signal=o.signal,a=()=>{t=!0}}else{o=new AbortController;const e=i.signal,t=()=>{o.abort(e.reason)};e.aborted?o.abort(e.reason):e.addEventListener("abort",t),i.signal=o.signal,a=()=>{e.removeEventListener("abort",t)}}else{o=new AbortController;const e=new s,t=new bu(()=>{o.abort(e)},i.timer??r);o.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=o.signal,i.timer=t,a=()=>{t.cancel()}}const c=e(i,...n);return new cu((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},o).finally(()=>{a()},o)}((e,...t)=>a.apply(this,t),"boolean"==typeof e?e:e(this),"number"==typeof t?t:t(this),r,n,s)},Object.defineProperty(n.value,"name",{value:"symbol"==typeof i?`[${i.description}]`:i}),n}},lp=["rsa_pkcs1_sha256","rsa_pkcs1_sha384","rsa_pkcs1_sha512","rsa_pss_rsae_sha256","rsa_pss_rsae_sha384","rsa_pss_rsae_sha512","ecdsa_secp256r1_sha256","ecdsa_secp384r1_sha384","ecdsa_secp521r1_sha512","ed25519"].join(":"),hp=1/0,up={sigalgs:lp,verifyPeer:!0,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:gd.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:gd.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:gd.MAX_CONNECTION_WINDOW,maxStreamWindow:gd.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},dp={sigalgs:lp,verifyPeer:!1,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:gd.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:gd.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:gd.MAX_CONNECTION_WINDOW,maxStreamWindow:gd.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},fp=t(import.meta.url)("stream/web");var pp=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};const gp=Symbol("abort readableP reason");let yp=class{static createQUICStream({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i=()=>0,codeToReason:n=(e,t)=>new Error(`${e.toString()} ${t.toString()}`),logger:o=new Hh(`${this.name} ${t}`)}){o.info(`Create ${this.name}`);const a=new this({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:o});return"uni"===a.type&&("local"===e?(a.readableController.close(),a._readClosed=!0):"peer"===e&&(a.writable.close().catch(()=>{}),a._writeClosed=!0)),a.addEventListener(Yf.name,a.handleEventQUICStreamError),a.addEventListener(Xf.name,a.handleEventQUICStreamCloseRead,{once:!0}),a.addEventListener(Zf.name,a.handleEventQUICStreamCloseWrite,{once:!0}),o.info(`Created ${this.name}`),a}type;initiated;streamId;readable;writable;closedP;logger;connection;reasonToCode;codeToReason;readableController;writableController;_readClosed=!1;_writeClosed=!1;readableChunk;resolveReadableP;rejectReadableP;resolveWritableP;rejectWritableP;resolveClosedP;handleEventQUICStreamError=e=>{const t=e.detail;if(t instanceof of)throw this.logger.debug(kf(t)),t;t instanceof tf||t instanceof sf?this.dispatchEvent(new Xf({detail:t})):(t instanceof rf||t instanceof nf)&&this.dispatchEvent(new Zf({detail:t}))};handleEventQUICStreamCloseRead=async()=>{this._readClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[Bu]||"destroying"===this[Ou]||await this.destroy({force:!1}))};handleEventQUICStreamCloseWrite=async()=>{this._writeClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[Bu]||"destroying"===this[Ou]||await this.destroy({force:!1}))};constructor({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:o}){!function(e){return!(2&e)}(t)?function(e){return!!(2&e)}(t)&&(this.type="uni"):this.type="bidi",this.logger=o,this.initiated=e,this.streamId=t,this.connection=r,this.reasonToCode=i,this.codeToReason=n;const{p:a,resolveP:c}=df();if(this.closedP=a,this.resolveClosedP=c,"uni"===this.type&&"local"===e?this.readableChunk=void 0:this.readableChunk=Buffer.allocUnsafe(s.readableChunkSize),"uni"===this.type&&"local"===e?this.readable=new fp.ReadableStream({start:this.readableStart.bind(this)}):this.readable=new fp.ReadableStream({start:this.readableStart.bind(this),pull:this.readablePull.bind(this),cancel:this.readableCancel.bind(this)},new fp.CountQueuingStrategy({highWaterMark:1})),"uni"===this.type&&"peer"===this.initiated)this.writable=new fp.WritableStream({start:this.writableStart.bind(this)});else{this.writable=new fp.WritableStream({start:this.writableStart.bind(this),write:this.writableWrite.bind(this),close:this.writableClose.bind(this),abort:this.writableAbort.bind(this)},{highWaterMark:1});try{r.conn.streamSend(t,new Uint8Array(0),!1)}catch(e){if(!1===xf(e)){if("StreamLimit"===e.message){const t="bidi"===this.type?s.initialMaxStreamsBidi:s.initialMaxStreamsUni;throw new af(`Stream limit of ${t} has been reached`,{cause:e})}throw new of(`Failed to prime local stream state with a 0-length message: ${e.message}`,{cause:e})}}}}get writeClosed(){return this._writeClosed}get readClosed(){return this._readClosed}get meta(){return this.connection.meta()}get closed(){return this._readClosed&&this._writeClosed}async destroy({force:e=!0,reason:t}={}){this.logger.info(`Destroy ${this.constructor.name}`),!e||this._readClosed&&this._writeClosed||this.cancel(t),await this.closedP,this.removeEventListener(Yf.name,this.handleEventQUICStreamError),this.removeEventListener(Xf.name,this.handleEventQUICStreamCloseRead),this.removeEventListener(Zf.name,this.handleEventQUICStreamCloseWrite),this.logger.info(`Destroyed ${this.constructor.name}`)}cancel(e){this.readableCancel(e),this.writableAbort(e)}read(){if(this.connection.conn.streamFinished(this.streamId)){let e;try{e=this.connection.conn.streamRecv(this.streamId,this.readableChunk)}catch(e){let t;if(!1!==(t=_f(e))){const e=this.codeToReason("read",t),r=new sf("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),this.rejectReadableP?.(e),void this.dispatchEvent(new Yf({detail:r}))}{const t=new of("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.rejectReadableP?.(t),this.dispatchEvent(new Yf({detail:t})),t}}if(null===e){const e=new of("Failed `streamRecv` on the readable stream");throw this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new Yf({detail:e})),e}const[t]=e;return t>0&&this.readableController.enqueue(Buffer.from(this.readableChunk.subarray(0,t))),this.readableController.close(),this.dispatchEvent(new Xf),void this.rejectReadableP?.(gp)}this.resolveReadableP?.()}write(){try{this.connection.conn.streamCapacity(this.streamId)}catch(e){let t;if(!1!==(t=xf(e))){this.connection.conn.streamShutdown(this.streamId,gd.Shutdown.Write,t);const e=this.codeToReason("write",t),r=new nf("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),this.rejectWritableP?.(e),void this.dispatchEvent(new Yf({detail:r}))}{const t=new of("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.rejectWritableP?.(t),this.dispatchEvent(new Yf({detail:t})),t}}this.resolveWritableP?.()}readableStart(e){this.readableController=e}writableStart(e){this.writableController=e}async readablePull(){if(!this.connection.conn.streamReadable(this.streamId)){const{p:e,resolveP:t,rejectP:r}=df();e.catch(()=>{}),this.resolveReadableP=t,this.rejectReadableP=r;try{await e}catch(e){return}}let e;try{e=this.connection.conn.streamRecv(this.streamId,this.readableChunk)}catch(e){let t;if(!1!==(t=_f(e))){const e=this.codeToReason("read",t),r=new sf("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),void this.dispatchEvent(new Yf({detail:r}))}{const t=new of("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.dispatchEvent(new Yf({detail:t})),t}}if(null===e){const e=new of("Failed `streamRecv` on the readable stream because it is not readable");throw this.readableController.error(e),this.dispatchEvent(new Yf({detail:e})),e}const[t,r]=e;t>0&&this.readableController.enqueue(Buffer.from(this.readableChunk.subarray(0,t))),r&&(this.readableController.close(),this.dispatchEvent(new Xf)),this.dispatchEvent(new ep)}async writableWrite(e){if(0===e.byteLength)return;let t;for(;;){try{const r=this.connection.conn.streamSend(this.streamId,e,!1);t=null===r?0:r}catch(e){let t;if(!1!==(t=xf(e))){const e=this.codeToReason("write",t),r=new nf("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new Yf({detail:r}))}{const t=new of("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new Yf({detail:t})),t}}if(this.dispatchEvent(new ep),t<e.byteLength){e=e.subarray(t,e.byteLength);const{p:r,resolveP:s,rejectP:i}=df();r.catch(()=>{}),this.resolveWritableP=s,this.rejectWritableP=i,await r;continue}return}}writableClose(){try{this.connection.conn.streamSend(this.streamId,new Uint8Array(0),!0)}catch(e){let t;if(!1!==(t=xf(e))){const e=this.codeToReason("write",t),r=new nf("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new Yf({detail:r}))}{const t=new of("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new Yf({detail:t})),t}}this.dispatchEvent(new Zf),this.dispatchEvent(new ep)}readableCancel(e){if(this._readClosed)return;const t=this.reasonToCode("read",e);try{this.connection.conn.streamShutdown(this.streamId,gd.Shutdown.Read,t)}catch(r){const e=new of("Local stream readable could not be shutdown",{cause:r});throw this.readableController.error(e),this.dispatchEvent(new Yf({detail:e})),e}const r=new tf("Closing readable stream locally",{data:{code:t},cause:e});this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new Yf({detail:r})),this.dispatchEvent(new ep)}writableAbort(e){if(this._writeClosed)return;const t=this.reasonToCode("write",e);try{this.connection.conn.streamShutdown(this.streamId,gd.Shutdown.Write,t)}catch(r){const e=new of("Local stream writable could not be shutdown",{cause:r});throw this.writableController.error(e),this.dispatchEvent(new Yf({detail:e})),e}const r=new rf("Closing writable stream locally",{data:{code:t},cause:e});this.writableController.error(e),this.rejectWritableP?.(e),this.dispatchEvent(new Yf({detail:r})),this.dispatchEvent(new ep)}};pp([Zu(new ef)],yp.prototype,"meta",null),pp([Zu(new ef,!1,["destroying"])],yp.prototype,"read",null),pp([Zu(new ef,!1,["destroying"])],yp.prototype,"write",null),yp=pp([Xu({eventDestroy:class extends Wf{},eventDestroyed:Jf})],yp);const mp=yp;var bp,Ap,Ip,vp,wp,Sp;!function(e){e[e.Reno=0]="Reno",e[e.CUBIC=1]="CUBIC",e[e.BBR=2]="BBR"}(bp||(bp={})),function(e){e[e.Read=0]="Read",e[e.Write=1]="Write"}(Ap||(Ap={})),function(e){e[e.Initial=0]="Initial",e[e.Retry=1]="Retry",e[e.Handshake=2]="Handshake",e[e.ZeroRTT=3]="ZeroRTT",e[e.VersionNegotiation=4]="VersionNegotiation",e[e.Short=5]="Short"}(Ip||(Ip={})),function(e){e[e.NoError=0]="NoError",e[e.InternalError=1]="InternalError",e[e.ConnectionRefused=2]="ConnectionRefused",e[e.FlowControlError=3]="FlowControlError",e[e.StreamLimitError=4]="StreamLimitError",e[e.StreamStateError=5]="StreamStateError",e[e.FinalSizeError=6]="FinalSizeError",e[e.FrameEncodingError=7]="FrameEncodingError",e[e.TransportParameterError=8]="TransportParameterError",e[e.ConnectionIdLimitError=9]="ConnectionIdLimitError",e[e.ProtocolViolation=10]="ProtocolViolation",e[e.InvalidToken=11]="InvalidToken",e[e.ApplicationError=12]="ApplicationError",e[e.CryptoBufferExceeded=13]="CryptoBufferExceeded",e[e.KeyUpdateError=14]="KeyUpdateError",e[e.AEADLimitReached=15]="AEADLimitReached",e[e.NoViablePath=16]="NoViablePath"}(vp||(vp={})),(Sp=wp||(wp={}))[Sp.CloseNotify=256]="CloseNotify",Sp[Sp.UnexpectedMessage=266]="UnexpectedMessage",Sp[Sp.BadRecordMac=276]="BadRecordMac",Sp[Sp.RecordOverflow=278]="RecordOverflow",Sp[Sp.HandshakeFailure=296]="HandshakeFailure",Sp[Sp.BadCertificate=298]="BadCertificate",Sp[Sp.UnsupportedCertificate=299]="UnsupportedCertificate",Sp[Sp.CertificateRevoked=300]="CertificateRevoked",Sp[Sp.CertificateExpired=301]="CertificateExpired",Sp[Sp.CertificateUnknown=302]="CertificateUnknown",Sp[Sp.IllegalParameter=303]="IllegalParameter",Sp[Sp.UnknownCA=304]="UnknownCA",Sp[Sp.AccessDenied=305]="AccessDenied",Sp[Sp.DecodeError=306]="DecodeError",Sp[Sp.DecryptError=307]="DecryptError",Sp[Sp.ProtocolVersion=326]="ProtocolVersion",Sp[Sp.InsufficientSecurity=327]="InsufficientSecurity",Sp[Sp.InternalError=336]="InternalError",Sp[Sp.InappropriateFallback=342]="InappropriateFallback",Sp[Sp.UserCanceled=346]="UserCanceled",Sp[Sp.MissingExtension=365]="MissingExtension",Sp[Sp.UnsupportedExtension=366]="UnsupportedExtension",Sp[Sp.UnrecognizedName=368]="UnrecognizedName",Sp[Sp.BadCertificateStatusResponse=369]="BadCertificateStatusResponse",Sp[Sp.UnknownPSKIdentity=371]="UnknownPSKIdentity",Sp[Sp.CertificateRequired=372]="CertificateRequired",Sp[Sp.NoApplicationProtocol=376]="NoApplicationProtocol";var Ep=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let Cp=class{type;closedP;conn;streamMap=new Map;sendId;logger;socket;config;reasonToCode;codeToReason;recvLock=new Eu;streamIdClientBidi=0;streamIdServerBidi=1;streamIdClientUni=2;streamIdServerUni=3;streamIdUsedClientBidi=-4;streamIdUsedServerBidi=-3;streamIdUsedClientUni=-2;streamIdUsedServerUni=-1;streamIdUsedSet=new Set;connTimeoutTimer;keepAliveIntervalTimer;_remoteHost;_remotePort;certDERs=[];caDERs=[];secureEstablished=!1;secureEstablishedP;resolveSecureEstablishedP;rejectSecureEstablishedP;resolveClosedP;errorLast=null;handleEventQUICConnectionError=e=>{const t=e.detail;if(this.errorLast=t,this.logger.info(kf(t)),t instanceof Xd)throw t;this.dispatchEvent(new Gf({detail:t}))};handleEventQUICConnectionClose=async e=>{const t=e.detail;this.secureEstablished||this.rejectSecureEstablishedP(t),t instanceof qd&&await this.send(),this[xu]&&"stopping"!==this[Ou]&&await this.stop({force:!0})};handleEventQUICStream=e=>{e.detail instanceof Qh&&!(e.detail instanceof ep)&&this.dispatchEvent(e.detail.clone())};handleEventQUICStreamSend=async()=>{this[xu]&&await this.send()};handleEventQUICStreamDestroyed=e=>{const t=e.target;t.removeEventListener(ep.name,this.handleEventQUICStreamSend),t.removeEventListener(jh.name,this.handleEventQUICStream),this.streamMap.delete(t.streamId)};constructor({type:e,scid:t,dcid:r,serverName:s=null,remoteInfo:i,config:n,socket:o,reasonToCode:a=()=>0,codeToReason:c=(e,t)=>new Error(`${e} ${t}`),logger:l}){if(this.logger=l??new Hh(`${this.constructor.name} ${t}`),this.sendId=t.toString(),null!=n.keepAliveIntervalTime&&0!==n.maxIdleTimeout&&n.keepAliveIntervalTime>=n.maxIdleTimeout)throw new Gd("`keepAliveIntervalTime` must be less than `maxIdleTimeout`");const h=function(e){if(null!=e.key&&null==e.cert)throw new wd("The cert option must be set when key is set");if(null==e.key&&null!=e.cert)throw new wd("The key option must be set when cert is set");if(null!=e.key&&null!=e.cert&&Array.isArray(e.key)&&Array.isArray(e.cert)&&e.key.length!==e.cert.length)throw new wd("The number of keys must match the number of certs");let t,r,s,i;if(null!=e.ca){const r=Ef(e.ca);t=cf.encode(r.join(""))}null!=e.key&&(r=Ef(e.key).map(e=>cf.encode(e))),null!=e.cert&&(s=Ef(e.cert).map(e=>cf.encode(e)));try{i=gd.Config.withBoringSslCtx(e.verifyPeer,null!=e.verifyCallback,t,r,s,e.sigalgs)}catch(e){throw new wd(`Failed to build Quiche config with custom SSL context: ${e.message}`,{cause:e})}return null!=e.logKeys&&i.logKeys(),e.enableEarlyData&&i.enableEarlyData(),i.grease(e.grease),i.setMaxIdleTimeout(e.maxIdleTimeout),i.setMaxRecvUdpPayloadSize(e.maxRecvUdpPayloadSize),i.setMaxSendUdpPayloadSize(e.maxSendUdpPayloadSize),i.setInitialMaxData(e.initialMaxData),i.setInitialMaxStreamDataBidiLocal(e.initialMaxStreamDataBidiLocal),i.setInitialMaxStreamDataBidiRemote(e.initialMaxStreamDataBidiRemote),i.setInitialMaxStreamDataUni(e.initialMaxStreamDataUni),i.setInitialMaxStreamsBidi(e.initialMaxStreamsBidi),i.setInitialMaxStreamsUni(e.initialMaxStreamsUni),i.enableDgram(...e.enableDgram),i.setDisableActiveMigration(e.disableActiveMigration),i.setApplicationProtos(e.applicationProtos),i}(n);let u;if("client"===e?(this.logger.info(`Connect ${this.constructor.name}`),u=gd.Connection.connect(s,t,{host:o.host,port:o.port},{host:i.host,port:i.port},h)):"server"===e&&(this.logger.info(`Accept ${this.constructor.name}`),u=gd.Connection.accept(t,r,{host:o.host,port:o.port},{host:i.host,port:i.port},h)),null!=n.logKeys&&u.setKeylog(n.logKeys),this.type=e,this.conn=u,this.socket=o,this.config=n,null!=this.config.cert){const e=Ef(this.config.cert);this.certDERs=e.map(Cf)}if(null!=this.config.ca){const e=Ef(this.config.ca);this.caDERs=e.map(Cf)}this.reasonToCode=a,this.codeToReason=c,this._remoteHost=i.host,this._remotePort=i.port;const{p:d,resolveP:f,rejectP:p}=df();d.catch(()=>{}),this.secureEstablishedP=d,this.resolveSecureEstablishedP=()=>{this.secureEstablished=!0,f()},this.rejectSecureEstablishedP=p;const{p:g,resolveP:y}=df();this.closedP=g,this.resolveClosedP=y}get connectionId(){const e=this.conn.sourceId();return new sd(e.buffer,e.byteOffset,e.byteLength)}get connectionIdPeer(){const e=this.conn.destinationId();return new sd(e.buffer,e.byteOffset,e.byteLength)}get connectionIdShared(){const e=this.conn.sourceId(),t=this.conn.destinationId();return Buffer.compare(e,t)<=0?new sd(Buffer.concat([e,t])):new sd(Buffer.concat([t,e]))}get remoteHost(){return this._remoteHost}get remotePort(){return this._remotePort}get localHost(){return this.socket.host}get localPort(){return this.socket.port}get closed(){return this.conn.isClosed()}async start({data:e,remoteInfo:t}={},r){if(this.logger.info(`Start ${this.constructor.name}`),this.conn.isClosed())throw new $d;r.signal.throwIfAborted();const{p:s,rejectP:i}=df();s.catch(()=>{});const n=()=>{i(r.signal.reason)};if(r.signal.addEventListener("abort",n),this.addEventListener(jf.name,this.handleEventQUICConnectionError),this.addEventListener(Gf.name,this.handleEventQUICConnectionClose,{once:!0}),"client"===this.type)await this.send();else if("server"===this.type){if(null==e||null==t)throw new jd("Starting a server connection requires initial data and remote information");await this.recv(e,t)}try{await Promise.race([this.secureEstablishedP,s])}catch(e){if(r.signal.aborted){for(const t of this.conn.readable())this.conn.streamShutdown(t,gd.Shutdown.Read,this.reasonToCode("read",e));for(const t of this.conn.writable())this.conn.streamShutdown(t,gd.Shutdown.Write,this.reasonToCode("write",e));this.conn.close(!1,vp.ApplicationError,Buffer.from(""));const t=this.conn.localError(),r=new qd("Failed to start QUIC connection due to start timeout",{data:t,cause:e});this.dispatchEvent(new jf({detail:r}))}throw await this.closedP,e}finally{r.signal.removeEventListener("abort",n)}null!=this.config.keepAliveIntervalTime&&this.startKeepAliveIntervalTimer(this.config.keepAliveIntervalTime),this.logger.info(`Started ${this.constructor.name}`)}async stop({isApp:e=!0,errorCode:t=0,reason:r=new Uint8Array,force:s=!0}={}){this.logger.info(`Stop ${this.constructor.name}`),this.stopKeepAliveIntervalTimer(),await async function(){return await new Promise(e=>queueMicrotask(e))}();const i=[];for(const e of this.streamMap.values())i.push(e.destroy({reason:this.errorLast,force:s||this.conn.isDraining()||this.conn.isClosed()}));if(await Promise.all(i),!this.conn.isDraining()&&!this.conn.isClosed()){this.conn.close(e,t,r);const s=this.conn.localError(),i=`Locally closed with ${s.isApp?"application":"transport"} code ${s.errorCode}`,n=new qd(i,{data:s});this.dispatchEvent(new jf({detail:n}))}await this.closedP,this.removeEventListener(jf.name,this.handleEventQUICConnectionError),this.removeEventListener(Gf.name,this.handleEventQUICConnectionClose),this.logger.info(`Stopped ${this.constructor.name}`)}getConnectionError(){return this.conn.localError()??this.conn.peerError()??void 0}getLocalCACertsChain(){return this.caDERs}getLocalCertsChain(){return this.certDERs}getRemoteCertsChain(){return this.conn.peerCertChain()??[]}meta(){return{localHost:this.localHost,localPort:this.localPort,remoteHost:this.remoteHost,remotePort:this.remotePort,localCertsChain:this.certDERs,localCACertsChain:this.caDERs,remoteCertsChain:this.getRemoteCertsChain()}}async recv(e,t){await this.recvLock.withF(async()=>{const r={to:{host:this.localHost,port:this.localPort},from:{host:t.host,port:t.port}};try{this.conn.recv(e,r)}catch(e){const t=this.conn.localError();if(null==t){const t=new Xd("Failed connection recv due with unknown error",{cause:e});throw this.dispatchEvent(new jf({detail:t})),t}{let r;return r="TlsFail"===e.message?new zd("Failed connection due to native TLS verification",{cause:e,data:t}):new qd("Failed connection due to local error",{cause:e,data:t}),void this.dispatchEvent(new jf({detail:r}))}}this._remoteHost=t.host,this._remotePort=t.port,!this.secureEstablished&&this.conn.isEstablished()&&null==this.config.verifyCallback&&this.resolveSecureEstablishedP(),this.secureEstablished&&this.processStreams(),await this.send()})}async send(){let e,t;for(;;){const r=Buffer.allocUnsafe(this.config.maxSendUdpPayloadSize);try{const s=this.conn.send(r);if(null===s)break;[e,t]=s}catch(e){const t=new Xd("Failed connection send with unknown internal error",{cause:e});throw this.dispatchEvent(new jf({detail:t})),t}this.dispatchEvent(new zf({detail:{id:this.sendId,msg:r.subarray(0,e),port:t.to.port,address:t.to.host}}))}if(this.setConnTimeoutTimer(),!this.secureEstablished&&!this.conn.isDraining()&&!this.conn.isClosed()&&this.conn.isEstablished()&&this.config.verifyPeer&&null!=this.config.verifyCallback){const e=this.conn.peerCertChain(),t=await this.config.verifyCallback(e,this.caDERs);if(null!=t){this.conn.close(!1,t,Buffer.from(""));const e=this.conn.localError(),r=new zd("Failed connection due to custom TLS verification",{data:e});return void this.dispatchEvent(new jf({detail:r}))}this.resolveSecureEstablishedP(),this.processStreams()}if("stopping"!==this[Ou]){const e=this.conn.peerError();if(null!=e){const t=`Peer closed with ${e.isApp?"application":"transport"} code ${e.errorCode}`;return void(e.errorCode>=gd.CRYPTO_ERROR_START&&e.errorCode<=gd.CRYPTO_ERROR_STOP?this.dispatchEvent(new jf({detail:new Jd(t,{data:e})})):this.dispatchEvent(new jf({detail:new Wd(t,{data:e})})))}}}isStreamUsed(e){let t;switch(3&e){case 0:if(t=this.streamIdUsedClientBidi+4,e<=this.streamIdUsedClientBidi||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedClientBidi=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;case 1:if(t=this.streamIdUsedServerBidi+4,e<=this.streamIdUsedServerBidi||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedServerBidi=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;case 2:if(t=this.streamIdUsedClientUni+4,e<=this.streamIdUsedClientUni||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedClientUni=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;case 3:if(t=this.streamIdUsedServerUni+4,e<=this.streamIdUsedServerUni||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedServerUni=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;default:hf("got an unexpected ID type")}}processStreams(){for(const e of this.conn.readable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[xu]||"stopping"===this[Ou]){this.conn.streamShutdown(e,Ap.Write,this.reasonToCode("write",Vd)),this.conn.streamShutdown(e,Ap.Read,this.reasonToCode("read",Vd));continue}this.isStreamUsed(e)&&hf("We should never repeat streamIds when creating streams"),t=mp.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${mp.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(ep.name,this.handleEventQUICStreamSend),t.addEventListener(Jf.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(jh.name,this.handleEventQUICStream),this.dispatchEvent(new qf({detail:t}))}t.read()}for(const e of this.conn.writable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[xu]||"stopping"===this[Ou]){this.conn.streamShutdown(e,Ap.Write,this.reasonToCode("write",Vd)),this.conn.streamShutdown(e,Ap.Read,this.reasonToCode("read",Vd));continue}if(this.isStreamUsed(e)){try{this.conn.streamSend(e,new Uint8Array,!1)}catch(e){if(!1!==xf(e))continue;if("FinalSize"===e.message)continue;throw e}hf("We never expect a duplicate stream to be readable")}t=mp.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${mp.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(ep.name,this.handleEventQUICStreamSend),t.addEventListener(Jf.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(jh.name,this.handleEventQUICStream),this.dispatchEvent(new qf({detail:t}))}t.write()}}setConnTimeoutTimer(){const e=async t=>{if(t.aborted)return;if(this.conn.onTimeout(),this.conn.isClosed())return this.resolveClosedP(),void(this.conn.isTimedOut()&&this.dispatchEvent(new jf({detail:new Yd})));await this.send();const r=this.conn.timeout();null!=r&&(this.connTimeoutTimer=new bu({delay:r+1,handler:e,lazy:!0}))},t=this.conn.timeout();if(null==t)return this.connTimeoutTimer?.cancel(),delete this.connTimeoutTimer,void(this.conn.isClosed()&&(this.resolveClosedP(),this.conn.isTimedOut()&&this.dispatchEvent(new jf({detail:new Yd}))));null==this.connTimeoutTimer||"settled"===this.connTimeoutTimer.status?this.connTimeoutTimer=new bu({delay:t+1,handler:e,lazy:!0}):null==this.connTimeoutTimer.status&&this.connTimeoutTimer.reset(t+1)}newStream(e="bidi"){let t;"client"===this.type&&"bidi"===e?t=this.streamIdClientBidi:"server"===this.type&&"bidi"===e?t=this.streamIdServerBidi:"client"===this.type&&"uni"===e?t=this.streamIdClientUni:"server"===this.type&&"uni"===e&&(t=this.streamIdServerUni),this.isStreamUsed(t)&&hf("We should never repeat streamIds when creating streams");const r=mp.createQUICStream({initiated:"local",streamId:t,connection:this,config:this.config,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${mp.name} ${t}`)});return this.streamMap.set(r.streamId,r),r.addEventListener(ep.name,this.handleEventQUICStreamSend),r.addEventListener(Jf.name,this.handleEventQUICStreamDestroyed,{once:!0}),r.addEventListener(jh.name,this.handleEventQUICStream),"client"===this.type&&"bidi"===e?this.streamIdClientBidi=this.streamIdClientBidi+4:"server"===this.type&&"bidi"===e?this.streamIdServerBidi=this.streamIdServerBidi+4:"client"===this.type&&"uni"===e?this.streamIdClientUni=this.streamIdClientUni+4:"server"===this.type&&"uni"===e&&(this.streamIdServerUni=this.streamIdServerUni+4),r}destroyStreams(e){for(const t of this.streamMap.values())t.cancel(e)}startKeepAliveIntervalTimer(e){const t=async r=>{r.aborted||(this.conn.sendAckEliciting(),await this.send(),r.aborted||(this.keepAliveIntervalTimer=new bu({delay:e,handler:t,lazy:!0})))};this.keepAliveIntervalTimer=new bu({delay:e,handler:t,lazy:!0})}stopKeepAliveIntervalTimer(){this.keepAliveIntervalTimer?.cancel()}};var kp,xp;Ep([td(new Fd)],Cp.prototype,"connectionIdPeer",null),Ep([td(new Fd)],Cp.prototype,"connectionIdShared",null),Ep([cp(!0,hp,class extends Qd{static description="QUIC Connection start timeout"}),(kp=1,xp=np,function(e,t){xp(e,t,kp)})],Cp.prototype,"start",null),Ep([td(new Fd,!1,["starting","stopping"])],Cp.prototype,"recv",null),Ep([td(new Fd,!1,["starting","stopping"])],Cp.prototype,"send",null),Ep([td(new Fd)],Cp.prototype,"newStream",null),Cp=Ep([ed({eventStart:class extends Ff{},eventStarted:class extends Ff{},eventStop:class extends Ff{},eventStopped:$f})],Cp);const _p=Cp;var Bp=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let Rp=class{isSocketShared;reasonToCode;codeToReason;minIdleTimeout;logger;socket;crypto;config;_closed=!1;_closedP;resolveClosedP;stopAbortController;handleEventQUICServerError=e=>{const t=e.detail;if(this.logger.info(kf(t)),t instanceof Hd)throw t;this.dispatchEvent(new Vf({detail:t}))};handleEventQUICServerClose=async e=>{const t=e.detail;if(!(t instanceof Pd||this.isSocketShared)){this.socket.removeEventListener(Uf.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new Hd("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new Qf({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[xu]&&"stopping"!==this[Ou]&&(void 0!==t?await this.stop({isApp:!1,errorCode:vp.InternalError,reason:Buffer.from(t.description),force:!0}):await this.stop({force:!0}))};handleEventQUICSocket=e=>{e.detail instanceof Qh&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new Pd;this.removeEventListener(jh.name,this.handleEventQUICSocket),this.dispatchEvent(new Qf({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof Qh&&!(e.detail instanceof zf)&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionSend=async e=>{if(this.socket[xu]&&"stopping"!==this.socket[Ou])try{await this.socket.send_(e.detail.msg,e.detail.port,e.detail.address)}catch(t){switch(t.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":case"EHOSTUNREACH":this.dispatchEvent(new Pf(`${Pf.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new Qf({detail:new Hd("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(zf.name,this.handleEventQUICConnectionSend),t.removeEventListener(jh.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({crypto:e,config:t,socket:r,resolveHostname:s=Af,reasonToCode:i,codeToReason:n,minIdleTimeout:o,logger:a}){this.logger=a??new Hh(this.constructor.name),this.crypto=e,null==r?(this.socket=new sp({resolveHostname:s,logger:this.logger.getChild(sp.name)}),this.isSocketShared=!1):(this.socket=r,this.isSocketShared=!0),this.config={...dp,...t},this.reasonToCode=i,this.codeToReason=n,this.minIdleTimeout=o;const{p:c,resolveP:l}=df();this._closedP=c,this.resolveClosedP=l}get host(){return this.socket.host}get port(){return this.socket.port}get closed(){return this._closed}get closedP(){return this._closedP}async start({host:e="::",port:t=0,reuseAddr:r,ipv6Only:s}={}){let i;if(this.stopAbortController=new AbortController,Bf(this.stopAbortController.signal),this.isSocketShared){if(!this.socket[xu])throw new Pd;i=wf(this.socket.host,this.socket.port),this.logger.info(`Start ${this.constructor.name} on ${i}`)}else i=wf(e,t),this.logger.info(`Start ${this.constructor.name} on ${i}`),await this.socket.start({host:e,port:t,reuseAddr:r,ipv6Only:s}),i=wf(this.socket.host,this.socket.port);this.socket.setServer(this),this.addEventListener(Qf.name,this.handleEventQUICServerError),this.addEventListener(Vf.name,this.handleEventQUICServerClose,{once:!0}),this.socket.addEventListener(Uf.name,this.handleEventQUICSocketStopped,{once:!0}),this.isSocketShared||this.socket.addEventListener(jh.name,this.handleEventQUICSocket),this._closed=!1,this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({isApp:e=!0,errorCode:t=0,reason:r=new Uint8Array,force:s=!0}={}){let i;this.socket[xu]&&(i=wf(this.socket.host,this.socket.port)),this.logger.info(`Stop ${this.constructor.name}${null!=i?` on ${i}`:""}`),this.socket.unsetServer();const n=[];s&&this.stopAbortController?.abort(new Kd),this.stopAbortController=void 0;for(const i of this.socket.connectionMap.serverConnections.values())n.push(i.stop({isApp:e,errorCode:t,reason:r,force:s}));await Promise.all(n),this._closed||this.dispatchEvent(new Vf),await this._closedP;const{p:o,resolveP:a}=df();this._closedP=o,this.resolveClosedP=a,this.removeEventListener(Qf.name,this.handleEventQUICServerError),this.removeEventListener(Vf.name,this.handleEventQUICServerClose),this.socket.removeEventListener(Uf.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(jh.name,this.handleEventQUICSocket),this.logger.info(`Stopped ${this.constructor.name}${null!=i?` on ${i}`:""}`)}async acceptConnection(e,t,r,s){if(t.ty!==gd.Type.Initial&&t.ty!==gd.Type.ZeroRTT)return;const i=new sd(await this.crypto.ops.sign(this.crypto.key,r),0,gd.MAX_CONN_ID_LEN),n=wf(e.host,e.port);if(!gd.versionIsSupported(t.version)){const r=Buffer.allocUnsafe(gd.MAX_DATAGRAM_SIZE),s=gd.negotiateVersion(t.scid,t.dcid,r);try{await this.socket.send_(r,0,s,e.port,e.host)}catch(e){throw new Ld(`Failed to send version datagram ${n}`,{cause:e})}return}const o=t.token;if(0===o.byteLength){const s=await this.mintToken(r,e.host),o=Buffer.allocUnsafe(gd.MAX_DATAGRAM_SIZE),a=gd.retry(t.scid,t.dcid,i,s,t.version,o);try{await this.socket.send_(o,0,a,e.port,e.host)}catch(e){throw new Ld(`Failed to send stateless retry datagram to ${n}`,{cause:e})}return}const a=await this.validateToken(Buffer.from(o),e.host);if(null==a)return;if(i.byteLength!==t.dcid.byteLength)return;const c=new sd(t.dcid),l=new _p({type:"server",scid:c,dcid:a,socket:this.socket,remoteInfo:e,config:{...this.config},reasonToCode:this.reasonToCode,codeToReason:this.codeToReason,logger:this.logger.getChild(`${_p.name} ${i.toString()}`)});this.socket.connectionMap.set(l.connectionId,l),l.addEventListener(zf.name,this.handleEventQUICConnectionSend),l.addEventListener($f.name,this.handleEventQUICConnectionStopped,{once:!0}),l.addEventListener(jh.name,this.handleEventQUICConnection);try{await l.start({data:s,remoteInfo:e},{timer:this.minIdleTimeout,signal:this.stopAbortController?.signal})}catch(e){throw l.removeEventListener(zf.name,this.handleEventQUICConnectionSend),l.removeEventListener($f.name,this.handleEventQUICConnectionStopped),l.removeEventListener(jh.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(l.connectionId),new Ld("Failed to start accepted connection",{cause:e})}return this.dispatchEvent(new Kf({detail:l})),l}updateCrypto(e){this.crypto={...this.crypto,...e}}updateConfig(e){this.config={...this.config,...e}}async mintToken(e,t){return async function(e,t,r){const s={dcid:e.toString(),host:t},i=JSON.stringify(s),n=Buffer.from(i),o=Buffer.from(await r.ops.sign(r.key,n)),a={msg:n.toString("base64url"),sig:o.toString("base64url")},c=JSON.stringify(a);return Buffer.from(c)}(e,t,this.crypto)}async validateToken(e,t){return async function(e,t,r){let s;try{s=JSON.parse(e.toString())}catch{return}if("object"!=typeof s||null==s)return;if("string"!=typeof s.msg||"string"!=typeof s.sig)return;const i=Buffer.from(s.msg,"base64url"),n=Buffer.from(s.sig,"base64url");if(!await r.ops.verify(r.key,i,n))return;let o;try{o=JSON.parse(i.toString())}catch{return}return"object"==typeof o&&null!=o&&"string"==typeof o.dcid&&"string"==typeof o.host&&o.host===t?sd.fromString(o.dcid):void 0}(e,t,this.crypto)}};Bp([td(new Md)],Rp.prototype,"host",null),Bp([td(new Md)],Rp.prototype,"port",null),Bp([td(new Md)],Rp.prototype,"acceptConnection",null),Rp=Bp([ed({eventStart:class extends Hf{},eventStarted:class extends Hf{},eventStop:class extends Hf{},eventStopped:class extends Hf{}})],Rp);var Op=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let Up=class{static async createQUICClient({host:e,port:t,serverName:r,localHost:s="::",localPort:i=0,socket:n,crypto:o,config:a={},resolveHostname:c=Af,reuseAddr:l,ipv6Only:h,reasonToCode:u,codeToReason:d,logger:f=new Hh(`${this.name}`)},p){let g=wf(e,t);f.info(`Create ${this.name} to ${g}`);const y={...up,...a},m=new ArrayBuffer(gd.MAX_CONN_ID_LEN);await o.ops.randomBytes(m);const b=new sd(m);let[A,I]=await If(e,c);const v=vf(t);let w,S;if(A=bf(A),null==n){const[e]=await If(s,c),t=vf(i);n=new sp({resolveHostname:c,logger:f.getChild(sp.name)}),w=!1,await n.start({host:e,port:t,reuseAddr:l,ipv6Only:h})}else if(w=!0,!n[xu])throw new Pd;try{A=Sf(n.host,n.type,A,I,Td)}catch(e){throw w||await n.stop({force:!0}),e}try{S=new _p({type:"client",scid:b,serverName:r??e,socket:n,remoteInfo:{host:A,port:v},config:y,reasonToCode:u,codeToReason:d,logger:f.getChild(`${_p.name} ${b.toString()}`)})}catch(e){throw w||await n.stop({force:!0}),e}const E=new this({socket:n,connection:S,isSocketShared:w,logger:f});w||n.addEventListener(jh.name,E.handleEventQUICSocket),n.addEventListener(Uf.name,E.handleEventQUICSocketStopped,{once:!0}),S.addEventListener(jh.name,E.handleEventQUICConnection),S.addEventListener(jf.name,E.handleEventQUICConnectionError),S.addEventListener(zf.name,E.handleEventQUICConnectionSend),S.addEventListener($f.name,E.handleEventQUICConnectionStopped,{once:!0}),E.addEventListener(Mf.name,E.handleEventQUICClientError),E.addEventListener(Lf.name,E.handleEventQUICClientClose,{once:!0}),n.connectionMap.set(S.connectionId,S);const C=new AbortController,k=()=>{C.abort(p.signal.reason)};p.signal.aborted?C.abort(p.signal.reason):p.signal.addEventListener("abort",k);const x=e=>{switch(e.detail.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":C.abort(new Ud(void 0,{cause:e.detail}))}};E.addEventListener(`${Pf.name}-${S.sendId}`,x);try{await S.start(void 0,{timer:p.timer,signal:C.signal})}catch(e){throw n.connectionMap.delete(S.connectionId),n.removeEventListener(Uf.name,E.handleEventQUICSocketStopped),w||(n.removeEventListener(jh.name,E.handleEventQUICSocket),await n.stop({force:!0})),S.removeEventListener(jh.name,E.handleEventQUICConnection),S.removeEventListener(jf.name,E.handleEventQUICConnectionError),S.removeEventListener(zf.name,E.handleEventQUICConnectionSend),S.removeEventListener($f.name,E.handleEventQUICConnectionStopped),E.removeEventListener(Mf.name,E.handleEventQUICClientError),E.removeEventListener(Lf.name,E.handleEventQUICClientClose),e}finally{p.signal.removeEventListener("abort",k),E.removeEventListener(`${Pf.name}-${S.sendId}`,x)}return g=wf(A,t),f.info(`Created ${this.name} to ${g}`),E}isSocketShared;connection;closedP;logger;socket;config;_closed=!1;resolveClosedP;handleEventQUICClientError=e=>{const t=e.detail;if(this.logger.info(kf(t)),t instanceof Nd||t instanceof Xd)throw t;this.dispatchEvent(new Lf({detail:t}))};handleEventQUICClientClose=async e=>{const t=e.detail;if(this.connection.removeEventListener(jf.name,this.handleEventQUICConnectionError),await this.connection.stop({isApp:!1,errorCode:vp.InternalError,reason:Buffer.from(t.description),force:!0}),!(t instanceof Od||this.isSocketShared)){this.socket.removeEventListener(Uf.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new Nd("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new Mf({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[Bu]||"destroying"===this[Ou]||await this.destroy({force:!0})};handleEventQUICSocket=e=>{e.detail instanceof Qh&&!(e.detail instanceof zf)&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new Od;this.removeEventListener(jh.name,this.handleEventQUICSocket),this.dispatchEvent(new Mf({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof Qh&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionError=e=>{const t=e.detail;this.dispatchEvent(new Mf({detail:t}))};handleEventQUICConnectionSend=async e=>{try{if(!this.socket[xu]||"stopping"===this.socket[Ou])return;await this.socket.send_(e.detail.msg,e.detail.port,e.detail.address)}catch(t){switch(t.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":case"EHOSTUNREACH":this.dispatchEvent(new Pf(`${Pf.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new Mf({detail:new Nd("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(jf.name,this.handleEventQUICConnectionError),t.removeEventListener(zf.name,this.handleEventQUICConnectionSend),t.removeEventListener(jh.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({socket:e,isSocketShared:t,connection:r,logger:s}){this.logger=s,this.socket=e,this.isSocketShared=t,this.connection=r;const{p:i,resolveP:n}=df();this.closedP=i,this.resolveClosedP=n}get host(){return this.connection.remoteHost}get port(){return this.connection.remotePort}get localHost(){return this.socket.host}get localPort(){return this.socket.port}get closed(){return this._closed}async destroy({isApp:e=!0,errorCode:t=0,reason:r=new Uint8Array,force:s=!0}={}){let i;this.connection[xu]&&(i=wf(this.connection.remoteHost,this.connection.remotePort)),this.logger.info(`Destroy ${this.constructor.name}${null!=i?` to ${i}`:""}`),this._closed||await this.connection.stop({isApp:e,errorCode:t,reason:r,force:s}),await this.closedP,this.removeEventListener(Mf.name,this.handleEventQUICClientError),this.removeEventListener(Lf.name,this.handleEventQUICClientClose),this.socket.removeEventListener(Uf.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(jh.name,this.handleEventQUICSocket),this.logger.info(`Destroyed ${this.constructor.name}${null!=i?` to ${i}`:""}`)}};Op([Zu(new Rd)],Up.prototype,"host",null),Op([Zu(new Rd)],Up.prototype,"port",null),Op([Zu(new Rd)],Up.prototype,"localHost",null),Op([Zu(new Rd)],Up.prototype,"localPort",null),Op([cp(!0,hp,class extends Bd{static description="QUIC Client create timeout"}),function(e,t){return function(r,s){t(r,s,e)}}(1,np)],Up,"createQUICClient",null),Up=Op([Xu({eventDestroy:class extends Df{},eventDestroyed:class extends Df{}})],Up),t(import.meta.url)("node:crypto");class Tp{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){const r=Tp.toUint8Array(e),s=Tp.toUint8Array(t);if(r.length!==s.byteLength)return!1;for(let e=0;e<r.length;e++)if(r[e]!==s[e])return!1;return!0}static concat(...e){let t;t=!Array.isArray(e[0])||e[1]instanceof Function?Array.isArray(e[0])&&e[1]instanceof Function?e[0]:e[e.length-1]instanceof Function?e.slice(0,e.length-1):e:e[0];let r=0;for(const e of t)r+=e.byteLength;const s=new Uint8Array(r);let i=0;for(const e of t){const t=this.toUint8Array(e);s.set(t,i),i+=t.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}}const Np="string",Dp=/^[0-9a-f\s]+$/i,Mp=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Pp=/^[a-zA-Z0-9-_]+$/;class Lp{static fromString(e){const t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}static toString(e){const t=Tp.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return decodeURIComponent(escape(r))}}class Hp{static toString(e,t=!1){const r=Tp.toArrayBuffer(e),s=new DataView(r);let i="";for(let e=0;e<r.byteLength;e+=2){const r=s.getUint16(e,t);i+=String.fromCharCode(r)}return i}static fromString(e,t=!1){const r=new ArrayBuffer(2*e.length),s=new DataView(r);for(let r=0;r<e.length;r++)s.setUint16(2*r,e.charCodeAt(r),t);return r}}class Kp{static isHex(e){return typeof e===Np&&Dp.test(e)}static isBase64(e){return typeof e===Np&&Mp.test(e)}static isBase64Url(e){return typeof e===Np&&Pp.test(e)}static ToString(e,t="utf8"){const r=Tp.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(r);case"binary":return this.ToBinary(r);case"hex":return this.ToHex(r);case"base64":return this.ToBase64(r);case"base64url":return this.ToBase64Url(r);case"utf16le":return Hp.toString(r,!0);case"utf16":case"utf16be":return Hp.toString(r);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Hp.fromString(e,!0);case"utf16":case"utf16be":return Hp.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=Tp.toUint8Array(e);if("undefined"!=typeof btoa){const e=this.ToString(t,"binary");return btoa(e)}return Buffer.from(t).toString("base64")}static FromBase64(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!Kp.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!=typeof atob?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!Kp.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=Kp.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Lp.fromString(e);case"utf16":case"utf16be":return Hp.fromString(e);case"utf16le":case"usc2":return Hp.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=Kp.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Lp.toString(e);case"utf16":case"utf16be":return Hp.toString(e);case"utf16le":case"usc2":return Hp.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){const t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return r.buffer}static ToBinary(e){const t=Tp.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return r}static ToHex(e){const t=Tp.toUint8Array(e);let r="";const s=t.length;for(let e=0;e<s;e++){const s=t[e];s<16&&(r+="0"),r+=s.toString(16)}return r}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!Kp.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);const r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2){const s=t.slice(e,e+2);r[e/2]=parseInt(s,16)}return r.buffer}static ToUtf16String(e,t=!1){return Hp.toString(e,t)}static FromUtf16String(e,t=!1){return Hp.fromString(e,t)}static Base64Padding(e){const t=4-e.length%4;if(t<4)for(let r=0;r<t;r++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}function Qp(...e){const t=e.map(e=>e.byteLength).reduce((e,t)=>e+t),r=new Uint8Array(t);let s=0;return e.map(e=>new Uint8Array(e)).forEach(e=>{for(const t of e)r[s++]=t}),r.buffer}function Vp(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(r[t]!==s[t])return!1;return!0}function Fp(e,t){let r=0;if(1===e.length)return e[0];for(let s=e.length-1;s>=0;s--)r+=e[e.length-1-s]*Math.pow(2,t*s);return r}function $p(e,t,r=-1){const s=r;let i=e,n=0,o=Math.pow(2,t);for(let r=1;r<8;r++){if(e<o){let e;if(s<0)e=new ArrayBuffer(r),n=r;else{if(s<r)return new ArrayBuffer(0);e=new ArrayBuffer(s),n=s}const o=new Uint8Array(e);for(let e=r-1;e>=0;e--){const r=Math.pow(2,e*t);o[n-e-1]=Math.floor(i/r),i-=o[n-e-1]*r}return e}o*=Math.pow(2,t)}return new ArrayBuffer(0)}function jp(...e){let t=0,r=0;for(const r of e)t+=r.length;const s=new ArrayBuffer(t),i=new Uint8Array(s);for(const t of e)i.set(t,r),r+=t.length;return i}function Gp(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const t=255===e[0]&&128&e[1],r=0===e[0]&&!(128&e[1]);(t||r)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(t);for(let e=0;e<this.valueHex.byteLength;e++)r[e]=0;r[0]=128&e[0];const s=Fp(r,8),i=new ArrayBuffer(this.valueHex.byteLength),n=new Uint8Array(i);for(let t=0;t<this.valueHex.byteLength;t++)n[t]=e[t];return n[0]&=127,Fp(n,8)-s}function qp(e,t){const r=e.toString(10);if(t<r.length)return"";const s=t-r.length,i=new Array(s);for(let e=0;e<s;e++)i[e]="0";return i.join("").concat(r)}function zp(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Wp(e){let t=0,r=0;for(let r=0;r<e.length;r++)t+=e[r].byteLength;const s=new Uint8Array(t);for(let t=0;t<e.length;t++){const i=e[t];s.set(new Uint8Array(i),r),r+=i.byteLength}return s.buffer}function Jp(e,t,r,s){return t instanceof Uint8Array?t.byteLength?r<0?(e.error="Wrong parameter: inputOffset less than zero",!1):s<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(t.byteLength-r-s<0&&(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",1)):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}Kp.DEFAULT_UTF8_ENCODING="utf8",Math.log(2);class Yp{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Wp(this.items)}}const Xp=[new Uint8Array([1])],Zp="0123456789",eg="name",tg="valueHexView",rg="isHexOnly",sg="idBlock",ig="tagClass",ng="tagNumber",og="isConstructed",ag="fromBER",cg="toBER",lg="local",hg="",ug=new ArrayBuffer(0),dg=new Uint8Array(0),fg="EndOfContent",pg="OCTET STRING",gg="BIT STRING";function yg(e){var t;return t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(...e){var t;super(...e);const r=e[0]||{};this.isHexOnly=null!==(t=r.isHexOnly)&&void 0!==t&&t,this.valueHexView=r.valueHex?Tp.toUint8Array(r.valueHex):dg}fromBER(e,t,r){const s=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!Jp(this,s,t,r))return-1;const i=t+r;return this.valueHexView=s.subarray(t,i),this.valueHexView.length?(this.blockLength=r,i):(this.warnings.push("Zero buffer length"),t)}toBER(e=!1){return this.isHexOnly?e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",ug)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Kp.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class mg{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=hg,warnings:r=[],valueBeforeDecode:s=dg}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=Tp.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Kp.ToHex(this.valueBeforeDecodeView)}}}mg.NAME="baseBlock";class bg extends mg{fromBER(e,t,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}bg.NAME="valueBlock";class Ag extends(yg(mg)){constructor({idBlock:e={}}={}){var t,r,s,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?Tp.toUint8Array(e.valueHex):dg,this.tagClass=null!==(r=e.tagClass)&&void 0!==r?r:-1,this.tagNumber=null!==(s=e.tagNumber)&&void 0!==s?s:-1,this.isConstructed=null!==(i=e.isConstructed)&&void 0!==i&&i):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",ug}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){const r=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,t|=e,r[0]=t}return r.buffer}if(!this.isHexOnly){const r=$p(this.tagNumber,7),s=new Uint8Array(r),i=r.byteLength,n=new Uint8Array(i+1);if(n[0]=31|t,!e){for(let e=0;e<i-1;e++)n[e+1]=128|s[e];n[i]=s[i-1]}return n.buffer}const r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=31|t,!e){const e=this.valueHexView;for(let t=0;t<e.length-1;t++)r[t+1]=128|e[t];r[this.valueHexView.byteLength]=e[e.length-1]}return r.buffer}fromBER(e,t,r){const s=Tp.toUint8Array(e);if(!Jp(this,s,t,r))return-1;const i=s.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;switch(192&i[0]){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=!(32&~i[0]),this.isHexOnly=!1;const n=31&i[0];if(31!==n)this.tagNumber=n,this.blockLength=1;else{let e=1,t=this.valueHexView=new Uint8Array(255),r=255;for(;128&i[e];){if(t[e-1]=127&i[e],e++,e>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(e===r){r+=255;const e=new Uint8Array(r);for(let r=0;r<t.length;r++)e[r]=t[r];t=this.valueHexView=new Uint8Array(r)}}this.blockLength=e+1,t[e-1]=127&i[e];const s=new Uint8Array(e);for(let r=0;r<e;r++)s[r]=t[r];t=this.valueHexView=new Uint8Array(e),t.set(s),this.blockLength<=9?this.tagNumber=Fp(t,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}Ag.NAME="identificationBlock";class Ig extends mg{constructor({lenBlock:e={}}={}){var t,r,s;super(),this.isIndefiniteForm=null!==(t=e.isIndefiniteForm)&&void 0!==t&&t,this.longFormUsed=null!==(r=e.longFormUsed)&&void 0!==r&&r,this.length=null!==(s=e.length)&&void 0!==s?s:0}fromBER(e,t,r){const s=Tp.toUint8Array(e);if(!Jp(this,s,t,r))return-1;const i=s.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;if(255===i[0])return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=128===i[0],this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(128&i[0]),!1===this.longFormUsed)return this.length=i[0],this.blockLength=1,t+this.blockLength;const n=127&i[0];if(n>8)return this.error="Too big integer",-1;if(n+1>i.length)return this.error="End of input reached before message was fully decoded",-1;const o=t+1,a=s.subarray(o,o+n);return 0===a[n-1]&&this.warnings.push("Needlessly long encoded length"),this.length=Fp(a,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=n+1,t+this.blockLength}toBER(e=!1){let t,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=128),t;if(this.longFormUsed){const s=$p(this.length,8);if(s.byteLength>127)return this.error="Too big length",ug;if(t=new ArrayBuffer(s.byteLength+1),e)return t;const i=new Uint8Array(s);r=new Uint8Array(t),r[0]=128|s.byteLength;for(let e=0;e<s.byteLength;e++)r[e+1]=i[e];return t}return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}Ig.NAME="lengthBlock";const vg={};class wg extends mg{constructor({name:e=hg,optional:t=!1,primitiveSchema:r,...s}={},i){super(s),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new Ag(s),this.lenBlock=new Ig(s),this.valueBlock=i?new i(s):new bg(s)}fromBER(e,t,r){const s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===s?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}toBER(e,t){const r=t||new Yp;t||Sg(this);const s=this.idBlock.toBER(e);if(r.write(s),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,r),r.write(new ArrayBuffer(2));else{const t=this.valueBlock.toBER(e);this.lenBlock.length=t.byteLength;const s=this.lenBlock.toBER(e);r.write(s),r.write(t)}return t?ug:r.final()}toJSON(){const e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return"ascii"===e?this.onAsciiEncoding():Kp.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${Kp.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){return this===e||e instanceof this.constructor&&function(e,t){if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let e=0;e<r.length;e++)if(r[e]!==s[e])return!1;return!0}(this.toBER(),e.toBER())}}function Sg(e){var t;if(e instanceof vg.Constructed)for(const t of e.valueBlock.value)Sg(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}wg.NAME="BaseBlock";class Eg extends wg{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=hg,...t}={},r){super(t,r),e&&this.fromString(e)}fromBER(e,t,r){const s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===s?(this.error=this.valueBlock.error,s):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}Eg.NAME="BaseStringBlock";class Cg extends(yg(bg)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var kg,xg,_g,Bg,Rg,Og,Ug,Tg,Ng,Dg,Mg,Pg,Lg,Hg,Kg,Qg,Vg,Fg,$g,jg,Gg,qg,zg,Wg,Jg,Yg,Xg,Zg,ey,ty,ry,sy,iy,ny,oy,ay;Cg.NAME="PrimitiveValueBlock";class cy extends wg{constructor(e={}){super(e,Cg),this.idBlock.isConstructed=!1}}function ly(e,t=0,r=e.length){const s=t;let i=new wg({},bg);const n=new mg;if(!Jp(n,e,t,r))return i.error=n.error,{offset:-1,result:i};if(!e.subarray(t,t+r).length)return i.error="Zero buffer length",{offset:-1,result:i};let o=i.idBlock.fromBER(e,t,r);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),-1===o)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=o,r-=i.idBlock.blockLength,o=i.lenBlock.fromBER(e,t,r),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),-1===o)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=o,r-=i.lenBlock.blockLength,!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let a=wg;if(1===i.idBlock.tagClass){if(i.idBlock.tagNumber>=37&&!1===i.idBlock.isHexOnly)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};a=vg.EndOfContent;break;case 1:a=vg.Boolean;break;case 2:a=vg.Integer;break;case 3:a=vg.BitString;break;case 4:a=vg.OctetString;break;case 5:a=vg.Null;break;case 6:a=vg.ObjectIdentifier;break;case 10:a=vg.Enumerated;break;case 12:a=vg.Utf8String;break;case 13:a=vg.RelativeObjectIdentifier;break;case 14:a=vg.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:a=vg.Sequence;break;case 17:a=vg.Set;break;case 18:a=vg.NumericString;break;case 19:a=vg.PrintableString;break;case 20:a=vg.TeletexString;break;case 21:a=vg.VideotexString;break;case 22:a=vg.IA5String;break;case 23:a=vg.UTCTime;break;case 24:a=vg.GeneralizedTime;break;case 25:a=vg.GraphicString;break;case 26:a=vg.VisibleString;break;case 27:a=vg.GeneralString;break;case 28:a=vg.UniversalString;break;case 29:a=vg.CharacterString;break;case 30:a=vg.BmpString;break;case 31:a=vg.DATE;break;case 32:a=vg.TimeOfDay;break;case 33:a=vg.DateTime;break;case 34:a=vg.Duration;break;default:{const e=i.idBlock.isConstructed?new vg.Constructed:new vg.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else a=i.idBlock.isConstructed?vg.Constructed:vg.Primitive;return i=function(e,t){if(e instanceof t)return e;const r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(i,a),o=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?r:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(s,s+i.blockLength),{offset:o,result:i}}function hy(e){if(!e.byteLength){const e=new wg({},bg);return e.error="Input buffer has zero length",{offset:-1,result:e}}return ly(Tp.toUint8Array(e).slice(),0,e.byteLength)}function uy(e,t){return e?1:t}kg=cy,vg.Primitive=kg,cy.NAME="PRIMITIVE";class dy extends bg{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const s=Tp.toUint8Array(e);if(!Jp(this,s,t,r))return-1;if(this.valueBeforeDecodeView=s.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;let i=t;for(;uy(this.isIndefiniteForm,r)>0;){const e=ly(s,i,r);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(i=e.offset,this.blockLength+=e.result.blockLength,r-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===fg)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===fg?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){const r=t||new Yp;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?ug:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}dy.NAME="ConstructedValueBlock";class fy extends wg{constructor(e={}){super(e,dy),this.idBlock.isConstructed=!0}fromBER(e,t,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===s?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){const e=[];for(const t of this.valueBlock.value)e.push(t.toString("ascii").split("\n").map(e=>` ${e}`).join("\n"));const t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join("\n")}`:`${t} :`}}xg=fy,vg.Constructed=xg,fy.NAME="CONSTRUCTED";class py extends bg{fromBER(e,t,r){return t}toBER(e){return ug}}py.override="EndOfContentValueBlock";class gy extends wg{constructor(e={}){super(e,py),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}_g=gy,vg.EndOfContent=_g,gy.NAME=fg;class yy extends wg{constructor(e={}){super(e,bg),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=r,t+r>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+r}toBER(e,t){const r=new ArrayBuffer(2);if(!e){const e=new Uint8Array(r);e[0]=5,e[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}Bg=yy,vg.Null=Bg,yy.NAME="NULL";class my extends(yg(bg)){get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=Tp.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,r){const s=Tp.toUint8Array(e);return Jp(this,s,t,r)?(this.valueHexView=s.subarray(t,t+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Gp.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}my.NAME="BooleanValueBlock";class by extends wg{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,my),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}Rg=by,vg.Boolean=Rg,by.NAME="BOOLEAN";class Ay extends(yg(dy)){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=dy.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(let e=0;e<this.value.length;e++){const t=this.value[e].constructor.NAME;if(t===fg){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==pg)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,r),this.blockLength=r;return s}toBER(e,t){return this.isConstructed?dy.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Ay.NAME="OctetStringValueBlock";class Iy extends wg{constructor({idBlock:e={},lenBlock:t={},...r}={}){var s,i;null!==(s=r.isConstructed)&&void 0!==s||(r.isConstructed=!!(null===(i=r.value)||void 0===i?void 0:i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Ay),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,0===r)return 0===this.idBlock.error.length&&(this.blockLength+=this.idBlock.blockLength),0===this.lenBlock.error.length&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){const s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+r);try{if(s.byteLength){const e=ly(s,0,s.byteLength);-1!==e.offset&&e.offset===r&&(this.valueBlock.value=[e.result])}}catch{}}return super.fromBER(e,t,r)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?fy.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${Kp.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const t of this.valueBlock.value)t instanceof Og&&e.push(t.valueBlock.valueHexView);return Tp.concat(e)}}Og=Iy,vg.OctetString=Og,Iy.NAME=pg;class vy extends(yg(dy)){constructor({unusedBits:e=0,isConstructed:t=!1,...r}={}){super(r),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r){if(!r)return t;let s=-1;if(this.isConstructed){if(s=dy.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(const e of this.value){const t=e.constructor.NAME;if(t===fg){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==gg)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const r=e.valueBlock;if(this.unusedBits>0&&r.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=r.unusedBits}return s}const i=Tp.toUint8Array(e);if(!Jp(this,i,t,r))return-1;const n=i.subarray(t,t+r);if(this.unusedBits=n[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const e=n.subarray(1);try{if(e.byteLength){const t=ly(e,0,e.byteLength);-1!==t.offset&&t.offset===r-1&&(this.value=[t.result])}}catch{}}return this.valueHexView=n.subarray(1),this.blockLength=n.length,t+r}toBER(e,t){if(this.isConstructed)return dy.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ug;const r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}vy.NAME="BitStringValueBlock";class wy extends wg{constructor({idBlock:e={},lenBlock:t={},...r}={}){var s,i;null!==(s=r.isConstructed)&&void 0!==s||(r.isConstructed=!!(null===(i=r.value)||void 0===i?void 0:i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},vy),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return fy.prototype.onAsciiEncoding.call(this);{const e=[],t=this.valueBlock.valueHexView;for(const r of t)e.push(r.toString(2).padStart(8,"0"));const r=e.join("");return`${this.constructor.NAME} : ${r.substring(0,r.length-this.valueBlock.unusedBits)}`}}}function Sy(e,t){const r=new Uint8Array([0]),s=new Uint8Array(e),i=new Uint8Array(t);let n=s.slice(0);const o=n.length-1,a=i.slice(0),c=a.length-1;let l=0,h=0;for(let e=c<o?o:c;e>=0;e--,h++)l=1==h<a.length?n[o-h]+a[c-h]+r[0]:n[o-h]+r[0],r[0]=l/10,1==h>=n.length?n=jp(new Uint8Array([l%10]),n):n[o-h]=l%10;return r[0]>0&&(n=jp(r,n)),n}function Ey(e){if(e>=Xp.length)for(let t=Xp.length;t<=e;t++){const e=new Uint8Array([0]);let r=Xp[t-1].slice(0);for(let t=r.length-1;t>=0;t--){const s=new Uint8Array([(r[t]<<1)+e[0]]);e[0]=s[0]/10,r[t]=s[0]%10}e[0]>0&&(r=jp(e,r)),Xp.push(r)}return Xp[e]}function Cy(e,t){let r=0;const s=new Uint8Array(e),i=new Uint8Array(t),n=s.slice(0),o=n.length-1,a=i.slice(0),c=a.length-1;let l,h=0;for(let e=c;e>=0;e--,h++)l=n[o-h]-a[c-h]-r,1==l<0?(r=1,n[o-h]=l+10):(r=0,n[o-h]=l);if(r>0)for(let e=o-c+1;e>=0;e--,h++){if(l=n[o-h]-r,!(l<0)){r=0,n[o-h]=l;break}r=1,n[o-h]=l+10}return n.slice()}Ug=wy,vg.BitString=Ug,wy.NAME=gg;class ky extends(yg(bg)){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Gp.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),void 0!==e&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){const t=e<0?-1*e:e;let r=128;for(let s=1;s<8;s++){if(t<=r){if(e<0){const e=$p(r-t,8,s);return new Uint8Array(e)[0]|=128,e}let i=$p(t,8,s),n=new Uint8Array(i);if(128&n[0]){const e=i.slice(0),t=new Uint8Array(e);i=new ArrayBuffer(i.byteLength+1),n=new Uint8Array(i);for(let r=0;r<e.byteLength;r++)n[r+1]=t[r];n[0]=0}return i}r*=Math.pow(2,8)}return new ArrayBuffer(0)}(e))}get valueDec(){return this._valueDec}fromDER(e,t,r,s=0){const i=this.fromBER(e,t,r);if(-1===i)return i;const n=this.valueHexView;return 0===n[0]&&128&n[1]?this.valueHexView=n.subarray(1):0!==s&&n.length<s&&(s-n.length>1&&(s=n.length+1),this.valueHexView=n.subarray(s-n.length)),i}toDER(e=!1){const t=this.valueHexView;switch(!0){case!!(128&t[0]):{const e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case 0===t[0]&&!(128&t[1]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){const s=super.fromBER(e,t,r);return-1===s||this.setValueHex(),s}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=8*this.valueHexView.length-1;let t,r=new Uint8Array(8*this.valueHexView.length/3),s=0;const i=this.valueHexView;let n="",o=!1;for(let o=i.byteLength-1;o>=0;o--){t=i[o];for(let i=0;i<8;i++)1&~t||(s===e?(r=Cy(Ey(s),r),n="-"):r=Sy(r,Ey(s))),s++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(o=!0),o&&(n+=Zp.charAt(r[e]));return!1===o&&(n+=Zp.charAt(0)),n}}Tg=ky,ky.NAME="IntegerValueBlock",Object.defineProperty(Tg.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class xy extends wg{constructor(e={}){super(e,ky),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return zp(),BigInt(this.valueBlock.toString())}static fromBigInt(e){zp();const t=BigInt(e),r=new Yp,s=t.toString(16).replace(/^-/,""),i=new Uint8Array(Kp.FromHex(s));if(t<0){const e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;const s=BigInt(`0x${Kp.ToHex(e)}`)+t,n=Tp.toUint8Array(Kp.FromHex(s.toString(16)));n[0]|=128,r.write(n)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);return new Ng({valueHex:r.final()})}convertToDER(){const e=new Ng({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Ng({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}Ng=xy,vg.Integer=Ng,xy.NAME="INTEGER";class _y extends xy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Dg=_y,vg.Enumerated=Dg,_y.NAME="ENUMERATED";class By extends(yg(bg)){constructor({valueDec:e=-1,isFirstSid:t=!1,...r}={}){super(r),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,r){if(!r)return t;const s=Tp.toUint8Array(e);if(!Jp(this,s,t,r))return-1;const i=s.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&i[e],this.blockLength++,128&i[e]);e++);const n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)n[e]=this.valueHexView[e];return this.valueHexView=n,128&i[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Fp(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){zp();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;const r=new Uint8Array(t.length/7);for(let e=0;e<r.length;e++)r[e]=parseInt(t.slice(7*e,7*e+7),2)+(e+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}const t=$p(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",ug;const r=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),s=t.byteLength-1;for(let t=0;t<s;t++)r[t]=128|e[t];r[s]=e[s]}return r}toString(){let e="";if(this.isHexOnly)e=Kp.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}By.NAME="sidBlock";class Ry extends bg{constructor({value:e=hg,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new By;if(s=t.fromBER(e,s,r),-1===s)return this.blockLength=0,this.error=t.error,s;0===this.value.length&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return s}toBER(e){const t=[];for(let r=0;r<this.value.length;r++){const s=this.value[r].toBER(e);if(0===s.byteLength)return this.error=this.value[r].error,ug;t.push(s)}return Wp(t)}fromString(e){this.value=[];let t=0,r=0,s="",i=!1;do{if(r=e.indexOf(".",t),s=-1===r?e.substring(t):e.substring(t,r),t=r+1,i){const e=this.value[0];let t=0;switch(e.valueDec){case 0:break;case 1:t=40;break;case 2:t=80;break;default:return void(this.value=[])}const r=parseInt(s,10);if(isNaN(r))return;e.valueDec=r+t,i=!1}else{const e=new By;if(s>Number.MAX_SAFE_INTEGER){zp();const t=BigInt(s);e.valueBigInt=t}else if(e.valueDec=parseInt(s,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,i=!0),this.value.push(e)}}while(-1!==r)}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let s=this.value[r].toString();0!==r&&(e=`${e}.`),t?(s=`{${s}}`,this.value[r].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}Ry.NAME="ObjectIdentifierValueBlock";class Oy extends wg{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Ry),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Mg=Oy,vg.ObjectIdentifier=Mg,Oy.NAME="OBJECT IDENTIFIER";class Uy extends(yg(mg)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const s=Tp.toUint8Array(e);if(!Jp(this,s,t,r))return-1;const i=s.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&i[e],this.blockLength++,128&i[e]);e++);const n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)n[e]=this.valueHexView[e];return this.valueHexView=n,128&i[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Fp(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}const t=$p(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",ug;const r=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),s=t.byteLength-1;for(let t=0;t<s;t++)r[t]=128|e[t];r[s]=e[s]}return r.buffer}toString(){let e="";return e=this.isHexOnly?Kp.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Uy.NAME="relativeSidBlock";class Ty extends bg{constructor({value:e=hg,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new Uy;if(s=t.fromBER(e,s,r),-1===s)return this.blockLength=0,this.error=t.error,s;this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return s}toBER(e,t){const r=[];for(let t=0;t<this.value.length;t++){const s=this.value[t].toBER(e);if(0===s.byteLength)return this.error=this.value[t].error,ug;r.push(s)}return Wp(r)}fromString(e){this.value=[];let t=0,r=0,s="";do{r=e.indexOf(".",t),s=-1===r?e.substring(t):e.substring(t,r),t=r+1;const i=new Uy;if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(-1!==r);return!0}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let s=this.value[r].toString();0!==r&&(e=`${e}.`),t?(s=`{${s}}`,e+=s):e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}Ty.NAME="RelativeObjectIdentifierValueBlock";class Ny extends wg{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Ty),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Pg=Ny,vg.RelativeObjectIdentifier=Pg,Ny.NAME="RelativeObjectIdentifier";class Dy extends fy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}Lg=Dy,vg.Sequence=Lg,Dy.NAME="SEQUENCE";class My extends fy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}Hg=My,vg.Set=Hg,My.NAME="SET";class Py extends(yg(bg)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=hg}toJSON(){return{...super.toJSON(),value:this.value}}}Py.NAME="StringValueBlock";class Ly extends Py{}Ly.NAME="SimpleStringValueBlock";class Hy extends Eg{constructor({...e}={}){super(e,Ly)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,Tp.toUint8Array(e))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);this.valueBlock.value=e}}Hy.NAME="SIMPLE STRING";class Ky extends Hy{fromBuffer(e){this.valueBlock.valueHexView=Tp.toUint8Array(e);try{this.valueBlock.value=Kp.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=Kp.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Kp.FromUtf8String(e)),this.valueBlock.value=e}}Ky.NAME="Utf8StringValueBlock";class Qy extends Ky{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}Kg=Qy,vg.Utf8String=Kg,Qy.NAME="UTF8String";class Vy extends Hy{fromBuffer(e){this.valueBlock.value=Kp.ToUtf16String(e),this.valueBlock.valueHexView=Tp.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Kp.FromUtf16String(e))}}Vy.NAME="BmpStringValueBlock";class Fy extends Vy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}Qg=Fy,vg.BmpString=Qg,Fy.NAME="BMPString";class $y extends Hy{fromBuffer(e){const t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(t);for(let e=0;e<r.length;e+=4)r[e]=r[e+3],r[e+1]=r[e+2],r[e+2]=0,r[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(4*t);for(let s=0;s<t;s++){const t=$p(e.charCodeAt(s),8),i=new Uint8Array(t);if(i.length>4)continue;const n=4-i.length;for(let e=i.length-1;e>=0;e--)r[4*s+e+n]=i[e]}this.valueBlock.value=e}}$y.NAME="UniversalStringValueBlock";class jy extends $y{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Vg=jy,vg.UniversalString=Vg,jy.NAME="UniversalString";class Gy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}Fg=Gy,vg.NumericString=Fg,Gy.NAME="NumericString";class qy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}$g=qy,vg.PrintableString=$g,qy.NAME="PrintableString";class zy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}jg=zy,vg.TeletexString=jg,zy.NAME="TeletexString";class Wy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Gg=Wy,vg.VideotexString=Gg,Wy.NAME="VideotexString";class Jy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}qg=Jy,vg.IA5String=qg,Jy.NAME="IA5String";class Yy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}zg=Yy,vg.GraphicString=zg,Yy.NAME="GraphicString";class Xy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}Wg=Xy,vg.VisibleString=Wg,Xy.NAME="VisibleString";class Zy extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}Jg=Zy,vg.GeneralString=Jg,Zy.NAME="GeneralString";class em extends Hy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}Yg=em,vg.CharacterString=Yg,em.NAME="CharacterString";class tm extends Xy{constructor({value:e,valueDate:t,...r}={}){if(super(r),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let t=0;t<e.length;t++)this.valueBlock.valueHexView[t]=e.charCodeAt(t)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,Tp.toUint8Array(e)))}toBuffer(){const e=this.toString(),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(null===t)return void(this.error="Wrong input string for conversion");const r=parseInt(t[1],10);this.year=r>=50?1900+r:2e3+r,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e="iso"){if("iso"===e){const e=new Array(7);return e[0]=qp(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=qp(this.month,2),e[2]=qp(this.day,2),e[3]=qp(this.hour,2),e[4]=qp(this.minute,2),e[5]=qp(this.second,2),e[6]="Z",e.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}Xg=tm,vg.UTCTime=Xg,tm.NAME="UTCTime";class rm extends tm{constructor(e={}){var t;super(e),null!==(t=this.millisecond)&&void 0!==t||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){const e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t,r=!1,s="",i="",n=0,o=0,a=0;if("Z"===e[e.length-1])s=e.substring(0,e.length-1),r=!0;else{const t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw new Error("Wrong input string for conversion");s=e}if(r){if(-1!==s.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==s.indexOf("-"))throw new Error("Wrong input string for conversion")}else{let e=1,t=s.indexOf("+"),r="";if(-1===t&&(t=s.indexOf("-"),e=-1),-1!==t){if(r=s.substring(t+1),s=s.substring(0,t),2!==r.length&&4!==r.length)throw new Error("Wrong input string for conversion");let i=parseInt(r.substring(0,2),10);if(isNaN(i.valueOf()))throw new Error("Wrong input string for conversion");if(o=e*i,4===r.length){if(i=parseInt(r.substring(2,4),10),isNaN(i.valueOf()))throw new Error("Wrong input string for conversion");a=e*i}}}let c=s.indexOf(".");if(-1===c&&(c=s.indexOf(",")),-1!==c){const e=new Number(`0${s.substring(c)}`);if(isNaN(e.valueOf()))throw new Error("Wrong input string for conversion");n=e.valueOf(),i=s.substring(0,c)}else i=s;switch(!0){case 8===i.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==c)throw new Error("Wrong input string for conversion");break;case 10===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*n;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 12===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*n;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){const e=1e3*n;this.millisecond=Math.floor(e)}break;default:throw new Error("Wrong input string for conversion")}const l=t.exec(i);if(null===l)throw new Error("Wrong input string for conversion");for(let e=1;e<l.length;e++)switch(e){case 1:this.year=parseInt(l[e],10);break;case 2:this.month=parseInt(l[e],10);break;case 3:this.day=parseInt(l[e],10);break;case 4:this.hour=parseInt(l[e],10)+o;break;case 5:this.minute=parseInt(l[e],10)+a;break;case 6:this.second=parseInt(l[e],10);break;default:throw new Error("Wrong input string for conversion")}if(!1===r){const e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e="iso"){if("iso"===e){const e=[];return e.push(qp(this.year,4)),e.push(qp(this.month,2)),e.push(qp(this.day,2)),e.push(qp(this.hour,2)),e.push(qp(this.minute,2)),e.push(qp(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(qp(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}Zg=rm,vg.GeneralizedTime=Zg,rm.NAME="GeneralizedTime";class sm extends Qy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}ey=sm,vg.DATE=ey,sm.NAME="DATE";class im extends Qy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}ty=im,vg.TimeOfDay=ty,im.NAME="TimeOfDay";class nm extends Qy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}ry=nm,vg.DateTime=ry,nm.NAME="DateTime";class om extends Qy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}sy=om,vg.Duration=sy,om.NAME="Duration";class am extends Qy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}iy=am,vg.TIME=iy,am.NAME="TIME";class cm{constructor({name:e=hg,optional:t=!1}={}){this.name=e,this.optional=t}}class lm extends cm{constructor({value:e=[],...t}={}){super(t),this.value=e}}class hm extends cm{constructor({value:e=new cm,local:t=!1,...r}={}){super(r),this.value=e,this.local=t}}class um{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=Tp.toUint8Array(e)}constructor({data:e=dg}={}){this.dataView=Tp.toUint8Array(e)}fromBER(e,t,r){const s=t+r;return this.dataView=Tp.toUint8Array(e).subarray(t,s),s}toBER(e){return this.dataView.slice().buffer}}function dm(e,t,r){if(r instanceof lm){for(const s of r.value)if(dm(e,t,s).verified)return{verified:!0,result:e};{const e={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(eg)&&(e.name=r.name),e}}if(r instanceof cm)return r.hasOwnProperty(eg)&&(e[r.name]=t),{verified:!0,result:e};if(e instanceof Object==0)return{verified:!1,result:{error:"Wrong root object"}};if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(r instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(sg in r==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(ag in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(cg in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const s=r.idBlock.toBER(!1);if(0===s.byteLength)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(-1===r.idBlock.fromBER(s,0,s.byteLength))return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(!1===r.idBlock.hasOwnProperty(ig))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==t.idBlock.tagClass)return{verified:!1,result:e};if(!1===r.idBlock.hasOwnProperty(ng))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==t.idBlock.tagNumber)return{verified:!1,result:e};if(!1===r.idBlock.hasOwnProperty(og))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(rg in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==t.idBlock.isHexOnly)return{verified:!1,result:e};if(r.idBlock.isHexOnly){if(tg in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const s=r.idBlock.valueHexView,i=t.idBlock.valueHexView;if(s.length!==i.length)return{verified:!1,result:e};for(let t=0;t<s.length;t++)if(s[t]!==i[1])return{verified:!1,result:e}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hg),r.name&&(e[r.name]=t)),r instanceof vg.Constructed){let s=0,i={verified:!1,result:{error:"Unknown error"}},n=r.valueBlock.value.length;if(n>0&&r.valueBlock.value[0]instanceof hm&&(n=t.valueBlock.value.length),0===n)return{verified:!0,result:e};if(0===t.valueBlock.value.length&&0!==r.valueBlock.value.length){let t=!0;for(let e=0;e<r.valueBlock.value.length;e++)t=t&&(r.valueBlock.value[e].optional||!1);return t?{verified:!0,result:e}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hg),r.name&&delete e[r.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(let o=0;o<n;o++)if(o-s>=t.valueBlock.value.length){if(!1===r.valueBlock.value[o].optional){const t={verified:!1,result:e};return e.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hg),r.name&&(delete e[r.name],t.name=r.name)),t}}else if(r.valueBlock.value[0]instanceof hm){if(i=dm(e,t.valueBlock.value[o],r.valueBlock.value[0].value),!1===i.verified){if(!r.valueBlock.value[0].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hg),r.name&&delete e[r.name]),i;s++}if(eg in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let s={};s=lg in r.valueBlock.value[0]&&r.valueBlock.value[0].local?t:e,void 0===s[r.valueBlock.value[0].name]&&(s[r.valueBlock.value[0].name]=[]),s[r.valueBlock.value[0].name].push(t.valueBlock.value[o])}}else if(i=dm(e,t.valueBlock.value[o-s],r.valueBlock.value[o]),!1===i.verified){if(!r.valueBlock.value[o].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hg),r.name&&delete e[r.name]),i;s++}if(!1===i.verified){const t={verified:!1,result:e};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hg),r.name&&(delete e[r.name],t.name=r.name)),t}return{verified:!0,result:e}}if(r.primitiveSchema&&tg in t.valueBlock){const s=ly(t.valueBlock.valueHexView);if(-1===s.offset){const t={verified:!1,result:s.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,hg),r.name&&(delete e[r.name],t.name=r.name)),t}return dm(e,s.result,r.primitiveSchema)}return{verified:!0,result:e}}function fm(e,t){if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=ly(Tp.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:dm(r.result,r.result,t)}(ay=ny||(ny={}))[ay.Sequence=0]="Sequence",ay[ay.Set=1]="Set",ay[ay.Choice=2]="Choice",function(e){e[e.Any=1]="Any",e[e.Boolean=2]="Boolean",e[e.OctetString=3]="OctetString",e[e.BitString=4]="BitString",e[e.Integer=5]="Integer",e[e.Enumerated=6]="Enumerated",e[e.ObjectIdentifier=7]="ObjectIdentifier",e[e.Utf8String=8]="Utf8String",e[e.BmpString=9]="BmpString",e[e.UniversalString=10]="UniversalString",e[e.NumericString=11]="NumericString",e[e.PrintableString=12]="PrintableString",e[e.TeletexString=13]="TeletexString",e[e.VideotexString=14]="VideotexString",e[e.IA5String=15]="IA5String",e[e.GraphicString=16]="GraphicString",e[e.VisibleString=17]="VisibleString",e[e.GeneralString=18]="GeneralString",e[e.CharacterString=19]="CharacterString",e[e.UTCTime=20]="UTCTime",e[e.GeneralizedTime=21]="GeneralizedTime",e[e.DATE=22]="DATE",e[e.TimeOfDay=23]="TimeOfDay",e[e.DateTime=24]="DateTime",e[e.Duration=25]="Duration",e[e.TIME=26]="TIME",e[e.Null=27]="Null"}(oy||(oy={}));class pm{constructor(e,t=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if("number"==typeof e)this.fromNumber(e);else{if(!Tp.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=Tp.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof wy))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=e.valueBlock.valueHex,this}toASN(){return new wy({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new wy({name:e})}toNumber(){let e="";const t=new Uint8Array(this.value);for(const r of t)e+=r.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let t=e.toString(2);const r=t.length+7>>3;this.unusedBits=(r<<3)-t.length;const s=new Uint8Array(r);t=t.padStart(r<<3,"0").split("").reverse().join("");let i=0;for(;i<r;)s[i]=parseInt(t.slice(i<<3,8+(i<<3)),2),i++;this.value=s.buffer}}class gm{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):Tp.isBufferSource(e)?this.buffer=Tp.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Iy))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new Iy({valueHex:this.buffer})}toSchema(e){return new Iy({name:e})}}const ym={fromASN:e=>e instanceof yy?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new yy;const t=hy(e);if(t.result.error)throw new Error(t.result.error);return t.result}},mm={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new xy({value:+e})},bm={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new _y({value:e})},Am={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new xy({valueHex:e})},Im={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new wy({valueHex:e})},vm={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Oy({value:e})},wm={fromASN:e=>e.valueBlock.value,toASN:e=>new by({value:e})},Sm={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Iy({valueHex:e})},Em={fromASN:e=>new gm(e.getValue()),toASN:e=>e.toASN()};function Cm(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}const km=Cm(Qy),xm=Cm(Fy),_m=Cm(jy),Bm=Cm(Gy),Rm=Cm(qy),Om=Cm(zy),Um=Cm(Wy),Tm=Cm(Jy),Nm=Cm(Yy),Dm=Cm(Xy),Mm=Cm(Zy),Pm=Cm(em),Lm={fromASN:e=>e.toDate(),toASN:e=>new tm({valueDate:e})},Hm={fromASN:e=>e.toDate(),toASN:e=>new rm({valueDate:e})},Km={fromASN:()=>null,toASN:()=>new yy};function Qm(e){switch(e){case oy.Any:return ym;case oy.BitString:return Im;case oy.BmpString:return xm;case oy.Boolean:return wm;case oy.CharacterString:return Pm;case oy.Enumerated:return bm;case oy.GeneralString:return Mm;case oy.GeneralizedTime:return Hm;case oy.GraphicString:return Nm;case oy.IA5String:return Tm;case oy.Integer:return mm;case oy.Null:return Km;case oy.NumericString:return Bm;case oy.ObjectIdentifier:return vm;case oy.OctetString:return Sm;case oy.PrintableString:return Rm;case oy.TeletexString:return Om;case oy.UTCTime:return Lm;case oy.UniversalString:return _m;case oy.Utf8String:return km;case oy.VideotexString:return Um;case oy.VisibleString:return Dm;default:return null}}function Vm(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||Vm(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function Fm(e){var t;if(e){const r=Object.getPrototypeOf(e);return(null===(t=null==r?void 0:r.prototype)||void 0===t?void 0:t.constructor)===Array||Fm(r)}return!1}function $m(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(r[t]!==s[t])return!1;return!0}const jm=new class{constructor(){this.items=new WeakMap}has(e){return this.items.has(e)}get(e,t=!1){const r=this.items.get(e);if(!r)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!r.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return r}cache(e){const t=this.get(e);t.schema||(t.schema=this.create(e,!0))}createDefault(e){const t={type:ny.Sequence,items:{}},r=this.findParentSchema(e);return r&&(Object.assign(t,r),t.items=Object.assign({},t.items,r.items)),t}create(e,t){const r=this.items.get(e)||this.createDefault(e),s=[];for(const e in r.items){const i=r.items[e],n=t?e:"";let o;if("number"==typeof i.type){const e=oy[i.type],t=a[e];if(!t)throw new Error(`Cannot get ASN1 class by name '${e}'`);o=new t({name:n})}else Vm(i.type)?o=(new i.type).toSchema(n):i.optional?this.get(i.type).type===ny.Choice?o=new cm({name:n}):(o=this.create(i.type,!1),o.name=n):o=new cm({name:n});const c=!!i.optional||void 0!==i.defaultValue;if(i.repeated&&(o.name="",o=new("set"===i.repeated?My:Dy)({name:"",value:[new hm({name:n,value:o})]})),null!==i.context&&void 0!==i.context)if(i.implicit)if("number"==typeof i.type||Vm(i.type)){const e=i.repeated?fy:cy;s.push(new e({name:n,optional:c,idBlock:{tagClass:3,tagNumber:i.context}}))}else{this.cache(i.type);const e=!!i.repeated;let t=e?o:this.get(i.type,!0).schema;t="valueBlock"in t?t.valueBlock.value:t.value,s.push(new fy({name:e?"":n,optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}else s.push(new fy({optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:[o]}));else o.optional=c,s.push(o)}switch(r.type){case ny.Sequence:return new Dy({value:s,name:""});case ny.Set:return new My({value:s,name:""});case ny.Choice:return new lm({value:s,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){const t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}},Gm=e=>t=>{let r;jm.has(t)?r=jm.get(t):(r=jm.createDefault(t),jm.set(t,r)),Object.assign(r,e)},qm=e=>(t,r)=>{let s;jm.has(t.constructor)?s=jm.get(t.constructor):(s=jm.createDefault(t.constructor),jm.set(t.constructor,s));const i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){const s=Qm(e.type);if(!s)throw new Error(`Cannot get default converter for property '${r}' of ${t.constructor.name}`);i.converter=s}s.items[r]=i};class zm extends Error{constructor(){super(...arguments),this.schemas=[]}}class Wm{static parse(e,t){const r=hy(e);if(r.result.error)throw new Error(r.result.error);return this.fromASN(r.result,t)}static fromASN(e,t){var r;try{if(Vm(t))return(new t).fromASN(e);const s=jm.get(t);jm.cache(t);let i=s.schema;if(e.constructor===fy&&s.type!==ny.Choice){i=new fy({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:s.schema.valueBlock.value});for(const t in s.items)delete e[t]}const n=dm({},e,i);if(!n.verified)throw new zm(`Data does not match to ${t.name} ASN1 schema. ${n.result.error}`);const o=new t;if(Fm(t)){if(!("value"in e.valueBlock)||!Array.isArray(e.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const r=s.itemType;if("number"==typeof r){const s=Qm(r);if(!s)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);return t.from(e.valueBlock.value,e=>s.fromASN(e))}return t.from(e.valueBlock.value,e=>this.fromASN(e,r))}for(const e in s.items){const t=n.result[e];if(!t)continue;const i=s.items[e],c=i.type;if("number"==typeof c||Vm(c)){const s=null!==(r=i.converter)&&void 0!==r?r:Vm(c)?new c:null;if(!s)throw new Error("Converter is empty");if(i.repeated)if(i.implicit){const r=new("sequence"===i.repeated?Dy:My);r.valueBlock=t.valueBlock;const n=hy(r.toBER(!1));if(-1===n.offset)throw new Error(`Cannot parse the child item. ${n.result.error}`);if(!("value"in n.result.valueBlock)||!Array.isArray(n.result.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const a=n.result.valueBlock.value;o[e]=Array.from(a,e=>s.fromASN(e))}else o[e]=Array.from(t,e=>s.fromASN(e));else{let r=t;if(i.implicit){let e;if(Vm(c))e=(new c).toSchema("");else{const t=oy[c],r=a[t];if(!r)throw new Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=r.valueBlock,r=hy(e.toBER(!1)).result}o[e]=s.fromASN(r)}}else if(i.repeated){if(!Array.isArray(t))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");o[e]=Array.from(t,e=>this.fromASN(e,c))}else o[e]=this.fromASN(t,c)}return o}catch(e){throw e instanceof zm&&e.schemas.push(t.name),e}}}class Jm{static serialize(e){return e instanceof wg?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&"object"==typeof e&&Vm(e))return e.toASN();if(!e||"object"!=typeof e)throw new TypeError("Parameter 1 should be type of Object.");const t=e.constructor,r=jm.get(t);jm.cache(t);let s,i=[];if(r.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if("number"==typeof r.itemType){const s=Qm(r.itemType);if(!s)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);i=e.map(e=>s.toASN(e))}else i=e.map(e=>this.toAsnItem({type:r.itemType},"[]",t,e))}else for(const s in r.items){const n=r.items[s],o=e[s];if(void 0===o||n.defaultValue===o||"object"==typeof n.defaultValue&&"object"==typeof o&&$m(this.serialize(n.defaultValue),this.serialize(o)))continue;const a=Jm.toAsnItem(n,s,t,o);if("number"==typeof n.context)if(n.implicit)if(n.repeated||"number"!=typeof n.type&&!Vm(n.type))i.push(new fy({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:a.valueBlock.value}));else{const e={};e.valueHex=a instanceof yy?a.valueBeforeDecodeView:a.valueBlock.toBER(),i.push(new cy({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},...e}))}else i.push(new fy({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:[a]}));else n.repeated?i=i.concat(a):i.push(a)}switch(r.type){case ny.Sequence:s=new Dy({value:i});break;case ny.Set:s=new My({value:i});break;case ny.Choice:if(!i[0])throw new Error(`Schema '${t.name}' has wrong data. Choice cannot be empty.`);s=i[0]}return s}static toAsnItem(e,t,r,s){let i;if("number"==typeof e.type){const n=e.converter;if(!n)throw new Error(`Property '${t}' doesn't have converter for type ${oy[e.type]} in schema '${r.name}'`);if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");const t=Array.from(s,e=>n.toASN(e));i=new("sequence"===e.repeated?Dy:My)({value:t})}else i=n.toASN(s)}else if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");const t=Array.from(s,e=>this.toASN(e));i=new("sequence"===e.repeated?Dy:My)({value:t})}else i=this.toASN(s);return i}}class Ym extends Array{constructor(e=[]){if("number"==typeof e)super(e);else{super();for(const t of e)this.push(t)}}}class Xm{static serialize(e){return Jm.serialize(e)}static parse(e,t){return Wm.parse(e,t)}static toString(e){const t=hy(Tp.isBufferSource(e)?Tp.toArrayBuffer(e):Xm.serialize(e));if(-1===t.offset)throw new Error(`Cannot decode ASN.1 data. ${t.result.error}`);return t.result.toString()}}function Zm(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;class eb extends Error{constructor(e,t){super(t?`${e}. See the inner exception for more details.`:e),this.message=e,this.innerError=t}}class tb extends eb{constructor(e,t,r){super(t,r),this.schema=e}}class rb extends tb{constructor(e,t,r){super(e,`JSON doesn't match to '${e.target.name}' schema. ${t}`,r)}}class sb extends eb{}class ib extends eb{constructor(e,t,r){super(`Cannot serialize by '${e}' schema. ${t}`,r),this.schemaName=e}}class nb extends rb{constructor(e,t,r={}){super(e,"Some keys doesn't match to schema"),this.keys=t,this.errors=r}}var ob;function ab(e,t){if(!function(e,t){switch(t){case ob.Boolean:return"boolean"==typeof e;case ob.Number:return"number"==typeof e;case ob.String:return"string"==typeof e}return!0}(e,t))throw new TypeError(`Value must be ${ob[t]}`)}function cb(e){return e&&e.prototype?!(!e.prototype.toJSON||!e.prototype.fromJSON)||cb(e.prototype):!!(e&&e.toJSON&&e.fromJSON)}!function(e){e[e.Any=0]="Any",e[e.Boolean=1]="Boolean",e[e.Number=2]="Number",e[e.String=3]="String"}(ob||(ob={}));const lb="default",hb=new class{constructor(){this.items=new Map}has(e){return this.items.has(e)||!!this.findParentSchema(e)}get(e){const t=this.items.get(e)||this.findParentSchema(e);if(!t)throw new Error("Cannot get schema for current target");return t}create(e){const t={names:{}},r=this.findParentSchema(e);if(r){Object.assign(t,r),t.names={};for(const e in r.names)t.names[e]=Object.assign({},r.names[e])}return t.target=e,t}set(e,t){return this.items.set(e,t),this}findParentSchema(e){const t=e.__proto__;return t?this.items.get(t)||this.findParentSchema(t):null}};class ub{constructor(e){this.pattern=new RegExp(e)}validate(e){const t=new RegExp(this.pattern.source,this.pattern.flags);if("string"!=typeof e)throw new sb("Incoming value must be string");if(!t.exec(e))throw new sb(`Value doesn't match to pattern '${t.toString()}'`)}}class db{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(ab(e,ob.Number),!(this.min<=e&&e<=this.max)){const e=this.min===Number.MIN_VALUE?"MIN":this.min,t=this.max===Number.MAX_VALUE?"MAX":this.max;throw new sb(`Value doesn't match to diapason [${e},${t}]`)}}}class fb{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(ab(e,ob.Number),!(this.min<e&&e<this.max)){const e=this.min===Number.MIN_VALUE?"MIN":this.min,t=this.max===Number.MAX_VALUE?"MAX":this.max;throw new sb(`Value doesn't match to diapason (${e},${t})`)}}}class pb{constructor(e,t,r){this.length=e,this.minLength=t,this.maxLength=r}validate(e){if(void 0===this.length){if(void 0!==this.minLength&&e.length<this.minLength)throw new sb(`Value length must be more than ${this.minLength}.`);if(void 0!==this.maxLength&&e.length>this.maxLength)throw new sb(`Value length must be less than ${this.maxLength}.`)}else if(e.length!==this.length)throw new sb(`Value length must be exactly ${this.length}.`)}}class gb{constructor(e){this.enumeration=e}validate(e){if(ab(e,ob.String),!this.enumeration.includes(e))throw new sb(`Value must be one of ${this.enumeration.map(e=>`'${e}'`).join(", ")}`)}}class yb{static checkValues(e,t){const r=Array.isArray(e)?e:[e];for(const s of r)for(const r of t.validations)r instanceof pb&&t.repeated?r.validate(e):r.validate(s)}static checkTypes(e,t){if(t.repeated&&!Array.isArray(e))throw new TypeError("Value must be Array");if("number"==typeof t.type){const r=Array.isArray(e)?e:[e];for(const e of r)ab(e,t.type)}}static getSchemaByName(e,t=lb){return{...e.names[lb],...e.names[t]}}}class mb extends yb{static serialize(e,t,r,s){const i=this.toJSON(e,t);return JSON.stringify(i,r,s)}static toJSON(e,t={}){let r,s=t.targetSchema;const i=t.schemaName||lb;if(cb(e))return e.toJSON();if(Array.isArray(e)){r=[];for(const s of e)r.push(this.toJSON(s,t))}else if("object"==typeof e){if(s&&!hb.has(s))throw new eb("Cannot get schema for `targetSchema` param");if(s=s||e.constructor,hb.has(s)){const t=hb.get(s);r={};const n=this.getSchemaByName(t,i);for(const o in n)try{const t=n[o],a=e[o];let c;if(t.optional&&void 0===a||void 0!==t.defaultValue&&a===t.defaultValue)continue;if(!t.optional&&void 0===a)throw new ib(s.name,`Property '${o}' is required.`);c="number"==typeof t.type?t.converter?t.repeated?a.map(r=>t.converter.toJSON(r,e)):t.converter.toJSON(a,e):a:t.repeated?a.map(e=>this.toJSON(e,{schemaName:i})):this.toJSON(a,{schemaName:i}),this.checkTypes(c,t),this.checkValues(c,t),r[t.name||o]=c}catch(e){throw e instanceof ib?e:new ib(t.target.name,`Property '${o}' is wrong. ${e.message}`,e)}}else{r={};for(const t in e)r[t]=this.toJSON(e[t],{schemaName:i})}}else r=e;return r}}class bb extends yb{static parse(e,t){const r=JSON.parse(e);return this.fromJSON(r,t)}static fromJSON(e,t){const r=t.targetSchema,s=t.schemaName||lb,i=new r;if(cb(i))return i.fromJSON(e);const n=hb.get(r),o=this.getSchemaByName(n,s),a={};t.strictProperty&&!Array.isArray(e)&&bb.checkStrictProperty(e,o,n);for(const r in o)try{const a=o[r],c=a.name||r,l=e[c];if(void 0===l&&(a.optional||void 0!==a.defaultValue))continue;if(!a.optional&&void 0===l)throw new rb(n,`Property '${c}' is required.`);if(this.checkTypes(l,a),this.checkValues(l,a),"number"==typeof a.type)a.converter?a.repeated?i[r]=l.map(e=>a.converter.fromJSON(e,i)):i[r]=a.converter.fromJSON(l,i):i[r]=l;else{const e={...t,targetSchema:a.type,schemaName:s};a.repeated?i[r]=l.map(t=>this.fromJSON(t,e)):i[r]=this.fromJSON(l,e)}}catch(e){if(e instanceof rb||(e=new rb(n,`Property '${r}' is wrong. ${e.message}`,e)),!t.strictAllKeys)throw e;a[r]=e}const c=Object.keys(a);if(c.length)throw new nb(n,c,a);return i}static checkStrictProperty(e,t,r){const s=Object.keys(e),i=Object.keys(t),n=[];for(const e of s)-1===i.indexOf(e)&&n.push(e);if(n.length)throw new nb(r,n)}}const Ab=(e={})=>(t,r)=>{const s=`Cannot set type for ${r} property of ${t.constructor.name} schema`;let i;hb.has(t.constructor)?(i=hb.get(t.constructor),i.target!==t.constructor&&(i=hb.create(t.constructor),hb.set(t.constructor,i))):(i=hb.create(t.constructor),hb.set(t.constructor,i));const n={type:ob.Any,validations:[]},o=Object.assign(n,e);if(o.validations=function(e){const t=[];return e.pattern&&t.push(new ub(e.pattern)),e.type!==ob.Number&&e.type!==ob.Any||(void 0===e.minInclusive&&void 0===e.maxInclusive||t.push(new db(e.minInclusive,e.maxInclusive)),void 0===e.minExclusive&&void 0===e.maxExclusive||t.push(new fb(e.minExclusive,e.maxExclusive)),void 0!==e.enumeration&&t.push(new gb(e.enumeration))),(e.type===ob.String||e.repeated||e.type===ob.Any)&&(void 0===e.length&&void 0===e.minLength&&void 0===e.maxLength||t.push(new pb(e.length,e.minLength,e.maxLength))),t}(o),"number"!=typeof o.type&&!hb.has(o.type)&&!cb(o.type))throw new Error(`${s}. Assigning type doesn't have schema.`);let a;a=Array.isArray(e.schema)?e.schema:[e.schema||lb];for(const e of a)i.names[e]||(i.names[e]={}),i.names[e][r]=o};class Ib extends Error{}class vb extends Ib{}class wb extends Ib{constructor(e){super("Unsupported operation: "+(e?`${e}`:""))}}class Sb extends Ib{}class Eb extends Ib{constructor(e){super(`${e}: Missing required property`)}}class Cb{static toArrayBuffer(e){const t=e.replace(/-{5}(BEGIN|END) .*-{5}/g,"").replace("\r","").replace("\n","");return Kp.FromBase64(t)}static toUint8Array(e){const t=this.toArrayBuffer(e);return new Uint8Array(t)}static fromBufferSource(e,t){const r=Kp.ToBase64(e);let s,i=0;const n=[];for(;i<r.length&&(s=r.slice(i,i+64),s.length);)n.push(s),i+=64;const o=t.toUpperCase();return`-----BEGIN ${o}-----\n${n.join("\n")}\n-----END ${o}-----`}static isPEM(e){return/-----BEGIN .+-----[A-Za-z0-9+/+=\s\n]+-----END .+-----/i.test(e)}static getTagName(e){if(!this.isPEM(e))throw new Error("Bad parameter. Incoming data is not right PEM");const t=/-----BEGIN (.+)-----/.exec(e);if(!t)throw new Error("Cannot get tag from PEM");return t[1]}static hasTagName(e,t){const r=this.getTagName(e);return t.toLowerCase()===r.toLowerCase()}static isCertificate(e){return this.hasTagName(e,"certificate")}static isCertificateRequest(e){return this.hasTagName(e,"certificate request")}static isCRL(e){return this.hasTagName(e,"x509 crl")}static isPublicKey(e){return this.hasTagName(e,"public key")}}class kb{async digest(...e){return this.checkDigest.apply(this,e),this.onDigest.apply(this,e)}checkDigest(e,t){this.checkAlgorithmName(e)}async onDigest(e,t){throw new wb("digest")}async generateKey(...e){return this.checkGenerateKey.apply(this,e),this.onGenerateKey.apply(this,e)}checkGenerateKey(e,t,r,...s){if(this.checkAlgorithmName(e),this.checkGenerateKeyParams(e),!r||!r.length)throw new TypeError("Usages cannot be empty when creating a key.");let i;i=Array.isArray(this.usages)?this.usages:this.usages.privateKey.concat(this.usages.publicKey),this.checkKeyUsages(r,i)}checkGenerateKeyParams(e){}async onGenerateKey(e,t,r,...s){throw new wb("generateKey")}async sign(...e){return this.checkSign.apply(this,e),this.onSign.apply(this,e)}checkSign(e,t,r,...s){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,"sign")}async onSign(e,t,r,...s){throw new wb("sign")}async verify(...e){return this.checkVerify.apply(this,e),this.onVerify.apply(this,e)}checkVerify(e,t,r,s,...i){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,"verify")}async onVerify(e,t,r,s,...i){throw new wb("verify")}async encrypt(...e){return this.checkEncrypt.apply(this,e),this.onEncrypt.apply(this,e)}checkEncrypt(e,t,r,s={},...i){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,s.keyUsage?"encrypt":void 0)}async onEncrypt(e,t,r,...s){throw new wb("encrypt")}async decrypt(...e){return this.checkDecrypt.apply(this,e),this.onDecrypt.apply(this,e)}checkDecrypt(e,t,r,s={},...i){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,s.keyUsage?"decrypt":void 0)}async onDecrypt(e,t,r,...s){throw new wb("decrypt")}async deriveBits(...e){return this.checkDeriveBits.apply(this,e),this.onDeriveBits.apply(this,e)}checkDeriveBits(e,t,r,s={},...i){if(this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,s.keyUsage?"deriveBits":void 0),r%8!=0)throw new Sb("length: Is not multiple of 8")}async onDeriveBits(e,t,r,...s){throw new wb("deriveBits")}async exportKey(...e){return this.checkExportKey.apply(this,e),this.onExportKey.apply(this,e)}checkExportKey(e,t,...r){if(this.checkKeyFormat(e),this.checkCryptoKey(t),!t.extractable)throw new Ib("key: Is not extractable")}async onExportKey(e,t,...r){throw new wb("exportKey")}async importKey(...e){return this.checkImportKey.apply(this,e),this.onImportKey.apply(this,e)}checkImportKey(e,t,r,s,i,...n){this.checkKeyFormat(e),this.checkKeyData(e,t),this.checkAlgorithmName(r),this.checkImportParams(r),Array.isArray(this.usages)&&this.checkKeyUsages(i,this.usages)}async onImportKey(e,t,r,s,i,...n){throw new wb("importKey")}checkAlgorithmName(e){if(e.name.toLowerCase()!==this.name.toLowerCase())throw new vb("Unrecognized name")}checkAlgorithmParams(e){}checkDerivedKeyParams(e){}checkKeyUsages(e,t){for(const r of e)if(-1===t.indexOf(r))throw new TypeError("Cannot create a key using the specified key usages")}checkCryptoKey(e,t){if(this.checkAlgorithmName(e.algorithm),t&&-1===e.usages.indexOf(t))throw new Ib("key does not match that of operation")}checkRequiredProperty(e,t){if(!(t in e))throw new Eb(t)}checkHashAlgorithm(e,t){for(const r of t)if(r.toLowerCase()===e.name.toLowerCase())return;throw new Sb(`hash: Must be one of ${t.join(", ")}`)}checkImportParams(e){}checkKeyFormat(e){switch(e){case"raw":case"pkcs8":case"spki":case"jwk":break;default:throw new TypeError("format: Is invalid value. Must be 'jwk', 'raw', 'spki', or 'pkcs8'")}}checkKeyData(e,t){if(!t)throw new TypeError("keyData: Cannot be empty on empty on key importing");if("jwk"===e){if("object"!=typeof(r=t)||!("kty"in r))throw new TypeError("keyData: Is not JsonWebToken")}else if(!Tp.isBufferSource(t))throw new TypeError("keyData: Is not ArrayBufferView or ArrayBuffer");var r}prepareData(e){return Tp.toArrayBuffer(e)}}class xb extends kb{checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not of type Number");switch(e.length){case 128:case 192:case 256:break;default:throw new TypeError("length: Must be 128, 192, or 256")}}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class _b extends xb{constructor(){super(...arguments),this.name="AES-CBC",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"iv"),!(e.iv instanceof ArrayBuffer||ArrayBuffer.isView(e.iv)))throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(16!==e.iv.byteLength)throw new TypeError("iv: Must have length 16 bytes")}}class Bb extends xb{constructor(){super(...arguments),this.name="AES-CMAC",this.usages=["sign","verify"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not a Number");if(e.length<1)throw new Sb("length: Must be more than 0")}}class Rb extends xb{constructor(){super(...arguments),this.name="AES-CTR",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"counter"),!(e.counter instanceof ArrayBuffer||ArrayBuffer.isView(e.counter)))throw new TypeError("counter: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(16!==e.counter.byteLength)throw new TypeError("iv: Must have length 16 bytes");if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not a Number");if(e.length<1)throw new Sb("length: Must be more than 0")}}class Ob extends xb{constructor(){super(...arguments),this.name="AES-ECB",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}}class Ub extends xb{constructor(){super(...arguments),this.name="AES-GCM",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){var t;if(this.checkRequiredProperty(e,"iv"),!(e.iv instanceof ArrayBuffer||ArrayBuffer.isView(e.iv)))throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(e.iv.byteLength<1)throw new Sb("iv: Must have length more than 0 and less than 2^64 - 1");switch(null!==(t=e.tagLength)&&void 0!==t||(e.tagLength=128),e.tagLength){case 32:case 64:case 96:case 104:case 112:case 120:case 128:break;default:throw new Sb("tagLength: Must be one of 32, 64, 96, 104, 112, 120 or 128")}}}class Tb extends xb{constructor(){super(...arguments),this.name="AES-KW",this.usages=["wrapKey","unwrapKey"]}}class Nb extends kb{constructor(){super(...arguments),this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){if(this.ivSize){if(this.checkRequiredProperty(e,"iv"),!(e.iv instanceof ArrayBuffer||ArrayBuffer.isView(e.iv)))throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(e.iv.byteLength!==this.ivSize)throw new TypeError(`iv: Must have length ${this.ivSize} bytes`)}}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not of type Number");if(e.length!==this.keySizeBits)throw new Sb(`algorithm.length: Must be ${this.keySizeBits}`)}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class Db extends kb{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"]}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),this.checkRequiredProperty(e,"publicExponent"),!(e.publicExponent&&e.publicExponent instanceof Uint8Array))throw new TypeError("publicExponent: Missing or not a Uint8Array");const t=Kp.ToBase64(e.publicExponent);if("Aw=="!==t&&"AQAB"!==t)throw new TypeError("publicExponent: Must be [3] or [1,0,1]");if(this.checkRequiredProperty(e,"modulusLength"),e.modulusLength%8||e.modulusLength<256||e.modulusLength>16384)throw new TypeError("The modulus length must be a multiple of 8 bits and >= 256 and <= 16384")}checkImportParams(e){this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms)}}class Mb extends Db{constructor(){super(...arguments),this.name="RSASSA-PKCS1-v1_5",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class Pb extends Db{constructor(){super(...arguments),this.name="RSA-PSS",this.usages={privateKey:["sign"],publicKey:["verify"]}}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"saltLength"),"number"!=typeof e.saltLength)throw new TypeError("saltLength: Is not a Number");if(e.saltLength<0)throw new RangeError("saltLength: Must be positive number")}}class Lb extends Db{constructor(){super(...arguments),this.name="RSA-OAEP",this.usages={privateKey:["decrypt","unwrapKey"],publicKey:["encrypt","wrapKey"]}}checkAlgorithmParams(e){if(e.label&&!(e.label instanceof ArrayBuffer||ArrayBuffer.isView(e.label)))throw new TypeError("label: Is not of type '(ArrayBuffer or ArrayBufferView)'")}}class Hb extends kb{checkGenerateKeyParams(e){this.checkRequiredProperty(e,"namedCurve"),this.checkNamedCurve(e.namedCurve)}checkNamedCurve(e){for(const t of this.namedCurves)if(t.toLowerCase()===e.toLowerCase())return;throw new Sb(`namedCurve: Must be one of ${this.namedCurves.join(", ")}`)}}class Kb extends Hb{constructor(){super(...arguments),this.name="ECDSA",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["P-256","P-384","P-521","K-256"]}checkAlgorithmParams(e){this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms)}}const Qb=["secret","private","public"];class Vb{static create(e,t,r,s){const i=new this;return i.algorithm=e,i.type=t,i.extractable=r,i.usages=s,i}static isKeyType(e){return-1!==Qb.indexOf(e)}get[Symbol.toStringTag](){return"CryptoKey"}}class Fb extends Hb{constructor(){super(...arguments),this.name="ECDH",this.usages={privateKey:["deriveBits","deriveKey"],publicKey:[]},this.namedCurves=["P-256","P-384","P-521","K-256"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"public"),!(e.public instanceof Vb))throw new TypeError("public: Is not a CryptoKey");if("public"!==e.public.type)throw new Sb("public: Is not a public key");if(e.public.algorithm.name!==this.name)throw new Sb(`public: Is not ${this.name} key`)}}class $b extends Fb{constructor(){super(...arguments),this.name="ECDH-ES",this.namedCurves=["X25519","X448"]}}class jb extends Hb{constructor(){super(...arguments),this.name="EdDSA",this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["Ed25519","Ed448"]}}let Gb=class{constructor(e){e&&(this.value=e)}};Zm([qm({type:oy.ObjectIdentifier})],Gb.prototype,"value",void 0),Gb=Zm([Gm({type:ny.Choice})],Gb);class qb{constructor(e){Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],qb.prototype,"algorithm",void 0),Zm([qm({type:oy.Any,optional:!0})],qb.prototype,"parameters",void 0);class zb{constructor(){this.version=0,this.privateKeyAlgorithm=new qb,this.privateKey=new ArrayBuffer(0)}}Zm([qm({type:oy.Integer})],zb.prototype,"version",void 0),Zm([qm({type:qb})],zb.prototype,"privateKeyAlgorithm",void 0),Zm([qm({type:oy.OctetString})],zb.prototype,"privateKey",void 0),Zm([qm({type:oy.Any,optional:!0})],zb.prototype,"attributes",void 0);class Wb{constructor(){this.publicKeyAlgorithm=new qb,this.publicKey=new ArrayBuffer(0)}}Zm([qm({type:qb})],Wb.prototype,"publicKeyAlgorithm",void 0),Zm([qm({type:oy.BitString})],Wb.prototype,"publicKey",void 0);const Jb={fromJSON:e=>Kp.FromBase64Url(e),toJSON:e=>Kp.ToBase64Url(new Uint8Array(e))},Yb={fromASN:e=>{const t=e.valueBlock.valueHex;return new Uint8Array(t)[0]?e.valueBlock.valueHex:e.valueBlock.valueHex.slice(1)},toASN:e=>{const t=new Uint8Array(e)[0]>127?Qp(new Uint8Array([0]).buffer,e):e;return new xy({valueHex:t})}};class Xb{constructor(){this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0)}}Zm([qm({type:oy.Integer,converter:mm})],Xb.prototype,"version",void 0),Zm([qm({type:oy.Integer,converter:Yb}),Ab({name:"n",converter:Jb})],Xb.prototype,"modulus",void 0),Zm([qm({type:oy.Integer,converter:Yb}),Ab({name:"e",converter:Jb})],Xb.prototype,"publicExponent",void 0),Zm([qm({type:oy.Integer,converter:Yb}),Ab({name:"d",converter:Jb})],Xb.prototype,"privateExponent",void 0),Zm([qm({type:oy.Integer,converter:Yb}),Ab({name:"p",converter:Jb})],Xb.prototype,"prime1",void 0),Zm([qm({type:oy.Integer,converter:Yb}),Ab({name:"q",converter:Jb})],Xb.prototype,"prime2",void 0),Zm([qm({type:oy.Integer,converter:Yb}),Ab({name:"dp",converter:Jb})],Xb.prototype,"exponent1",void 0),Zm([qm({type:oy.Integer,converter:Yb}),Ab({name:"dq",converter:Jb})],Xb.prototype,"exponent2",void 0),Zm([qm({type:oy.Integer,converter:Yb}),Ab({name:"qi",converter:Jb})],Xb.prototype,"coefficient",void 0),Zm([qm({type:oy.Any,optional:!0})],Xb.prototype,"otherPrimeInfos",void 0);class Zb{constructor(){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0)}}Zm([qm({type:oy.Integer,converter:Yb}),Ab({name:"n",converter:Jb})],Zb.prototype,"modulus",void 0),Zm([qm({type:oy.Integer,converter:Yb}),Ab({name:"e",converter:Jb})],Zb.prototype,"publicExponent",void 0);let eA=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){let e=new Uint8Array(this.value);if(4!==e[0])throw new Ib("Wrong ECPoint. Current version supports only Uncompressed (0x04) point");e=new Uint8Array(this.value.slice(1));const t=e.length/2;return{x:Kp.ToBase64Url(e.buffer.slice(0,0+t)),y:Kp.ToBase64Url(e.buffer.slice(0+t,0+t+t))}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");if(!("y"in e))throw new Error("y: Missing required property");const t=Kp.FromBase64Url(e.x),r=Kp.FromBase64Url(e.y),s=Qp(new Uint8Array([4]).buffer,t,r);return this.value=new Uint8Array(s).buffer,this}};Zm([qm({type:oy.OctetString})],eA.prototype,"value",void 0),eA=Zm([Gm({type:ny.Choice})],eA);class tA{constructor(){this.version=1,this.privateKey=new ArrayBuffer(0)}fromJSON(e){if(!("d"in e))throw new Error("d: Missing required property");if(this.privateKey=Kp.FromBase64Url(e.d),"x"in e){const t=new eA;t.fromJSON(e);const r=Jm.toASN(t);"valueHex"in r.valueBlock&&(this.publicKey=r.valueBlock.valueHex)}return this}toJSON(){const e={};return e.d=Kp.ToBase64Url(this.privateKey),this.publicKey&&Object.assign(e,new eA(this.publicKey).toJSON()),e}}Zm([qm({type:oy.Integer,converter:mm})],tA.prototype,"version",void 0),Zm([qm({type:oy.OctetString})],tA.prototype,"privateKey",void 0),Zm([qm({context:0,type:oy.Any,optional:!0})],tA.prototype,"parameters",void 0),Zm([qm({context:1,type:oy.BitString,optional:!0})],tA.prototype,"publicKey",void 0);const rA={fromASN:e=>{const t=new Uint8Array(e.valueBlock.valueHex);return 0===t[0]?t.buffer.slice(1):t.buffer},toASN:e=>{const t=new Uint8Array(e);if(t[0]>127){const e=new Uint8Array(t.length+1);return e.set(t,1),new xy({valueHex:e.buffer})}return new xy({valueHex:e})}};var sA=Object.freeze({__proto__:null,AsnIntegerWithoutPaddingConverter:rA});class iA{static decodePoint(e,t){const r=Tp.toUint8Array(e);if(0===r.length||4!==r[0])throw new Error("Only uncompressed point format supported");const s=(r.length-1)/2;if(s!==Math.ceil(t/8))throw new Error("Point does not match field size");return{x:r.slice(1,s+1),y:r.slice(s+1,s+1+s)}}static encodePoint(e,t){const r=Math.ceil(t/8);if(e.x.byteLength!==r||e.y.byteLength!==r)throw new Error("X,Y coordinates don't match point size criteria");const s=Tp.toUint8Array(e.x),i=Tp.toUint8Array(e.y),n=new Uint8Array(2*r+1);return n[0]=4,n.set(s,1),n.set(i,r+1),n}static getSize(e){return Math.ceil(e/8)}static encodeSignature(e,t){const r=this.getSize(t),s=Tp.toUint8Array(e.r),i=Tp.toUint8Array(e.s),n=new Uint8Array(2*r);return n.set(this.padStart(s,r)),n.set(this.padStart(i,r),r),n}static decodeSignature(e,t){const r=this.getSize(t),s=Tp.toUint8Array(e);if(s.length!==2*r)throw new Error("Incorrect size of the signature");const i=s.slice(0,r),n=s.slice(r);return{r:this.trimStart(i),s:this.trimStart(n)}}static trimStart(e){let t=0;for(;t<e.length-1&&0===e[t];)t++;return 0===t?e:e.slice(t,e.length)}static padStart(e,t){if(t===e.length)return e;const r=new Uint8Array(t);return r.set(e,t-e.length),r}}class nA{constructor(){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0)}static fromWebCryptoSignature(e){const t=e.byteLength/2,r=iA.decodeSignature(e,8*t),s=new nA;return s.r=Tp.toArrayBuffer(r.r),s.s=Tp.toArrayBuffer(r.s),s}toWebCryptoSignature(e){if(!e){const t=Math.max(this.r.byteLength,this.s.byteLength);e=t<=32?256:t<=48?384:521}return iA.encodeSignature(this,e).buffer}}Zm([qm({type:oy.Integer,converter:rA})],nA.prototype,"r",void 0),Zm([qm({type:oy.Integer,converter:rA})],nA.prototype,"s",void 0);class oA extends zb{}Zm([qm({context:1,implicit:!0,type:oy.BitString,optional:!0})],oA.prototype,"publicKey",void 0);let aA=class{constructor(){this.value=new ArrayBuffer(0)}fromJSON(e){if(!e.d)throw new Error("d: Missing required property");return this.value=Kp.FromBase64Url(e.d),this}toJSON(){return{d:Kp.ToBase64Url(this.value)}}};Zm([qm({type:oy.OctetString})],aA.prototype,"value",void 0),aA=Zm([Gm({type:ny.Choice})],aA);let cA=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){return{x:Kp.ToBase64Url(this.value)}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");return this.value=Kp.FromBase64Url(e.x),this}};Zm([qm({type:oy.BitString})],cA.prototype,"value",void 0),cA=Zm([Gm({type:ny.Choice})],cA);let lA=class{};Zm([qm({type:oy.OctetString}),Ab({type:ob.String,converter:Jb})],lA.prototype,"d",void 0),lA=Zm([Gm({type:ny.Choice})],lA);const hA="1.2.840.10045.3.1.7",uA="1.3.132.0",dA=`${uA}.34`,fA=`${uA}.35`,pA=`${uA}.10`,gA="1.3.36.3.3.2.8.1.1",yA=`${gA}.1`,mA=`${gA}.2`,bA=`${gA}.3`,AA=`${gA}.4`,IA=`${gA}.5`,vA=`${gA}.6`,wA=`${gA}.7`,SA=`${gA}.8`,EA=`${gA}.9`,CA=`${gA}.10`,kA=`${gA}.11`,xA=`${gA}.12`,_A=`${gA}.13`,BA=`${gA}.14`;var RA=Object.freeze({__proto__:null,AlgorithmIdentifier:qb,get CurvePrivateKey(){return lA},EcDsaSignature:nA,EcPrivateKey:tA,get EcPublicKey(){return eA},get EdPrivateKey(){return aA},get EdPublicKey(){return cA},get ObjectIdentifier(){return Gb},OneAsymmetricKey:oA,PrivateKeyInfo:zb,PublicKeyInfo:Wb,RsaPrivateKey:Xb,RsaPublicKey:Zb,converters:sA,idBrainpoolP160r1:yA,idBrainpoolP160t1:mA,idBrainpoolP192r1:bA,idBrainpoolP192t1:AA,idBrainpoolP224r1:IA,idBrainpoolP224t1:vA,idBrainpoolP256r1:wA,idBrainpoolP256t1:SA,idBrainpoolP320r1:EA,idBrainpoolP320t1:CA,idBrainpoolP384r1:kA,idBrainpoolP384t1:xA,idBrainpoolP512r1:_A,idBrainpoolP512t1:BA,idEd25519:"1.3.101.112",idEd448:"1.3.101.113",idEllipticCurve:uA,idSecp256k1:pA,idSecp256r1:hA,idSecp384r1:dA,idSecp521r1:fA,idVersionOne:gA,idX25519:"1.3.101.110",idX448:"1.3.101.111"});class OA{constructor(){}static register(e){const t=new Gb;t.value=e.id;const r=Xm.serialize(t);this.items.push({...e,raw:r}),this.names.push(e.name)}static find(e){e=e.toUpperCase();for(const t of this.items)if(t.name.toUpperCase()===e||t.id.toUpperCase()===e)return t;return null}static get(e){const t=this.find(e);if(!t)throw new Error(`Unsupported EC named curve '${e}'`);return t}}OA.items=[],OA.names=[],OA.register({name:"P-256",id:hA,size:256}),OA.register({name:"P-384",id:dA,size:384}),OA.register({name:"P-521",id:fA,size:521}),OA.register({name:"K-256",id:pA,size:256}),OA.register({name:"brainpoolP160r1",id:yA,size:160}),OA.register({name:"brainpoolP160t1",id:mA,size:160}),OA.register({name:"brainpoolP192r1",id:bA,size:192}),OA.register({name:"brainpoolP192t1",id:AA,size:192}),OA.register({name:"brainpoolP224r1",id:IA,size:224}),OA.register({name:"brainpoolP224t1",id:vA,size:224}),OA.register({name:"brainpoolP256r1",id:wA,size:256}),OA.register({name:"brainpoolP256t1",id:SA,size:256}),OA.register({name:"brainpoolP320r1",id:EA,size:320}),OA.register({name:"brainpoolP320t1",id:CA,size:320}),OA.register({name:"brainpoolP384r1",id:kA,size:384}),OA.register({name:"brainpoolP384t1",id:xA,size:384}),OA.register({name:"brainpoolP512r1",id:_A,size:512}),OA.register({name:"brainpoolP512t1",id:BA,size:512});class UA extends kb{constructor(){super(...arguments),this.name="X25519",this.usages={privateKey:["deriveKey","deriveBits"],publicKey:[]}}checkAlgorithmParams(e){this.checkRequiredProperty(e,"public")}}class TA extends kb{constructor(){super(...arguments),this.name="Ed25519",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class NA extends kb{constructor(){super(...arguments),this.name="HMAC",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages=["sign","verify"]}getDefaultLength(e){switch(e.toUpperCase()){case"SHA-1":case"SHA-256":case"SHA-384":case"SHA-512":return 512;default:throw new Error(`Unknown algorithm name '${e}'`)}}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),"length"in e){if("number"!=typeof e.length)throw new TypeError("length: Is not a Number");if(e.length<1)throw new RangeError("length: Number is out of range")}}checkImportParams(e){this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms)}}class DA extends kb{constructor(){super(...arguments),this.name="PBKDF2",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages=["deriveBits","deriveKey"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),this.checkRequiredProperty(e,"salt"),!(e.salt instanceof ArrayBuffer||ArrayBuffer.isView(e.salt)))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"iterations"),"number"!=typeof e.iterations)throw new TypeError("iterations: Is not a Number");if(e.iterations<1)throw new TypeError("iterations: Is less than 1")}checkImportKey(e,t,r,s,i,...n){if(super.checkImportKey(e,t,r,s,i,...n),s)throw new SyntaxError("extractable: Must be 'false'")}}class MA extends kb{constructor(){super(...arguments),this.name="HKDF",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages=["deriveKey","deriveBits"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),this.checkRequiredProperty(e,"salt"),!Tp.isBufferSource(e.salt))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"info"),!Tp.isBufferSource(e.info))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'")}checkImportKey(e,t,r,s,i,...n){if(super.checkImportKey(e,t,r,s,i,...n),s)throw new SyntaxError("extractable: Must be 'false'")}}class PA extends kb{constructor(){super(...arguments),this.usages=[],this.defaultLength=0}digest(...e){return e[0]={length:this.defaultLength,...e[0]},super.digest.apply(this,e)}checkDigest(e,t){super.checkDigest(e,t);const r=e.length||0;if("number"!=typeof r)throw new TypeError("length: Is not a Number");if(r<0)throw new TypeError("length: Is negative")}}class LA extends PA{constructor(){super(...arguments),this.name="shake128",this.defaultLength=16}}class HA extends PA{constructor(){super(...arguments),this.name="shake256",this.defaultLength=32}}class KA{get[Symbol.toStringTag](){return"Crypto"}randomUUID(){const e=this.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Kp.ToHex(e).toLowerCase();return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}}class QA{constructor(){this.items={}}get(e){return this.items[e.toLowerCase()]||null}set(e){this.items[e.name.toLowerCase()]=e}removeAt(e){const t=this.get(e.toLowerCase());return t&&delete this.items[e],t}has(e){return!!this.get(e)}get length(){return Object.keys(this.items).length}get algorithms(){const e=[];for(const t in this.items){const r=this.items[t];e.push(r.name)}return e.sort()}}const VA={jwk:["private","public","secret"],pkcs8:["private"],spki:["public"],raw:["secret","public"]},FA=["pkcs8","spki","raw"];class $A{constructor(){this.providers=new QA}static isHashedAlgorithm(e){return!!(e&&"object"==typeof e&&"name"in e&&"hash"in e)}get[Symbol.toStringTag](){return"SubtleCrypto"}async digest(...e){this.checkRequiredArguments(e,2,"digest");const[t,r,...s]=e,i=this.prepareAlgorithm(t),n=Tp.toArrayBuffer(r),o=this.getProvider(i.name);return await o.digest(i,n,...s)}async generateKey(...e){this.checkRequiredArguments(e,3,"generateKey");const[t,r,s,...i]=e,n=this.prepareAlgorithm(t),o=this.getProvider(n.name);return await o.generateKey({...n,name:o.name},r,s,...i)}async sign(...e){this.checkRequiredArguments(e,3,"sign");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=Tp.toArrayBuffer(s),a=this.getProvider(n.name);return await a.sign({...n,name:a.name},r,o,...i)}async verify(...e){this.checkRequiredArguments(e,4,"verify");const[t,r,s,i,...n]=e;this.checkCryptoKey(r);const o=this.prepareAlgorithm(t),a=Tp.toArrayBuffer(i),c=Tp.toArrayBuffer(s),l=this.getProvider(o.name);return await l.verify({...o,name:l.name},r,c,a,...n)}async encrypt(...e){this.checkRequiredArguments(e,3,"encrypt");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=Tp.toArrayBuffer(s),a=this.getProvider(n.name);return await a.encrypt({...n,name:a.name},r,o,{keyUsage:!0},...i)}async decrypt(...e){this.checkRequiredArguments(e,3,"decrypt");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=Tp.toArrayBuffer(s),a=this.getProvider(n.name);return await a.decrypt({...n,name:a.name},r,o,{keyUsage:!0},...i)}async deriveBits(...e){this.checkRequiredArguments(e,3,"deriveBits");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=this.getProvider(n.name);return await o.deriveBits({...n,name:o.name},r,s,{keyUsage:!0},...i)}async deriveKey(...e){this.checkRequiredArguments(e,5,"deriveKey");const[t,r,s,i,n,...o]=e,a=this.prepareAlgorithm(s);this.getProvider(a.name).checkDerivedKeyParams(a);const c=this.prepareAlgorithm(t),l=this.getProvider(c.name);l.checkCryptoKey(r,"deriveKey");const h=await l.deriveBits({...c,name:l.name},r,s.length||512,{keyUsage:!1},...o);return this.importKey("raw",h,s,i,n,...o)}async exportKey(...e){this.checkRequiredArguments(e,2,"exportKey");const[t,r,...s]=e;if(this.checkCryptoKey(r),!VA[t])throw new TypeError("Invalid keyFormat argument");if(!VA[t].includes(r.type))throw new DOMException("The key is not of the expected type");const i=this.getProvider(r.algorithm.name);return await i.exportKey(t,r,...s)}async importKey(...e){this.checkRequiredArguments(e,5,"importKey");const[t,r,s,i,n,...o]=e,a=this.prepareAlgorithm(s),c=this.getProvider(a.name);if("jwk"===t){if("object"!=typeof r||!r.kty)throw new TypeError("Key data must be an object for JWK import")}else{if(!FA.includes(t))throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView or JsonWebKey)'");if(!Tp.isBufferSource(r))throw new TypeError("Key data must be a BufferSource for non-JWK formats")}return c.importKey(t,r,{...a,name:c.name},i,n,...o)}async wrapKey(e,t,r,s,...i){let n=await this.exportKey(e,t,...i);if("jwk"===e){const e=JSON.stringify(n);n=Kp.FromUtf8String(e)}const o=this.prepareAlgorithm(s),a=Tp.toArrayBuffer(n),c=this.getProvider(o.name);return c.encrypt({...o,name:c.name},r,a,{keyUsage:!1},...i)}async unwrapKey(e,t,r,s,i,n,o,...a){const c=this.prepareAlgorithm(s),l=Tp.toArrayBuffer(t),h=this.getProvider(c.name);let u=await h.decrypt({...c,name:h.name},r,l,{keyUsage:!1},...a);if("jwk"===e)try{u=JSON.parse(Kp.ToUtf8String(u))}catch(e){const t=new TypeError("wrappedKey: Is not a JSON");throw t.internal=e,t}return this.importKey(e,u,i,n,o,...a)}checkRequiredArguments(e,t,r){if(e.length<t)throw new TypeError(`Failed to execute '${r}' on 'SubtleCrypto': ${t} arguments required, but only ${e.length} present`)}prepareAlgorithm(e){if("string"==typeof e)return{name:e};if($A.isHashedAlgorithm(e)){const t={...e};return t.hash=this.prepareAlgorithm(e.hash),t}return{...e}}getProvider(e){const t=this.providers.get(e);if(!t)throw new vb("Unrecognized name");return t}checkCryptoKey(e){if(!(e instanceof Vb))throw new TypeError("Key is not of type 'CryptoKey'")}}const jA=t(import.meta.url)("buffer"),GA=t(import.meta.url)("crypto");var qA=o.n(GA);const zA={fromJSON:e=>jA.Buffer.from(Kp.FromBase64Url(e)),toJSON:e=>Kp.ToBase64Url(e)};class WA extends Vb{constructor(){super(...arguments),this.data=jA.Buffer.alloc(0),this.algorithm={name:""},this.extractable=!1,this.type="secret",this.usages=[],this.kty="oct",this.alg=""}}Zm([Ab({name:"ext",type:ob.Boolean,optional:!0})],WA.prototype,"extractable",void 0),Zm([Ab({name:"key_ops",type:ob.String,repeated:!0,optional:!0})],WA.prototype,"usages",void 0),Zm([Ab({type:ob.String})],WA.prototype,"kty",void 0),Zm([Ab({type:ob.String,optional:!0})],WA.prototype,"alg",void 0);class JA extends WA{constructor(){super(...arguments),this.kty="oct",this.type="secret"}}class YA extends WA{}class XA extends JA{get alg(){switch(this.algorithm.name.toUpperCase()){case"AES-CBC":return`A${this.algorithm.length}CBC`;case"AES-CTR":return`A${this.algorithm.length}CTR`;case"AES-GCM":return`A${this.algorithm.length}GCM`;case"AES-KW":return`A${this.algorithm.length}KW`;case"AES-CMAC":return`A${this.algorithm.length}CMAC`;case"AES-ECB":return`A${this.algorithm.length}ECB`;default:throw new vb("Unsupported algorithm name")}}set alg(e){}}Zm([Ab({name:"k",converter:zA})],XA.prototype,"data",void 0);class ZA{static async generateKey(e,t,r){const s=new XA;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=qA().randomBytes(e.length>>3),s}static async exportKey(e,t){if(!(t instanceof XA))throw new Error("key: Is not AesCryptoKey");switch(e.toLowerCase()){case"jwk":return mb.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new Sb("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=bb.fromJSON(t,{targetSchema:XA});break;case"raw":n=new XA,n.data=jA.Buffer.from(t);break;default:throw new Sb("format: Must be 'jwk' or 'raw'")}switch(n.algorithm=r,n.algorithm.length=n.data.length<<3,n.extractable=s,n.usages=i,n.algorithm.length){case 128:case 192:case 256:break;default:throw new Sb("keyData: Is wrong key length")}return n}static async encrypt(e,t,r){switch(e.name.toUpperCase()){case"AES-CBC":return this.encryptAesCBC(e,t,jA.Buffer.from(r));case"AES-CTR":return this.encryptAesCTR(e,t,jA.Buffer.from(r));case"AES-GCM":return this.encryptAesGCM(e,t,jA.Buffer.from(r));case"AES-KW":return this.encryptAesKW(e,t,jA.Buffer.from(r));case"AES-ECB":return this.encryptAesECB(e,t,jA.Buffer.from(r));default:throw new Sb("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof XA))throw new Error("key: Is not AesCryptoKey");switch(e.name.toUpperCase()){case"AES-CBC":return this.decryptAesCBC(e,t,jA.Buffer.from(r));case"AES-CTR":return this.decryptAesCTR(e,t,jA.Buffer.from(r));case"AES-GCM":return this.decryptAesGCM(e,t,jA.Buffer.from(r));case"AES-KW":return this.decryptAesKW(e,t,jA.Buffer.from(r));case"AES-ECB":return this.decryptAesECB(e,t,jA.Buffer.from(r));default:throw new Sb("algorithm: Is not recognized")}}static async encryptAesCBC(e,t,r){const s=qA().createCipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=jA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCBC(e,t,r){const s=qA().createDecipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=jA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesCTR(e,t,r){const s=qA().createCipheriv(`aes-${t.algorithm.length}-ctr`,t.data,jA.Buffer.from(e.counter));let i=s.update(r);return i=jA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCTR(e,t,r){const s=qA().createDecipheriv(`aes-${t.algorithm.length}-ctr`,t.data,new Uint8Array(e.counter));let i=s.update(r);return i=jA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesGCM(e,t,r){const s=qA().createCipheriv(`aes-${t.algorithm.length}-gcm`,t.data,jA.Buffer.from(e.iv),{authTagLength:(e.tagLength||128)>>3});e.additionalData&&s.setAAD(jA.Buffer.from(e.additionalData));let i=s.update(r);return i=jA.Buffer.concat([i,s.final(),s.getAuthTag()]),new Uint8Array(i).buffer}static async decryptAesGCM(e,t,r){const s=(e.tagLength||128)>>3,i=qA().createDecipheriv(`aes-${t.algorithm.length}-gcm`,t.data,new Uint8Array(e.iv),{authTagLength:s}),n=r.slice(0,r.length-s),o=r.slice(r.length-s);e.additionalData&&i.setAAD(jA.Buffer.from(e.additionalData)),i.setAuthTag(o);let a=i.update(n);return a=jA.Buffer.concat([a,i.final()]),new Uint8Array(a).buffer}static async encryptAesKW(e,t,r){const s=qA().createCipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=jA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesKW(e,t,r){const s=qA().createDecipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=jA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesECB(e,t,r){const s=qA().createCipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=jA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesECB(e,t,r){const s=qA().createDecipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=jA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}ZA.AES_KW_IV=jA.Buffer.from("A6A6A6A6A6A6A6A6","hex");const eI=new WeakMap;function tI(e){const t=eI.get(e);if(!t)throw new Sb("Cannot get CryptoKey from secure storage");return t}function rI(e){const t=Vb.create(e.algorithm,e.type,e.extractable,e.usages);return Object.freeze(t),eI.set(t,e),t}class sI extends _b{async onGenerateKey(e,t,r){return rI(await ZA.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return ZA.encrypt(e,tI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return ZA.decrypt(e,tI(t),new Uint8Array(r))}async onExportKey(e,t){return ZA.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await ZA.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(tI(e)instanceof XA))throw new TypeError("key: Is not a AesCryptoKey")}}const iI=jA.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),nI=jA.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,135]),oI=16;function aI(e){const t=jA.Buffer.alloc(e.length),r=e.length-1;for(let s=0;s<r;s++)t[s]=e[s]<<1,128&e[s+1]&&(t[s]+=1);return t[r]=e[r]<<1,t}function cI(e,t){const r=Math.min(e.length,t.length),s=jA.Buffer.alloc(r);for(let i=0;i<r;i++)s[i]=e[i]^t[i];return s}function lI(e,t){const r=qA().createCipheriv("aes"+(e.length<<3),e,iI),s=r.update(t);return r.final(),s}function hI(e,t){const r=jA.Buffer.alloc(oI),s=t*oI,i=s+oI;return e.copy(r,0,s,i),r}class uI extends Bb{async onGenerateKey(e,t,r){return rI(await ZA.generateKey({name:this.name,length:e.length},t,r))}async onSign(e,t,r){const s=function(e,t){const r=function(e){const t=lI(e,iI);let r=aI(t);128&t[0]&&(r=cI(r,nI));let s=aI(r);return 128&r[0]&&(s=cI(s,nI)),{subkey1:r,subkey2:s}}(e);let s,i,n=Math.ceil(t.length/oI);0===n?(n=1,s=!1):s=t.length%oI===0;const o=n-1;i=s?cI(hI(t,o),r.subkey1):cI(function(e,t){const r=jA.Buffer.alloc(oI),s=t*oI,i=e.length;return r.fill(0),e.copy(r,0,s,i),r[i-s]=128,r}(t,o),r.subkey2);let a,c=iI;for(let r=0;r<o;r++)a=cI(c,hI(t,r)),c=lI(e,a);return a=cI(i,c),lI(e,a)}(tI(t).data,jA.Buffer.from(r));return new Uint8Array(s).buffer}async onVerify(e,t,r,s){const i=await this.sign(e,t,s);return 0===jA.Buffer.from(r).compare(jA.Buffer.from(i))}async onExportKey(e,t){return ZA.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await ZA.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(tI(e)instanceof XA))throw new TypeError("key: Is not a AesCryptoKey")}}class dI extends Rb{async onGenerateKey(e,t,r){return rI(await ZA.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return ZA.encrypt(e,tI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return ZA.decrypt(e,tI(t),new Uint8Array(r))}async onExportKey(e,t){return ZA.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await ZA.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(tI(e)instanceof XA))throw new TypeError("key: Is not a AesCryptoKey")}}class fI extends Ub{async onGenerateKey(e,t,r){return rI(await ZA.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return ZA.encrypt(e,tI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return ZA.decrypt(e,tI(t),new Uint8Array(r))}async onExportKey(e,t){return ZA.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await ZA.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(tI(e)instanceof XA))throw new TypeError("key: Is not a AesCryptoKey")}}class pI extends Tb{async onGenerateKey(e,t,r){return rI(await ZA.generateKey({name:this.name,length:e.length},t,r))}async onExportKey(e,t){return ZA.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await ZA.importKey(e,t,{name:r.name},s,i))}async onEncrypt(e,t,r){return ZA.encrypt(e,tI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return ZA.decrypt(e,tI(t),new Uint8Array(r))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(tI(e)instanceof XA))throw new TypeError("key: Is not a AesCryptoKey")}}class gI extends Ob{async onGenerateKey(e,t,r){return rI(await ZA.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return ZA.encrypt(e,tI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return ZA.decrypt(e,tI(t),new Uint8Array(r))}async onExportKey(e,t){return ZA.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await ZA.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(tI(e)instanceof XA))throw new TypeError("key: Is not a AesCryptoKey")}}class yI extends JA{get alg(){switch(this.algorithm.name.toUpperCase()){case"DES-CBC":return"DES-CBC";case"DES-EDE3-CBC":return"3DES-CBC";default:throw new vb("Unsupported algorithm name")}}set alg(e){}}Zm([Ab({name:"k",converter:zA})],yI.prototype,"data",void 0);class mI{static async generateKey(e,t,r){const s=new yI;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=qA().randomBytes(e.length>>3),s}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return mb.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new Sb("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=bb.fromJSON(t,{targetSchema:yI});break;case"raw":n=new yI,n.data=jA.Buffer.from(t);break;default:throw new Sb("format: Must be 'jwk' or 'raw'")}return n.algorithm=r,n.extractable=s,n.usages=i,n}static async encrypt(e,t,r){switch(e.name.toUpperCase()){case"DES-CBC":return this.encryptDesCBC(e,t,jA.Buffer.from(r));case"DES-EDE3-CBC":return this.encryptDesEDE3CBC(e,t,jA.Buffer.from(r));default:throw new Sb("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof yI))throw new Error("key: Is not DesCryptoKey");switch(e.name.toUpperCase()){case"DES-CBC":return this.decryptDesCBC(e,t,jA.Buffer.from(r));case"DES-EDE3-CBC":return this.decryptDesEDE3CBC(e,t,jA.Buffer.from(r));default:throw new Sb("algorithm: Is not recognized")}}static async encryptDesCBC(e,t,r){const s=qA().createCipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=jA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesCBC(e,t,r){const s=qA().createDecipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=jA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptDesEDE3CBC(e,t,r){const s=qA().createCipheriv("des-ede3-cbc",t.data,jA.Buffer.from(e.iv));let i=s.update(r);return i=jA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesEDE3CBC(e,t,r){const s=qA().createDecipheriv("des-ede3-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=jA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}class bI extends Nb{constructor(){super(...arguments),this.keySizeBits=64,this.ivSize=8,this.name="DES-CBC"}async onGenerateKey(e,t,r){return rI(await mI.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return mI.encrypt(e,tI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return mI.decrypt(e,tI(t),new Uint8Array(r))}async onExportKey(e,t){return mI.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){const n=await mI.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new Sb("keyData: Wrong key size");return rI(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(tI(e)instanceof yI))throw new TypeError("key: Is not a DesCryptoKey")}}class AI extends Nb{constructor(){super(...arguments),this.keySizeBits=192,this.ivSize=8,this.name="DES-EDE3-CBC"}async onGenerateKey(e,t,r){return rI(await mI.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return mI.encrypt(e,tI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return mI.decrypt(e,tI(t),new Uint8Array(r))}async onExportKey(e,t){return mI.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){const n=await mI.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new Sb("keyData: Wrong key size");return rI(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(tI(e)instanceof yI))throw new TypeError("key: Is not a DesCryptoKey")}}function II(e){switch(e.name.toUpperCase()){case"RSA-OAEP":{const t=/(\d+)$/.exec(e.hash.name)[1];return"RSA-OAEP"+("1"!==t?`-${t}`:"")}case"RSASSA-PKCS1-V1_5":return`RS${/(\d+)$/.exec(e.hash.name)[1]}`;case"RSA-PSS":return`PS${/(\d+)$/.exec(e.hash.name)[1]}`;case"RSA-PKCS1":return"RS1";default:throw new Sb("algorithm: Is not recognized")}}class vI extends YA{constructor(){super(...arguments),this.type="private"}getKey(){const e=Wm.parse(this.data,RA.PrivateKeyInfo);return Wm.parse(e.privateKey,RA.RsaPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:II(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,mb.toJSON(e))}fromJSON(e){const t=bb.fromJSON(e,{targetSchema:RA.RsaPrivateKey}),r=new RA.PrivateKeyInfo;r.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.privateKeyAlgorithm.parameters=null,r.privateKey=Jm.serialize(t),this.data=jA.Buffer.from(Jm.serialize(r))}}class wI extends YA{constructor(){super(...arguments),this.type="public"}getKey(){const e=Wm.parse(this.data,RA.PublicKeyInfo);return Wm.parse(e.publicKey,RA.RsaPublicKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:II(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,mb.toJSON(e))}fromJSON(e){const t=bb.fromJSON(e,{targetSchema:RA.RsaPublicKey}),r=new RA.PublicKeyInfo;r.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.publicKeyAlgorithm.parameters=null,r.publicKey=Jm.serialize(t),this.data=jA.Buffer.from(Jm.serialize(r))}}class SI{static async generateKey(e,t,r){const s=new vI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new wI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=jA.Buffer.concat([jA.Buffer.alloc(4-e.publicExponent.byteLength,0),jA.Buffer.from(e.publicExponent)]).readInt32BE(0),o=qA().generateKeyPairSync("rsa",{modulusLength:e.modulusLength,publicExponent:n,publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=o.privateKey,i.data=o.publicKey,{privateKey:s,publicKey:i}}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return mb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;default:throw new Sb("format: Must be 'jwk', 'pkcs8' or 'spki'")}}static async importKey(e,t,r,s,i){switch(e.toLowerCase()){case"jwk":if(t.d){const e=bb.fromJSON(t,{targetSchema:RA.RsaPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=bb.fromJSON(t,{targetSchema:RA.RsaPublicKey});return this.importPublicKey(e,r,s,i)}case"spki":{const e=Wm.parse(new Uint8Array(t),RA.PublicKeyInfo),n=Wm.parse(e.publicKey,RA.RsaPublicKey);return this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=Wm.parse(new Uint8Array(t),RA.PrivateKeyInfo),n=Wm.parse(e.privateKey,RA.RsaPrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new Sb("format: Must be 'jwk', 'pkcs8' or 'spki'")}}static async sign(e,t,r){switch(e.name.toUpperCase()){case"RSA-PSS":case"RSASSA-PKCS1-V1_5":return this.signRsa(e,t,r);default:throw new Sb("algorithm: Is not recognized")}}static async verify(e,t,r,s){switch(e.name.toUpperCase()){case"RSA-PSS":case"RSASSA-PKCS1-V1_5":return this.verifySSA(e,t,s,r);default:throw new Sb("algorithm: Is not recognized")}}static async encrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.encryptOAEP(e,t,r);throw new Sb("algorithm: Is not recognized")}static async decrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.decryptOAEP(e,t,r);throw new Sb("algorithm: Is not recognized")}static importPrivateKey(e,t,r,s){const i=new RA.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.privateKeyAlgorithm.parameters=null,i.privateKey=Jm.serialize(e);const n=new vI;return n.data=jA.Buffer.from(Jm.serialize(i)),n.algorithm=Object.assign({},t),n.algorithm.publicExponent=new Uint8Array(e.publicExponent),n.algorithm.modulusLength=e.modulus.byteLength<<3,n.extractable=r,n.usages=s,n}static importPublicKey(e,t,r,s){const i=new RA.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.publicKeyAlgorithm.parameters=null,i.publicKey=Jm.serialize(e);const n=new wI;return n.data=jA.Buffer.from(Jm.serialize(i)),n.algorithm=Object.assign({},t),n.algorithm.publicExponent=new Uint8Array(e.publicExponent),n.algorithm.modulusLength=e.modulus.byteLength<<3,n.extractable=r,n.usages=s,n}static getCryptoAlgorithm(e){switch(e.hash.name.toUpperCase()){case"SHA-1":return"RSA-SHA1";case"SHA-256":return"RSA-SHA256";case"SHA-384":return"RSA-SHA384";case"SHA-512":return"RSA-SHA512";case"SHA3-256":return"RSA-SHA3-256";case"SHA3-384":return"RSA-SHA3-384";case"SHA3-512":return"RSA-SHA3-512";default:throw new Sb("algorithm.hash: Is not recognized")}}static signRsa(e,t,r){const s=this.getCryptoAlgorithm(t.algorithm),i=qA().createSign(s);i.update(jA.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem};"RSA-PSS"===e.name.toUpperCase()&&(n.padding=qA().constants.RSA_PKCS1_PSS_PADDING,n.saltLength=e.saltLength);const o=i.sign(n);return new Uint8Array(o).buffer}static verifySSA(e,t,r,s){const i=this.getCryptoAlgorithm(t.algorithm),n=qA().createVerify(i);n.update(jA.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const o={key:t.pem};return"RSA-PSS"===e.name.toUpperCase()&&(o.padding=qA().constants.RSA_PKCS1_PSS_PADDING,o.saltLength=e.saltLength),n.verify(o,s)}static encryptOAEP(e,t,r){const s={key:`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`,padding:qA().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(qA().publicEncrypt(s,r)).buffer}static decryptOAEP(e,t,r){const s={key:`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`,padding:qA().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(qA().privateDecrypt(s,r)).buffer}}SI.publicKeyUsages=["verify","encrypt","wrapKey"],SI.privateKeyUsages=["sign","decrypt","unwrapKey"];class EI extends Mb{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await SI.generateKey({...e,name:this.name},t,r);return{privateKey:rI(s.privateKey),publicKey:rI(s.publicKey)}}async onSign(e,t,r){return SI.sign(e,tI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return SI.verify(e,tI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return SI.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await SI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=tI(e);if(!(r instanceof vI||r instanceof wI))throw new TypeError("key: Is not RSA CryptoKey")}}class CI extends Pb{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await SI.generateKey({...e,name:this.name},t,r);return{privateKey:rI(s.privateKey),publicKey:rI(s.publicKey)}}async onSign(e,t,r){return SI.sign(e,tI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return SI.verify(e,tI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return SI.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await SI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=tI(e);if(!(r instanceof vI||r instanceof wI))throw new TypeError("key: Is not RSA CryptoKey")}}class kI{static size(e){switch(e.name.toUpperCase()){case"SHA-1":return 160;case"SHA-256":case"SHA3-256":return 256;case"SHA-384":case"SHA3-384":return 384;case"SHA-512":case"SHA3-512":return 512;default:throw new Error("Unrecognized name")}}static getAlgorithmName(e){switch(e.name.toUpperCase()){case"SHA-1":return"sha1";case"SHA-256":return"sha256";case"SHA-384":return"sha384";case"SHA-512":return"sha512";case"SHA3-256":return"sha3-256";case"SHA3-384":return"sha3-384";case"SHA3-512":return"sha3-512";default:throw new Error("Unrecognized name")}}static digest(e,t){const r=this.getAlgorithmName(e),s=qA().createHash(r).update(jA.Buffer.from(t)).digest();return new Uint8Array(s).buffer}}class xI extends Lb{async onGenerateKey(e,t,r){const s=await SI.generateKey({...e,name:this.name},t,r);return{privateKey:rI(s.privateKey),publicKey:rI(s.publicKey)}}async onEncrypt(e,t,r){const s=tI(t),i=new Uint8Array(r),n=Math.ceil(s.algorithm.modulusLength>>3),o=kI.size(s.algorithm.hash)>>3,a=i.byteLength,c=n-a-2*o-2;if(a>n-2*o-2)throw new Error("Data too large");const l=new Uint8Array(n),h=l.subarray(1,o+1),u=l.subarray(o+1);u.set(i,o+c+1);const d=qA().createHash(s.algorithm.hash.name.replace("-","")).update(Tp.toUint8Array(e.label||new Uint8Array(0))).digest();u.set(d,0),u[o+c]=1,qA().randomFillSync(h);const f=this.mgf1(s.algorithm.hash,h,u.length);for(let e=0;e<u.length;e++)u[e]^=f[e];const p=this.mgf1(s.algorithm.hash,u,h.length);for(let e=0;e<h.length;e++)h[e]^=p[e];s.pem||(s.pem=`-----BEGIN PUBLIC KEY-----\n${s.data.toString("base64")}\n-----END PUBLIC KEY-----`);const g=qA().publicEncrypt({key:s.pem,padding:qA().constants.RSA_NO_PADDING},jA.Buffer.from(l));return new Uint8Array(g).buffer}async onDecrypt(e,t,r){const s=tI(t),i=Math.ceil(s.algorithm.modulusLength>>3),n=kI.size(s.algorithm.hash)>>3;if(r.byteLength!==i)throw new Error("Bad data");s.pem||(s.pem=`-----BEGIN PRIVATE KEY-----\n${s.data.toString("base64")}\n-----END PRIVATE KEY-----`);let o=qA().privateDecrypt({key:s.pem,padding:qA().constants.RSA_NO_PADDING},jA.Buffer.from(r));const a=o[0],c=o.subarray(1,n+1),l=o.subarray(n+1);if(0!==a)throw new Error("Decryption failed");const h=this.mgf1(s.algorithm.hash,l,c.length);for(let e=0;e<c.length;e++)c[e]^=h[e];const u=this.mgf1(s.algorithm.hash,c,l.length);for(let e=0;e<l.length;e++)l[e]^=u[e];const d=qA().createHash(s.algorithm.hash.name.replace("-","")).update(Tp.toUint8Array(e.label||new Uint8Array(0))).digest();for(let e=0;e<n;e++)if(d[e]!==l[e])throw new Error("Decryption failed");let f=n;for(;f<l.length;f++){const e=l[f];if(1===e)break;if(0!==e)throw new Error("Decryption failed")}if(f===l.length)throw new Error("Decryption failed");return o=l.subarray(f+1),new Uint8Array(o).buffer}async onExportKey(e,t){return SI.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await SI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=tI(e);if(!(r instanceof vI||r instanceof wI))throw new TypeError("key: Is not RSA CryptoKey")}mgf1(e,t,r=0){const s=kI.size(e)>>3,i=new Uint8Array(r),n=new Uint8Array(4),o=Math.ceil(r/s);for(let r=0;r<o;r++){n[0]=r>>>24,n[1]=r>>>16&255,n[2]=r>>>8&255,n[3]=255&r;const o=i.subarray(r*s);let a=qA().createHash(e.name.replace("-","")).update(t).update(n).digest();a.length>o.length&&(a=a.subarray(0,o.length)),o.set(a)}return i}}class _I extends kb{constructor(){super(...arguments),this.name="RSAES-PKCS1-v1_5",this.usages={publicKey:["encrypt","wrapKey"],privateKey:["decrypt","unwrapKey"]}}async onGenerateKey(e,t,r){const s=await SI.generateKey({...e,name:this.name},t,r);return{privateKey:rI(s.privateKey),publicKey:rI(s.publicKey)}}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"publicExponent"),!(e.publicExponent&&e.publicExponent instanceof Uint8Array))throw new TypeError("publicExponent: Missing or not a Uint8Array");const t=Kp.ToBase64(e.publicExponent);if("Aw=="!==t&&"AQAB"!==t)throw new TypeError("publicExponent: Must be [3] or [1,0,1]");switch(this.checkRequiredProperty(e,"modulusLength"),e.modulusLength){case 1024:case 2048:case 4096:break;default:throw new TypeError("modulusLength: Must be 1024, 2048, or 4096")}}async onEncrypt(e,t,r){const s=this.toCryptoOptions(t),i=qA().publicEncrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onDecrypt(e,t,r){const s=this.toCryptoOptions(t),i=qA().privateDecrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onExportKey(e,t){return SI.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await SI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=tI(e);if(!(r instanceof vI||r instanceof wI))throw new TypeError("key: Is not RSA CryptoKey")}toCryptoOptions(e){const t=e.type.toUpperCase();return{key:`-----BEGIN ${t} KEY-----\n${tI(e).data.toString("base64")}\n-----END ${t} KEY-----`,padding:qA().constants.RSA_PKCS1_PADDING}}}const BI={"1.2.840.10045.3.1.7":"P-256","P-256":"1.2.840.10045.3.1.7","1.3.132.0.34":"P-384","P-384":"1.3.132.0.34","1.3.132.0.35":"P-521","P-521":"1.3.132.0.35","1.3.132.0.10":"K-256","K-256":"1.3.132.0.10",brainpoolP160r1:"1.3.36.3.3.2.8.1.1.1","1.3.36.3.3.2.8.1.1.1":"brainpoolP160r1",brainpoolP160t1:"1.3.36.3.3.2.8.1.1.2","1.3.36.3.3.2.8.1.1.2":"brainpoolP160t1",brainpoolP192r1:"1.3.36.3.3.2.8.1.1.3","1.3.36.3.3.2.8.1.1.3":"brainpoolP192r1",brainpoolP192t1:"1.3.36.3.3.2.8.1.1.4","1.3.36.3.3.2.8.1.1.4":"brainpoolP192t1",brainpoolP224r1:"1.3.36.3.3.2.8.1.1.5","1.3.36.3.3.2.8.1.1.5":"brainpoolP224r1",brainpoolP224t1:"1.3.36.3.3.2.8.1.1.6","1.3.36.3.3.2.8.1.1.6":"brainpoolP224t1",brainpoolP256r1:"1.3.36.3.3.2.8.1.1.7","1.3.36.3.3.2.8.1.1.7":"brainpoolP256r1",brainpoolP256t1:"1.3.36.3.3.2.8.1.1.8","1.3.36.3.3.2.8.1.1.8":"brainpoolP256t1",brainpoolP320r1:"1.3.36.3.3.2.8.1.1.9","1.3.36.3.3.2.8.1.1.9":"brainpoolP320r1",brainpoolP320t1:"1.3.36.3.3.2.8.1.1.10","1.3.36.3.3.2.8.1.1.10":"brainpoolP320t1",brainpoolP384r1:"1.3.36.3.3.2.8.1.1.11","1.3.36.3.3.2.8.1.1.11":"brainpoolP384r1",brainpoolP384t1:"1.3.36.3.3.2.8.1.1.12","1.3.36.3.3.2.8.1.1.12":"brainpoolP384t1",brainpoolP512r1:"1.3.36.3.3.2.8.1.1.13","1.3.36.3.3.2.8.1.1.13":"brainpoolP512r1",brainpoolP512t1:"1.3.36.3.3.2.8.1.1.14","1.3.36.3.3.2.8.1.1.14":"brainpoolP512t1"};function RI(e){const t=BI[e];if(!t)throw new Sb(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class OI extends YA{constructor(){super(...arguments),this.type="private"}getKey(){const e=Wm.parse(this.data,RA.PrivateKeyInfo);return Wm.parse(e.privateKey,RA.EcPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,mb.toJSON(e))}fromJSON(e){if(!e.crv)throw new Sb("Cannot get named curve from JWK. Property 'crv' is required");const t=new RA.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",t.privateKeyAlgorithm.parameters=Jm.serialize(new RA.ObjectIdentifier(RI(e.crv)));const r=bb.fromJSON(e,{targetSchema:RA.EcPrivateKey});return t.privateKey=Jm.serialize(r),this.data=jA.Buffer.from(Jm.serialize(t)),this}}class UI extends YA{constructor(){super(...arguments),this.type="public"}getKey(){const e=Wm.parse(this.data,RA.PublicKeyInfo);return new RA.EcPublicKey(e.publicKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,mb.toJSON(e))}fromJSON(e){if(!e.crv)throw new Sb("Cannot get named curve from JWK. Property 'crv' is required");const t=bb.fromJSON(e,{targetSchema:RA.EcPublicKey}),r=new RA.PublicKeyInfo;return r.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1",r.publicKeyAlgorithm.parameters=Jm.serialize(new RA.ObjectIdentifier(RI(e.crv))),r.publicKey=Jm.toASN(t).valueHex,this.data=jA.Buffer.from(Jm.serialize(r)),this}}class TI extends kb{constructor(){super(...arguments),this.name="SHA-1",this.usages=[]}async onDigest(e,t){return kI.digest(e,t)}}class NI extends kb{constructor(){super(...arguments),this.name="SHA-256",this.usages=[]}async onDigest(e,t){return kI.digest(e,t)}}class DI extends kb{constructor(){super(...arguments),this.name="SHA-384",this.usages=[]}async onDigest(e,t){return kI.digest(e,t)}}class MI extends kb{constructor(){super(...arguments),this.name="SHA-512",this.usages=[]}async onDigest(e,t){return kI.digest(e,t)}}class PI extends kb{constructor(){super(...arguments),this.name="SHA3-256",this.usages=[]}async onDigest(e,t){return kI.digest(e,t)}}class LI extends kb{constructor(){super(...arguments),this.name="SHA3-384",this.usages=[]}async onDigest(e,t){return kI.digest(e,t)}}class HI extends kb{constructor(){super(...arguments),this.name="SHA3-512",this.usages=[]}async onDigest(e,t){return kI.digest(e,t)}}class KI{static async generateKey(e,t,r){const s=new OI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new UI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=qA().generateKeyPairSync("ec",{namedCurve:this.getOpenSSLNamedCurve(e.namedCurve),publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=n.privateKey,i.data=n.publicKey,{privateKey:s,publicKey:i}}static async sign(e,t,r){const s=kI.getAlgorithmName(e.hash),i=qA().createSign(s);i.update(jA.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem},o=i.sign(n),a=Wm.parse(o,RA.EcDsaSignature);return iA.encodeSignature(a,OA.get(t.algorithm.namedCurve).size).buffer}static async verify(e,t,r,s){const i=kI.getAlgorithmName(e.hash),n=qA().createVerify(i);n.update(jA.Buffer.from(s)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const o={key:t.pem},a=new RA.EcDsaSignature,c=OA.get(t.algorithm.namedCurve),l=iA.decodeSignature(r,c.size);a.r=Tp.toArrayBuffer(l.r),a.s=Tp.toArrayBuffer(l.s);const h=jA.Buffer.from(Jm.serialize(a));return n.verify(o,h)}static async deriveBits(e,t,r){const s=this.getOpenSSLNamedCurve(t.algorithm.namedCurve),i=qA().createECDH(s),n=Wm.parse(t.data,RA.PrivateKeyInfo),o=Wm.parse(n.privateKey,RA.EcPrivateKey);i.setPrivateKey(jA.Buffer.from(o.privateKey));const a=Wm.parse(e.public.data,RA.PublicKeyInfo),c=i.computeSecret(jA.Buffer.from(a.publicKey));return null===r?c:new Uint8Array(c).buffer.slice(0,r>>3)}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return mb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return Wm.parse(t.data,RA.PublicKeyInfo).publicKey;default:throw new Sb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'")}}static async importKey(e,t,r,s,i){switch(e.toLowerCase()){case"jwk":if(t.d){const e=bb.fromJSON(t,{targetSchema:RA.EcPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=bb.fromJSON(t,{targetSchema:RA.EcPublicKey});return this.importPublicKey(e,r,s,i)}case"raw":{const e=new RA.EcPublicKey(t);return this.importPublicKey(e,r,s,i)}case"spki":{const e=Wm.parse(new Uint8Array(t),RA.PublicKeyInfo),n=new RA.EcPublicKey(e.publicKey);return this.assertKeyParameters(e.publicKeyAlgorithm.parameters,r.namedCurve),this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=Wm.parse(new Uint8Array(t),RA.PrivateKeyInfo),n=Wm.parse(e.privateKey,RA.EcPrivateKey);return this.assertKeyParameters(e.privateKeyAlgorithm.parameters,r.namedCurve),this.importPrivateKey(n,r,s,i)}default:throw new Sb("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static assertKeyParameters(e,t){if(!e)throw new Ib("Key info doesn't have required parameters");let r="";try{r=Wm.parse(e,RA.ObjectIdentifier).value}catch(e){throw new Ib("Cannot read key info parameters")}if(RI(t)!==r)throw new Ib("Key info parameter doesn't match to named curve")}static async importPrivateKey(e,t,r,s){const i=new RA.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",i.privateKeyAlgorithm.parameters=Jm.serialize(new RA.ObjectIdentifier(RI(t.namedCurve))),i.privateKey=Jm.serialize(e);const n=new OI;return n.data=jA.Buffer.from(Jm.serialize(i)),n.algorithm=Object.assign({},t),n.extractable=r,n.usages=s,n}static async importPublicKey(e,t,r,s){const i=new RA.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1";const n=RI(t.namedCurve);i.publicKeyAlgorithm.parameters=Jm.serialize(new RA.ObjectIdentifier(n)),i.publicKey=e.value;const o=new UI;return o.data=jA.Buffer.from(Jm.serialize(i)),o.algorithm=Object.assign({},t),o.extractable=r,o.usages=s,o}static getOpenSSLNamedCurve(e){switch(e.toUpperCase()){case"P-256":return"prime256v1";case"K-256":return"secp256k1";case"P-384":return"secp384r1";case"P-521":return"secp521r1";default:return e}}}KI.publicKeyUsages=["verify"],KI.privateKeyUsages=["sign","deriveKey","deriveBits"];class QI extends Kb{constructor(){super(...arguments),this.namedCurves=OA.names,this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await KI.generateKey({...e,name:this.name},t,r);return{privateKey:rI(s.privateKey),publicKey:rI(s.publicKey)}}async onSign(e,t,r){return KI.sign(e,tI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return KI.verify(e,tI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return KI.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await KI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=tI(e);if(!(r instanceof OI||r instanceof UI))throw new TypeError("key: Is not EC CryptoKey")}}class VI extends Fb{constructor(){super(...arguments),this.namedCurves=OA.names}async onGenerateKey(e,t,r){const s=await KI.generateKey({...e,name:this.name},t,r);return{privateKey:rI(s.privateKey),publicKey:rI(s.publicKey)}}async onExportKey(e,t){return KI.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await KI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=tI(e);if(!(r instanceof OI||r instanceof UI))throw new TypeError("key: Is not EC CryptoKey")}async onDeriveBits(e,t,r){return await KI.deriveBits({...e,public:tI(e.public)},tI(t),r)}}const FI={[RA.idEd448]:"Ed448",ed448:RA.idEd448,[RA.idX448]:"X448",x448:RA.idX448,[RA.idEd25519]:"Ed25519",ed25519:RA.idEd25519,[RA.idX25519]:"X25519",x25519:RA.idX25519};function $I(e){const t=FI[e.toLowerCase()];if(!t)throw new Sb(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class jI extends YA{constructor(){super(...arguments),this.type="private"}getKey(){const e=Wm.parse(this.data,RA.PrivateKeyInfo);return Wm.parse(e.privateKey,RA.CurvePrivateKey)}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,mb.toJSON(e))}fromJSON(e){if(!e.crv)throw new Sb("Cannot get named curve from JWK. Property 'crv' is required");const t=new RA.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm=$I(e.crv);const r=bb.fromJSON(e,{targetSchema:RA.CurvePrivateKey});return t.privateKey=Jm.serialize(r),this.data=jA.Buffer.from(Jm.serialize(t)),this}}class GI extends YA{constructor(){super(...arguments),this.type="public"}getKey(){return Wm.parse(this.data,RA.PublicKeyInfo).publicKey}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,{x:Kp.ToBase64Url(e)})}fromJSON(e){if(!e.crv)throw new Sb("Cannot get named curve from JWK. Property 'crv' is required");if(!e.x)throw new Sb("Cannot get property from JWK. Property 'x' is required");const t=new RA.PublicKeyInfo;return t.publicKeyAlgorithm.algorithm=$I(e.crv),t.publicKey=Kp.FromBase64Url(e.x),this.data=jA.Buffer.from(Jm.serialize(t)),this}}class qI{static async generateKey(e,t,r){const s=new jI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new GI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=e.namedCurve.toLowerCase(),o=qA().generateKeyPairSync(n,{publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=o.privateKey,i.data=o.publicKey,{privateKey:s,publicKey:i}}static async sign(e,t,r){t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const s={key:t.pem},i=qA().sign(null,jA.Buffer.from(r),s);return Tp.toArrayBuffer(i)}static async verify(e,t,r,s){t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const i={key:t.pem};return qA().verify(null,jA.Buffer.from(s),i,jA.Buffer.from(r))}static async deriveBits(e,t,r){const s=qA().createPublicKey({key:e.public.data,format:"der",type:"spki"}),i=qA().createPrivateKey({key:t.data,format:"der",type:"pkcs8"}),n=qA().diffieHellman({publicKey:s,privateKey:i});return new Uint8Array(n).buffer.slice(0,r>>3)}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return mb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return Wm.parse(t.data,RA.PublicKeyInfo).publicKey;default:throw new Sb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'")}}static async importKey(e,t,r,s,i){switch(e.toLowerCase()){case"jwk":{const e=t;if(e.d){const e=bb.fromJSON(t,{targetSchema:RA.CurvePrivateKey});return this.importPrivateKey(e,r,s,i)}if(!e.x)throw new TypeError("keyData: Cannot get required 'x' filed");return this.importPublicKey(Kp.FromBase64Url(e.x),r,s,i)}case"raw":return this.importPublicKey(t,r,s,i);case"spki":{const e=Wm.parse(new Uint8Array(t),RA.PublicKeyInfo);return this.importPublicKey(e.publicKey,r,s,i)}case"pkcs8":{const e=Wm.parse(new Uint8Array(t),RA.PrivateKeyInfo),n=Wm.parse(e.privateKey,RA.CurvePrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new Sb("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static importPrivateKey(e,t,r,s){const i=new jI;return i.fromJSON({crv:t.namedCurve,d:Kp.ToBase64Url(e.d)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}static async importPublicKey(e,t,r,s){const i=new GI;return i.fromJSON({crv:t.namedCurve,x:Kp.ToBase64Url(e)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}}qI.publicKeyUsages=["verify"],qI.privateKeyUsages=["sign","deriveKey","deriveBits"];class zI extends jb{async onGenerateKey(e,t,r){const s=await qI.generateKey({name:this.name,namedCurve:e.namedCurve.replace(/^ed/i,"Ed")},t,r);return{privateKey:rI(s.privateKey),publicKey:rI(s.publicKey)}}async onSign(e,t,r){return qI.sign(e,tI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return qI.verify(e,tI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return qI.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await qI.importKey(e,t,{...r,name:this.name},s,i))}}class WI extends $b{async onGenerateKey(e,t,r){const s=await qI.generateKey({name:this.name,namedCurve:e.namedCurve.toUpperCase()},t,r);return{privateKey:rI(s.privateKey),publicKey:rI(s.publicKey)}}async onDeriveBits(e,t,r){return await qI.deriveBits({...e,public:tI(e.public)},tI(t),r)}async onExportKey(e,t){return qI.exportKey(e,tI(t))}async onImportKey(e,t,r,s,i){return rI(await qI.importKey(e,t,{...r,name:this.name},s,i))}}class JI extends WA{constructor(e,t,r,s){super(),this.algorithm=e,this.extractable=t,this.usages=r,this.data=Buffer.from(s)}toJWK(){return{kty:"OKP",crv:this.algorithm.name,key_ops:this.usages,ext:this.extractable}}}class YI extends JI{constructor(){super(...arguments),this.type="private"}toJWK(){const e=qA().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"}),t=Cb.toUint8Array(this.data.toString()),r=Xm.parse(t,RA.PrivateKeyInfo),s=Xm.parse(r.privateKey,RA.EdPrivateKey).value;return{...super.toJWK(),...e,d:Buffer.from(new Uint8Array(s)).toString("base64url")}}}class XI extends JI{constructor(){super(...arguments),this.type="public"}toJWK(){const e=qA().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"});return{...super.toJWK(),...e}}}class ZI{static async generateKey(e,t,r){const s=e.name.toLowerCase(),i=qA().generateKeyPairSync(s,{publicKeyEncoding:{format:"pem",type:"spki"},privateKeyEncoding:{format:"pem",type:"pkcs8"}}),n={name:"ed25519"===s?"Ed25519":"X25519"},o=r.filter(e=>this.privateKeyUsages.includes(e)),a=r.filter(e=>this.publicKeyUsages.includes(e));return{privateKey:new YI(n,t,o,i.privateKey),publicKey:new XI(n,!0,a,i.publicKey)}}static async sign(e,t,r){const s=qA().sign(null,Buffer.from(r),t.data);return Tp.toArrayBuffer(s)}static async verify(e,t,r,s){return qA().verify(null,Buffer.from(s),t.data,r)}static async exportKey(e,t){switch(e){case"jwk":return t.toJWK();case"pkcs8":case"spki":return Cb.toArrayBuffer(t.data.toString());case"raw":{const e=t.toJWK();return Kp.FromBase64Url(e.x)}default:return Promise.reject(new Sb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}static async importKey(e,t,r,s,i){switch(e){case"jwk":{const e=t;if(e.d){const t=new RA.EdPrivateKey;t.value=Tp.toArrayBuffer(Buffer.from(e.d,"base64url"));const n=new RA.PrivateKeyInfo;n.privateKeyAlgorithm.algorithm="ed25519"===r.name.toLowerCase()?RA.idEd25519:RA.idX25519,n.privateKey=Xm.serialize(t);const o=Xm.serialize(n),a=Cb.fromBufferSource(o,"PRIVATE KEY");return new YI(r,s,i,a)}if(e.x){const t=qA().createPublicKey({format:"jwk",key:e}).export({format:"pem",type:"spki"});return new XI(r,s,i,t)}throw new Sb("keyData: Cannot import JWK. 'd' or 'x' must be presented")}case"pkcs8":{const e=Cb.fromBufferSource(t,"PRIVATE KEY");return new YI(r,s,i,e)}case"spki":{const e=Cb.fromBufferSource(t,"PUBLIC KEY");return new XI(r,s,i,e)}case"raw":{const e=t,n=qA().createPublicKey({format:"jwk",key:{kty:"OKP",crv:"ed25519"===r.name.toLowerCase()?"Ed25519":"X25519",x:Kp.ToBase64Url(e)}}).export({format:"pem",type:"spki"});return new XI(r,s,i,n)}default:return Promise.reject(new Sb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}}ZI.privateKeyUsages=["sign","deriveBits","deriveKey"],ZI.publicKeyUsages=["verify"];class ev extends TA{async onGenerateKey(e,t,r){const s=await ZI.generateKey(e,t,r);return{privateKey:rI(s.privateKey),publicKey:rI(s.publicKey)}}async onSign(e,t,r){const s=tI(t);return ZI.sign(e,s,new Uint8Array(r))}onVerify(e,t,r,s){const i=tI(t);return ZI.verify(e,i,new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){const r=tI(t);return ZI.exportKey(e,r)}async onImportKey(e,t,r,s,i){return rI(await ZI.importKey(e,t,r,s,i))}}class tv extends UA{async onGenerateKey(e,t,r){const s=await ZI.generateKey(e,t,r);return{privateKey:rI(s.privateKey),publicKey:rI(s.publicKey)}}async onDeriveBits(e,t,r){const s=tI(t),i=tI(e.public),n=qA().createPublicKey({key:i.data.toString(),format:"pem",type:"spki"}),o=qA().createPrivateKey({key:s.data.toString(),format:"pem",type:"pkcs8"}),a=qA().diffieHellman({publicKey:n,privateKey:o});return new Uint8Array(a).buffer.slice(0,r>>3)}async onExportKey(e,t){const r=tI(t);return ZI.exportKey(e,r)}async onImportKey(e,t,r,s,i){return rI(await ZI.importKey(e,t,r,s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(tI(e)instanceof JI))throw new TypeError("key: Is not a Ed25519CryptoKey")}}class rv extends WA{}class sv extends DA{async onDeriveBits(e,t,r){return new Promise((s,i)=>{const n=Tp.toArrayBuffer(e.salt),o=e.hash.name.replace("-","");qA().pbkdf2(tI(t).data,jA.Buffer.from(n),e.iterations,r>>3,o,(e,t)=>{e?i(e):s(new Uint8Array(t).buffer)})})}async onImportKey(e,t,r,s,i){if("raw"===e){const e=new rv;return e.data=jA.Buffer.from(t),e.algorithm={name:this.name},e.extractable=!1,e.usages=i,rI(e)}throw new Sb("format: Must be 'raw'")}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(tI(e)instanceof rv))throw new TypeError("key: Is not PBKDF CryptoKey")}}class iv extends WA{get alg(){return`HS${this.algorithm.hash.name.toUpperCase().replace("SHA-","")}`}set alg(e){}}Zm([Ab({name:"k",converter:zA})],iv.prototype,"data",void 0);class nv extends NA{async onGenerateKey(e,t,r){const s=(e.length||this.getDefaultLength(e.hash.name))>>3<<3,i=new iv;return i.algorithm={...e,length:s,name:this.name},i.extractable=t,i.usages=r,i.data=qA().randomBytes(s>>3),rI(i)}async onSign(e,t,r){const s=kI.getAlgorithmName(t.algorithm.hash),i=qA().createHmac(s,tI(t).data).update(jA.Buffer.from(r)).digest();return new Uint8Array(i).buffer}async onVerify(e,t,r,s){const i=kI.getAlgorithmName(t.algorithm.hash);return 0===qA().createHmac(i,tI(t).data).update(jA.Buffer.from(s)).digest().compare(jA.Buffer.from(r))}async onImportKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=bb.fromJSON(t,{targetSchema:iv});break;case"raw":n=new iv,n.data=jA.Buffer.from(t);break;default:throw new Sb("format: Must be 'jwk' or 'raw'")}return n.algorithm={hash:{name:r.hash.name},name:this.name,length:n.data.length<<3},n.extractable=s,n.usages=i,rI(n)}async onExportKey(e,t){switch(e.toLowerCase()){case"jwk":return mb.toJSON(tI(t));case"raw":return new Uint8Array(tI(t).data).buffer;default:throw new Sb("format: Must be 'jwk' or 'raw'")}}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(tI(e)instanceof iv))throw new TypeError("key: Is not HMAC CryptoKey")}}class ov extends WA{}class av extends MA{async onImportKey(e,t,r,s,i){if("raw"!==e.toLowerCase())throw new Sb("Operation not supported");const n=new ov;return n.data=jA.Buffer.from(t),n.algorithm={name:this.name},n.extractable=s,n.usages=i,rI(n)}async onDeriveBits(e,t,r){const s=e.hash.name.replace("-",""),i=qA().createHash(s).digest().length,n=r/8,o=Tp.toUint8Array(e.info),a=qA().createHmac(s,Tp.toUint8Array(e.salt)).update(Tp.toUint8Array(tI(t).data)).digest(),c=[jA.Buffer.alloc(0)],l=Math.ceil(n/i)+1;for(let e=1;e<l;++e)c.push(qA().createHmac(s,a).update(jA.Buffer.concat([c[e-1],o,jA.Buffer.from([e])])).digest());return jA.Buffer.concat(c).slice(0,n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(tI(e)instanceof ov))throw new TypeError("key: Is not HKDF CryptoKey")}}class cv{static digest(e,t){const r=qA().createHash(e.name.toLowerCase(),{outputLength:e.length}).update(jA.Buffer.from(t)).digest();return new Uint8Array(r).buffer}}class lv extends LA{async onDigest(e,t){return cv.digest(e,t)}}class hv extends HA{async onDigest(e,t){return cv.digest(e,t)}}class uv extends $A{constructor(){var e;super(),this.providers.set(new sI),this.providers.set(new dI),this.providers.set(new fI),this.providers.set(new uI),this.providers.set(new pI),this.providers.set(new gI),qA().getCiphers().includes("des-cbc")&&this.providers.set(new bI),this.providers.set(new AI),this.providers.set(new EI),this.providers.set(new CI),this.providers.set(new xI),this.providers.set(new _I),this.providers.set(new QI),this.providers.set(new VI),this.providers.set(new TI),this.providers.set(new NI),this.providers.set(new DI),this.providers.set(new MI),this.providers.set(new sv),this.providers.set(new nv),this.providers.set(new av);const t=null===(e=/^v(\d+)/.exec(od.version))||void 0===e?void 0:e[1];t&&parseInt(t,10)>=12&&(this.providers.set(new lv),this.providers.set(new hv));const r=qA().getHashes();r.includes("sha3-256")&&this.providers.set(new PI),r.includes("sha3-384")&&this.providers.set(new LI),r.includes("sha3-512")&&this.providers.set(new HI),t&&parseInt(t,10)>=14&&(this.providers.set(new zI),this.providers.set(new WI),this.providers.set(new ev),this.providers.set(new tv))}}var dv,fv,pv;o(909);class gv{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){const t=e.split(".");if(4!==t.length)throw new Error("Invalid IPv4 address");return t.map(e=>{const t=parseInt(e,10);if(isNaN(t)||t<0||t>255)throw new Error("Invalid IPv4 address part");return t})}static parseIPv6(e){const t=this.expandIPv6(e).split(":");if(8!==t.length)throw new Error("Invalid IPv6 address");return t.reduce((e,t)=>{const r=parseInt(t,16);if(isNaN(r)||r<0||r>65535)throw new Error("Invalid IPv6 address part");return e.push(r>>8&255),e.push(255&r),e},[])}static expandIPv6(e){if(!e.includes("::"))return e;const t=e.split("::");if(t.length>2)throw new Error("Invalid IPv6 address");const r=t[0]?t[0].split(":"):[],s=t[1]?t[1].split(":"):[],i=8-(r.length+s.length);if(i<0)throw new Error("Invalid IPv6 address");return[...r,...Array(i).fill("0"),...s].join(":")}static formatIPv6(e){const t=[];for(let r=0;r<16;r+=2)t.push((e[r]<<8|e[r+1]).toString(16));return this.compressIPv6(t.join(":"))}static compressIPv6(e){const t=e.split(":");let r=-1,s=0,i=-1,n=0;for(let e=0;e<t.length;e++)"0"===t[e]?(-1===i&&(i=e),n++):(n>s&&(r=i,s=n),i=-1,n=0);return n>s&&(r=i,s=n),s>1?`${t.slice(0,r).join(":")}::${t.slice(r+s).join(":")}`:e}static parseCIDR(e){const[t,r]=e.split("/"),s=parseInt(r,10);if(this.isIPv4(t)){if(s<0||s>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(t),s]}if(s<0||s>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(t),s]}static decodeIP(e){if(64===e.length&&0===parseInt(e,16))return"::/0";if(16!==e.length)return e;const t=parseInt(e.slice(8),16).toString(2).split("").reduce((e,t)=>e+ +t,0);let r=e.slice(0,8).replace(/(.{2})/g,e=>`${parseInt(e,16)}.`);return r=r.slice(0,-1),`${r}/${t}`}static toString(e){const t=new Uint8Array(e);if(4===t.length)return Array.from(t).join(".");if(16===t.length)return this.formatIPv6(t);if(8===t.length||32===t.length){const e=t.length/2,r=t.slice(0,e),s=t.slice(e);if(t.every(e=>0===e))return 8===t.length?"0.0.0.0/0":"::/0";const i=s.reduce((e,t)=>e+(t.toString(2).match(/1/g)||[]).length,0);return 8===t.length?`${Array.from(r).join(".")}/${i}`:`${this.formatIPv6(r)}/${i}`}return this.decodeIP(Kp.ToHex(e))}static fromString(e){if(e.includes("/")){const[t,r]=this.parseCIDR(e),s=new Uint8Array(t.length);let i=r;for(let e=0;e<s.length;e++)i>=8?(s[e]=255,i-=8):i>0&&(s[e]=255<<8-i,i=0);const n=new Uint8Array(2*t.length);return n.set(t,0),n.set(s,t.length),n.buffer}const t=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(t).buffer}}let yv=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};Zm([qm({type:oy.TeletexString})],yv.prototype,"teletexString",void 0),Zm([qm({type:oy.PrintableString})],yv.prototype,"printableString",void 0),Zm([qm({type:oy.UniversalString})],yv.prototype,"universalString",void 0),Zm([qm({type:oy.Utf8String})],yv.prototype,"utf8String",void 0),Zm([qm({type:oy.BmpString})],yv.prototype,"bmpString",void 0),yv=Zm([Gm({type:ny.Choice})],yv);let mv=class extends yv{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Kp.ToHex(this.anyValue):super.toString())}};Zm([qm({type:oy.IA5String})],mv.prototype,"ia5String",void 0),Zm([qm({type:oy.Any})],mv.prototype,"anyValue",void 0),mv=Zm([Gm({type:ny.Choice})],mv);class bv{constructor(e={}){this.type="",this.value=new mv,Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],bv.prototype,"type",void 0),Zm([qm({type:mv})],bv.prototype,"value",void 0);let Av=dv=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,dv.prototype)}};Av=dv=Zm([Gm({type:ny.Set,itemType:bv})],Av);let Iv=fv=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,fv.prototype)}};Iv=fv=Zm([Gm({type:ny.Sequence,itemType:Av})],Iv);let vv=pv=class extends Iv{constructor(e){super(e),Object.setPrototypeOf(this,pv.prototype)}};vv=pv=Zm([Gm({type:ny.Sequence})],vv);const wv={fromASN:e=>gv.toString(Sm.fromASN(e)),toASN:e=>Sm.toASN(gv.fromString(e))};class Sv{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],Sv.prototype,"typeId",void 0),Zm([qm({type:oy.Any,context:0})],Sv.prototype,"value",void 0);class Ev{constructor(e={}){this.partyName=new yv,Object.assign(this,e)}}Zm([qm({type:yv,optional:!0,context:0,implicit:!0})],Ev.prototype,"nameAssigner",void 0),Zm([qm({type:yv,context:1,implicit:!0})],Ev.prototype,"partyName",void 0);let Cv=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:Sv,context:0,implicit:!0})],Cv.prototype,"otherName",void 0),Zm([qm({type:oy.IA5String,context:1,implicit:!0})],Cv.prototype,"rfc822Name",void 0),Zm([qm({type:oy.IA5String,context:2,implicit:!0})],Cv.prototype,"dNSName",void 0),Zm([qm({type:oy.Any,context:3,implicit:!0})],Cv.prototype,"x400Address",void 0),Zm([qm({type:vv,context:4,implicit:!1})],Cv.prototype,"directoryName",void 0),Zm([qm({type:Ev,context:5})],Cv.prototype,"ediPartyName",void 0),Zm([qm({type:oy.IA5String,context:6,implicit:!0})],Cv.prototype,"uniformResourceIdentifier",void 0),Zm([qm({type:oy.OctetString,context:7,implicit:!0,converter:wv})],Cv.prototype,"iPAddress",void 0),Zm([qm({type:oy.ObjectIdentifier,context:8,implicit:!0})],Cv.prototype,"registeredID",void 0),Cv=Zm([Gm({type:ny.Choice})],Cv);const kv="1.3.6.1.5.5.7",xv=`${kv}.3`,_v=`${kv}.48`,Bv=`${_v}.1`,Rv=`${_v}.2`,Ov=`${_v}.3`,Uv=`${_v}.5`,Tv="2.5.29";var Nv;const Dv=`${kv}.1.1`;class Mv{constructor(e={}){this.accessMethod="",this.accessLocation=new Cv,Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],Mv.prototype,"accessMethod",void 0),Zm([qm({type:Cv})],Mv.prototype,"accessLocation",void 0);let Pv=Nv=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Nv.prototype)}};Pv=Nv=Zm([Gm({type:ny.Sequence,itemType:Mv})],Pv);const Lv=`${Tv}.35`;class Hv extends gm{}class Kv{constructor(e={}){e&&Object.assign(this,e)}}Zm([qm({type:Hv,context:0,optional:!0,implicit:!0})],Kv.prototype,"keyIdentifier",void 0),Zm([qm({type:Cv,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Kv.prototype,"authorityCertIssuer",void 0),Zm([qm({type:oy.Integer,context:2,optional:!0,implicit:!0,converter:Am})],Kv.prototype,"authorityCertSerialNumber",void 0);const Qv=`${Tv}.19`;class Vv{constructor(e={}){this.cA=!1,Object.assign(this,e)}}var Fv;Zm([qm({type:oy.Boolean,defaultValue:!1})],Vv.prototype,"cA",void 0),Zm([qm({type:oy.Integer,optional:!0})],Vv.prototype,"pathLenConstraint",void 0);let $v=Fv=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Fv.prototype)}};var jv;$v=Fv=Zm([Gm({type:ny.Sequence,itemType:Cv})],$v);let Gv=jv=class extends $v{constructor(e){super(e),Object.setPrototypeOf(this,jv.prototype)}};var qv;Gv=jv=Zm([Gm({type:ny.Sequence})],Gv);const zv=`${Tv}.32`;let Wv=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};Zm([qm({type:oy.IA5String})],Wv.prototype,"ia5String",void 0),Zm([qm({type:oy.VisibleString})],Wv.prototype,"visibleString",void 0),Zm([qm({type:oy.BmpString})],Wv.prototype,"bmpString",void 0),Zm([qm({type:oy.Utf8String})],Wv.prototype,"utf8String",void 0),Wv=Zm([Gm({type:ny.Choice})],Wv);class Jv{constructor(e={}){this.organization=new Wv,this.noticeNumbers=[],Object.assign(this,e)}}Zm([qm({type:Wv})],Jv.prototype,"organization",void 0),Zm([qm({type:oy.Integer,repeated:"sequence"})],Jv.prototype,"noticeNumbers",void 0);class Yv{constructor(e={}){Object.assign(this,e)}}Zm([qm({type:Jv,optional:!0})],Yv.prototype,"noticeRef",void 0),Zm([qm({type:Wv,optional:!0})],Yv.prototype,"explicitText",void 0);let Xv=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:oy.IA5String})],Xv.prototype,"cPSuri",void 0),Zm([qm({type:Yv})],Xv.prototype,"userNotice",void 0),Xv=Zm([Gm({type:ny.Choice})],Xv);class Zv{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],Zv.prototype,"policyQualifierId",void 0),Zm([qm({type:oy.Any})],Zv.prototype,"qualifier",void 0);class ew{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],ew.prototype,"policyIdentifier",void 0),Zm([qm({type:Zv,repeated:"sequence",optional:!0})],ew.prototype,"policyQualifiers",void 0);let tw=qv=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,qv.prototype)}};tw=qv=Zm([Gm({type:ny.Sequence,itemType:ew})],tw);let rw=class{constructor(e=0){this.value=e}};Zm([qm({type:oy.Integer})],rw.prototype,"value",void 0),rw=Zm([Gm({type:ny.Choice})],rw);let sw=class extends rw{};var iw;sw=Zm([Gm({type:ny.Choice})],sw);const nw=`${Tv}.31`;var ow;!function(e){e[e.unused=1]="unused",e[e.keyCompromise=2]="keyCompromise",e[e.cACompromise=4]="cACompromise",e[e.affiliationChanged=8]="affiliationChanged",e[e.superseded=16]="superseded",e[e.cessationOfOperation=32]="cessationOfOperation",e[e.certificateHold=64]="certificateHold",e[e.privilegeWithdrawn=128]="privilegeWithdrawn",e[e.aACompromise=256]="aACompromise"}(ow||(ow={}));class aw extends pm{toJSON(){const e=[],t=this.toNumber();return t&ow.aACompromise&&e.push("aACompromise"),t&ow.affiliationChanged&&e.push("affiliationChanged"),t&ow.cACompromise&&e.push("cACompromise"),t&ow.certificateHold&&e.push("certificateHold"),t&ow.cessationOfOperation&&e.push("cessationOfOperation"),t&ow.keyCompromise&&e.push("keyCompromise"),t&ow.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&ow.superseded&&e.push("superseded"),t&ow.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let cw=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:Cv,context:0,repeated:"sequence",implicit:!0})],cw.prototype,"fullName",void 0),Zm([qm({type:Av,context:1,implicit:!0})],cw.prototype,"nameRelativeToCRLIssuer",void 0),cw=Zm([Gm({type:ny.Choice})],cw);class lw{constructor(e={}){Object.assign(this,e)}}Zm([qm({type:cw,context:0,optional:!0})],lw.prototype,"distributionPoint",void 0),Zm([qm({type:aw,context:1,optional:!0,implicit:!0})],lw.prototype,"reasons",void 0),Zm([qm({type:Cv,context:2,optional:!0,repeated:"sequence",implicit:!0})],lw.prototype,"cRLIssuer",void 0);let hw=iw=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,iw.prototype)}};var uw;hw=iw=Zm([Gm({type:ny.Sequence,itemType:lw})],hw);let dw=uw=class extends hw{constructor(e){super(e),Object.setPrototypeOf(this,uw.prototype)}};dw=uw=Zm([Gm({type:ny.Sequence,itemType:lw})],dw);class fw{constructor(e={}){this.onlyContainsUserCerts=fw.ONLY,this.onlyContainsCACerts=fw.ONLY,this.indirectCRL=fw.ONLY,this.onlyContainsAttributeCerts=fw.ONLY,Object.assign(this,e)}}var pw;fw.ONLY=!1,Zm([qm({type:cw,context:0,optional:!0})],fw.prototype,"distributionPoint",void 0),Zm([qm({type:oy.Boolean,context:1,defaultValue:fw.ONLY,implicit:!0})],fw.prototype,"onlyContainsUserCerts",void 0),Zm([qm({type:oy.Boolean,context:2,defaultValue:fw.ONLY,implicit:!0})],fw.prototype,"onlyContainsCACerts",void 0),Zm([qm({type:aw,context:3,optional:!0,implicit:!0})],fw.prototype,"onlySomeReasons",void 0),Zm([qm({type:oy.Boolean,context:4,defaultValue:fw.ONLY,implicit:!0})],fw.prototype,"indirectCRL",void 0),Zm([qm({type:oy.Boolean,context:5,defaultValue:fw.ONLY,implicit:!0})],fw.prototype,"onlyContainsAttributeCerts",void 0),function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(pw||(pw={}));let gw=class{constructor(e=pw.unspecified){this.reason=pw.unspecified,this.reason=e}toJSON(){return pw[this.reason]}toString(){return this.toJSON()}};var yw;Zm([qm({type:oy.Enumerated})],gw.prototype,"reason",void 0),gw=Zm([Gm({type:ny.Choice})],gw);const mw=`${Tv}.37`;let bw=yw=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,yw.prototype)}};bw=yw=Zm([Gm({type:ny.Sequence,itemType:oy.ObjectIdentifier})],bw);const Aw=`${xv}.1`,Iw=`${xv}.2`,vw=`${xv}.3`,ww=`${xv}.4`,Sw=`${xv}.8`,Ew=`${xv}.9`;let Cw=class{constructor(e=new ArrayBuffer(0)){this.value=e}};Zm([qm({type:oy.Integer,converter:Am})],Cw.prototype,"value",void 0),Cw=Zm([Gm({type:ny.Choice})],Cw);let kw=class{constructor(e){this.value=new Date,e&&(this.value=e)}};var xw;Zm([qm({type:oy.GeneralizedTime})],kw.prototype,"value",void 0),kw=Zm([Gm({type:ny.Choice})],kw);let _w=xw=class extends $v{constructor(e){super(e),Object.setPrototypeOf(this,xw.prototype)}};_w=xw=Zm([Gm({type:ny.Sequence})],_w);const Bw=`${Tv}.15`;var Rw,Ow;!function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(Rw||(Rw={}));class Uw extends pm{toJSON(){const e=this.toNumber(),t=[];return e&Rw.cRLSign&&t.push("crlSign"),e&Rw.dataEncipherment&&t.push("dataEncipherment"),e&Rw.decipherOnly&&t.push("decipherOnly"),e&Rw.digitalSignature&&t.push("digitalSignature"),e&Rw.encipherOnly&&t.push("encipherOnly"),e&Rw.keyAgreement&&t.push("keyAgreement"),e&Rw.keyCertSign&&t.push("keyCertSign"),e&Rw.keyEncipherment&&t.push("keyEncipherment"),e&Rw.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}}class Tw{constructor(e={}){this.base=new Cv,this.minimum=0,Object.assign(this,e)}}Zm([qm({type:Cv})],Tw.prototype,"base",void 0),Zm([qm({type:oy.Integer,context:0,defaultValue:0,implicit:!0})],Tw.prototype,"minimum",void 0),Zm([qm({type:oy.Integer,context:1,optional:!0,implicit:!0})],Tw.prototype,"maximum",void 0);let Nw=Ow=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Ow.prototype)}};Nw=Ow=Zm([Gm({type:ny.Sequence,itemType:Tw})],Nw);class Dw{constructor(e={}){Object.assign(this,e)}}Zm([qm({type:Nw,context:0,optional:!0,implicit:!0})],Dw.prototype,"permittedSubtrees",void 0),Zm([qm({type:Nw,context:1,optional:!0,implicit:!0})],Dw.prototype,"excludedSubtrees",void 0);class Mw{constructor(e={}){Object.assign(this,e)}}var Pw;Zm([qm({type:oy.Integer,context:0,implicit:!0,optional:!0,converter:Am})],Mw.prototype,"requireExplicitPolicy",void 0),Zm([qm({type:oy.Integer,context:1,implicit:!0,optional:!0,converter:Am})],Mw.prototype,"inhibitPolicyMapping",void 0);class Lw{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],Lw.prototype,"issuerDomainPolicy",void 0),Zm([qm({type:oy.ObjectIdentifier})],Lw.prototype,"subjectDomainPolicy",void 0);let Hw=Pw=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Pw.prototype)}};var Kw;Hw=Pw=Zm([Gm({type:ny.Sequence,itemType:Lw})],Hw);const Qw=`${Tv}.17`;let Vw=Kw=class extends $v{constructor(e){super(e),Object.setPrototypeOf(this,Kw.prototype)}};Vw=Kw=Zm([Gm({type:ny.Sequence})],Vw);class Fw{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}}var $w;Zm([qm({type:oy.ObjectIdentifier})],Fw.prototype,"type",void 0),Zm([qm({type:oy.Any,repeated:"set"})],Fw.prototype,"values",void 0);let jw=$w=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,$w.prototype)}};jw=$w=Zm([Gm({type:ny.Sequence,itemType:Fw})],jw);const Gw=`${Tv}.14`;class qw extends Hv{}class zw{constructor(e={}){Object.assign(this,e)}}var Ww,Jw;Zm([qm({type:oy.GeneralizedTime,context:0,implicit:!0,optional:!0})],zw.prototype,"notBefore",void 0),Zm([qm({type:oy.GeneralizedTime,context:1,implicit:!0,optional:!0})],zw.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(Ww||(Ww={}));class Yw extends pm{toJSON(){const e=[],t=this.toNumber();return t&Ww.pKIXCertificate&&e.push("pKIXCertificate"),t&Ww.newExtensions&&e.push("newExtensions"),t&Ww.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class Xw{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new Yw,Object.assign(this,e)}}Zm([qm({type:oy.GeneralString})],Xw.prototype,"entrustVers",void 0),Zm([qm({type:Yw})],Xw.prototype,"entrustInfoFlags",void 0);let Zw=Jw=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Jw.prototype)}};Zw=Jw=Zm([Gm({type:ny.Sequence,itemType:Mv})],Zw);class eS{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof eS&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Vp(e.parameters,this.parameters)||e.parameters===this.parameters)}}Zm([qm({type:oy.ObjectIdentifier})],eS.prototype,"algorithm",void 0),Zm([qm({type:oy.Any,optional:!0})],eS.prototype,"parameters",void 0);class tS{constructor(e={}){this.algorithm=new eS,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:eS})],tS.prototype,"algorithm",void 0),Zm([qm({type:oy.BitString})],tS.prototype,"subjectPublicKey",void 0);let rS=class{constructor(e){if(e)if("string"==typeof e||"number"==typeof e||e instanceof Date){const t=new Date(e);t.getUTCFullYear()>2049?this.generalTime=t:this.utcTime=t}else Object.assign(this,e)}getTime(){const e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};Zm([qm({type:oy.UTCTime})],rS.prototype,"utcTime",void 0),Zm([qm({type:oy.GeneralizedTime})],rS.prototype,"generalTime",void 0),rS=Zm([Gm({type:ny.Choice})],rS);class sS{constructor(e){this.notBefore=new rS(new Date),this.notAfter=new rS(new Date),e&&(this.notBefore=new rS(e.notBefore),this.notAfter=new rS(e.notAfter))}}var iS;Zm([qm({type:rS})],sS.prototype,"notBefore",void 0),Zm([qm({type:rS})],sS.prototype,"notAfter",void 0);class nS{constructor(e={}){this.extnID="",this.critical=nS.CRITICAL,this.extnValue=new gm,Object.assign(this,e)}}nS.CRITICAL=!1,Zm([qm({type:oy.ObjectIdentifier})],nS.prototype,"extnID",void 0),Zm([qm({type:oy.Boolean,defaultValue:nS.CRITICAL})],nS.prototype,"critical",void 0),Zm([qm({type:gm})],nS.prototype,"extnValue",void 0);let oS=iS=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,iS.prototype)}};var aS;oS=iS=Zm([Gm({type:ny.Sequence,itemType:nS})],oS),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(aS||(aS={}));class cS{constructor(e={}){this.version=aS.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new eS,this.issuer=new vv,this.validity=new sS,this.subject=new vv,this.subjectPublicKeyInfo=new tS,Object.assign(this,e)}}Zm([qm({type:oy.Integer,context:0,defaultValue:aS.v1})],cS.prototype,"version",void 0),Zm([qm({type:oy.Integer,converter:Am})],cS.prototype,"serialNumber",void 0),Zm([qm({type:eS})],cS.prototype,"signature",void 0),Zm([qm({type:vv})],cS.prototype,"issuer",void 0),Zm([qm({type:sS})],cS.prototype,"validity",void 0),Zm([qm({type:vv})],cS.prototype,"subject",void 0),Zm([qm({type:tS})],cS.prototype,"subjectPublicKeyInfo",void 0),Zm([qm({type:oy.BitString,context:1,implicit:!0,optional:!0})],cS.prototype,"issuerUniqueID",void 0),Zm([qm({type:oy.BitString,context:2,implicit:!0,optional:!0})],cS.prototype,"subjectUniqueID",void 0),Zm([qm({type:oS,context:3,optional:!0})],cS.prototype,"extensions",void 0);class lS{constructor(e={}){this.tbsCertificate=new cS,this.signatureAlgorithm=new eS,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:cS})],lS.prototype,"tbsCertificate",void 0),Zm([qm({type:eS})],lS.prototype,"signatureAlgorithm",void 0),Zm([qm({type:oy.BitString})],lS.prototype,"signatureValue",void 0);class hS{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new rS,Object.assign(this,e)}}Zm([qm({type:oy.Integer,converter:Am})],hS.prototype,"userCertificate",void 0),Zm([qm({type:rS})],hS.prototype,"revocationDate",void 0),Zm([qm({type:nS,optional:!0,repeated:"sequence"})],hS.prototype,"crlEntryExtensions",void 0);class uS{constructor(e={}){this.signature=new eS,this.issuer=new vv,this.thisUpdate=new rS,Object.assign(this,e)}}Zm([qm({type:oy.Integer,optional:!0})],uS.prototype,"version",void 0),Zm([qm({type:eS})],uS.prototype,"signature",void 0),Zm([qm({type:vv})],uS.prototype,"issuer",void 0),Zm([qm({type:rS})],uS.prototype,"thisUpdate",void 0),Zm([qm({type:rS,optional:!0})],uS.prototype,"nextUpdate",void 0),Zm([qm({type:hS,repeated:"sequence",optional:!0})],uS.prototype,"revokedCertificates",void 0),Zm([qm({type:nS,optional:!0,context:0,repeated:"sequence"})],uS.prototype,"crlExtensions",void 0);class dS{constructor(e={}){this.tbsCertList=new uS,this.signatureAlgorithm=new eS,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:uS})],dS.prototype,"tbsCertList",void 0),Zm([qm({type:eS})],dS.prototype,"signatureAlgorithm",void 0),Zm([qm({type:oy.BitString})],dS.prototype,"signature",void 0);class fS{constructor(e={}){this.issuer=new vv,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:vv})],fS.prototype,"issuer",void 0),Zm([qm({type:oy.Integer,converter:Am})],fS.prototype,"serialNumber",void 0);let pS=class{constructor(e={}){Object.assign(this,e)}};var gS;Zm([qm({type:qw,context:0,implicit:!0})],pS.prototype,"subjectKeyIdentifier",void 0),Zm([qm({type:fS})],pS.prototype,"issuerAndSerialNumber",void 0),pS=Zm([Gm({type:ny.Choice})],pS),function(e){e[e.v0=0]="v0",e[e.v1=1]="v1",e[e.v2=2]="v2",e[e.v3=3]="v3",e[e.v4=4]="v4",e[e.v5=5]="v5"}(gS||(gS={}));let yS=class extends eS{};yS=Zm([Gm({type:ny.Sequence})],yS);let mS=class extends eS{};mS=Zm([Gm({type:ny.Sequence})],mS);let bS=class extends eS{};bS=Zm([Gm({type:ny.Sequence})],bS);let AS=class extends eS{};AS=Zm([Gm({type:ny.Sequence})],AS);let IS=class extends eS{};IS=Zm([Gm({type:ny.Sequence})],IS);let vS=class extends eS{};vS=Zm([Gm({type:ny.Sequence})],vS);class wS{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}}var SS;Zm([qm({type:oy.ObjectIdentifier})],wS.prototype,"attrType",void 0),Zm([qm({type:oy.Any,repeated:"set"})],wS.prototype,"attrValues",void 0);class ES{constructor(e={}){this.version=gS.v0,this.sid=new pS,this.digestAlgorithm=new yS,this.signatureAlgorithm=new mS,this.signature=new gm,Object.assign(this,e)}}Zm([qm({type:oy.Integer})],ES.prototype,"version",void 0),Zm([qm({type:pS})],ES.prototype,"sid",void 0),Zm([qm({type:yS})],ES.prototype,"digestAlgorithm",void 0),Zm([qm({type:wS,repeated:"set",context:0,implicit:!0,optional:!0})],ES.prototype,"signedAttrs",void 0),Zm([qm({type:mS})],ES.prototype,"signatureAlgorithm",void 0),Zm([qm({type:gm})],ES.prototype,"signature",void 0),Zm([qm({type:wS,repeated:"set",context:1,implicit:!0,optional:!0})],ES.prototype,"unsignedAttrs",void 0);let CS=SS=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,SS.prototype)}};CS=SS=Zm([Gm({type:ny.Set,itemType:ES})],CS);let kS=class extends rS{};kS=Zm([Gm({type:ny.Choice})],kS);let xS=class extends ES{};xS=Zm([Gm({type:ny.Sequence})],xS);class _S{constructor(e={}){this.acIssuer=new Cv,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}var BS;Zm([qm({type:Cv})],_S.prototype,"acIssuer",void 0),Zm([qm({type:oy.Integer})],_S.prototype,"acSerial",void 0),Zm([qm({type:Fw,repeated:"sequence"})],_S.prototype,"attrs",void 0);let RS=BS=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,BS.prototype)}};RS=BS=Zm([Gm({type:ny.Sequence,itemType:oy.ObjectIdentifier})],RS);class OS{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}}Zm([qm({type:oy.Integer,optional:!0})],OS.prototype,"pathLenConstraint",void 0),Zm([qm({type:RS,implicit:!0,context:0,optional:!0})],OS.prototype,"permittedAttrs",void 0),Zm([qm({type:RS,implicit:!0,context:1,optional:!0})],OS.prototype,"excludedAttrs",void 0),Zm([qm({type:oy.Boolean,defaultValue:!0})],OS.prototype,"permitUnSpecified",void 0);class US{constructor(e={}){this.issuer=new $v,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}var TS;Zm([qm({type:$v})],US.prototype,"issuer",void 0),Zm([qm({type:oy.Integer,converter:Am})],US.prototype,"serial",void 0),Zm([qm({type:oy.BitString,optional:!0})],US.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}(TS||(TS={}));class NS{constructor(e={}){this.digestedObjectType=TS.publicKey,this.digestAlgorithm=new eS,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.Enumerated})],NS.prototype,"digestedObjectType",void 0),Zm([qm({type:oy.ObjectIdentifier,optional:!0})],NS.prototype,"otherObjectTypeID",void 0),Zm([qm({type:eS})],NS.prototype,"digestAlgorithm",void 0),Zm([qm({type:oy.BitString})],NS.prototype,"objectDigest",void 0);class DS{constructor(e={}){Object.assign(this,e)}}Zm([qm({type:$v,optional:!0})],DS.prototype,"issuerName",void 0),Zm([qm({type:US,context:0,implicit:!0,optional:!0})],DS.prototype,"baseCertificateID",void 0),Zm([qm({type:NS,context:1,implicit:!0,optional:!0})],DS.prototype,"objectDigestInfo",void 0);let MS=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:Cv,repeated:"sequence"})],MS.prototype,"v1Form",void 0),Zm([qm({type:DS,context:0,implicit:!0})],MS.prototype,"v2Form",void 0),MS=Zm([Gm({type:ny.Choice})],MS);class PS{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}Zm([qm({type:oy.GeneralizedTime})],PS.prototype,"notBeforeTime",void 0),Zm([qm({type:oy.GeneralizedTime})],PS.prototype,"notAfterTime",void 0);class LS{constructor(e={}){Object.assign(this,e)}}var HS,KS,QS;Zm([qm({type:US,implicit:!0,context:0,optional:!0})],LS.prototype,"baseCertificateID",void 0),Zm([qm({type:$v,implicit:!0,context:1,optional:!0})],LS.prototype,"entityName",void 0),Zm([qm({type:NS,implicit:!0,context:2,optional:!0})],LS.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(HS||(HS={}));class VS{constructor(e={}){this.version=HS.v2,this.holder=new LS,this.issuer=new MS,this.signature=new eS,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new PS,this.attributes=[],Object.assign(this,e)}}Zm([qm({type:oy.Integer})],VS.prototype,"version",void 0),Zm([qm({type:LS})],VS.prototype,"holder",void 0),Zm([qm({type:MS})],VS.prototype,"issuer",void 0),Zm([qm({type:eS})],VS.prototype,"signature",void 0),Zm([qm({type:oy.Integer,converter:Am})],VS.prototype,"serialNumber",void 0),Zm([qm({type:PS})],VS.prototype,"attrCertValidityPeriod",void 0),Zm([qm({type:Fw,repeated:"sequence"})],VS.prototype,"attributes",void 0),Zm([qm({type:oy.BitString,optional:!0})],VS.prototype,"issuerUniqueID",void 0),Zm([qm({type:oS,optional:!0})],VS.prototype,"extensions",void 0);class FS{constructor(e={}){this.acinfo=new VS,this.signatureAlgorithm=new eS,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:VS})],FS.prototype,"acinfo",void 0),Zm([qm({type:eS})],FS.prototype,"signatureAlgorithm",void 0),Zm([qm({type:oy.BitString})],FS.prototype,"signatureValue",void 0),function(e){e[e.unmarked=1]="unmarked",e[e.unclassified=2]="unclassified",e[e.restricted=4]="restricted",e[e.confidential=8]="confidential",e[e.secret=16]="secret",e[e.topSecret=32]="topSecret"}(KS||(KS={}));class $S extends pm{}class jS{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier,implicit:!0,context:0})],jS.prototype,"type",void 0),Zm([qm({type:oy.Any,implicit:!0,context:1})],jS.prototype,"value",void 0);class GS{constructor(e={}){this.policyId="",this.classList=new $S(KS.unclassified),Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],GS.prototype,"policyId",void 0),Zm([qm({type:$S,defaultValue:new $S(KS.unclassified)})],GS.prototype,"classList",void 0),Zm([qm({type:jS,repeated:"set"})],GS.prototype,"securityCategories",void 0);class qS{constructor(e={}){Object.assign(this,e)}}Zm([qm({type:gm})],qS.prototype,"cotets",void 0),Zm([qm({type:oy.ObjectIdentifier})],qS.prototype,"oid",void 0),Zm([qm({type:oy.Utf8String})],qS.prototype,"string",void 0);class zS{constructor(e={}){this.values=[],Object.assign(this,e)}}Zm([qm({type:$v,implicit:!0,context:0,optional:!0})],zS.prototype,"policyAuthority",void 0),Zm([qm({type:qS,repeated:"sequence"})],zS.prototype,"values",void 0);class WS{constructor(e={}){this.targetCertificate=new US,Object.assign(this,e)}}Zm([qm({type:US})],WS.prototype,"targetCertificate",void 0),Zm([qm({type:Cv,optional:!0})],WS.prototype,"targetName",void 0),Zm([qm({type:NS,optional:!0})],WS.prototype,"certDigestInfo",void 0);let JS=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:Cv,context:0,implicit:!0})],JS.prototype,"targetName",void 0),Zm([qm({type:Cv,context:1,implicit:!0})],JS.prototype,"targetGroup",void 0),Zm([qm({type:WS,context:2,implicit:!0})],JS.prototype,"targetCert",void 0),JS=Zm([Gm({type:ny.Choice})],JS);let YS=QS=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,QS.prototype)}};var XS;YS=QS=Zm([Gm({type:ny.Sequence,itemType:JS})],YS);let ZS=XS=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,XS.prototype)}};ZS=XS=Zm([Gm({type:ny.Sequence,itemType:YS})],ZS);class eE{constructor(e={}){Object.assign(this,e)}}Zm([qm({type:$v,implicit:!0,context:0,optional:!0})],eE.prototype,"roleAuthority",void 0),Zm([qm({type:Cv,implicit:!0,context:1})],eE.prototype,"roleName",void 0);class tE{constructor(e={}){this.service=new Cv,this.ident=new Cv,Object.assign(this,e)}}var rE;Zm([qm({type:Cv})],tE.prototype,"service",void 0),Zm([qm({type:Cv})],tE.prototype,"ident",void 0),Zm([qm({type:gm,optional:!0})],tE.prototype,"authInfo",void 0);class sE{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],sE.prototype,"otherCertFormat",void 0),Zm([qm({type:oy.Any})],sE.prototype,"otherCert",void 0);let iE=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:lS})],iE.prototype,"certificate",void 0),Zm([qm({type:FS,context:2,implicit:!0})],iE.prototype,"v2AttrCert",void 0),Zm([qm({type:sE,context:3,implicit:!0})],iE.prototype,"other",void 0),iE=Zm([Gm({type:ny.Choice})],iE);let nE=rE=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,rE.prototype)}};nE=rE=Zm([Gm({type:ny.Set,itemType:iE})],nE);class oE{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],oE.prototype,"contentType",void 0),Zm([qm({type:oy.Any,context:0})],oE.prototype,"content",void 0);let aE=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:gm})],aE.prototype,"single",void 0),Zm([qm({type:oy.Any})],aE.prototype,"any",void 0),aE=Zm([Gm({type:ny.Choice})],aE);class cE{constructor(e={}){this.eContentType="",Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],cE.prototype,"eContentType",void 0),Zm([qm({type:aE,context:0,optional:!0})],cE.prototype,"eContent",void 0);let lE=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:gm,context:0,implicit:!0,optional:!0})],lE.prototype,"value",void 0),Zm([qm({type:gm,converter:Em,context:0,implicit:!0,optional:!0,repeated:"sequence"})],lE.prototype,"constructedValue",void 0),lE=Zm([Gm({type:ny.Choice})],lE);class hE{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new AS,Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],hE.prototype,"contentType",void 0),Zm([qm({type:AS})],hE.prototype,"contentEncryptionAlgorithm",void 0),Zm([qm({type:lE,optional:!0})],hE.prototype,"encryptedContent",void 0);class uE{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}}var dE;Zm([qm({type:oy.ObjectIdentifier})],uE.prototype,"keyAttrId",void 0),Zm([qm({type:oy.Any,optional:!0})],uE.prototype,"keyAttr",void 0);class fE{constructor(e={}){this.subjectKeyIdentifier=new qw,Object.assign(this,e)}}Zm([qm({type:qw})],fE.prototype,"subjectKeyIdentifier",void 0),Zm([qm({type:oy.GeneralizedTime,optional:!0})],fE.prototype,"date",void 0),Zm([qm({type:uE,optional:!0})],fE.prototype,"other",void 0);let pE=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:fE,context:0,implicit:!0,optional:!0})],pE.prototype,"rKeyId",void 0),Zm([qm({type:fS,optional:!0})],pE.prototype,"issuerAndSerialNumber",void 0),pE=Zm([Gm({type:ny.Choice})],pE);class gE{constructor(e={}){this.rid=new pE,this.encryptedKey=new gm,Object.assign(this,e)}}Zm([qm({type:pE})],gE.prototype,"rid",void 0),Zm([qm({type:gm})],gE.prototype,"encryptedKey",void 0);let yE=dE=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,dE.prototype)}};yE=dE=Zm([Gm({type:ny.Sequence,itemType:gE})],yE);class mE{constructor(e={}){this.algorithm=new eS,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:eS})],mE.prototype,"algorithm",void 0),Zm([qm({type:oy.BitString})],mE.prototype,"publicKey",void 0);let bE=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:qw,context:0,implicit:!0,optional:!0})],bE.prototype,"subjectKeyIdentifier",void 0),Zm([qm({type:mE,context:1,implicit:!0,optional:!0})],bE.prototype,"originatorKey",void 0),Zm([qm({type:fS,optional:!0})],bE.prototype,"issuerAndSerialNumber",void 0),bE=Zm([Gm({type:ny.Choice})],bE);class AE{constructor(e={}){this.version=gS.v3,this.originator=new bE,this.keyEncryptionAlgorithm=new bS,this.recipientEncryptedKeys=new yE,Object.assign(this,e)}}Zm([qm({type:oy.Integer})],AE.prototype,"version",void 0),Zm([qm({type:bE,context:0})],AE.prototype,"originator",void 0),Zm([qm({type:gm,context:1,optional:!0})],AE.prototype,"ukm",void 0),Zm([qm({type:bS})],AE.prototype,"keyEncryptionAlgorithm",void 0),Zm([qm({type:yE})],AE.prototype,"recipientEncryptedKeys",void 0);let IE=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:qw,context:0,implicit:!0})],IE.prototype,"subjectKeyIdentifier",void 0),Zm([qm({type:fS})],IE.prototype,"issuerAndSerialNumber",void 0),IE=Zm([Gm({type:ny.Choice})],IE);class vE{constructor(e={}){this.version=gS.v0,this.rid=new IE,this.keyEncryptionAlgorithm=new bS,this.encryptedKey=new gm,Object.assign(this,e)}}Zm([qm({type:oy.Integer})],vE.prototype,"version",void 0),Zm([qm({type:IE})],vE.prototype,"rid",void 0),Zm([qm({type:bS})],vE.prototype,"keyEncryptionAlgorithm",void 0),Zm([qm({type:gm})],vE.prototype,"encryptedKey",void 0);class wE{constructor(e={}){this.keyIdentifier=new gm,Object.assign(this,e)}}Zm([qm({type:gm})],wE.prototype,"keyIdentifier",void 0),Zm([qm({type:oy.GeneralizedTime,optional:!0})],wE.prototype,"date",void 0),Zm([qm({type:uE,optional:!0})],wE.prototype,"other",void 0);class SE{constructor(e={}){this.version=gS.v4,this.kekid=new wE,this.keyEncryptionAlgorithm=new bS,this.encryptedKey=new gm,Object.assign(this,e)}}Zm([qm({type:oy.Integer})],SE.prototype,"version",void 0),Zm([qm({type:wE})],SE.prototype,"kekid",void 0),Zm([qm({type:bS})],SE.prototype,"keyEncryptionAlgorithm",void 0),Zm([qm({type:gm})],SE.prototype,"encryptedKey",void 0);class EE{constructor(e={}){this.version=gS.v0,this.keyEncryptionAlgorithm=new bS,this.encryptedKey=new gm,Object.assign(this,e)}}Zm([qm({type:oy.Integer})],EE.prototype,"version",void 0),Zm([qm({type:vS,context:0,optional:!0})],EE.prototype,"keyDerivationAlgorithm",void 0),Zm([qm({type:bS})],EE.prototype,"keyEncryptionAlgorithm",void 0),Zm([qm({type:gm})],EE.prototype,"encryptedKey",void 0);class CE{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],CE.prototype,"oriType",void 0),Zm([qm({type:oy.Any})],CE.prototype,"oriValue",void 0);let kE=class{constructor(e={}){Object.assign(this,e)}};var xE;Zm([qm({type:vE,optional:!0})],kE.prototype,"ktri",void 0),Zm([qm({type:AE,context:1,implicit:!0,optional:!0})],kE.prototype,"kari",void 0),Zm([qm({type:SE,context:2,implicit:!0,optional:!0})],kE.prototype,"kekri",void 0),Zm([qm({type:EE,context:3,implicit:!0,optional:!0})],kE.prototype,"pwri",void 0),Zm([qm({type:CE,context:4,implicit:!0,optional:!0})],kE.prototype,"ori",void 0),kE=Zm([Gm({type:ny.Choice})],kE);let _E=xE=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,xE.prototype)}};var BE;_E=xE=Zm([Gm({type:ny.Set,itemType:kE})],_E);class RE{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],RE.prototype,"otherRevInfoFormat",void 0),Zm([qm({type:oy.Any})],RE.prototype,"otherRevInfo",void 0);let OE=class{constructor(e={}){this.other=new RE,Object.assign(this,e)}};Zm([qm({type:RE,context:1,implicit:!0})],OE.prototype,"other",void 0),OE=Zm([Gm({type:ny.Choice})],OE);let UE=BE=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,BE.prototype)}};UE=BE=Zm([Gm({type:ny.Set,itemType:OE})],UE);class TE{constructor(e={}){Object.assign(this,e)}}var NE;Zm([qm({type:nE,context:0,implicit:!0,optional:!0})],TE.prototype,"certs",void 0),Zm([qm({type:UE,context:1,implicit:!0,optional:!0})],TE.prototype,"crls",void 0);let DE=NE=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,NE.prototype)}};DE=NE=Zm([Gm({type:ny.Set,itemType:wS})],DE);class ME{constructor(e={}){this.version=gS.v0,this.recipientInfos=new _E,this.encryptedContentInfo=new hE,Object.assign(this,e)}}Zm([qm({type:oy.Integer})],ME.prototype,"version",void 0),Zm([qm({type:TE,context:0,implicit:!0,optional:!0})],ME.prototype,"originatorInfo",void 0),Zm([qm({type:_E})],ME.prototype,"recipientInfos",void 0),Zm([qm({type:hE})],ME.prototype,"encryptedContentInfo",void 0),Zm([qm({type:DE,context:1,implicit:!0,optional:!0})],ME.prototype,"unprotectedAttrs",void 0);const PE="1.2.840.113549.1.7.2";var LE;let HE=LE=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,LE.prototype)}};HE=LE=Zm([Gm({type:ny.Set,itemType:yS})],HE);class KE{constructor(e={}){this.version=gS.v0,this.digestAlgorithms=new HE,this.encapContentInfo=new cE,this.signerInfos=new CS,Object.assign(this,e)}}Zm([qm({type:oy.Integer})],KE.prototype,"version",void 0),Zm([qm({type:HE})],KE.prototype,"digestAlgorithms",void 0),Zm([qm({type:cE})],KE.prototype,"encapContentInfo",void 0),Zm([qm({type:nE,context:0,implicit:!0,optional:!0})],KE.prototype,"certificates",void 0),Zm([qm({type:UE,context:1,implicit:!0,optional:!0})],KE.prototype,"crls",void 0),Zm([qm({type:CS})],KE.prototype,"signerInfos",void 0);const QE="1.2.840.10045.2.1",VE="1.2.840.10045.4.1",FE="1.2.840.10045.4.3.1",$E="1.2.840.10045.4.3.2",jE="1.2.840.10045.4.3.3",GE="1.2.840.10045.4.3.4",qE="1.2.840.10045.3.1.7",zE="1.3.132.0.34",WE="1.3.132.0.35";function JE(e){return new eS({algorithm:e})}const YE=JE(VE),XE=(JE(FE),JE($E)),ZE=JE(jE),eC=JE(GE);let tC=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:oy.ObjectIdentifier})],tC.prototype,"fieldType",void 0),Zm([qm({type:oy.Any})],tC.prototype,"parameters",void 0),tC=Zm([Gm({type:ny.Sequence})],tC);let rC=class{constructor(e={}){Object.assign(this,e)}};var sC;Zm([qm({type:oy.OctetString})],rC.prototype,"a",void 0),Zm([qm({type:oy.OctetString})],rC.prototype,"b",void 0),Zm([qm({type:oy.BitString,optional:!0})],rC.prototype,"seed",void 0),rC=Zm([Gm({type:ny.Sequence})],rC),function(e){e[e.ecpVer1=1]="ecpVer1"}(sC||(sC={}));let iC=class{constructor(e={}){this.version=sC.ecpVer1,Object.assign(this,e)}};Zm([qm({type:oy.Integer})],iC.prototype,"version",void 0),Zm([qm({type:tC})],iC.prototype,"fieldID",void 0),Zm([qm({type:rC})],iC.prototype,"curve",void 0),Zm([qm({type:class extends gm{}})],iC.prototype,"base",void 0),Zm([qm({type:oy.Integer,converter:Am})],iC.prototype,"order",void 0),Zm([qm({type:oy.Integer,optional:!0})],iC.prototype,"cofactor",void 0),iC=Zm([Gm({type:ny.Sequence})],iC);let nC=class{constructor(e={}){Object.assign(this,e)}};Zm([qm({type:oy.ObjectIdentifier})],nC.prototype,"namedCurve",void 0),Zm([qm({type:oy.Null})],nC.prototype,"implicitCurve",void 0),Zm([qm({type:iC})],nC.prototype,"specifiedCurve",void 0),nC=Zm([Gm({type:ny.Choice})],nC);class oC{constructor(e={}){this.version=1,this.privateKey=new gm,Object.assign(this,e)}}Zm([qm({type:oy.Integer})],oC.prototype,"version",void 0),Zm([qm({type:gm})],oC.prototype,"privateKey",void 0),Zm([qm({type:nC,context:0,optional:!0})],oC.prototype,"parameters",void 0),Zm([qm({type:oy.BitString,context:1,optional:!0})],oC.prototype,"publicKey",void 0);class aC{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.Integer,converter:Am})],aC.prototype,"r",void 0),Zm([qm({type:oy.Integer,converter:Am})],aC.prototype,"s",void 0);const cC="1.2.840.113549.1.1",lC=`${cC}.1`,hC=`${cC}.7`,uC=`${cC}.9`,dC=`${cC}.10`,fC=`${cC}.2`,pC=`${cC}.4`,gC=`${cC}.5`,yC=`${cC}.14`,mC=`${cC}.11`,bC=`${cC}.12`,AC=`${cC}.13`,IC=`${cC}.15`,vC=`${cC}.16`,wC="1.3.14.3.2.26",SC="2.16.840.1.101.3.4.2.4",EC="2.16.840.1.101.3.4.2.1",CC="2.16.840.1.101.3.4.2.2",kC="2.16.840.1.101.3.4.2.3",xC=`${cC}.8`;function _C(e){return new eS({algorithm:e,parameters:null})}_C("1.2.840.113549.2.2"),_C("1.2.840.113549.2.5");const BC=_C(wC),RC=(_C(SC),_C(EC),_C(CC),_C(kC),_C("2.16.840.1.101.3.4.2.5"),_C("2.16.840.1.101.3.4.2.6"),new eS({algorithm:xC,parameters:Xm.serialize(BC)})),OC=new eS({algorithm:uC,parameters:Xm.serialize(Sm.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});_C(lC),_C(fC),_C(pC),_C(gC),_C(IC),_C(vC),_C(bC),_C(AC),_C(IC),_C(vC);class UC{constructor(e={}){this.hashAlgorithm=new eS(BC),this.maskGenAlgorithm=new eS({algorithm:xC,parameters:Xm.serialize(BC)}),this.pSourceAlgorithm=new eS(OC),Object.assign(this,e)}}Zm([qm({type:eS,context:0,defaultValue:BC})],UC.prototype,"hashAlgorithm",void 0),Zm([qm({type:eS,context:1,defaultValue:RC})],UC.prototype,"maskGenAlgorithm",void 0),Zm([qm({type:eS,context:2,defaultValue:OC})],UC.prototype,"pSourceAlgorithm",void 0),new eS({algorithm:hC,parameters:Xm.serialize(new UC)});class TC{constructor(e={}){this.hashAlgorithm=new eS(BC),this.maskGenAlgorithm=new eS({algorithm:xC,parameters:Xm.serialize(BC)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}Zm([qm({type:eS,context:0,defaultValue:BC})],TC.prototype,"hashAlgorithm",void 0),Zm([qm({type:eS,context:1,defaultValue:RC})],TC.prototype,"maskGenAlgorithm",void 0),Zm([qm({type:oy.Integer,context:2,defaultValue:20})],TC.prototype,"saltLength",void 0),Zm([qm({type:oy.Integer,context:3,defaultValue:1})],TC.prototype,"trailerField",void 0),new eS({algorithm:dC,parameters:Xm.serialize(new TC)});class NC{constructor(e={}){this.digestAlgorithm=new eS,this.digest=new gm,Object.assign(this,e)}}var DC;Zm([qm({type:eS})],NC.prototype,"digestAlgorithm",void 0),Zm([qm({type:gm})],NC.prototype,"digest",void 0);class MC{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.Integer,converter:Am})],MC.prototype,"prime",void 0),Zm([qm({type:oy.Integer,converter:Am})],MC.prototype,"exponent",void 0),Zm([qm({type:oy.Integer,converter:Am})],MC.prototype,"coefficient",void 0);let PC=DC=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,DC.prototype)}};PC=DC=Zm([Gm({type:ny.Sequence,itemType:MC})],PC);class LC{constructor(e={}){this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.Integer})],LC.prototype,"version",void 0),Zm([qm({type:oy.Integer,converter:Am})],LC.prototype,"modulus",void 0),Zm([qm({type:oy.Integer,converter:Am})],LC.prototype,"publicExponent",void 0),Zm([qm({type:oy.Integer,converter:Am})],LC.prototype,"privateExponent",void 0),Zm([qm({type:oy.Integer,converter:Am})],LC.prototype,"prime1",void 0),Zm([qm({type:oy.Integer,converter:Am})],LC.prototype,"prime2",void 0),Zm([qm({type:oy.Integer,converter:Am})],LC.prototype,"exponent1",void 0),Zm([qm({type:oy.Integer,converter:Am})],LC.prototype,"exponent2",void 0),Zm([qm({type:oy.Integer,converter:Am})],LC.prototype,"coefficient",void 0),Zm([qm({type:PC,optional:!0})],LC.prototype,"otherPrimeInfos",void 0);class HC{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}var KC;Zm([qm({type:oy.Integer,converter:Am})],HC.prototype,"modulus",void 0),Zm([qm({type:oy.Integer,converter:Am})],HC.prototype,"publicExponent",void 0),function(e){e[e.Transient=0]="Transient",e[e.Singleton=1]="Singleton",e[e.ResolutionScoped=2]="ResolutionScoped",e[e.ContainerScoped=3]="ContainerScoped"}(KC||(KC={}));const QC=KC;var VC=function(e,t){return VC=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},VC(e,t)};function FC(e,t){function r(){this.constructor=e}VC(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function $C(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],s=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function jC(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var s,i,n=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(e){i={error:e}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return o}function GC(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(jC(arguments[t]));return e}function qC(e){return!!e.useClass}function zC(e){return!!e.useFactory}var WC=function(){function e(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return e.prototype.createProxy=function(e){var t,r=this,s=!1;return new Proxy({},this.createHandler(function(){return s||(t=e(r.wrap()),s=!0),t}))},e.prototype.createHandler=function(e){var t={};return this.reflectMethods.forEach(function(r){t[r]=function(){for(var t=[],s=0;s<arguments.length;s++)t[s]=arguments[s];return t[0]=e(),Reflect[r].apply(void 0,GC(t))}}),t},e}();function JC(e){return"string"==typeof e||"symbol"==typeof e}function YC(e){return"object"==typeof e&&"token"in e&&"transform"in e}function XC(e){return!!e.useToken}function ZC(e){return null!=e.useValue}var ek=function(){function e(){this._registryMap=new Map}return e.prototype.entries=function(){return this._registryMap.entries()},e.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},e.prototype.get=function(e){this.ensure(e);var t=this._registryMap.get(e);return t[t.length-1]||null},e.prototype.set=function(e,t){this.ensure(e),this._registryMap.get(e).push(t)},e.prototype.setAll=function(e,t){this._registryMap.set(e,t)},e.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},e.prototype.clear=function(){this._registryMap.clear()},e.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},e}();const tk=ek,rk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return FC(t,e),t}(tk),sk=function(){this.scopedResolutions=new Map};var ik=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return FC(t,e),t}(tk),nk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return FC(t,e),t}(tk);const ok=function(){this.preResolution=new ik,this.postResolution=new nk};var ak=new Map,ck=function(){function e(e){this.parent=e,this._registry=new rk,this.interceptors=new ok,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var s;if(void 0===r&&(r={lifecycle:QC.Transient}),this.ensureNotDisposed(),s=function(e){return qC(e)||ZC(e)||XC(e)||zC(e)}(t)?t:{useClass:t},XC(s))for(var i=[e],n=s;null!=n;){var o=n.useToken;if(i.includes(o))throw new Error("Token registration cycle detected! "+GC(i,[o]).join(" -> "));i.push(o);var a=this._registry.get(o);n=a&&XC(a.provider)?a.provider:null}if((r.lifecycle===QC.Singleton||r.lifecycle==QC.ContainerScoped||r.lifecycle==QC.ResolutionScoped)&&(ZC(s)||zC(s)))throw new Error('Cannot use lifecycle "'+QC[r.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:s,options:r}),this},e.prototype.registerType=function(e,t){return this.ensureNotDisposed(),JC(t)?this.register(e,{useToken:t}):this.register(e,{useClass:t})},e.prototype.registerInstance=function(e,t){return this.ensureNotDisposed(),this.register(e,{useValue:t})},e.prototype.registerSingleton=function(e,t){if(this.ensureNotDisposed(),JC(e)){if(JC(t))return this.register(e,{useToken:t},{lifecycle:QC.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:QC.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!JC(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:QC.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new sk),void 0===r&&(r=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&JC(e)){if(r)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),s){var i=this.resolveRegistration(s,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(function(e){return"function"==typeof e||e instanceof WC}(e))return i=this.construct(e,t),this.executePostResolutionInterceptor(e,i,"Single"),i;throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},e.prototype.executePreResolutionInterceptor=function(e,t){var r,s;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var n=$C(this.interceptors.preResolution.getAll(e)),o=n.next();!o.done;o=n.next()){var a=o.value;"Once"!=a.options.frequency&&i.push(a),a.callback(e,t)}}catch(e){r={error:e}}finally{try{o&&!o.done&&(s=n.return)&&s.call(n)}finally{if(r)throw r.error}}this.interceptors.preResolution.setAll(e,i)}},e.prototype.executePostResolutionInterceptor=function(e,t,r){var s,i;if(this.interceptors.postResolution.has(e)){var n=[];try{for(var o=$C(this.interceptors.postResolution.getAll(e)),a=o.next();!a.done;a=o.next()){var c=a.value;"Once"!=c.options.frequency&&n.push(c),c.callback(e,t,r)}}catch(e){s={error:e}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(s)throw s.error}}this.interceptors.postResolution.setAll(e,n)}},e.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===QC.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,s=e.options.lifecycle===QC.Singleton,i=e.options.lifecycle===QC.ContainerScoped,n=s||i;return r=ZC(e.provider)?e.provider.useValue:XC(e.provider)?n?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):qC(e.provider)?n?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):zC(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===QC.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var s=this;void 0===t&&(t=new sk),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&JC(e)){if(r)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),i){var n=i.map(function(e){return s.resolveRegistration(e,t)});return this.executePostResolutionInterceptor(e,n,"All"),n}var o=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,o,"All"),o},e.prototype.isRegistered=function(e,t){return void 0===t&&(t=!1),this.ensureNotDisposed(),this._registry.has(e)||t&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},e.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},e.prototype.clearInstances=function(){var e,t;this.ensureNotDisposed();try{for(var r=$C(this._registry.entries()),s=r.next();!s.done;s=r.next()){var i=jC(s.value,2),n=i[0],o=i[1];this._registry.setAll(n,o.filter(function(e){return!ZC(e.provider)}).map(function(e){return e.instance=void 0,e}))}}catch(t){e={error:t}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}},e.prototype.createChildContainer=function(){var t,r;this.ensureNotDisposed();var s=new e(this);try{for(var i=$C(this._registry.entries()),n=i.next();!n.done;n=i.next()){var o=jC(n.value,2),a=o[0],c=o[1];c.some(function(e){return e.options.lifecycle===QC.ContainerScoped})&&s._registry.setAll(a,c.map(function(e){return e.options.lifecycle===QC.ContainerScoped?{provider:e.provider,options:e.options}:e}))}}catch(e){t={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return s},e.prototype.beforeResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:t,options:r})},e.prototype.afterResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:t,options:r})},e.prototype.dispose=function(){return function(e,t,r,s){return new(r||(r=Promise))(function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((s=s.apply(e,t||[])).next())})}(this,void 0,void 0,function(){var e;return function(e,t){var r,s,i,n,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return n={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function a(n){return function(a){return function(n){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,s&&(i=2&n[0]?s.return:n[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,n[1])).done)return i;switch(s=0,i&&(n=[2&n[0],i.value]),n[0]){case 0:case 1:i=n;break;case 4:return o.label++,{value:n[1],done:!1};case 5:o.label++,s=n[1],n=[0];continue;case 7:n=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==n[0]&&2!==n[0])){o=0;continue}if(3===n[0]&&(!i||n[1]>i[0]&&n[1]<i[3])){o.label=n[1];break}if(6===n[0]&&o.label<i[1]){o.label=i[1],i=n;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(n);break}i[2]&&o.ops.pop(),o.trys.pop();continue}n=t.call(e,o)}catch(e){n=[6,e],s=0}finally{r=i=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,a])}}}(this,function(t){switch(t.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(t){var r=t.dispose();r&&e.push(r)}),[4,Promise.all(e)];case 1:return t.sent(),[2]}})})},e.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},e.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},e.prototype.construct=function(e,t){var r=this;if(e instanceof WC)return e.createProxy(function(e){return r.resolve(e,t)});var s,i=function(){var s=ak.get(e);if(!s||0===s.length){if(0===e.length)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var i=s.map(r.resolveParams(t,e));return new(e.bind.apply(e,GC([void 0],i)))}();return"function"!=typeof(s=i).dispose||s.dispose.length>0||this.disposables.add(i),i},e.prototype.resolveParams=function(e,t){var r=this;return function(s,i){var n,o,a,c;try{return"object"==typeof(c=s)&&"token"in c&&"multiple"in c?YC(s)?s.multiple?(n=r.resolve(s.transform)).transform.apply(n,GC([r.resolveAll(s.token,new sk,s.isOptional)],s.transformArgs)):(o=r.resolve(s.transform)).transform.apply(o,GC([r.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?r.resolveAll(s.token,new sk,s.isOptional):r.resolve(s.token,e,s.isOptional):YC(s)?(a=r.resolve(s.transform,e)).transform.apply(a,GC([r.resolve(s.token,e)],s.transformArgs)):r.resolve(s,e)}catch(e){throw new Error(function(e,t,r){var s,i,n=jC(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return function(e,t,r){return void 0===r&&(r=" "),GC([e],t.message.split("\n").map(function(e){return r+e})).join("\n")}("Cannot inject the dependency "+(i=t,(null===(s=void 0===n?null:n)?"at position #"+i:'"'+s.split(",")[i].trim()+'" at position #'+i)+' of "')+e.name+'" constructor. Reason:',r)}(t,i,e))}}},e.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},e}(),lk=new ck;const hk=function(e){return function(t){ak.set(t,function(e){var t=Reflect.getMetadata("design:paramtypes",e)||[],r=Reflect.getOwnMetadata("injectionTokens",e)||{};return Object.keys(r).forEach(function(e){t[+e]=r[e]}),t}(t)),e&&e.token&&(Array.isArray(e.token)?e.token.forEach(function(e){lk.register(e,t)}):lk.register(e.token,t))}};if("undefined"==typeof Reflect||!Reflect.getMetadata)throw new Error("tsyringe requires a reflect polyfill. Please add 'import \"reflect-metadata\"' to the top of your entry point.");var uk;class dk{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}}Zm([qm({type:oy.ObjectIdentifier})],dk.prototype,"attrId",void 0),Zm([qm({type:oy.Any,repeated:"set"})],dk.prototype,"attrValues",void 0);let fk=uk=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,uk.prototype)}};var pk;fk=uk=Zm([Gm({type:ny.Sequence,itemType:dk})],fk);let gk=pk=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,pk.prototype)}};gk=pk=Zm([Gm({type:ny.Sequence,itemType:oE})],gk);class yk{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],yk.prototype,"certId",void 0),Zm([qm({type:oy.Any,context:0})],yk.prototype,"certValue",void 0);class mk{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],mk.prototype,"crlId",void 0),Zm([qm({type:oy.Any,context:0})],mk.prototype,"crltValue",void 0);class bk extends gm{}class Ak{constructor(e={}){this.encryptionAlgorithm=new eS,this.encryptedData=new bk,Object.assign(this,e)}}var Ik,vk;Zm([qm({type:eS})],Ak.prototype,"encryptionAlgorithm",void 0),Zm([qm({type:bk})],Ak.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(vk||(vk={}));class wk extends gm{}let Sk=Ik=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Ik.prototype)}};Sk=Ik=Zm([Gm({type:ny.Sequence,itemType:Fw})],Sk);class Ek{constructor(e={}){this.version=vk.v1,this.privateKeyAlgorithm=new eS,this.privateKey=new wk,Object.assign(this,e)}}Zm([qm({type:oy.Integer})],Ek.prototype,"version",void 0),Zm([qm({type:eS})],Ek.prototype,"privateKeyAlgorithm",void 0),Zm([qm({type:wk})],Ek.prototype,"privateKey",void 0),Zm([qm({type:Sk,implicit:!0,context:0,optional:!0})],Ek.prototype,"attributes",void 0);let Ck=class extends Ek{};Ck=Zm([Gm({type:ny.Sequence})],Ck);let kk=class extends Ak{};kk=Zm([Gm({type:ny.Sequence})],kk);class xk{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],xk.prototype,"secretTypeId",void 0),Zm([qm({type:oy.Any,context:0})],xk.prototype,"secretValue",void 0);class _k{constructor(e={}){this.mac=new NC,this.macSalt=new gm,this.iterations=1,Object.assign(this,e)}}Zm([qm({type:NC})],_k.prototype,"mac",void 0),Zm([qm({type:gm})],_k.prototype,"macSalt",void 0),Zm([qm({type:oy.Integer,defaultValue:1})],_k.prototype,"iterations",void 0);class Bk{constructor(e={}){this.version=3,this.authSafe=new oE,this.macData=new _k,Object.assign(this,e)}}var Rk;Zm([qm({type:oy.Integer})],Bk.prototype,"version",void 0),Zm([qm({type:oE})],Bk.prototype,"authSafe",void 0),Zm([qm({type:_k,optional:!0})],Bk.prototype,"macData",void 0);class Ok{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:oy.ObjectIdentifier})],Ok.prototype,"bagId",void 0),Zm([qm({type:oy.Any,context:0})],Ok.prototype,"bagValue",void 0),Zm([qm({type:dk,repeated:"set",optional:!0})],Ok.prototype,"bagAttributes",void 0);let Uk=Rk=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Rk.prototype)}};var Tk,Nk,Dk;Uk=Rk=Zm([Gm({type:ny.Sequence,itemType:Ok})],Uk);const Mk="1.2.840.113549.1.9",Pk=`${Mk}.7`,Lk=`${Mk}.14`;let Hk=class extends yv{constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};Zm([qm({type:oy.IA5String})],Hk.prototype,"ia5String",void 0),Hk=Zm([Gm({type:ny.Choice})],Hk);let Kk=class extends oE{};Kk=Zm([Gm({type:ny.Sequence})],Kk);let Qk=class extends Bk{};Qk=Zm([Gm({type:ny.Sequence})],Qk);let Vk=class extends Ak{};Vk=Zm([Gm({type:ny.Sequence})],Vk);let Fk=class{constructor(e=""){this.value=e}toString(){return this.value}};Zm([qm({type:oy.IA5String})],Fk.prototype,"value",void 0),Fk=Zm([Gm({type:ny.Choice})],Fk);let $k=class extends Hk{};$k=Zm([Gm({type:ny.Choice})],$k);let jk=class extends yv{};jk=Zm([Gm({type:ny.Choice})],jk);let Gk=class{constructor(e=new Date){this.value=e}};Zm([qm({type:oy.GeneralizedTime})],Gk.prototype,"value",void 0),Gk=Zm([Gm({type:ny.Choice})],Gk);let qk=class extends yv{};qk=Zm([Gm({type:ny.Choice})],qk);let zk=class{constructor(e="M"){this.value=e}toString(){return this.value}};Zm([qm({type:oy.PrintableString})],zk.prototype,"value",void 0),zk=Zm([Gm({type:ny.Choice})],zk);let Wk=class{constructor(e=""){this.value=e}toString(){return this.value}};Zm([qm({type:oy.PrintableString})],Wk.prototype,"value",void 0),Wk=Zm([Gm({type:ny.Choice})],Wk);let Jk=class extends Wk{};Jk=Zm([Gm({type:ny.Choice})],Jk);let Yk=class extends yv{};Yk=Zm([Gm({type:ny.Choice})],Yk);let Xk=class{constructor(e=""){this.value=e}toString(){return this.value}};Zm([qm({type:oy.ObjectIdentifier})],Xk.prototype,"value",void 0),Xk=Zm([Gm({type:ny.Choice})],Xk);let Zk=class extends rS{};Zk=Zm([Gm({type:ny.Choice})],Zk);let ex=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};Zm([qm({type:oy.Integer})],ex.prototype,"value",void 0),ex=Zm([Gm({type:ny.Choice})],ex);let tx=class extends ES{};tx=Zm([Gm({type:ny.Sequence})],tx);let rx=class extends yv{};rx=Zm([Gm({type:ny.Choice})],rx);let sx=Tk=class extends oS{constructor(e){super(e),Object.setPrototypeOf(this,Tk.prototype)}};sx=Tk=Zm([Gm({type:ny.Sequence})],sx);let ix=Nk=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Nk.prototype)}};ix=Nk=Zm([Gm({type:ny.Set,itemType:wS})],ix);let nx=class{constructor(e=""){this.value=e}toString(){return this.value}};Zm([qm({type:oy.BmpString})],nx.prototype,"value",void 0),nx=Zm([Gm({type:ny.Choice})],nx);let ox=class extends eS{};ox=Zm([Gm({type:ny.Sequence})],ox);let ax=Dk=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,Dk.prototype)}};var cx;ax=Dk=Zm([Gm({type:ny.Sequence,itemType:ox})],ax);let lx=cx=class extends Ym{constructor(e){super(e),Object.setPrototypeOf(this,cx.prototype)}};lx=cx=Zm([Gm({type:ny.Sequence,itemType:Fw})],lx);class hx{constructor(e={}){this.version=0,this.subject=new vv,this.subjectPKInfo=new tS,this.attributes=new lx,Object.assign(this,e)}}Zm([qm({type:oy.Integer})],hx.prototype,"version",void 0),Zm([qm({type:vv})],hx.prototype,"subject",void 0),Zm([qm({type:tS})],hx.prototype,"subjectPKInfo",void 0),Zm([qm({type:lx,implicit:!0,context:0})],hx.prototype,"attributes",void 0);class ux{constructor(e={}){this.certificationRequestInfo=new hx,this.signatureAlgorithm=new eS,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Zm([qm({type:hx})],ux.prototype,"certificationRequestInfo",void 0),Zm([qm({type:eS})],ux.prototype,"signatureAlgorithm",void 0),Zm([qm({type:oy.BitString})],ux.prototype,"signature",void 0);const dx="crypto.algorithm",fx="crypto.algorithmProvider";var px;lk.registerSingleton(fx,class{getAlgorithms(){return lk.resolveAll(dx)}toAsnAlgorithm(e){for(const t of this.getAlgorithms()){const r=t.toAsnAlgorithm(e);if(r)return r}if(/^[0-9.]+$/.test(e.name)){const t=new eS({algorithm:e.name});if("parameters"in e){const r=e;t.parameters=r.parameters}return t}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(const t of this.getAlgorithms()){const r=t.toWebAlgorithm(e);if(r)return r}return{name:e.algorithm,parameters:e.parameters}}});const gx="1.3.36.3.3.2.8.1.1",yx=`${gx}.1`,mx=`${gx}.2`,bx=`${gx}.3`,Ax=`${gx}.4`,Ix=`${gx}.5`,vx=`${gx}.6`,wx=`${gx}.7`,Sx=`${gx}.8`,Ex=`${gx}.9`,Cx=`${gx}.10`,kx=`${gx}.11`,xx=`${gx}.12`,_x=`${gx}.13`,Bx=`${gx}.14`,Rx="brainpoolP160r1",Ox="brainpoolP160t1",Ux="brainpoolP192r1",Tx="brainpoolP192t1",Nx="brainpoolP224r1",Dx="brainpoolP224t1",Mx="brainpoolP256r1",Px="brainpoolP256t1",Lx="brainpoolP320r1",Hx="brainpoolP320t1",Kx="brainpoolP384r1",Qx="brainpoolP384t1",Vx="brainpoolP512r1",Fx="brainpoolP512t1",$x="ECDSA";let jx=px=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===$x.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return YE;case"sha-256":return XE;case"sha-384":return ZE;case"sha-512":return eC}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=qE;break;case"K-256":t=px.SECP256K1;break;case"P-384":t=zE;break;case"P-521":t=WE;break;case Rx:t=yx;break;case Ox:t=mx;break;case Ux:t=bx;break;case Tx:t=Ax;break;case Nx:t=Ix;break;case Dx:t=vx;break;case Mx:t=wx;break;case Px:t=Sx;break;case Lx:t=Ex;break;case Hx:t=Cx;break;case Kx:t=kx;break;case Qx:t=xx;break;case Vx:t=_x;break;case Fx:t=Bx}if(t)return new eS({algorithm:QE,parameters:Xm.serialize(new nC({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case VE:return{name:$x,hash:{name:"SHA-1"}};case $E:return{name:$x,hash:{name:"SHA-256"}};case jE:return{name:$x,hash:{name:"SHA-384"}};case GE:return{name:$x,hash:{name:"SHA-512"}};case QE:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Xm.parse(e.parameters,nC).namedCurve){case qE:return{name:$x,namedCurve:"P-256"};case px.SECP256K1:return{name:$x,namedCurve:"K-256"};case zE:return{name:$x,namedCurve:"P-384"};case WE:return{name:$x,namedCurve:"P-521"};case yx:return{name:$x,namedCurve:Rx};case mx:return{name:$x,namedCurve:Ox};case bx:return{name:$x,namedCurve:Ux};case Ax:return{name:$x,namedCurve:Tx};case Ix:return{name:$x,namedCurve:Nx};case vx:return{name:$x,namedCurve:Dx};case wx:return{name:$x,namedCurve:Mx};case Sx:return{name:$x,namedCurve:Px};case Ex:return{name:$x,namedCurve:Lx};case Cx:return{name:$x,namedCurve:Hx};case kx:return{name:$x,namedCurve:Kx};case xx:return{name:$x,namedCurve:Qx};case _x:return{name:$x,namedCurve:Vx};case Bx:return{name:$x,namedCurve:Fx}}}return null}};jx.SECP256K1="1.3.132.0.10",jx=px=Zm([hk()],jx),lk.registerSingleton(dx,jx);const Gx=Symbol("name"),qx=Symbol("value");class zx{constructor(e,t={},r=""){this[Gx]=e,this[qx]=r;for(const e in t)this[e]=t[e]}}zx.NAME=Gx,zx.VALUE=qx;class Wx{static toString(e){return this.items[e]||e}}Wx.items={[wC]:"sha1",[SC]:"sha224",[EC]:"sha256",[CC]:"sha384",[kC]:"sha512",[lC]:"rsaEncryption",[gC]:"sha1WithRSAEncryption",[yC]:"sha224WithRSAEncryption",[mC]:"sha256WithRSAEncryption",[bC]:"sha384WithRSAEncryption",[AC]:"sha512WithRSAEncryption",[QE]:"ecPublicKey",[VE]:"ecdsaWithSHA1",[FE]:"ecdsaWithSHA224",[$E]:"ecdsaWithSHA256",[jE]:"ecdsaWithSHA384",[GE]:"ecdsaWithSHA512",[Aw]:"TLS WWW server authentication",[Iw]:"TLS WWW client authentication",[vw]:"Code Signing",[ww]:"E-mail Protection",[Sw]:"Time Stamping",[Ew]:"OCSP Signing",[PE]:"Signed Data"};class Jx{static serialize(e){return this.serializeObj(e).join("\n")}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,t=0){const r=[];let s=this.pad(t++),i="";const n=e[zx.VALUE];n&&(i=` ${n}`),r.push(`${s}${e[zx.NAME]}:${i}`),s=this.pad(t);for(const i in e){if("symbol"==typeof i)continue;const n=e[i],o=i?`${i}: `:"";if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)r.push(`${s}${o}${n}`);else if(n instanceof Date)r.push(`${s}${o}${n.toUTCString()}`);else if(Array.isArray(n))for(const e of n)e[zx.NAME]=i,r.push(...this.serializeObj(e,t));else if(n instanceof zx)n[zx.NAME]=i,r.push(...this.serializeObj(n,t));else if(Tp.isBufferSource(n))i?(r.push(`${s}${o}`),r.push(...this.serializeBufferSource(n,t+1))):r.push(...this.serializeBufferSource(n,t));else{if(!("toTextObject"in n))throw new TypeError("Cannot serialize data in text format. Unsupported type.");{const e=n.toTextObject();e[zx.NAME]=i,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),s=Tp.toUint8Array(e),i=[];for(let e=0;e<s.length;){const t=[];for(let r=0;r<16&&e<s.length;r++){8===r&&t.push("");const i=s[e++].toString(16).padStart(2,"0");t.push(i)}i.push(`${r}${t.join(" ")}`)}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}Jx.oidSerializer=Wx,Jx.algorithmSerializer=class{static toTextObject(e){const t=new zx("Algorithm Identifier",{},Wx.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case QE:{const r=(new jx).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class Yx{constructor(...e){if(1===e.length){const t=e[0];this.rawData=Xm.serialize(t),this.onInit(t)}else{const t=Xm.parse(e[0],e[1]);this.rawData=Tp.toArrayBuffer(e[0]),this.onInit(t)}}equal(e){return e instanceof Yx&&Vp(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return Xm.toString(this.rawData);case"text":return Jx.serialize(this.toTextObject());case"hex":return Kp.ToHex(this.rawData);case"base64":return Kp.ToBase64(this.rawData);case"base64url":return Kp.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new zx(this.getTextName(),{},e)}}Yx.NAME="ASN";class Xx extends Yx{constructor(...e){let t;t=Tp.isBufferSource(e[0])?Tp.toArrayBuffer(e[0]):Xm.serialize(new nS({extnID:e[0],critical:e[1],extnValue:new gm(Tp.toArrayBuffer(e[2]))})),super(t,nS)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[zx.NAME]===Xx.NAME&&(e[zx.NAME]=Wx.toString(this.type)),e}}var Zx;class e_{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&void 0!==e.extractable}constructor(){this.items=new Map,this[Zx]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(e_.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(e_.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=e_.DEFAULT){const t=this.items.get(e.toLowerCase());if(!t)throw new Error(`Cannot get Crypto by name '${e}'`);return t}set(e,t){if("string"==typeof e){if(!t)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),t)}else this.items.set(e_.DEFAULT,e);return this}}Zx=Symbol.toStringTag,e_.DEFAULT="default";const t_=new e_,r_=/^[0-2](?:\.[1-9][0-9]*)+$/;class s_{constructor(e={}){this.items={};for(const t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return t=e,new RegExp(r_).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const i_=new s_;function n_(e,t){return`\\${Kp.ToHex(Kp.FromUtf8String(t)).toUpperCase()}`}i_.register("CN","2.5.4.3"),i_.register("L","2.5.4.7"),i_.register("ST","2.5.4.8"),i_.register("O","2.5.4.10"),i_.register("OU","2.5.4.11"),i_.register("C","2.5.4.6"),i_.register("DC","0.9.2342.19200300.100.1.25"),i_.register("E","1.2.840.113549.1.9.1"),i_.register("G","2.5.4.42"),i_.register("I","2.5.4.43"),i_.register("SN","2.5.4.4"),i_.register("T","2.5.4.12");class o_{static isASCII(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new s_,this.asn=new vv;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const r=t[e];this.extraNames.register(e,r)}"string"==typeof e?this.asn=this.fromString(e):e instanceof vv?this.asn=e:Tp.isBufferSource(e)?this.asn=Xm.parse(e,vv):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||i_.findId(e),r=[];for(const e of this.asn)for(const s of e)s.type===t&&r.push(s.value.toString());return r}getName(e){return this.extraNames.get(e)||i_.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${Kp.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,n_)}`).join("+")).join(", ")}toJSON(){var e;const t=[];for(const r of this.asn){const s={};for(const t of r){const r=this.getName(t.type)||t.type;null!==(e=s[r])&&void 0!==e||(s[r]=[]),s[r].push(t.value.anyValue?`#${Kp.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(s)}return t}fromString(e){const t=new vv,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let s=null,i=",";for(;s=r.exec(`${e},`);){let[,e,r]=s;const n=r[r.length-1];","!==n&&"+"!==n||(r=r.slice(0,r.length-1),s[3]=n);const o=s[3];e=this.getTypeOid(e);const a=this.createAttribute(e,r);"+"===i?t[t.length-1].push(a):t.push(new Av([a])),i=o}return t}fromJSON(e){const t=new vv;for(const r of e){const e=new Av;for(const t in r){const s=this.getTypeOid(t),i=r[t];for(const t of i){const r=this.createAttribute(s,t);e.push(r)}}t.push(e)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,t){const r=new bv({type:e});if("object"==typeof t)for(const e in t)switch(e){case"ia5String":r.value.ia5String=t[e];break;case"utf8String":r.value.utf8String=t[e];break;case"universalString":r.value.universalString=t[e];break;case"bmpString":r.value.bmpString=t[e];break;case"printableString":r.value.printableString=t[e]}else if("#"===t[0])r.value.anyValue=Kp.FromHex(t.slice(1));else{const s=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=s:o_.isPrintableString(s)?r.value.printableString=s:r.value.utf8String=s}return r}processStringValue(e){const t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/gi,"\n").replace(/\\0d/gi,"\r").replace(/\\0g/gi,"\t").replace(/\\(.)/g,"$1")}toArrayBuffer(){return Xm.serialize(this.asn)}async getThumbprint(...e){var t;let r,s="SHA-1";return e.length>=1&&!(null===(t=e[0])||void 0===t?void 0:t.subtle)?(s=e[0]||s,r=e[1]||t_.get()):r=e[0]||t_.get(),await r.subtle.digest(s,this.toArrayBuffer())}}const a_="Cannot initialize GeneralName from ASN.1 data.",c_=`${a_} Unsupported string format in use.`,l_=`${a_} Value doesn't match to GUID regular expression.`,h_=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,u_="1.3.6.1.4.1.311.25.1",d_="1.3.6.1.4.1.311.20.2.3",f_="dns",p_="dn",g_="email",y_="ip",m_="url",b_="guid",A_="upn",I_="id";class v_ extends Yx{constructor(...e){let t;if(2===e.length)switch(e[0]){case p_:{const r=new o_(e[1]).toArrayBuffer(),s=Xm.parse(r,vv);t=new Cv({directoryName:s});break}case f_:t=new Cv({dNSName:e[1]});break;case g_:t=new Cv({rfc822Name:e[1]});break;case b_:{const r=new RegExp(h_,"i").exec(e[1]);if(!r)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const s=r.slice(1).map((e,t)=>t<3?Kp.ToHex(new Uint8Array(Kp.FromHex(e)).reverse()):e).join("");t=new Cv({otherName:new Sv({typeId:u_,value:Xm.serialize(new gm(Kp.FromHex(s)))})});break}case y_:t=new Cv({iPAddress:e[1]});break;case I_:t=new Cv({registeredID:e[1]});break;case A_:t=new Cv({otherName:new Sv({typeId:d_,value:Xm.serialize(km.toASN(e[1]))})});break;case m_:t=new Cv({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=Tp.isBufferSource(e[0])?Xm.parse(e[0],Cv):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=f_,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=g_,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=y_,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=m_,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=I_,this.value=e.registeredID;else if(null!=e.directoryName)this.type=p_,this.value=new o_(e.directoryName).toString();else{if(null==e.otherName)throw new Error(c_);if(e.otherName.typeId===u_){this.type=b_;const t=Xm.parse(e.otherName.value,gm),r=new RegExp(h_,"i").exec(Kp.ToHex(t));if(!r)throw new Error(l_);this.value=r.slice(1).map((e,t)=>t<3?Kp.ToHex(new Uint8Array(Kp.FromHex(e)).reverse()):e).join("-")}else{if(e.otherName.typeId!==d_)throw new Error(c_);this.type=A_,this.value=Xm.parse(e.otherName.value,yv).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case p_:case f_:case b_:case y_:case I_:case A_:case m_:e=this.type.toUpperCase();break;case g_:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===I_&&(t=Wx.toString(t)),new zx(e,void 0,t)}}class w_ extends Yx{constructor(e){let t;if(e instanceof $v)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof Cv)r.push(t);else{const e=Xm.parse(new v_(t.type,t.value).rawData,Cv);r.push(e)}t=new $v(r)}else{if(!Tp.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=Xm.parse(e,$v)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new v_(r)}catch{continue}t.push(e)}this.items=t}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){const e=super.toTextObjectEmpty();for(const t of this.items){const r=t.toTextObject();let s=e[r[zx.NAME]];Array.isArray(s)||(s=[],e[r[zx.NAME]]=s),s.push(r)}return e}}w_.NAME="GeneralNames";const S_="-{5}",E_="\\n",C_="\\n",k_=`${S_}BEGIN ([^${E_}]+(?=${S_}))${S_}${C_}(?:((?:[^:${E_}]+: (?:[^${E_}]+${C_}(?: +[^${E_}]+${C_})*))+))?${C_}?((?:[a-zA-Z0-9=+/]+${C_})+)${S_}END \\1${S_}`;class x_{static isPem(e){return"string"==typeof e&&new RegExp(k_,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(k_,"g"),r=[];let s=null;for(;s=t.exec(e);){const e=s[3].replace(new RegExp(`[${E_}]+`,"g"),""),t={type:s[1],headers:[],rawData:Kp.FromBase64(e)},i=s[2];if(i){const e=i.split(new RegExp(C_,"g"));let r=null;for(const s of e){const[e,i]=s.split(/:(.*)/);if(void 0===i){if(!r)throw new Error("Cannot parse PEM string. Incorrect header value");r.value+=e.trim()}else r&&t.headers.push(r),r={key:e,value:i.trim()}}r&&t.headers.push(r)}r.push(t)}return r}static decode(e){return this.decodeWithHeaders(e).map(e=>e.rawData)}static decodeFirst(e){const t=this.decode(e);if(!t.length)throw new RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){const r=new Array;return t?e.forEach(e=>{if(!Tp.isBufferSource(e))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:t,rawData:Tp.toArrayBuffer(e)}))}):e.forEach(e=>{if(!("type"in e))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(e))}),r.join("\n")}if(!t)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:Tp.toArrayBuffer(e)})}static encodeStruct(e){var t;const r=e.type.toLocaleUpperCase(),s=[];if(s.push(`-----BEGIN ${r}-----`),null===(t=e.headers)||void 0===t?void 0:t.length){for(const t of e.headers)s.push(`${t.key}: ${t.value}`);s.push("")}const i=Kp.ToBase64(e.rawData);let n,o=0;const a=Array();for(;o<i.length&&(i.length-o<64?n=i.substring(o):(n=i.substring(o,o+64),o+=64),0!==n.length)&&(a.push(n),!(n.length<64)););return s.push(...a),s.push(`-----END ${r}-----`),s.join("\n")}}x_.CertificateTag="CERTIFICATE",x_.CrlTag="CRL",x_.CertificateRequestTag="CERTIFICATE REQUEST",x_.PublicKeyTag="PUBLIC KEY",x_.PrivateKeyTag="PRIVATE KEY";class __ extends Yx{static isAsnEncoded(e){return Tp.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(x_.isPem(e))return x_.decode(e)[0];if(Kp.isHex(e))return Kp.FromHex(e);if(Kp.isBase64(e))return Kp.FromBase64(e);if(Kp.isBase64Url(e))return Kp.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=Kp.ToBinary(e);return x_.isPem(t)?x_.decode(t)[0]:Kp.isHex(t)?Kp.FromHex(t):Kp.isBase64(t)?Kp.FromBase64(t):Kp.isBase64Url(t)?Kp.FromBase64Url(t):Tp.toArrayBuffer(e)}}constructor(...e){__.isAsnEncoded(e[0])?super(__.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?x_.encode(this.rawData,this.tag):super.toString(e)}}class B_ extends __{static async create(e,t=t_.get()){if(e instanceof B_)return e;if(e_.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new B_(r)}if(e.publicKey)return e.publicKey;if(Tp.isBufferSource(e))return new B_(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){__.isAsnEncoded(e)?super(e,tS):super(e),this.tag=x_.PublicKeyTag}async export(...e){let t,r=["verify"],s={hash:"SHA-256",...this.algorithm};e.length>1?(s=e[0]||s,r=e[1]||r,t=e[2]||t_.get()):t=e[0]||t_.get();let i=this.rawData;const n=Xm.parse(this.rawData,tS);return n.algorithm.algorithm===dC&&(i=function(e){return e.algorithm=new eS({algorithm:lC,parameters:null}),Xm.serialize(e)}(n)),t.subtle.importKey("spki",i,s,!0,r)}onInit(e){const t=lk.resolve(fx),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case lC:{const t=Xm.parse(e.subjectPublicKey,HC),s=Tp.toUint8Array(t.modulus);r.publicExponent=Tp.toUint8Array(t.publicExponent),r.modulusLength=(s[0]?s:s.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){var t;let r,s="SHA-1";return e.length>=1&&!(null===(t=e[0])||void 0===t?void 0:t.subtle)?(s=e[0]||s,r=e[1]||t_.get()):r=e[0]||t_.get(),await r.subtle.digest(s,this.rawData)}async getKeyIdentifier(...e){let t,r="SHA-1";1===e.length?"string"==typeof e[0]?(r=e[0],t=t_.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=t_.get();const s=Xm.parse(this.rawData,tS);return await t.subtle.digest(r,s.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=Xm.parse(this.rawData,tS);return e.Algorithm=Jx.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===QE?e["EC Point"]=t.subjectPublicKey:e["Raw Data"]=t.subjectPublicKey,e}}class R_ extends Xx{static async create(e,t=!1,r=t_.get()){if("name"in e&&"serialNumber"in e)return new R_(e,t);const s=await B_.create(e,r),i=await s.getKeyIdentifier(r);return new R_(Kp.ToHex(i),t)}constructor(...e){if(Tp.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new Kv({keyIdentifier:new Hv(Kp.FromHex(e[0]))});super(Lv,e[1],Xm.serialize(t))}else{const t=e[0],r=t.name instanceof w_?Xm.parse(t.name.rawData,$v):t.name,s=new Kv({authorityCertIssuer:r,authorityCertSerialNumber:Kp.FromHex(t.serialNumber)});super(Lv,e[1],Xm.serialize(s))}}onInit(e){super.onInit(e);const t=Xm.parse(e.extnValue,Kv);t.keyIdentifier&&(this.keyId=Kp.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Kp.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Xm.parse(this.value,Kv);return t.authorityCertIssuer&&(e["Authority Issuer"]=new w_(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}R_.NAME="Authority Key Identifier";class O_ extends Xx{constructor(...e){if(Tp.isBufferSource(e[0])){super(e[0]);const t=Xm.parse(this.value,Vv);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new Vv({cA:e[0],pathLenConstraint:e[1]});super(Qv,e[2],Xm.serialize(t)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),void 0!==this.pathLength&&(e["Path Length"]=this.pathLength),e}}var U_,T_;O_.NAME="Basic Constraints",function(e){e.serverAuth="1.3.6.1.5.5.7.3.1",e.clientAuth="1.3.6.1.5.5.7.3.2",e.codeSigning="1.3.6.1.5.5.7.3.3",e.emailProtection="1.3.6.1.5.5.7.3.4",e.timeStamping="1.3.6.1.5.5.7.3.8",e.ocspSigning="1.3.6.1.5.5.7.3.9"}(U_||(U_={}));class N_ extends Xx{constructor(...e){if(Tp.isBufferSource(e[0])){super(e[0]);const t=Xm.parse(this.value,bw);this.usages=t.map(e=>e)}else{const t=new bw(e[0]);super(mw,e[1],Xm.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(e=>Wx.toString(e)).join(", "),e}}N_.NAME="Extended Key Usages",function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(T_||(T_={}));class D_ extends Xx{constructor(...e){if(Tp.isBufferSource(e[0])){super(e[0]);const t=Xm.parse(this.value,Uw);this.usages=t.toNumber()}else{const t=new Uw(e[0]);super(Bw,e[1],Xm.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Xm.parse(this.value,Uw);return e[""]=t.toJSON().join(", "),e}}D_.NAME="Key Usages";class M_ extends Xx{static async create(e,t=!1,r=t_.get()){const s=await B_.create(e,r),i=await s.getKeyIdentifier(r);return new M_(Kp.ToHex(i),t)}constructor(...e){if(Tp.isBufferSource(e[0])){super(e[0]);const t=Xm.parse(this.value,qw);this.keyId=Kp.ToHex(t)}else{const t="string"==typeof e[0]?Kp.FromHex(e[0]):e[0],r=new qw(t);super(Gw,e[1],Xm.serialize(r)),this.keyId=Kp.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Xm.parse(this.value,qw);return e[""]=t,e}}M_.NAME="Subject Key Identifier";class P_ extends Xx{constructor(...e){Tp.isBufferSource(e[0])?super(e[0]):super(Qw,e[1],new w_(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Xm.parse(e.extnValue,Vw);this.names=new w_(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}P_.NAME="Subject Alternative Name";class L_{static register(e,t){this.items.set(e,t)}static create(e){const t=new Xx(e),r=this.items.get(t.type);return r?new r(e):t}}L_.items=new Map;class H_ extends Xx{constructor(...e){var t;if(Tp.isBufferSource(e[0])){super(e[0]);const t=Xm.parse(this.value,tw);this.policies=t.map(e=>e.policyIdentifier)}else{const r=e[0],s=null!==(t=e[1])&&void 0!==t&&t,i=new tw(r.map(e=>new ew({policyIdentifier:e})));super(zv,s,Xm.serialize(i)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new zx("",{},Wx.toString(e))),e}}H_.NAME="Certificate Policies",L_.register(zv,H_);class K_ extends Xx{constructor(...e){var t;if(Tp.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map(e=>new lw({distributionPoint:new cw({fullName:[new Cv({uniformResourceIdentifier:e})]})})),r=new hw(t);super(nw,e[1],Xm.serialize(r))}else{const t=new hw(e[0]);super(nw,e[1],Xm.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=Xm.parse(e.extnValue,hw);this.distributionPoints=t}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(e=>{var t;const r={};return e.distributionPoint&&(r[""]=null===(t=e.distributionPoint.fullName)||void 0===t?void 0:t.map(e=>new v_(e).toString()).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map(e=>e.toString()).join(", ")),r}),e}}K_.NAME="CRL Distribution Points";class Q_ extends Xx{constructor(...e){var t,r,s,i;if(Tp.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Pv){const t=new Pv(e[0]);super(Dv,e[1],Xm.serialize(t))}else{const t=e[0],r=new Pv;F_(r,t,Bv,"ocsp"),F_(r,t,Rv,"caIssuers"),F_(r,t,Ov,"timeStamping"),F_(r,t,Uv,"caRepository"),super(Dv,e[1],Xm.serialize(r))}null!==(t=this.ocsp)&&void 0!==t||(this.ocsp=[]),null!==(r=this.caIssuers)&&void 0!==r||(this.caIssuers=[]),null!==(s=this.timeStamping)&&void 0!==s||(this.timeStamping=[]),null!==(i=this.caRepository)&&void 0!==i||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],Xm.parse(e.extnValue,Pv).forEach(e=>{switch(e.accessMethod){case Bv:this.ocsp.push(new v_(e.accessLocation));break;case Rv:this.caIssuers.push(new v_(e.accessLocation));break;case Ov:this.timeStamping.push(new v_(e.accessLocation));break;case Uv:this.caRepository.push(new v_(e.accessLocation))}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&V_(e,"OCSP",this.ocsp),this.caIssuers.length&&V_(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&V_(e,"Time Stamping",this.timeStamping),this.caRepository.length&&V_(e,"CA Repository",this.caRepository),e}}function V_(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const s=new zx("");r.forEach((e,t)=>{const r=e.toTextObject(),i=`${r[zx.NAME]} ${t+1}`;let n=s[i];Array.isArray(n)||(n=[],s[i]=n),n.push(r)}),e[t]=s}}function F_(e,t,r,s){const i=t[s];i&&(Array.isArray(i)?i:[i]).forEach(t=>{"string"==typeof t&&(t=new v_("url",t)),e.push(new Mv({accessMethod:r,accessLocation:Xm.parse(t.rawData,Cv)}))})}Q_.NAME="Authority Info Access";class $_ extends Yx{constructor(...e){let t;if(Tp.isBufferSource(e[0]))t=Tp.toArrayBuffer(e[0]);else{const r=e[0],s=Array.isArray(e[1])?e[1].map(e=>Tp.toArrayBuffer(e)):[];t=Xm.serialize(new Fw({type:r,values:s}))}super(t,Fw)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new zx("",{"":e})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[zx.NAME]===$_.NAME&&(e[zx.NAME]=Wx.toString(this.type)),e}}$_.NAME="Attribute";class j_ extends $_{constructor(...e){var t;if(Tp.isBufferSource(e[0]))super(e[0]);else{const t=new rx({printableString:e[0]});super(Pk,[Xm.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=Xm.parse(this.values[0],rx);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[zx.VALUE]=this.password,e}}j_.NAME="Challenge Password";class G_ extends $_{constructor(...e){var t;if(Tp.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new oS;for(const e of t)r.push(Xm.parse(e.rawData,nS));super(Lk,[Xm.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=Xm.parse(this.values[0],oS);this.items=e.map(e=>L_.create(Xm.serialize(e)))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(const r of t)e[r[zx.NAME]]=r;return e}}G_.NAME="Extensions";class q_{static register(e,t){this.items.set(e,t)}static create(e){const t=new $_(e),r=this.items.get(t.type);return r?new r(e):t}}q_.items=new Map;const z_="crypto.signatureFormatter";var W_;let J_=W_=class{static createPssParams(e,t){const r=W_.getHashAlgorithm(e);return r?new TC({hashAlgorithm:r,maskGenAlgorithm:new eS({algorithm:xC,parameters:Xm.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=lk.resolve(fx);return"string"==typeof e?t.toAsnAlgorithm({name:e}):"object"==typeof e&&e&&"name"in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if(!("hash"in e))return new eS({algorithm:lC,parameters:null});{let t;if("string"==typeof e.hash)t=e.hash;else{if(!e.hash||"object"!=typeof e.hash||!("name"in e.hash)||"string"!=typeof e.hash.name)throw new Error("Cannot get hash algorithm name");t=e.hash.name.toUpperCase()}switch(t.toLowerCase()){case"sha-1":return new eS({algorithm:gC,parameters:null});case"sha-256":return new eS({algorithm:mC,parameters:null});case"sha-384":return new eS({algorithm:bC,parameters:null});case"sha-512":return new eS({algorithm:AC,parameters:null})}}break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e)||"number"!=typeof e.saltLength)throw new Error("Cannot get 'saltLength' from 'alg' argument");const t=W_.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new eS({algorithm:dC,parameters:Xm.serialize(t)})}return new eS({algorithm:dC,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case lC:return{name:"RSASSA-PKCS1-v1_5"};case gC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case mC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case bC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case AC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case dC:if(e.parameters){const t=Xm.parse(e.parameters,TC);return{name:"RSA-PSS",hash:lk.resolve(fx).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};J_=W_=Zm([hk()],J_),lk.registerSingleton(dx,J_);let Y_=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new eS({algorithm:wC});case"sha-256":return new eS({algorithm:EC});case"sha-384":return new eS({algorithm:CC});case"sha-512":return new eS({algorithm:kC})}return null}toWebAlgorithm(e){switch(e.algorithm){case wC:return{name:"SHA-1"};case EC:return{name:"SHA-256"};case CC:return{name:"SHA-384"};case kC:return{name:"SHA-512"}}return null}};Y_=Zm([hk()],Y_),lk.registerSingleton(dx,Y_);class X_{addPadding(e,t){const r=Tp.toUint8Array(t),s=new Uint8Array(e);return s.set(r,e-r.length),s}removePadding(e,t=!1){let r=Tp.toUint8Array(e);for(let e=0;e<r.length;e++)if(r[e]){r=r.slice(e);break}if(t&&r[0]>127){const e=new Uint8Array(r.length+1);return e.set(r,1),e.buffer}return r.buffer}toAsnSignature(e,t){if("ECDSA"===e.name){const r=e.namedCurve,s=X_.namedCurveSize.get(r)||X_.defaultNamedCurveSize,i=new aC,n=Tp.toUint8Array(t);return i.r=this.removePadding(n.slice(0,s),!0),i.s=this.removePadding(n.slice(s,s+s),!0),Xm.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=Xm.parse(t,aC),s=e.namedCurve,i=X_.namedCurveSize.get(s)||X_.defaultNamedCurveSize;return Qp(this.addPadding(i,this.removePadding(r.r)),this.addPadding(i,this.removePadding(r.s)))}return null}}X_.namedCurveSize=new Map,X_.defaultNamedCurveSize=32;const Z_="1.3.101.110",eB="1.3.101.111",tB="1.3.101.112",rB="1.3.101.113";let sB=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=tB;break;case"x25519":t=Z_;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=tB;break;case"ed448":t=rB}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=Z_;break;case"x448":t=eB}}return t?new eS({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case tB:return{name:"Ed25519"};case rB:return{name:"EdDSA",namedCurve:"Ed448"};case Z_:return{name:"X25519"};case eB:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};sB=Zm([hk()],sB),lk.registerSingleton(dx,sB);(class extends __{constructor(e){__.isAsnEncoded(e)?super(e,ux):super(e),this.tag=x_.CertificateRequestTag}onInit(e){this.tbs=Xm.serialize(e.certificationRequestInfo),this.publicKey=new B_(e.certificationRequestInfo.subjectPKInfo);const t=lk.resolve(fx);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>q_.create(Xm.serialize(e)));const r=this.getAttribute(Lk);this.extensions=[],r instanceof G_&&(this.extensions=r.items),this.subjectName=new o_(e.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(e){for(const t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(const t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=t_.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),s=lk.resolveAll(z_).reverse();let i=null;for(const e of s)if(i=e.toWebSignature(t,this.signature),i)break;if(!i)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,r,i,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty(),t=Xm.parse(this.rawData,ux),r=t.certificationRequestInfo,s=new zx("",{Version:`${aS[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new zx("");for(const t of this.attributes){const r=t.toTextObject();e[r[zx.NAME]]=r}s.Attributes=e}return e.Data=s,e.Signature=new zx("",{Algorithm:Jx.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";var iB;(class extends __{constructor(e){__.isAsnEncoded(e)?super(e,lS):super(e),this.tag=x_.CertificateTag}onInit(e){const t=e.tbsCertificate;this.tbs=Xm.serialize(t),this.serialNumber=Kp.ToHex(t.serialNumber),this.subjectName=new o_(t.subject),this.subject=new o_(t.subject).toString(),this.issuerName=new o_(t.issuer),this.issuer=this.issuerName.toString();const r=lk.resolve(fx);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signatureValue;const s=t.validity.notBefore.utcTime||t.validity.notBefore.generalTime;if(!s)throw new Error("Cannot get 'notBefore' value");this.notBefore=s;const i=t.validity.notAfter.utcTime||t.validity.notAfter.generalTime;if(!i)throw new Error("Cannot get 'notAfter' value");this.notAfter=i,this.extensions=[],t.extensions&&(this.extensions=t.extensions.map(e=>L_.create(Xm.serialize(e)))),this.publicKey=new B_(t.subjectPublicKeyInfo)}getExtension(e){for(const t of this.extensions)if("string"==typeof e){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>"string"==typeof e?t.type===e:t instanceof e)}async verify(e={},t=t_.get()){let r,s;const i=e.publicKey;try{if(i)if("publicKey"in i)r={...i.publicKey.algorithm,...this.signatureAlgorithm},s=await i.publicKey.export(r,["verify"],t);else if(i instanceof B_)r={...i.algorithm,...this.signatureAlgorithm},s=await i.export(r,["verify"],t);else if(Tp.isBufferSource(i)){const e=new B_(i);r={...e.algorithm,...this.signatureAlgorithm},s=await e.export(r,["verify"],t)}else r={...i.algorithm,...this.signatureAlgorithm},s=i;else r={...this.publicKey.algorithm,...this.signatureAlgorithm},s=await this.publicKey.export(r,["verify"],t)}catch(e){return!1}const n=lk.resolveAll(z_).reverse();let o=null;for(const e of n)if(o=e.toWebSignature(r,this.signature),o)break;if(!o)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const a=await t.subtle.verify(this.signatureAlgorithm,s,o,this.tbs);if(e.signatureOnly)return a;{const t=(e.date||new Date).getTime();return a&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t,r="SHA-1";return e[0]&&(e[0].subtle?t=e[0]:(r=e[0]||r,t=e[1])),null!=t||(t=t_.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=t_.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=Xm.parse(this.rawData,lS),r=t.tbsCertificate,s=new zx("",{Version:`${aS[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":Jx.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new zx("",{"Not Before":r.validity.notBefore.getTime(),"Not After":r.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(r.issuerUniqueID&&(s["Issuer Unique ID"]=r.issuerUniqueID),r.subjectUniqueID&&(s["Subject Unique ID"]=r.subjectUniqueID),this.extensions.length){const e=new zx("");for(const t of this.extensions){const r=t.toTextObject();e[r[zx.NAME]]=r}s.Extensions=e}return e.Data=s,e.Signature=new zx("",{Algorithm:Jx.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}).NAME="Certificate",function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(iB||(iB={})),L_.register(Qv,O_),L_.register(mw,N_),L_.register(Bw,D_),L_.register(Gw,M_),L_.register(Lv,R_),L_.register(Qw,P_),L_.register(nw,K_),L_.register(Dv,Q_),q_.register(Pk,j_),q_.register(Lk,G_),lk.registerSingleton(z_,class{toAsnSignature(e,t){return Tp.toArrayBuffer(t)}toWebSignature(e,t){return Tp.toArrayBuffer(t)}}),lk.registerSingleton(z_,X_),X_.namedCurveSize.set("P-256",32),X_.namedCurveSize.set("K-256",32),X_.namedCurveSize.set("P-384",48),X_.namedCurveSize.set("P-521",66),m.new(void 0,"networking");const nB=new class extends KA{constructor(){super(...arguments),this.subtle=new uv}getRandomValues(e){if(!ArrayBuffer.isView(e))throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'");const t=jA.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return qA().randomFillSync(t),e}};var oB,aB,cB;function lB(e){return he(e)}t_.set(nB),(cB=oB||(oB={}))[cB.NoCertificate=0]="NoCertificate",cB[cB.NotEd25519=1]="NotEd25519",cB[cB.PublicKeyTypeMismatch=2]="PublicKeyTypeMismatch",cB[cB.AltNameMismatch=3]="AltNameMismatch",cB[cB.IncorrectSignature=4]="IncorrectSignature",function(e){e[e.Public=0]="Public",e[e.Private=1]="Private"}(aB||(aB={})),m.new(void 0,"net:peers"),m.new(void 0,"net"),m.new(void 0,"net"),m.new(void 0,"net"),m.new(void 0,"jamnps");const hB=lB(0);class uB extends Q{hash;slot;static Codec=Pe.Class(uB,{hash:Pe.bytes(Ct).asOpaque(),slot:Pe.u32.asOpaque()});static create({hash:e,slot:t}){return new uB(e,t)}constructor(e,t){super(),this.hash=e,this.slot=t}}class dB{final;leafs;static Codec=Pe.Class(dB,{final:uB.Codec,leafs:Pe.sequenceVarLen(uB.Codec)});static create({final:e,leafs:t}){return new dB(e,t)}constructor(e,t){this.final=e,this.leafs=t}}class fB extends Q{header;final;static Codec=Pe.Class(fB,{header:ns.Codec,final:uB.Codec});static create({header:e,final:t}){return new fB(e,t)}constructor(e,t){super(),this.header=e,this.final=t}}const pB=m.new(void 0,"protocol/up-0");class gB{getHandshake;onAnnouncement;kind=hB;handshakes=new Map;pendingHandshakes=new Map;constructor(e,t){this.getHandshake=e,this.onAnnouncement=t}onStreamMessage(e,t){const r=e.streamId;if(!this.handshakes.has(r)){const s=we.decodeObject(dB.Codec,t);return this.handshakes.set(r,s),void(this.pendingHandshakes.delete(r)||(pB.log(`[${r}] <-- responding with a handshake.`),e.bufferAndSend(_e.encodeObject(dB.Codec,this.getHandshake()))))}const s=we.decodeObject(fB.Codec,t);pB.info(`[${r}] got blocks announcement: ${s}`),this.onAnnouncement(s)}onClose(e){this.handshakes.delete(e)}sendHandshake(e,t){this.pendingHandshakes.set(e.streamId,!0),e.bufferAndSend(_e.encodeObject(dB.Codec,t))}sendAnnouncement(e,t){this.handshakes.has(e.streamId)?e.bufferAndSend(_e.encodeObject(fB.Codec,t)):pB.warn(`[${e.streamId}] no handshake yet, skipping announcement.`)}}var yB;lB(128),function(e){e[e.AscExcl=0]="AscExcl",e[e.DescIncl=1]="DescIncl"}(yB||(yB={}));class mB extends Q{headerHash;direction;maxBlocks;static Codec=Pe.Class(mB,{headerHash:Pe.bytes(Ct).asOpaque(),direction:Pe.u8.convert(e=>he(e),e=>{switch(e){case yB.AscExcl:return yB.AscExcl;case yB.DescIncl:return yB.DescIncl;default:throw new Error(`Invalid 'Direction' value: ${e}`)}}),maxBlocks:Pe.u32});static create({headerHash:e,direction:t,maxBlocks:r}){return new mB(e,t,r)}constructor(e,t,r){super(),this.headerHash=e,this.direction=t,this.maxBlocks=r}}m.new(void 0,"protocol/ce-128");const bB=lB(129),AB=Pe.bytes(64).convert(e=>Y.fromBlob(e.raw,64),e=>new ji(e.raw));class IB extends Q{key;value;static Codec=Pe.Class(IB,{key:Pe.bytes(Fi),value:Pe.blob});static create({key:e,value:t}){return new IB(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}class vB extends Q{keyValuePairs;static Codec=Pe.Class(vB,{keyValuePairs:Pe.sequenceVarLen(IB.Codec)});static create({keyValuePairs:e}){return new vB(e)}constructor(e){super(),this.keyValuePairs=e}}class wB extends Q{headerHash;startKey;endKey;maximumSize;static Codec=Pe.Class(wB,{headerHash:Pe.bytes(Ct).asOpaque(),startKey:Pe.bytes(Fi),endKey:Pe.bytes(Fi),maximumSize:Pe.u32});static create({headerHash:e,startKey:t,endKey:r,maximumSize:s}){return new wB(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.startKey=t,this.endKey=r,this.maximumSize=s}}const SB=m.new(void 0,"protocol/ce-129");class EB{isServer;getBoundaryNodes;getKeyValuePairs;kind=bB;boundaryNodes=new Map;onResponse=new Map;constructor(e=!1,t,r){if(this.isServer=e,this.getBoundaryNodes=t,this.getKeyValuePairs=r,e&&(void 0===t||void 0===r))throw new Error("getBoundaryNodes and getKeyValuePairs are required in server mode.")}onStreamMessage(e,t){if(this.isServer){if(SB.info(`[${e.streamId}][server]: Received request.`),void 0===this.getBoundaryNodes||void 0===this.getKeyValuePairs)return;const r=we.decodeObject(wB.Codec,t),s=this.getBoundaryNodes(r.headerHash,r.startKey,r.endKey),i=this.getKeyValuePairs(r.headerHash,r.startKey,r.endKey);return SB.info(`[${e.streamId}][server]: <-- responding with boundary nodes and key value pairs.`),e.bufferAndSend(_e.encodeObject(Pe.sequenceVarLen(AB),s)),e.bufferAndSend(_e.encodeObject(vB.Codec,vB.create({keyValuePairs:i}))),void e.close()}if(!this.boundaryNodes.has(e.streamId))return this.boundaryNodes.set(e.streamId,we.decodeObject(Pe.sequenceVarLen(AB),t)),void SB.info(`[${e.streamId}][client]: Received boundary nodes.`);this.onResponse.get(e.streamId)?.(we.decodeObject(vB.Codec,t)),SB.info(`[${e.streamId}][client]: Received state values.`)}onClose(e){this.boundaryNodes.delete(e),this.onResponse.delete(e)}getStateByKey(e,t,r,s){if(this.onResponse.has(e.streamId))throw new Error("It is disallowed to use the same stream for multiple requests.");this.onResponse.set(e.streamId,s),e.bufferAndSend(_e.encodeObject(wB.Codec,wB.create({headerHash:t,startKey:r,endKey:r,maximumSize:pe(4096)}))),e.close()}}lB(131),lB(132);class CB extends Q{epochIndex;ticket;static Codec=Pe.Class(CB,{epochIndex:Pe.u32.asOpaque(),ticket:Zr.Codec});static create({epochIndex:e,ticket:t}){return new CB(e,t)}constructor(e,t){super(),this.epochIndex=e,this.ticket=t}}m.new(void 0,"protocol/ce-131-ce-132"),lB(133);class kB extends Q{coreIndex;workPackage;static Codec=Pe.Class(kB,{coreIndex:Pe.u16.asOpaque(),workPackage:Rr.Codec});static create({coreIndex:e,workPackage:t}){return new kB(e,t)}constructor(e,t){super(),this.coreIndex=e,this.workPackage=t}}m.new(void 0,"protocol/ce-133"),Pe.blob,lB(134);class xB extends Q{coreIndex;segmentsRootMappings;static Codec=Pe.Class(xB,{coreIndex:Pe.u16.asOpaque(),segmentsRootMappings:Pe.sequenceVarLen(Pr.Codec)});static create({coreIndex:e,segmentsRootMappings:t}){return new xB(e,t)}constructor(e,t){super(),this.coreIndex=e,this.segmentsRootMappings=t}}class _B extends Q{workReportHash;signature;static Codec=Pe.Class(_B,{workReportHash:Pe.bytes(Ct).asOpaque(),signature:Pe.bytes(At).asOpaque()});static create({workReportHash:e,signature:t}){return new _B(e,t)}constructor(e,t){super(),this.workReportHash=e,this.signature=t}}m.new(void 0,"protocol/ce-134"),lB(135);class BB extends Q{report;slot;signatures;static Codec=Pe.Class(BB,{report:Lr.Codec,slot:Pe.u32.asOpaque(),signatures:dr(e=>fr(Kr.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2}))});static create({report:e,slot:t,signatures:r}){return new BB(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.signatures=r}}m.new(void 0,"protocol/ce-135");const RB=t(import.meta.url)("node:net"),OB=t(import.meta.url)("node:path"),UB=t(import.meta.url)("node:buffer");var TB;!function(e){e[e.Msg=0]="Msg",e[e.Open=1]="Open",e[e.Close=2]="Close"}(TB||(TB={}));class NB{streamId;type;data;static Codec=Pe.Class(NB,{streamId:Pe.u32,type:Pe.u8.convert(e=>he(e),e=>{switch(e){case TB.Msg:return TB.Msg;case TB.Open:return TB.Open;case TB.Close:return TB.Close;default:throw new Error(`Invalid 'StreamEnvelopeType' value: ${e}`)}}),data:Pe.blob});static create({streamId:e,type:t,data:r}){return new NB(e,t,r)}constructor(e,t,r){this.streamId=e,this.type=t,this.data=r}}class DB{streamByte;static Codec=Pe.Class(DB,{streamByte:Pe.u8});static create({streamByte:e}){return new DB(e)}constructor(e){this.streamByte=e}}const MB=m.new(void 0,"ext-ipc");class PB{streams=new Map;pendingStreams=new Map;streamHandlers=new Map;onEnd;sender;constructor(e){const t={finished:!1};t.listen=new Promise((e,r)=>{t.resolve=e,t.reject=r}),this.onEnd=t,this.sender=new HB(e)}registerHandlers(...e){for(const t of e)this.streamHandlers.set(t.kind,t)}withStreamOfKind(e,t){for(const[r,s]of this.streams.entries())if(s.kind===e)return void t(s,new LB(r,this.sender));throw new Error(`Missing handler for ${e}!`)}withNewStream(e,t){const r=this.streamHandlers.get(e);if(void 0===r)throw new Error(`Stream with unregistered handler of kind: ${e} was requested to be opened.`);const s=this.streams,i=function e(){const t=Math.floor(65536*Math.random());return s.has(t)?e():t}();this.streams.set(i,r),this.pendingStreams.set(i,!0);const n=new LB(i,this.sender);n.open(DB.create({streamByte:e})),t(r,n)}onSocketMessage(e){const t=we.decodeObject(NB.Codec,e),r=t.streamId;MB.log(`[${r}] incoming message: ${t.type} ${t.data}`);const s=this.streams.get(r),i=new LB(r,this.sender);if(void 0===s){if(t.type!==TB.Open)return void MB.warn(`[${r}] (unknown) got invalid type ${t.type}.`);const e=we.decodeObject(DB.Codec,t.data),s=this.streamHandlers.get(e.streamByte);return void 0!==s?(MB.log(`[${r}] new stream for ${s.kind}`),this.streams.set(r,s),void i.open(e)):void i.close()}if(t.type===TB.Close){const e=this.streams.get(r);return e?.onClose(r,!1),void this.streams.delete(r)}t.type===TB.Msg?s.onStreamMessage(i,t.data):this.pendingStreams.delete(r)||MB.warn(`[${r}] got invalid type ${t.type}.`)}onClose({error:e}){MB.log(`Closing the handler. Reason: ${void 0!==e?e.message:"close"}.`);for(const[t,r]of this.streams.entries())r.onClose(t,void 0===e);this.streams.clear(),this.onEnd.finished=!0,void 0!==e?this.onEnd.reject(e):this.onEnd.resolve()}waitForEnd(){return MB.log("Waiting for the handler to be closed."),this.onEnd.listen}}class LB{streamId;sender;constructor(e,t){this.streamId=e,this.sender=t}open(e){const t=_e.encodeObject(DB.Codec,e);this.sender.send(_e.encodeObject(NB.Codec,NB.create({streamId:this.streamId,type:TB.Open,data:t})))}bufferAndSend(e){return this.sender.send(_e.encodeObject(NB.Codec,NB.create({streamId:this.streamId,type:TB.Msg,data:e}))),!0}close(){this.sender.send(_e.encodeObject(NB.Codec,NB.create({streamId:this.streamId,type:TB.Close,data:J.blobFromNumbers([])})))}}class HB{socket;constructor(e){this.socket=e}send(e){!function(e,t){const r=new Uint8Array(KB);_e.create({destination:r}).i32(t.length),e.write(r),e.write(t)}(this.socket,e.raw)}close(){this.socket.end()}}const KB=4;function QB(e){const t=function(e){const t=new An.EventEmitter;let r=null;return e.bestHeader.on(e=>{const s=e.data.materialize(),i=e.hash,n=uB.create({hash:i,slot:s.timeSlotIndex});r=n,t.emit("announcement",fB.create({header:s,final:n}))}),function(e,t,r,s){const i="win32"===b.platform()?"\\\\.\\pipe\\typeberry":OB.join(b.tmpdir(),"typeberry.ipc"),n=m.new(void 0,"ext-ipc"),o=(0,RB.createServer)(i=>{n.log("Client connected");const o=new PB(i);o.registerHandlers(new gB(t,()=>{})),o.registerHandlers(new EB(!0,r,s));const a=e=>{if(!(e instanceof fB))throw new Error(`Invalid annoncement received: ${e}`);o.withStreamOfKind(hB,(t,r)=>{t.sendAnnouncement(r,e)})};e.on("announcement",a),i.on("data",function(e){let t=UB.Buffer.alloc(0),r=-1;return s=>{t=UB.Buffer.concat([t,s]);do{if(-1===r){if(t.length<KB)break;r=t.readUint32LE(),t=t.subarray(KB)}if(t.length<r)break;const s=t.subarray(0,r);t=t.subarray(r),r=-1,e(s)}while(t.length>0)}}(e=>{try{o.onSocketMessage(new Uint8Array(e))}catch(e){n.error(`Received invalid data on socket: ${e}. Closing connection.`),i.end()}})),i.on("end",()=>{n.log("Client disconnected"),o.onClose({}),e.off("annoucement",a)}),i.on("error",e=>{n.error(`Socket error: ${e}`),o.onClose({error:e}),i.end()})});try{O.unlinkSync(i)}catch{}const a=new AbortController;return o.listen({path:i,signal:a.signal},()=>{n.log(`IPC server is listening at ${i}`)}),o.on("error",e=>{throw e}),()=>{n.info("Closing IPC server."),o.close(),a.abort(),o.unref()}}(t,()=>{const e=r??uB.create({hash:Y.zero(Ct).asOpaque(),slot:Fr(0)});return dB.create({final:e,leafs:[]})},()=>[],(e,t)=>{let r=J.blobFromNumbers([255,255,0,0]);return Y.fromBlob(Dt("0x83bd3bde264a79a2e67c487696c1d7f0b549da89").raw.subarray(0,Fi),Fi).isEqualTo(t)&&(r=J.blobFromNumbers([255,255,255,0])),[new IB(t,r)]})}(e);return()=>{t()}}const VB=e=>e.endsWith(".json");function FB(e,t){const r=U().readFileSync(e),s=J.blobFrom(new Uint8Array(r));return we.decodeObject(us.Codec.View,s,t)}function $B(e,t){const r=U().readFileSync(e,"utf-8"),s=fs(JSON.parse(r),(i=t,gs.object({header:Qs,extrinsic:(n=i,gs.object({tickets:Ms,preimages:Ns,guarantees:Us,assurances:ms(n),disputes:ws},({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})=>hs.create({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})))},({header:e,extrinsic:t})=>us.create({header:e,extrinsic:t}))));var i,n;const o=_e.encodeObject(us.Codec,s,t);return we.decodeObject(us.Codec.View,o,t)}const jB=JSON.parse('{"$schema":"./config-v1.schema.json","version":1,"flavor":"tiny","authorship":{"omit_seal_verification":false},"chain_spec":{"id":"typeberry-dev","bootnodes":["e3r2oc62zwfj3crnuifuvsxvbtlzetk4o5qyhetkhagsc2fgl2oka@127.0.0.1:40000","eecgwpgwq3noky4ijm4jmvjtmuzv44qvigciusxakq5epnrfj2utb@127.0.0.1:12345","en5ejs5b2tybkfh4ym5vpfh7nynby73xhtfzmazumtvcijpcsz6ma@127.0.0.1:12346","ekwmt37xecoq6a7otkm4ux5gfmm4uwbat4bg5m223shckhaaxdpqa@127.0.0.1:12347"],"genesis_header":"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da293d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e948e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260fafff16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea020000ffff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","genesis_state":{"01000000000000000000000000000000000000000000000000000000000000":"08000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","02000000000000000000000000000000000000000000000000000000000000":"0b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb0","03000000000000000000000000000000000000000000000000000000000000":"00","04000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf426000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000085f9095f4abd040839d793d89ab5ff25c61e50c844ab6765e2c0b22373b5a8f6fbe5fc0cd61fdde580b3d44fe1be127197e33b91960b10d2c6fc75aec03f36e16c2a8204961097dbc2c5ba7655543385399cc9ef08bf2e520ccf3b0a7569d88492e630ae2b14e758ab0960e372172203f4c9a41777dadd529971d7ab9d23ab29fe0e9c85ec450505dde7f5ac038274cf01aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bc5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d48e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e33d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d03d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d05e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161df16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d3d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d0aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bcaa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bc3d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e300","05000000000000000000000000000000000000000000000000000000000000":"00000000","06000000000000000000000000000000000000000000000000000000000000":"6f6ad2224d7d58aec6573c623ab110700eaca20a48dc2965d535e466d524af2a835ac82bfa2ce8390bb50680d4b7a73dfa2a4cff6d8c30694b24a605f9574eafd2d34655ebcad804c56d2fd5f932c575b6a5dbb3f5652c5202bcc75ab9c2cc958a715731759b7fceaae288bcb70a605c31cbdfae83d0f4a45dfc2b2458dc9fae","07000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf4260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","08000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf4260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","09000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf4260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","0a000000000000000000000000000000000000000000000000000000000000":"0000","0b000000000000000000000000000000000000000000000000000000000000":"00000000","0c000000000000000000000000000000000000000000000000000000000000":"00000000000000000000000000","0d000000000000000000000000000000000000000000000000000000000000":"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","0e000000000000000000000000000000000000000000000000000000000000":"000000000000000000000000","0f000000000000000000000000000000000000000000000000000000000000":"000000000000000000000000","ff000000000000000000000000000000000000000000000000000000000000":"15f8485e3a88e86182e63280720d5ec9892578f0e577fb1bcdda5cf49795081500e40b540200000064000000000000006400000000000000100500000000000004000000","00fe00ff00ff00ff6326432b5b3213dfd1609495e13c6b276cb474d6796453":"09626f6f74737472617000000000000000000020000a00000000000628023307320015","00fe00ff00ff00fff8485e3a88e86182e63280720d5ec9892578f0e577fb1b":"09626f6f747374726170000000000000020000200032040000050283ae7900300194012f027802280d00000028ae00000028ab029511e07b10187b15107b1608648664783309043307000001ac967c9566fc5106769587047d7833050159083a8489ff003305025329c0002d3305035329e000253305045329f0001d3305055329f800153305065329fc000d8898fe009a850801ac564564587b175010029c026478e45607c95707d88709e48707c98707887720d479098217c8750594983307000001da95072805330801821018821510821608951120320000951150ff7b10a8007b15a0007b169800330908ac98e7003309fcaa97e5015107e101958af8957508510a457d583306015908408489ff003306025329c0002d3306035329e000253306045329f0001d3306055329f800153306065329fc000d8898fe009a860801ae6a092890003306017b166457646864a6501004e501821a51077be4a607c9a70753176072c85a089576a09587607b1751064c7d783305015908378489ff003305025329c0002d3305035329e000253305045329f0001d3305055329f800153305065329fc000d8898fe009a850801ac562a016458501006810128073305330701e45608c95808e47808c97808330921ae981d33083307000001018210a8008215a000821698009511b00032008219c89505c857077c792051090933083307286e958adf957521510a547d573306015907378477ff003306025327c0002d3306035327e000253306045327f0001d3306055327f800153306065327fc000d8877fe009a7608017b1aac6a920064576468501008e6006478821a28073306330801c86507e46a09c96909e6890801c878088088fc330964330a640a0964757b1708481114951714330804951908330a040a0395171833098000330850100a4a330820a107330964951a1864570a0b81180833070000023b080000029889183b090300029889103b090200029888083b080100023308202806ff0000003307000001330832008d7a84aa07c8a70b510a0e647c0178c895cc01acbcfbc9a903843cf8c8cb0a580c1d8482ff0014090101010101010101ca920c017bbc95bb08acabfb843907520905280ec8a9090178a895aa01ac9afb320051089b0064797c77510791005127ff0090006c7a570a09330a330828735527c0000d330a01330b80284a5527e0000e330a02330b40ff283c5527f0000e330a03330b20ff282e5527f8000e330a04330b10ff28205527fc000e330a05330b08ff2812887afe00330b04ff93ab02ff85aa0701ae8a2b3308c8b70764ab01c8b90c7ccc97880895bbffd4c808520bf28aa903cf9707c88707320032000000002124492a21494a22212121212132154a9224a5909a248d88482422494924242424244426ad0a258924a524121212121222a3504d92a43022a292a44a52120909090909914585aa26c924a924494a1421a984909090903c54495a92241140962465495111942a24854421514814124544a6342549923a","0023000000000000478648cd19b4f812f897a26976ecf312eac28508b4368d":"0100000000","004b000400000000f324d112c31c3778a072940b55dd35f3a4b77e72d2d2db":"0100000000"}},"database_base_path":"./database"}'),GB=m.new(void 0,"jam");var qB;async function zB(e,t){if(!T.isMainThread)return void GB.error("The main binary cannot be running as a Worker!");const r={isAuthoring:!1,blocksToImport:e.command===k.Import?e.args.files:null,nodeName:e.args.nodeName,config:ZB(e.args.configPath)},s=YB(r.config.flavor),{rootDb:i,dbPath:n,genesisHeaderHash:o}=XB(r.nodeName,r.config.chainSpec.genesisHeader,t(r.config.databaseBasePath));await async function(e,t,r,s){const i=new gn(e,r),n=new bn(e,r),o=i.getBestHeaderHash(),a=i.getPostStateRoot(o);if(GB.log(`🛢️ Best header hash: ${o}`),GB.log(`🛢️ Best state root: ${a}`),null!==a&&!a.isEqualTo(Y.zero(Ct))&&!o.isEqualTo(Y.zero(Ct)))return void await r.db.close();GB.log("🛢️ Database looks fresh. Initializing.");const c=we.decodeObject(ns.Codec,s.genesisHeader,e),l=us.create({header:ns.empty(),extrinsic:hs.create({tickets:[],preimages:[],assurances:[],guarantees:[],disputes:{verdicts:[],culprits:[],faults:[]}})}).extrinsic,h=us.create({header:c,extrinsic:l}),u=we.decodeObject(us.Codec.View,_e.encodeObject(us.Codec,h,e),e);GB.log(`🧬 Writing genesis block #${c.timeSlotIndex}: ${t}`);const{genesisStateSerialized:d,genesisStateRootHash:f}=function(e,t){const r=dn.fromEntries(Array.from(t.entries())),s=rn.fromTruncatedDictionaryUnsafe(r),i=Vi.fromStateEntries(e,s),n=s.getRootHash();return GB.info(`🧬 Genesis state root: ${n}`),{genesisState:i,genesisStateSerialized:s,genesisStateRootHash:n}}(e,s.genesisState);await i.insertBlock(new kt(t,u)),await n.insertState(t,d),await i.setPostStateRoot(t,f),await i.setBestHeaderHash(t),await r.db.close()}(s,o,i,r.config.chainSpec);const a=await async function(){const e=dh,t=new hh;return Mn(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/importer/index.ts"),e,"ready(main)",t)}(),c=QB({bestHeader:a.getState("ready(main)").onBestBlock}),l=new ur(s,n,r.config.authorship.omitSealVerification),h=a.transition((e,t)=>e.sendConfig(t,l)),u=JB(h,s,r.blocksToImport),d=await WB(r.isAuthoring,l,h);GB.info("[main]⌛ waiting for importer to finish");const f=await u;GB.log("[main] ☠️ Closing the extensions"),c(),GB.log("[main]⌛ waiting for tasks to finish"),await f.currentState().waitForWorkerToFinish(),GB.log("[main] ☠️ Closing the authorship module"),d(),GB.info("[main] ✅ Done.")}!function(e){e[e.InMemory=0]="InMemory",e[e.Lmdb=1]="Lmdb"}(qB||(qB={}));const WB=async(e,t,r)=>{if(!e)return()=>Promise.resolve();GB.info("✍️ Starting block generator.");const{generator:s,finish:i}=await async function(e){const t=(await async function(){const e=Ah,t=new mh;return Mn(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/block-generator/index.ts"),e,"ready(main)",t)}()).transition((t,r)=>t.sendConfig(r,e));return{generator:t,finish:()=>(t.transition((e,t)=>e.finish(t)),t.waitForState("finished"))}}(t);return r.doUntil("finished",async(e,t)=>{s.currentState().onBlock.on(r=>{GB.log(`✍️ Produced block. Size: [${r.length}]`),e.sendBlock(t,r)})}),i},JB=async(e,t,r)=>null===r?e.waitForState("finished"):(GB.info(`📖 Reading ${r.length} blocks`),e.transition((e,s)=>{const i=function*(e){const{chainSpec:t}=e;for(const r of e.files){const e=VB(r)?$B(r,t):FB(r,t);yield e}}({files:r,chainSpec:t});for(const t of i)GB.log(`📖 Importing block: #${t.header.view().timeSlotIndex.materialize()}`),e.sendBlock(s,t.encoded().raw);return GB.info("All blocks scheduled to be imported."),e.finish(s)})),YB=e=>{if(e===js.Full)return hr;if(e===js.Tiny)return lr;throw new Error(`Unknown chain spec: ${e}. Possible options: ${[js.Full,js.Tiny]}`)};function XB(e,t,r,{readOnly:s=!1}={}){const i=Dt(e).toString().substring(2,10),n=Nt(t).asOpaque(),o=`${r}/${i}/${n.toString().substring(2,10)}`;GB.info(`🛢️ Opening database at ${o}`);try{return{dbPath:o,rootDb:new mn(o,s),genesisHeaderHash:n}}catch(e){throw new Error(`Unable to open database at ${o}: ${e}`)}}function ZB(e){if(e===v)return fs(jB,qs.fromJson);try{const t=U().readFileSync(e,"utf8");return fs(JSON.parse(t),qs.fromJson)}catch(t){throw new Error(`Unable to load config file from ${e}: ${t}`)}}if("file:///home/runner/work/typeberry/typeberry/bin/jam/index.ts"===(0,c.pathToFileURL)(process.argv[1]).href){m.configureAll(process.env.JAM_LOG??"",l.LOG);const e="undefined/../..",t=t=>t.startsWith("/")?t:`${e}/${t}`;let r;try{r=_(process.argv.slice(2),t)}catch(e){console.error(`\n${e}\n`),console.info(S),process.exit(1)}zB(r,t).catch(e=>{console.error(`${e}`),process.exit(-1)})}let eR;m.configureAll(process.env.JAM_LOG??"",l.LOG);try{eR=_(process.argv.slice(2),tR)}catch(e){console.error(`\n${e}\n`),console.info(S),process.exit(1)}function tR(e){return e}zB(eR,tR).catch(e=>{console.error(`${e}`),process.exit(-1)});export{k as Command,w as DEFAULTS,v as DEV_CONFIG,qB as DatabaseKind,S as HELP,YB as getChainSpec,ZB as loadConfig,zB as main,XB as openDatabase,_ as parseArgs};
2
+ import{fileURLToPath as e}from"node:url";import{createRequire as t}from"node:module";import*as r from"minimist";import*as s from"lmdb";var i={8:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.matchingBitCount=t.intLog2=t.cidrPrefixToMaskBinaryString=t.leftPadWithZeroBit=t.dottedDecimalNotationToBinaryString=t.parseBinaryStringToBigInt=t.decimalNumberToOctetString=t.numberToBinaryString=void 0,t.numberToBinaryString=e=>e.toString(2),t.decimalNumberToOctetString=e=>{let r=t.numberToBinaryString(e);if(r.length>8)throw new Error("Given decimal in binary contains digits greater than an octet");return t.leftPadWithZeroBit(r,8)},t.parseBinaryStringToBigInt=e=>BigInt(`0b${e}`),t.dottedDecimalNotationToBinaryString=e=>e.split(".").reduce((e,r)=>e.concat(t.decimalNumberToOctetString(parseInt(r))),""),t.leftPadWithZeroBit=(e,t)=>{if(e.length>t)throw new Error(`Given string is already longer than given final length after padding: ${t}`);return"0".repeat(t-e.length).concat(e)},t.cidrPrefixToMaskBinaryString=(e,t)=>{let r;if(r="IPv4"==t?32:128,e>r)throw Error(`Value is greater than ${r}`);return`${"1".repeat(e)}${"0".repeat(r-e)}`},t.intLog2=e=>{let t=0;for(;e%2n==0n;){if(2n===e){t++;break}if((e>>=1n)%2n!=0n){t=0;break}t++}if(0==t)throw new Error(`The value of log2 for ${e.toString()} is not an integer`);return t},t.matchingBitCount=(e,t)=>{let r,s;e.length>=t.length?(r=e,s=t):(r=t,s=e);let i=0;for(;i<r.length&&r.charAt(i)===s.charAt(i);i++);return i}},54:e=>{e.exports=function e(r,s){if(!r){var i=new t(s);throw Error.captureStackTrace&&Error.captureStackTrace(i,e),i}};class t extends Error{}t.prototype.name="AssertionError"},154:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Hexadecatet=void 0;const s=r(660);class i{constructor(e){let t;t="string"==typeof e?parseInt(e,16):parseInt(String(e),16);let[r,i]=s.Validator.isValidIPv6Hexadecatet(BigInt(t));if(!r)throw Error(i.filter(e=>""!==e).toString());this.value=t}static fromString(e){return new i(e)}static fromNumber(e){return new i(e)}getValue(){return this.value}toString(){return this.value.toString(16)}}t.Hexadecatet=i},212:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIPv4=t.IPv6Mask=t.IPv4Mask=t.IPv6=t.Asn=t.IPv4=t.AbstractIPNum=void 0;const s=r(301),i=r(660),n=r(8),o=r(8),a=r(8),c=r(8),l=r(154),h=r(984),u=r(872),d=r(984);class f{getValue(){return this.value}toBinaryString(){return a.leftPadWithZeroBit(this.value.toString(2),this.bitSize)}hasNext(){return this.value<this.maximumBitSize}hasPrevious(){return this.value>0n}isEquals(e){return this.value===e.value}isLessThan(e){return this.value<e.value}isGreaterThan(e){return this.value>e.value}isLessThanOrEquals(e){return this.value<=e.value}isGreaterThanOrEquals(e){return this.value>=e.value}}t.AbstractIPNum=f;class p extends f{constructor(e){if(super(),this.bitSize=32,this.maximumBitSize=i.Validator.THIRTY_TWO_BIT_SIZE,this.type="IPv4",this.octets=[],this.separator=".","string"==typeof e){let[t,r]=this.constructFromDecimalDottedString(e);this.value=t,this.octets=r}else{let[t,r]=this.constructFromBigIntValue(e);this.value=t,this.octets=r}}static fromNumber(e){return new p(e)}static fromDecimalDottedString(e){return new p(e)}static fromString(e){return p.fromDecimalDottedString(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new p(o.parseBinaryStringToBigInt(e));throw Error(t[1].join(","))}toString(){return this.octets.map(e=>e.toString()).join(this.separator)}getOctets(){return this.octets}nextIPNumber(){return p.fromNumber(this.getValue()+1n)}previousIPNumber(){return p.fromNumber(this.getValue()-1n)}toIPv4MappedIPv6(){let e="1".repeat(16)+this.toBinaryString();return y.fromBinaryString(e)}constructFromDecimalDottedString(e){let t,r,[o,a]=i.Validator.isValidIPv4String(e);if(!o)throw new Error(a.filter(e=>""!==e).toString());return t=e.split(".").map(e=>s.Octet.fromString(e)),r=BigInt(`0b${n.dottedDecimalNotationToBinaryString(e)}`),[r,t]}constructFromBigIntValue(e){let[t,r]=i.Validator.isValidIPv4Number(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let s=c.numberToBinaryString(e);return[e="bigint"==typeof e?e:BigInt(e),this.binaryStringToDecimalOctets(s)]}binaryStringToDecimalOctets(e){return e.length<32&&(e=a.leftPadWithZeroBit(e,32)),e.match(/.{1,8}/g).map(e=>s.Octet.fromString(o.parseBinaryStringToBigInt(e).toString()))}}t.IPv4=p;class g extends f{constructor(e){if(super(),this.bitSize=32,this.maximumBitSize=i.Validator.THIRTY_TWO_BIT_SIZE,this.type="ASN","string"==typeof e)g.startWithASPrefix(e)?this.value=BigInt(parseInt(e.substring(2))):-1!=e.indexOf(".")?this.value=BigInt(this.parseFromDotNotation(e)):this.value=BigInt(parseInt(e));else{let t=BigInt(e),[r,s]=i.Validator.isValidAsnNumber(t);if(!r)throw Error(s.filter(e=>""!==e).toString());this.value=t}}static fromString(e){return new g(e)}static fromNumber(e){return new g(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new g(parseInt(e,2));throw Error(t[1].join(","))}toString(){let e=this.value.toString();return`${g.AS_PREFIX}${e}`}toASPlain(){return this.value.toString()}toASDot(){return this.value.valueOf()>=65536n?this.toASDotPlus():this.toASPlain()}toASDotPlus(){let e=this.value.valueOf()/65535n;return`${e}.${this.value.valueOf()%65535n-e}`}toBinaryString(){return c.numberToBinaryString(this.value)}is16Bit(){let[e]=i.Validator.isValid16BitAsnNumber(this.value);return e}is32Bit(){return!this.is16Bit()}nextIPNumber(){return new g(this.value.valueOf()+1n)}previousIPNumber(){return new g(this.value.valueOf()-1n)}static startWithASPrefix(e){return 0===e.indexOf(g.AS_PREFIX)}parseFromDotNotation(e){let t=e.split("."),r=parseInt(t[0]);return 65535*r+(parseInt(t[1])+r)}}t.Asn=g,g.AS_PREFIX="AS";class y extends f{constructor(e){if(super(),this.bitSize=128,this.maximumBitSize=i.Validator.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE,this.type="IPv6",this.hexadecatet=[],this.separator=":","string"==typeof e){let t=u.expandIPv6Number(e),[r,s]=this.constructFromHexadecimalDottedString(t);this.value=r,this.hexadecatet=s}else{let[t,r]=this.constructFromBigIntValue(e);this.value=t,this.hexadecatet=r}}static fromBigInt(e){return new y(e)}static fromHexadecatet(e){return new y(e)}static fromString(e){return y.fromHexadecatet(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0]){let t=a.leftPadWithZeroBit(e,128);return new y(o.parseBinaryStringToBigInt(t))}throw Error(t[1].join(","))}static fromIPv4(e){return e.toIPv4MappedIPv6()}static fromIPv4DotDecimalString(e){return new p(e).toIPv4MappedIPv6()}toString(){let e=this.hexadecatet.map(e=>e.toString()).join(":");return this.hexadecatet.length<8?"::"+e:e}getHexadecatet(){return this.hexadecatet}nextIPNumber(){return y.fromBigInt(this.getValue()+1n)}previousIPNumber(){return y.fromBigInt(this.getValue()-1n)}constructFromBigIntValue(e){let[t,r]=i.Validator.isValidIPv6Number(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let s=c.numberToBinaryString(e);return[e,this.binaryStringToHexadecatets(s)]}constructFromHexadecimalDottedString(e){let[t,r]=i.Validator.isValidIPv6String(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let s=e.split(":").map(e=>l.Hexadecatet.fromString(e));return[BigInt(`0b${d.hexadectetNotationToBinaryString(e)}`),s]}binaryStringToHexadecatets(e){let t=h.binaryStringToHexadecimalString(e);for(;t.length%4!=0;)t="0"+t;return t.match(/.{1,4}/g).map(e=>l.Hexadecatet.fromString(e))}}t.IPv6=y;class m extends p{constructor(e){let t,r;if(super(e),this.octets=[],[t,r]=i.Validator.isValidIPv4Mask(e),!t)throw new Error(r.filter(e=>""!==e).toString());let o=e.split(".");this.octets=o.map(e=>s.Octet.fromString(e));let a=n.dottedDecimalNotationToBinaryString(e);this.prefix=(a.match(/1/g)||[]).length,this.value=BigInt(`0b${a}`)}static fromDecimalDottedString(e){return new m(e)}}t.IPv4Mask=m;class b extends y{constructor(e){let t,r;super(e),this.hexadecatet=[];let s=u.expandIPv6Number(e);if([t,r]=i.Validator.isValidIPv6Mask(s),!t)throw new Error(r.filter(e=>""!==e).toString());let n=s.split(":");this.hexadecatet=n.map(e=>l.Hexadecatet.fromString(e));let o=d.hexadectetNotationToBinaryString(s);this.prefix=(o.match(/1/g)||[]).length,this.value=BigInt(`0b${o}`),this.value=BigInt(`0b${d.hexadectetNotationToBinaryString(s)}`)}static fromHexadecatet(e){return new b(e)}}t.IPv6Mask=b,t.isIPv4=function(e){return 32===e.bitSize}},259:e=>{var t,r,s=(()=>{for(var e=new Uint8Array(128),t=0;t<64;t++)e[t<26?t+65:t<52?t+71:t<62?t-4:4*t-205]=t;return t=>{for(var r=t.length,s=new Uint8Array(3*(r-("="==t[r-1])-("="==t[r-2]))/4|0),i=0,n=0;i<r;){var o=e[t.charCodeAt(i++)],a=e[t.charCodeAt(i++)],c=e[t.charCodeAt(i++)],l=e[t.charCodeAt(i++)];s[n++]=o<<2|a>>4,s[n++]=a<<4|c>>2,s[n++]=c<<6|l}return s}})(),i=(t={"wasm-binary:./blake2b.wat"(e,t){t.exports=s("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMKvz8EwAIAIABCADcDACAAQgA3AwggAEIANwMQIABCADcDGCAAQgA3AyAgAEIANwMoIABCADcDMCAAQgA3AzggAEIANwNAIABCADcDSCAAQgA3A1AgAEIANwNYIABCADcDYCAAQgA3A2ggAEIANwNwIABCADcDeCAAQoiS853/zPmE6gBBACkDAIU3A4ABIABCu86qptjQ67O7f0EIKQMAhTcDiAEgAEKr8NP0r+68tzxBECkDAIU3A5ABIABC8e30+KWn/aelf0EYKQMAhTcDmAEgAELRhZrv+s+Uh9EAQSApAwCFNwOgASAAQp/Y+dnCkdqCm39BKCkDAIU3A6gBIABC6/qG2r+19sEfQTApAwCFNwOwASAAQvnC+JuRo7Pw2wBBOCkDAIU3A7gBIABCADcDwAEgAEIANwPIASAAQgA3A9ABC20BA38gAEHAAWohAyAAQcgBaiEEIAQpAwCnIQUCQANAIAEgAkYNASAFQYABRgRAIAMgAykDACAFrXw3AwBBACEFIAAQAwsgACAFaiABLQAAOgAAIAVBAWohBSABQQFqIQEMAAsLIAQgBa03AwALYQEDfyAAQcABaiEBIABByAFqIQIgASABKQMAIAIpAwB8NwMAIABCfzcD0AEgAikDAKchAwJAA0AgA0GAAUYNASAAIANqQQA6AAAgA0EBaiEDDAALCyACIAOtNwMAIAAQAwuqOwIgfgl/IABBgAFqISEgAEGIAWohIiAAQZABaiEjIABBmAFqISQgAEGgAWohJSAAQagBaiEmIABBsAFqIScgAEG4AWohKCAhKQMAIQEgIikDACECICMpAwAhAyAkKQMAIQQgJSkDACEFICYpAwAhBiAnKQMAIQcgKCkDACEIQoiS853/zPmE6gAhCUK7zqqm2NDrs7t/IQpCq/DT9K/uvLc8IQtC8e30+KWn/aelfyEMQtGFmu/6z5SH0QAhDUKf2PnZwpHagpt/IQ5C6/qG2r+19sEfIQ9C+cL4m5Gjs/DbACEQIAApAwAhESAAKQMIIRIgACkDECETIAApAxghFCAAKQMgIRUgACkDKCEWIAApAzAhFyAAKQM4IRggACkDQCEZIAApA0ghGiAAKQNQIRsgACkDWCEcIAApA2AhHSAAKQNoIR4gACkDcCEfIAApA3ghICANIAApA8ABhSENIA8gACkD0AGFIQ8gASAFIBF8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSASfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgE3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBR8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAVfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFnx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBd8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAYfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgGXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBp8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAbfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgHHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIB18fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAefHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgH3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFICB8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAffHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgG3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBV8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAZfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHICB8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAefHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggF3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBJ8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAdfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgEXx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBN8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAcfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggGHx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBZ8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAUfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHHx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBl8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAdfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgEXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBZ8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByATfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggIHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIB58fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAbfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgH3x8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBR8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAXfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBJ8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAafHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFXx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBh8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAafHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFHx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBJ8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAefHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHXx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBx8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAffHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgE3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBd8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAWfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgG3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBV8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCARfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgIHx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBl8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAafHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEXx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBZ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAYfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgE3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBV8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAbfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggIHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIB98fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiASfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgHHx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB18fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAXfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggGXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBR8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAefHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgE3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIB18fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAXfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgG3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBF8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAcfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggGXx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBR8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAVfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBh8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAWfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggIHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB98fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSASfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgGnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB18fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAWfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgEnx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGICB8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAffHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHnx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBV8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAbfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBh8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAXfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBp8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCATfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGXx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBx8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAefHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgHHx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBh8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAffHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBJ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAUfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBZ8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiARfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgIHx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBV8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAZfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggF3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBN8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAbfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgF3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFICB8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAffHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGnx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBx8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAUfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggEXx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBl8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAdfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgE3x8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIB58fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAYfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggEnx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBV8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAbfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBt8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSATfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgGXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBV8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAYfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgF3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBJ8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAWfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgIHx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBx8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAafHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgH3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBR8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAdfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgHnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBF8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgISAhKQMAIAEgCYWFNwMAICIgIikDACACIAqFhTcDACAjICMpAwAgAyALhYU3AwAgJCAkKQMAIAQgDIWFNwMAICUgJSkDACAFIA2FhTcDACAmICYpAwAgBiAOhYU3AwAgJyAnKQMAIAcgD4WFNwMAICggKCkDACAIIBCFhTcDAAs=")}},function(){return r||(0,t[Object.keys(t)[0]])((r={exports:{}}).exports,r),r.exports})(),n=WebAssembly.compile(i);e.exports=async e=>(await WebAssembly.instantiate(await n,e)).exports},287:e=>{function t(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}e.exports={isBuffer:function(e){return Buffer.isBuffer(e)||e instanceof Uint8Array},isEncoding:function(e){return Buffer.isEncoding(e)},alloc:function(e,t,r){return Buffer.alloc(e,t,r)},allocUnsafe:function(e){return Buffer.allocUnsafe(e)},allocUnsafeSlow:function(e){return Buffer.allocUnsafeSlow(e)},byteLength:function(e,t){return Buffer.byteLength(e,t)},compare:function(e,t){return Buffer.compare(e,t)},concat:function(e,t){return Buffer.concat(e,t)},copy:function(e,r,s,i,n){return t(e).copy(r,s,i,n)},equals:function(e,r){return t(e).equals(r)},fill:function(e,r,s,i,n){return t(e).fill(r,s,i,n)},from:function(e,t,r){return Buffer.from(e,t,r)},includes:function(e,r,s,i){return t(e).includes(r,s,i)},indexOf:function(e,r,s,i){return t(e).indexOf(r,s,i)},lastIndexOf:function(e,r,s,i){return t(e).lastIndexOf(r,s,i)},swap16:function(e){return t(e).swap16()},swap32:function(e){return t(e).swap32()},swap64:function(e){return t(e).swap64()},toBuffer:t,toString:function(e,r,s,i){return t(e).toString(r,s,i)},write:function(e,r,s,i,n){return t(e).write(r,s,i,n)},writeDoubleLE:function(e,r,s){return t(e).writeDoubleLE(r,s)},writeFloatLE:function(e,r,s){return t(e).writeFloatLE(r,s)},writeUInt32LE:function(e,r,s){return t(e).writeUInt32LE(r,s)},writeInt32LE:function(e,r,s){return t(e).writeInt32LE(r,s)},readDoubleLE:function(e,r){return t(e).readDoubleLE(r)},readFloatLE:function(e,r){return t(e).readFloatLE(r)},readUInt32LE:function(e,r){return t(e).readUInt32LE(r)},readInt32LE:function(e,r){return t(e).readInt32LE(r)}}},301:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Octet=void 0;const s=r(660);class i{constructor(e){let t;t="string"==typeof e?parseInt(e):e;let[r,i]=s.Validator.isValidIPv4Octet(BigInt(t));if(!r)throw Error(i.filter(e=>""!==e).toString());this.value=t}static fromString(e){return new i(e)}static fromNumber(e){return new i(e)}getValue(){return this.value}toString(){return this.value.toString(10)}}t.Octet=i},405:(t,r,s)=>{var i=e(import.meta.url+"/..").slice(0,-1);let n,o=null;function a(){return null!==o&&0!==o.byteLength||(o=new Uint8Array(n.memory.buffer)),o}let c=0;function l(e,t){const r=t(1*e.length,1)>>>0;return a().set(e,r/1),c=e.length,r}let h=null;function u(){return null!==h&&0!==h.byteLength||(h=new Int32Array(n.memory.buffer)),h}function d(e,t){return e>>>=0,a().subarray(e/1,e/1+t)}t.exports.hc=function(e){try{const i=n.__wbindgen_add_to_stack_pointer(-16),o=l(e,n.__wbindgen_malloc),a=c;n.ring_commitment(i,o,a);var t=u()[i/4+0],r=u()[i/4+1],s=d(t,r).slice();return n.__wbindgen_free(t,1*r,1),s}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.KG=function(e,t,r,s,i){try{const f=n.__wbindgen_add_to_stack_pointer(-16),p=l(e,n.__wbindgen_malloc),g=c,y=l(r,n.__wbindgen_malloc),m=c,b=l(s,n.__wbindgen_malloc),A=c,I=l(i,n.__wbindgen_malloc),v=c;n.verify_seal(f,p,g,t,y,m,b,A,I,v);var o=u()[f/4+0],a=u()[f/4+1],h=d(o,a).slice();return n.__wbindgen_free(o,1*a,1),h}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.ZJ=function(e,t,r){try{const a=n.__wbindgen_add_to_stack_pointer(-16),h=l(e,n.__wbindgen_malloc),f=c,p=l(t,n.__wbindgen_malloc),g=c;n.batch_verify_tickets(a,h,f,p,g,r);var s=u()[a/4+0],i=u()[a/4+1],o=d(s,i).slice();return n.__wbindgen_free(s,1*i,1),o}finally{n.__wbindgen_add_to_stack_pointer(16)}};const f=s(928).join(i,"bandersnatch_bg.wasm"),p=s(896).readFileSync(f),g=new WebAssembly.Module(p),y=new WebAssembly.Instance(g,{});n=y.exports},412:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIPv4CidrRange=t.IPv6CidrRange=t.IPv4CidrRange=t.AbstractIPRange=t.RangedSet=void 0;const s=r(212),i=r(516),n=r(8),o=r(660);class a{constructor(e,t){if(this.first=e,this.last=t,e.isGreaterThan(t))throw new Error(`${e.toString()} should be lower than ${t.toString()}`);this.currentValue=e,this.bitValue=BigInt(e.bitSize)}static fromSingleIP(e){return new a(e,e)}static fromCidrRange(e){return new a(e.getFirst(),e.getLast())}static fromRangeString(e){let t=e.split("-").map(e=>e.trim());if(2!==t.length)throw new Error("Argument should be in the format firstip-lastip");let[r,i]=t,[n]=o.Validator.isValidIPv4String(r),[c]=o.Validator.isValidIPv4String(i),[l]=o.Validator.isValidIPv6String(r),[h]=o.Validator.isValidIPv6String(i);if(n&&c)return new a(s.IPv4.fromDecimalDottedString(r),s.IPv4.fromDecimalDottedString(i));if(l&&h)return new a(s.IPv6.fromHexadecatet(r),s.IPv6.fromHexadecatet(i));throw new Error("First IP and Last IP should be valid and same type")}getFirst(){return this.first}getLast(){return this.last}getSize(){return this.last.getValue()-this.first.getValue()+1n}toRangeString(){return`${this.getFirst()}-${this.getLast()}`}inside(e){return e.contains(this)}contains(e){let t=this.getFirst(),r=this.getLast(),s=e.getFirst(),i=e.getLast();return t.isLessThanOrEquals(s)&&r.isGreaterThanOrEquals(i)}isEquals(e){return this.getFirst().isEquals(e.getFirst())&&this.getLast().isEquals(e.getLast())}isLessThan(e){return!this.isEquals(e)&&(this.getFirst().isEquals(e.getFirst())?this.getSize()<e.getSize():this.getFirst().isLessThan(e.getFirst()))}isGreaterThan(e){return!this.isEquals(e)&&(this.getFirst().isEquals(e.getFirst())?this.getSize()>e.getSize():this.getFirst().isGreaterThan(e.getFirst()))}isOverlapping(e){let t=this.getFirst(),r=this.getLast(),s=e.getFirst(),i=e.getLast();return r.isGreaterThan(s)&&r.isLessThanOrEquals(i)&&t.isLessThan(s)||i.isGreaterThan(t)&&i.isLessThanOrEquals(r)&&s.isLessThan(t)}isCidrAble(){if(1n===this.getSize())return!0;try{let e=n.intLog2(this.getSize()),t=n.parseBinaryStringToBigInt(n.cidrPrefixToMaskBinaryString(e,s.isIPv4(this.currentValue)?"IPv4":"IPv6"));return this.first.getValue()===(t&this.first.getValue())}catch(e){return!1}}toCidrRange(){return s.isIPv4(this.currentValue)?this.toIPv4CidrRange():this.toIPv6CidrRange()}isConsecutive(e){let t=this.getFirst(),r=this.getLast(),s=e.getFirst(),i=e.getLast();return r.hasNext()&&r.nextIPNumber().isEquals(s)||i.hasNext()&&i.nextIPNumber().isEquals(t)}union(e){if(this.isEquals(e))return new a(e.getFirst(),e.getLast());if(this.isOverlapping(e))return this.getFirst().isLessThan(e.getFirst())?new a(this.getFirst(),e.getLast()):new a(e.getFirst(),this.getLast());if(this.contains(e))return new a(this.getFirst(),this.getLast());if(e.contains(this))return new a(e.getFirst(),e.getLast());throw new Error("Ranges do not overlap nor are equal")}prepend(e){if(e.getLast().nextIPNumber().isEquals(this.getFirst()))return new a(e.getFirst(),this.getLast());throw new Error("Range to prepend must be adjacent")}append(e){if(this.getLast().nextIPNumber().isEquals(e.getFirst()))return new a(this.getFirst(),e.getLast());throw new Error("Range to append must be adjacent")}subtract(e){if(!this.isOverlapping(e))throw new Error("Cannot subtract ranges that are not overlapping");if(!this.isLessThan(e))throw new Error("Cannot subtract a larger range from this range");return new a(this.getFirst(),e.getLast())}takeSubRange(e,t){if(e+t>this.getSize())throw new RangeError("Requested range is greater than what can be taken");if(0n===t)throw new Error("Sub range cannot be zero");let r=this.getFirst().value+e,i=s.isIPv4(this.getFirst())?s.IPv4.fromNumber(r):s.IPv6.fromBigInt(r),n=i.value+(t-1n),o=s.isIPv4(i)?s.IPv4.fromNumber(n):s.IPv6.fromBigInt(n);return new a(i,o)}difference(e){if(e.getSize()>this.getSize())throw new Error("Range is greater than range to be subtracted from");if(!this.contains(e))throw new Error("Range to subtract is not contained in this range");let t=[];try{t.push(new a(this.getFirst(),e.getFirst().previousIPNumber()))}catch(e){}try{t.push(new a(e.getLast().nextIPNumber(),this.getLast()))}catch(e){}return t}*take(e){let t=this.getFirst(),r=void 0===e?this.getSize().valueOf():e;for(;r>0;)r--,yield t,t=t.nextIPNumber()}*[Symbol.iterator](){yield*this.take()}toIPv4CidrRange(){let e=new l(s.IPv4.fromNumber(this.getFirst().getValue()),i.IPv4Prefix.fromRangeSize(this.getSize()));if(e.getFirst().isEquals(this.getFirst()))return e;throw new Error("Range cannot be converted to CIDR")}toIPv6CidrRange(){let e=new h(s.IPv6.fromBigInt(this.getFirst().getValue()),i.IPv6Prefix.fromRangeSize(this.getSize()));if(e.getFirst().isEquals(this.getFirst()))return e;throw new Error("Range cannot be converted to CIDR")}}t.RangedSet=a;class c{hasNextRange(){let e=this.getSize();return 2n**this.bitValue-e>=this.getFirst().getValue()+e}hasPreviousRange(){return this.getSize()<=this.getFirst().getValue()}toRangeSet(){return new a(this.getFirst(),this.getLast())}inside(e){return this.toRangeSet().inside(e.toRangeSet())}contains(e){return this.toRangeSet().contains(e.toRangeSet())}toRangeString(){return this.toRangeSet().toRangeString()}isOverlapping(e){return this.toRangeSet().isOverlapping(e.toRangeSet())}isConsecutive(e){return this.toRangeSet().isConsecutive(e.toRangeSet())}isCidrMergeable(e){const t=BigInt(n.matchingBitCount(this.getFirst().toBinaryString(),e.getFirst().toBinaryString()));return this.getPrefix().value-t===1n&&this.isConsecutive(e)&&this.getSize()===e.getSize()}isMergeable(e){return this.isCidrMergeable(e)||this.contains(e)||this.inside(e)}isEquals(e){return this.toRangeSet().isEquals(e.toRangeSet())}merge(e){if(!this.isCidrMergeable(e))throw new Error(`Cannot merge. Ranges (${this.toRangeString()},${e.toRangeString()}) are not consecutive and/or of same size`);return this.newInstance(this.getFirst(),this.getPrefix().merge())}*takeStream(e){return this.toRangeSet().take(e)}*[Symbol.iterator](){yield*this.toRangeSet()}}t.AbstractIPRange=c;class l extends c{constructor(e,t){super(),this.ipv4=e,this.cidrPrefix=t,this.bitValue=32n}static fromCidr(e){let[t,r]=o.Validator.isValidIPv4CidrNotation(e);if(!t){let e=r.filter(e=>""!==e);throw new Error(e.join(" and "))}let n=e.split("/"),a=n[0],c=BigInt(parseInt(n[1]));return new l(s.IPv4.fromDecimalDottedString(a),i.IPv4Prefix.fromNumber(c))}getSize(){return this.cidrPrefix.toRangeSize()}toCidrString(){return`${this.ipv4.toString().toString()}/${this.cidrPrefix.toString()}`}toRangeString(){return super.toRangeString()}getFirst(){return s.IPv4.fromNumber(this.ipv4.getValue()&this.cidrPrefix.toMask().getValue())}getLast(){return u(this,this.ipv4)}newInstance(e,t){return new l(e,t)}getPrefix(){return this.cidrPrefix}isConsecutive(e){return super.isConsecutive(e)}contains(e){return super.contains(e)}inside(e){return super.inside(e)}isOverlapping(e){return super.isOverlapping(e)}take(e){let t=[this.getFirst()],r=this.getFirst();if(e>this.getSize()){let t=o.Validator.takeOutOfRangeSizeMessage.replace("$count",e.toString()).replace("$size",this.getSize().toString());throw new Error(t)}for(let s=0;s<e-1n;s++)t.push(r.nextIPNumber()),r=r.nextIPNumber();return t}split(){let e=this.cidrPrefix.getValue();if(32n===e)throw new Error("Cannot split an IP range with a single IP number");let t=i.IPv4Prefix.fromNumber(e+1n),r=this.getFirst(),s=new l(r,t),n=s.getLast().nextIPNumber();return[s,new l(n,t)]}splitInto(e){let t=e.getValue()-this.cidrPrefix.getValue();if(t<0)throw new Error("Prefix to split into is larger than source prefix");if(0n===t)return[new l(this.getFirst(),e)];if(1n===t)return this.split();{let e=this.split();for(;t>1;)e=e.flatMap(e=>e.split()),t-=1n;return e}}hasNextRange(){return super.hasNextRange()}hasPreviousRange(){return super.hasPreviousRange()}nextRange(){if(this.hasNextRange()){let e=this.getSize(),t=this.getFirst().getValue()+e;return new l(new s.IPv4(t),this.cidrPrefix)}}previousRange(){if(this.hasPreviousRange()){let e=this.getSize(),t=this.getFirst().getValue()-e;return new l(new s.IPv4(t),this.cidrPrefix)}}}t.IPv4CidrRange=l;class h extends c{constructor(e,t){super(),this.ipv6=e,this.cidrPrefix=t,this.bitValue=128n}static fromCidr(e){let[t,r]=o.Validator.isValidIPv6CidrNotation(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let n=e.split("/"),a=n[0],c=BigInt(parseInt(n[1]));return new h(s.IPv6.fromHexadecatet(a),i.IPv6Prefix.fromNumber(c))}getSize(){return this.cidrPrefix.toRangeSize()}toCidrString(){return`${this.ipv6.toString().toString()}/${this.cidrPrefix.toString()}`}toRangeString(){return super.toRangeString()}getFirst(){return s.IPv6.fromBigInt(this.ipv6.getValue()&this.cidrPrefix.toMask().getValue())}getLast(){return u(this,this.ipv6)}newInstance(e,t){return new h(e,t)}getPrefix(){return this.cidrPrefix}isConsecutive(e){return super.isConsecutive(e)}contains(e){return super.contains(e)}inside(e){return super.inside(e)}isOverlapping(e){return super.isOverlapping(e)}take(e){let t=[this.getFirst()],r=this.getFirst();if(e>this.getSize())throw new Error(`${e.toString()} is greater than ${this.getSize().toString()}, the size of the range`);for(var s=0;s<e-1n;s++)t.push(r.nextIPNumber()),r=r.nextIPNumber();return t}split(){let e=this.cidrPrefix.getValue();if(128n===e)throw new Error("Cannot split an IP range with a single IP number");let t=i.IPv6Prefix.fromNumber(e+1n),r=this.getFirst(),s=new h(r,t),n=s.getLast().nextIPNumber();return[s,new h(n,t)]}splitInto(e){let t=e.getValue()-this.cidrPrefix.getValue();if(t<0)throw new Error("Prefix to split into is larger than source prefix");if(0n===t)return[new h(this.getFirst(),e)];if(1n===t)return this.split();{let e=this.split();for(;t>1;)e=e.flatMap(e=>e.split()),t-=1n;return e}}hasNextRange(){return super.hasNextRange()}hasPreviousRange(){return super.hasPreviousRange()}nextRange(){if(this.hasNextRange()){let e=this.getSize(),t=this.getFirst().getValue()+e;return new h(new s.IPv6(t),this.cidrPrefix)}}previousRange(){if(this.hasPreviousRange()){let e=this.getSize(),t=this.getFirst().getValue()-e;return new h(new s.IPv6(t),this.cidrPrefix)}}}t.IPv6CidrRange=h;let u=(e,t)=>{let r=Number(e.bitValue.valueOf()),i=BigInt(`0b${"1".repeat(r)}`),o=e.cidrPrefix.toMask().getValue(),a=n.leftPadWithZeroBit((o^i).toString(2),r);return d(e)?s.IPv4.fromNumber(t.getValue()|n.parseBinaryStringToBigInt(a)):s.IPv6.fromBigInt(t.getValue()|n.parseBinaryStringToBigInt(a))};function d(e){return 32n===e.bitValue.valueOf()}t.isIPv4CidrRange=d},429:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},516:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIPv4Prefix=t.IPv6Prefix=t.IPv4Prefix=void 0;const s=r(660),i=r(212),n=r(8),o=r(984),a=r(154);class c{constructor(e){let t,r;if(this.type="IPv4",this.bitValue=32n,[t,r]=s.Validator.isValidPrefixValue(e,"IPv4"),!t)throw new Error(r.filter(e=>""!==e).toString());this.value=e}static fromNumber(e){return new c(e)}static fromRangeSize(e){let t=1n===e?32:32-h(e,s.Validator.IPV4_SIZE);return c.fromNumber(BigInt(t))}getValue(){return this.value}toString(){return this.value.toString()}toMask(){let e="1".repeat(Number(this.value)),t="0".repeat(Number(32n-this.value));return i.IPv4Mask.fromDecimalDottedString(this.toDecimalNotation(`${e}${t}`))}toRangeSize(){return 1n<<this.bitValue-this.getValue()}merge(){return new c(this.value-1n)}split(){return new c(this.value+1n)}toDecimalNotation(e){return`${n.parseBinaryStringToBigInt(e.substr(0,8))}.${n.parseBinaryStringToBigInt(e.substr(8,8))}.${n.parseBinaryStringToBigInt(e.substr(16,8))}.${n.parseBinaryStringToBigInt(e.substr(24,8))}`}}t.IPv4Prefix=c;class l{constructor(e){let t,r;if(this.type="IPv6",this.bitValue=128n,[t,r]=s.Validator.isValidPrefixValue(e,"IPv6"),!t)throw new Error(r.filter(e=>""!==e).toString());this.value=e}static fromNumber(e){return new l(e)}static fromRangeSize(e){let t=1n===e?128:128-h(e,s.Validator.IPV6_SIZE);return l.fromNumber(BigInt(t))}getValue(){return this.value}toString(){return this.value.toString()}toMask(){let e="1".repeat(Number(this.value)),t="0".repeat(128-Number(this.value));return i.IPv6Mask.fromHexadecatet(this.toHexadecatetNotation(`${e}${t}`))}toRangeSize(){return 1n<<this.bitValue-this.getValue()}merge(){return new l(this.value-1n)}split(){return new l(this.value+1n)}toHexadecatetNotation(e){return e.match(/.{1,16}/g).map(e=>a.Hexadecatet.fromString(o.binaryStringToHexadecimalString(e))).map(e=>e.toString()).join(":")}}function h(e,t){let r=t>s.Validator.IPV4_SIZE?"IPv6":"IPv4";if(e>t||0n===e)throw new Error(s.Validator.invalidIPRangeSizeMessage.replace("$iptype",r));try{return n.intLog2(e)}catch(e){throw new Error(s.Validator.invalidIPRangeSizeForCidrMessage)}}t.IPv6Prefix=l,t.isIPv4Prefix=function(e){return"IPv4"===e.type}},578:(e,t,r)=>{var s=r(54),i=r(287),n=null,o="undefined"!=typeof WebAssembly&&r(259)().then(e=>{n=e}),a=64,c=[];e.exports=g;var l=e.exports.BYTES_MIN=16,h=e.exports.BYTES_MAX=64,u=(e.exports.BYTES=32,e.exports.KEYBYTES_MIN=16),d=e.exports.KEYBYTES_MAX=64,f=(e.exports.KEYBYTES=32,e.exports.SALTBYTES=16),p=e.exports.PERSONALBYTES=16;function g(e,t,r,i,o){if(!(this instanceof g))return new g(e,t,r,i,o);if(!n)throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");e||(e=32),!0!==o&&(s(e>=l,"digestLength must be at least "+l+", was given "+e),s(e<=h,"digestLength must be at most "+h+", was given "+e),null!=t&&(s(t instanceof Uint8Array,"key must be Uint8Array or Buffer"),s(t.length>=u,"key must be at least "+u+", was given "+t.length),s(t.length<=d,"key must be at least "+d+", was given "+t.length)),null!=r&&(s(r instanceof Uint8Array,"salt must be Uint8Array or Buffer"),s(r.length===f,"salt must be exactly "+f+", was given "+r.length)),null!=i&&(s(i instanceof Uint8Array,"personal must be Uint8Array or Buffer"),s(i.length===p,"personal must be exactly "+p+", was given "+i.length))),c.length||(c.push(a),a+=216),this.digestLength=e,this.finalized=!1,this.pointer=c.pop(),this._memory=new Uint8Array(n.memory.buffer),this._memory.fill(0,0,64),this._memory[0]=this.digestLength,this._memory[1]=t?t.length:0,this._memory[2]=1,this._memory[3]=1,r&&this._memory.set(r,32),i&&this._memory.set(i,48),this.pointer+216>this._memory.length&&this._realloc(this.pointer+216),n.blake2b_init(this.pointer,this.digestLength),t&&(this.update(t),this._memory.fill(0,a,a+t.length),this._memory[this.pointer+200]=128)}function y(){}g.prototype._realloc=function(e){n.memory.grow(Math.max(0,Math.ceil(Math.abs(e-this._memory.length)/65536))),this._memory=new Uint8Array(n.memory.buffer)},g.prototype.update=function(e){return s(!1===this.finalized,"Hash instance finalized"),s(e instanceof Uint8Array,"input must be Uint8Array or Buffer"),a+e.length>this._memory.length&&this._realloc(a+e.length),this._memory.set(e,a),n.blake2b_update(this.pointer,a,a+e.length),this},g.prototype.digest=function(e){if(s(!1===this.finalized,"Hash instance finalized"),this.finalized=!0,c.push(this.pointer),n.blake2b_final(this.pointer),!e||"binary"===e)return this._memory.slice(this.pointer+128,this.pointer+128+this.digestLength);if("string"==typeof e)return i.toString(this._memory,e,this.pointer+128,this.pointer+128+this.digestLength);s(e instanceof Uint8Array&&e.length>=this.digestLength,"input must be Uint8Array or Buffer");for(var t=0;t<this.digestLength;t++)e[t]=this._memory[this.pointer+128+t];return e},g.prototype.final=g.prototype.digest,g.WASM=n,g.SUPPORTED="undefined"!=typeof WebAssembly,g.ready=function(e){return e||(e=y),o?o.then(()=>e(),e):e(new Error("WebAssembly not supported"))},g.prototype.ready=g.ready,g.prototype.getPartialHash=function(){return this._memory.slice(this.pointer,this.pointer+216)},g.prototype.setPartialHash=function(e){this._memory.set(e,this.pointer)}},618:function(e,t,r){var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r),Object.defineProperty(e,s,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||t.hasOwnProperty(r)||s(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(8),t),i(r(154),t),i(r(984),t),i(r(212),t),i(r(429),t),i(r(951),t),i(r(412),t),i(r(872),t),i(r(301),t),i(r(516),t),i(r(660),t)},625:(t,r,s)=>{var i=e(import.meta.url+"/..").slice(0,-1);let n,o={};o.__wbindgen_placeholder__=t.exports;let a=null;function c(){return null!==a&&0!==a.byteLength||(a=new Uint8Array(n.memory.buffer)),a}let l=0;function h(e,t){const r=t(1*e.length,1)>>>0;return c().set(e,r/1),l=e.length,r}t.exports.verify_ed25519=function(e){const t=h(e,n.__wbindgen_malloc),r=l,s=n.verify_ed25519(t,r);var i,o,a=(i=s[0],o=s[1],i>>>=0,c().subarray(i/1,i/1+o)).slice();return n.__wbindgen_free(s[0],1*s[1],1),a},t.exports.verify_ed25519_batch=function(e){const t=h(e,n.__wbindgen_malloc),r=l;return 0!==n.verify_ed25519_batch(t,r)},t.exports.__wbindgen_init_externref_table=function(){const e=n.__wbindgen_export_0,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)};const u=s(928).join(i,"ed25519_wasm_bg.wasm"),d=s(896).readFileSync(u),f=new WebAssembly.Module(d),p=new WebAssembly.Instance(f,o);n=p.exports,t.exports.__wasm=n,n.__wbindgen_start()},660:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Validator=void 0;const s=r(8),i=r(8),n=r(872),o=r(984),a=r(984);class c{static isWithinRange(e,t,r){return e>=t&&e<=r}static isValidAsnNumber(e){let t=this.isWithinRange(e,0n,this.THIRTY_TWO_BIT_SIZE);return[t,t?[]:[c.invalidAsnRangeMessage]]}static isValid16BitAsnNumber(e){let t=c.isWithinRange(e,0n,c.SIXTEEN_BIT_SIZE);return[t,t?[]:[c.invalid16BitAsnRangeMessage]]}static isValidIPv4Number(e){e="bigint"==typeof e?e:BigInt(e);let t=this.isWithinRange(e,0n,this.THIRTY_TWO_BIT_SIZE);return t?[t,[]]:[t,[c.invalidIPv4NumberMessage]]}static isValidIPv6Number(e){let t=this.isWithinRange(e,0n,this.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE);return t?[t,[]]:[t,[c.invalidIPv6NumberMessage]]}static isValidIPv4Octet(e){let t=this.isWithinRange(e,0n,this.EIGHT_BIT_SIZE);return[t,t?[]:[c.invalidOctetRangeMessage]]}static isValidIPv6Hexadecatet(e){let t=this.isWithinRange(e,0n,this.SIXTEEN_BIT_SIZE);return t?[t,[]]:[t,[c.invalidHexadecatetMessage]]}static isValidIPv4String(e){let t=e.split(".");if(4!=t.length||t.includes(""))return[!1,[c.invalidOctetCountMessage]];let r=t.every(e=>!!c.isNumeric(e)&&c.isValidIPv4Octet(BigInt(e))[0]);return r?(r=c.IPV4_PATTERN.test(e),[r,r?[]:[c.invalidIPv4PatternMessage]]):[!1,[c.invalidOctetRangeMessage]]}static isValidIPv6String(e){try{let t=n.expandIPv6Number(e).split(":");if(8!=t.length)return[!1,[c.invalidHexadecatetCountMessage]];let r=t.every(e=>!!c.isHexadecatet(e)&&c.isValidIPv6Hexadecatet(BigInt(`0x${e}`))[0]);return r?(r=c.IPV6_PATTERN.test(e),[r,r?[]:[c.invalidIPv6PatternMessage]]):[!1,[c.invalidHexadecatetMessage]]}catch(e){return[!1,[e]]}}static isValidPrefixValue(e,t){if("IPv4"===t){let t=c.isWithinRange(BigInt(e),0n,32n);return[t,t?[]:[c.invalidPrefixValueMessage]]}if("IPv6"===t){let t=c.isWithinRange(BigInt(e),0n,128n);return[t,t?[]:[c.invalidPrefixValueMessage]]}return[!1,[c.invalidInetNumType]]}static isValidIPv4Mask(e){let t=s.dottedDecimalNotationToBinaryString(e),r=c.IPV4_CONTIGUOUS_MASK_BIT_PATTERN.test(t);return r?[r,[]]:[r,[c.invalidMaskMessage]]}static isValidIPv6Mask(e){let t=a.hexadectetNotationToBinaryString(e),r=c.IPV6_CONTIGUOUS_MASK_BIT_PATTERN.test(t);return r?[r,[]]:[r,[c.invalidMaskMessage]]}static isValidIPv4CidrNotation(e){let t=e.split("/");if(2!==t.length||0===t[0].length||0===t[1].length)return[!1,[c.invalidIPv4CidrNotationMessage]];let r=t[0],s=t[1];if(isNaN(Number(s)))return[!1,[c.invalidIPv4CidrNotationMessage]];let[i,n]=c.isValidIPv4String(r),[o,a]=c.isValidPrefixValue(BigInt(s),"IPv4"),l=i&&o,h=n.concat(a);return l?[l,[]]:[l,h]}static isValidIPv4CidrRange(e){return c.isValidCidrRange(e,c.isValidIPv4CidrNotation,s.dottedDecimalNotationToBinaryString,e=>i.cidrPrefixToMaskBinaryString(e,"IPv4"))}static isValidIPv6CidrRange(e){return c.isValidCidrRange(e,c.isValidIPv6CidrNotation,o.colonHexadecimalNotationToBinaryString,e=>i.cidrPrefixToMaskBinaryString(e,"IPv6"))}static isValidCidrRange(e,t,r,s){let i=t(e);if(!i[0])return i;let n=e.split("/"),o=n[0],a=n[1],l=BigInt(`0b${r(o)}`),h=(l&BigInt(`0b${s(parseInt(a))}`))===l;return h?[h,[]]:[h,[c.InvalidIPCidrRangeMessage]]}static isValidIPv4RangeString(e){return this.isValidRange(e,c.isValidIPv4String,(e,t)=>BigInt(`0b${s.dottedDecimalNotationToBinaryString(e)}`)>=BigInt(`0b${s.dottedDecimalNotationToBinaryString(t)}`))}static isValidIPv6RangeString(e){return this.isValidRange(e,c.isValidIPv6String,(e,t)=>BigInt(`0b${a.hexadectetNotationToBinaryString(e)}`)>=BigInt(`0b${a.hexadectetNotationToBinaryString(t)}`))}static isValidRange(e,t,r){let s=e.split("-").map(e=>e.trim());if(2!==s.length||0===s[0].length||0===s[1].length)return[!1,[c.invalidRangeNotationMessage]];let i=s[0],n=s[1],[o,a]=t(i),[l,h]=t(n),u=o&&l;if(u&&r(i,n))return[!1,[c.invalidRangeFirstNotGreaterThanLastMessage]];let d=a.concat(h);return u?[u,[]]:[u,d]}static isValidIPv6CidrNotation(e){let t=c.IPV6_RANGE_PATTERN.test(e);return t?[t,[]]:[t,[c.invalidIPv6CidrNotationString]]}static isValidBinaryString(e){return/^([10])+$/.test(e)?[!0,[]]:[!1,[c.invalidBinaryStringErrorMessage]]}static isNumeric(e){return/^(\d+)$/.test(e)}static isHexadecatet(e){return/^[0-9A-Fa-f]{4}$/.test(e)}}t.Validator=c,c.IPV4_PATTERN=new RegExp(/^(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/),c.IPV6_PATTERN=new RegExp(/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/),c.IPV4_RANGE_PATTERN=new RegExp(/^(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0?[0-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/)([1-9]|[1-2][0-9]|3[0-2])$/),c.IPV6_RANGE_PATTERN=new RegExp(/^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$/),c.IPV4_CONTIGUOUS_MASK_BIT_PATTERN=new RegExp(/^(1){0,32}(0){0,32}$/),c.IPV6_CONTIGUOUS_MASK_BIT_PATTERN=new RegExp(/^(1){0,128}(0){0,128}$/),c.EIGHT_BIT_SIZE=BigInt(`0b${"1".repeat(8)}`),c.SIXTEEN_BIT_SIZE=BigInt(`0b${"1".repeat(16)}`),c.THIRTY_TWO_BIT_SIZE=BigInt(`0b${"1".repeat(32)}`),c.ONE_HUNDRED_AND_TWENTY_EIGHT_BIT_SIZE=BigInt(`0b${"1".repeat(128)}`),c.IPV4_SIZE=BigInt("4294967296"),c.IPV6_SIZE=BigInt("340282366920938463463374607431768211456"),c.invalidAsnRangeMessage="ASN number given less than zero or is greater than 32bit",c.invalid16BitAsnRangeMessage="ASN number given less than zero or is greater than 16bit",c.invalidIPv4NumberMessage="IPv4 number given less than zero or is greater than 32bit",c.invalidIPv6NumberMessage="IPv6 number given less than zero or is greater than 128bit",c.invalidOctetRangeMessage="Value given contains an invalid Octet; Value is less than zero or is greater than 8bit",c.invalidHexadecatetMessage="The value given is less than zero or is greater than 16bit",c.invalidOctetCountMessage="An IP4 number cannot have less or greater than 4 octets",c.invalidHexadecatetCountMessage="An IP6 number must have exactly 8 hexadecatet",c.invalidMaskMessage="The Mask is invalid",c.invalidPrefixValueMessage="A Prefix value cannot be less than 0 or greater than 32",c.invalidIPv4CidrNotationMessage="Cidr notation should be in the form [ip number]/[range]",c.InvalidIPCidrRangeMessage="Given IP number portion must is not the start of the range",c.invalidRangeNotationMessage="Range notation should be in the form [first ip]-[last ip]",c.invalidRangeFirstNotGreaterThanLastMessage="First IP in [first ip]-[last ip] must be less than Last IP",c.invalidIPv6CidrNotationString="A Cidr notation string should contain an IPv6 number and prefix",c.takeOutOfRangeSizeMessage="$count is greater than $size, the size of the range",c.cannotSplitSingleRangeErrorMessage="Cannot split an IP range with a single IP number",c.invalidInetNumType="Given ipNumType must be either InetNumType.IPv4 or InetNumType.IPv6",c.invalidBinaryStringErrorMessage="Binary string should contain only contiguous 1s and 0s",c.invalidIPRangeSizeMessage="Given size is zero or greater than maximum size of $iptype",c.invalidIPRangeSizeForCidrMessage="Given size can't be created via cidr prefix",c.invalidIPv4PatternMessage="Given IPv4 is not confirm to a valid IPv6 address",c.invalidIPv6PatternMessage="Given IPv6 is not confirm to a valid IPv6 address"},675:(e,t,r)=>{var s=r(54),i=r(578);function n(e,t,r){var s=e[t]+e[r],i=e[t+1]+e[r+1];s>=4294967296&&i++,e[t]=s,e[t+1]=i}function o(e,t,r,s){var i=e[t]+r;r<0&&(i+=4294967296);var n=e[t+1]+s;i>=4294967296&&n++,e[t]=i,e[t+1]=n}function a(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function c(e,t,r,s,i,a){var c=d[i],l=d[i+1],h=d[a],f=d[a+1];n(u,e,t),o(u,e,c,l);var p=u[s]^u[e],g=u[s+1]^u[e+1];u[s]=g,u[s+1]=p,n(u,r,s),p=u[t]^u[r],g=u[t+1]^u[r+1],u[t]=p>>>24^g<<8,u[t+1]=g>>>24^p<<8,n(u,e,t),o(u,e,h,f),p=u[s]^u[e],g=u[s+1]^u[e+1],u[s]=p>>>16^g<<16,u[s+1]=g>>>16^p<<16,n(u,r,s),p=u[t]^u[r],g=u[t+1]^u[r+1],u[t]=g>>>31^p<<1,u[t+1]=p>>>31^g<<1}var l=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),h=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map(function(e){return 2*e})),u=new Uint32Array(32),d=new Uint32Array(32);function f(e,t){var r=0;for(r=0;r<16;r++)u[r]=e.h[r],u[r+16]=l[r];for(u[24]=u[24]^e.t,u[25]=u[25]^e.t/4294967296,t&&(u[28]=~u[28],u[29]=~u[29]),r=0;r<32;r++)d[r]=a(e.b,4*r);for(r=0;r<12;r++)c(0,8,16,24,h[16*r+0],h[16*r+1]),c(2,10,18,26,h[16*r+2],h[16*r+3]),c(4,12,20,28,h[16*r+4],h[16*r+5]),c(6,14,22,30,h[16*r+6],h[16*r+7]),c(0,10,20,30,h[16*r+8],h[16*r+9]),c(2,12,22,24,h[16*r+10],h[16*r+11]),c(4,14,16,26,h[16*r+12],h[16*r+13]),c(6,8,18,28,h[16*r+14],h[16*r+15]);for(r=0;r<16;r++)e.h[r]=e.h[r]^u[r]^u[r+16]}var p=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function g(e,t,r,s){p.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=e,p[0]=e,t&&(p[1]=t.length),p[2]=1,p[3]=1,r&&p.set(r,32),s&&p.set(s,48);for(var i=0;i<16;i++)this.h[i]=l[i]^a(p,4*i);t&&(y(this,t),this.c=128)}function y(e,t){for(var r=0;r<t.length;r++)128===e.c&&(e.t+=e.c,f(e,!1),e.c=0),e.b[e.c++]=t[r]}function m(e){return e<16?"0"+e.toString(16):e.toString(16)}g.prototype.update=function(e){return s(e instanceof Uint8Array,"input must be Uint8Array or Buffer"),y(this,e),this},g.prototype.digest=function(e){var t=e&&"binary"!==e&&"hex"!==e?e:new Uint8Array(this.outlen);return s(t instanceof Uint8Array,'out must be "binary", "hex", Uint8Array, or Buffer'),s(t.length>=this.outlen,"out must have at least outlen bytes of space"),function(e,t){for(e.t+=e.c;e.c<128;)e.b[e.c++]=0;f(e,!0);for(var r=0;r<e.outlen;r++)t[r]=e.h[r>>2]>>8*(3&r)}(this,t),"hex"===e?function(e){for(var t="",r=0;r<e.length;r++)t+=m(e[r]);return t}(t):t},g.prototype.final=g.prototype.digest,g.ready=function(e){i.ready(function(){e()})};var b=g;e.exports=function(e,t,r,i,n){return!0!==n&&(s(e>=A,"outlen must be at least "+A+", was given "+e),s(e<=I,"outlen must be at most "+I+", was given "+e),null!=t&&(s(t instanceof Uint8Array,"key must be Uint8Array or Buffer"),s(t.length>=v,"key must be at least "+v+", was given "+t.length),s(t.length<=w,"key must be at most "+w+", was given "+t.length)),null!=r&&(s(r instanceof Uint8Array,"salt must be Uint8Array or Buffer"),s(r.length===S,"salt must be exactly "+S+", was given "+r.length)),null!=i&&(s(i instanceof Uint8Array,"personal must be Uint8Array or Buffer"),s(i.length===E,"personal must be exactly "+E+", was given "+i.length))),new b(e,t,r,i)},e.exports.ready=function(e){i.ready(function(){e()})},e.exports.WASM_SUPPORTED=i.SUPPORTED,e.exports.WASM_LOADED=!1;var A=e.exports.BYTES_MIN=16,I=e.exports.BYTES_MAX=64,v=(e.exports.BYTES=32,e.exports.KEYBYTES_MIN=16),w=e.exports.KEYBYTES_MAX=64,S=(e.exports.KEYBYTES=32,e.exports.SALTBYTES=16),E=e.exports.PERSONALBYTES=16;i.ready(function(t){t||(e.exports.WASM_LOADED=!0,e.exports=i)})},810:(e,t,r)=>{e.exports=r.p+"b0733caf1cf3aa68.js"},872:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.collapseIPv6Number=t.expandIPv6Number=void 0;const s=r(8),i=r(660);let n=e=>e.includes("/")?`/${e.split("/")[1]}`:"";t.expandIPv6Number=e=>{let t=e=>e.map(e=>s.leftPadWithZeroBit(e,4)).join(":");if(/(:){3,}/.test(e))throw"given IPv6 contains consecutive : more than two";const r=n(e);if(e.includes("/")&&(e=e.split("/")[0]),!i.Validator.IPV6_PATTERN.test(e))throw Error(i.Validator.invalidIPv6PatternMessage);if(e.includes("::")){let s=e.split("::"),i=s[0],n=s[1],o=i.split(":").filter(e=>""!==e),a=n.split(":").filter(e=>""!==e),c=(e=>{let t=[];for(let r=0;r<e;r++)t.push("0000");return t.join(":")})(8-(o.length+a.length)),l=t(o);""!==l&&(l+=":");let h=t(a);return""!==h&&(h=":"+h),`${l}${c}${h}${r}`}return`${t(e.split(":"))}${r}`},t.collapseIPv6Number=e=>{const t=n(e);if(e.includes("/")&&(e=e.split("/")[0]),!i.Validator.IPV6_PATTERN.test(e))throw Error(i.Validator.invalidIPv6PatternMessage);let r=e.split(":").map(e=>{let t=e.replace(/^0+/,"");return""!==t?t:"0"}).join(":").replace(/((^0)?(:0){2,}|(^0)(:0){1,})/,":");return":"===r.slice(-1)?`${r}:${t}`:(r=r.replace(":0:","::"),`${r}${t}`)}},884:e=>{e.exports="data:application/javascript;base64,aW1wb3J0IHsgdHNJbXBvcnQgfSBmcm9tICJ0c3gvZXNtL2FwaSI7CmNvbnN0IHsgd29ya2VyIH0gPSBhd2FpdCB0c0ltcG9ydCgiLi93b3JrZXIudHMiLCBpbXBvcnQubWV0YS51cmwpOwp3b3JrZXIubGlzdGVuVG9QYXJlbnRQb3J0KCk7Cg=="},896:e=>{e.exports=t(import.meta.url)("fs")},909:()=>{var e;!function(e){!function(){var t="object"==typeof globalThis?globalThis:"object"==typeof global?global:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),r=s(e);function s(e,t){return function(r,s){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:s}),t&&t(r,s)}}void 0!==t.Reflect&&(r=s(t.Reflect,r)),function(e,t){var r=Object.prototype.hasOwnProperty,s="function"==typeof Symbol,i=s&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",n=s&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",o="function"==typeof Object.create,a={__proto__:[]}instanceof Array,c=!o&&!a,l={create:o?function(){return V(Object.create(null))}:a?function(){return V({__proto__:null})}:function(){return V({})},has:c?function(e,t){return r.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return r.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},h=Object.getPrototypeOf(Function),u="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:function(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[n]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:r,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}(),s=function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var r=this._find(e,!0);return this._values[r]=t,this},t.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var s=this._keys.length,i=r+1;i<s;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,N(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new r(this._keys,this._values,i)},t.prototype.values=function(){return new r(this._keys,this._values,o)},t.prototype.entries=function(){return new r(this._keys,this._values,a)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[n]=function(){return this.entries()},t.prototype._find=function(e,t){if(!N(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(N(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();return s;function i(e,t){return e}function o(e,t){return t}function a(e,t){return[e,t]}}(),d="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:function(){function e(){this._map=new u}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[n]=function(){return this.keys()},e}(),f="function"==typeof WeakMap?WeakMap:function(){var e=l.create(),t=s();return function(){function e(){this._key=s()}return e.prototype.has=function(e){var t=i(e,!1);return void 0!==t&&l.has(t,this._key)},e.prototype.get=function(e){var t=i(e,!1);return void 0!==t?l.get(t,this._key):void 0},e.prototype.set=function(e,t){return i(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=i(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=s()},e}();function s(){var t;do{t="@@WeakMap@@"+o()}while(l.has(e,t));return e[t]=!0,t}function i(e,s){if(!r.call(e,t)){if(!s)return;Object.defineProperty(e,t,{value:l.create()})}return e[t]}function n(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}function o(){var e=function(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):n(t,e),t}return n(new Array(e),e)}(16);e[6]=79&e[6]|64,e[8]=191&e[8]|128;for(var t="",r=0;r<16;++r){var s=e[r];4!==r&&6!==r&&8!==r||(t+="-"),s<16&&(t+="0"),t+=s.toString(16).toLowerCase()}return t}}(),p=s?Symbol.for("@reflect-metadata:registry"):void 0,g=function(){var e;return!C(p)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[p]),C(e)&&(e=function(){var e,r,s,i;C(p)||void 0===t.Reflect||p in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=function(e){var t=e.defineMetadata,r=e.hasOwnMetadata,s=e.getOwnMetadata,i=e.getOwnMetadataKeys,n=e.deleteMetadata,o=new f,a={isProviderFor:function(e,t){var r=o.get(e);return!(C(r)||!r.has(t))||!!i(e,t).length&&(C(r)&&(r=new d,o.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:s,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:n};return a}(t.Reflect));var n=new f,o={registerProvider:a,getProvider:l,setProvider:g};return o;function a(t){if(!Object.isExtensible(o))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case C(r):r=t;break;case r===t:break;case C(s):s=t;break;case s===t:break;default:void 0===i&&(i=new d),i.add(t)}}function c(t,n){if(!C(r)){if(r.isProviderFor(t,n))return r;if(!C(s)){if(s.isProviderFor(t,n))return r;if(!C(i))for(var o=M(i);;){var a=L(o);if(!a)return;var c=P(a);if(c.isProviderFor(t,n))return H(o),c}}}if(!C(e)&&e.isProviderFor(t,n))return e}function l(e,t){var r,s=n.get(e);return C(s)||(r=s.get(t)),C(r)?(C(r=c(e,t))||(C(s)&&(s=new u,n.set(e,s)),s.set(t,r)),r):r}function h(e){if(C(e))throw new TypeError;return r===e||s===e||!C(i)&&i.has(e)}function g(e,t,r){if(!h(r))throw new Error("Metadata provider not registered.");var s=l(e,t);if(s!==r){if(!C(s))return!1;var i=n.get(e);C(i)&&(i=new u,n.set(e,i)),i.set(t,r)}return!0}}()),!C(p)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,p,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}(),y=function(e){var t=new f,r={isProviderFor:function(e,r){var s=t.get(e);return!C(s)&&s.has(r)},OrdinaryDefineOwnMetadata:function(e,t,r,i){s(r,i,!0).set(e,t)},OrdinaryHasOwnMetadata:function(e,t,r){var i=s(t,r,!1);return!C(i)&&B(i.has(e))},OrdinaryGetOwnMetadata:function(e,t,r){var i=s(t,r,!1);if(!C(i))return i.get(e)},OrdinaryOwnMetadataKeys:function(e,t){var r=[],i=s(e,t,!1);if(C(i))return r;for(var n=M(i.keys()),o=0;;){var a=L(n);if(!a)return r.length=o,r;var c=P(a);try{r[o]=c}catch(e){try{H(n)}finally{throw e}}o++}},OrdinaryDeleteMetadata:function(e,r,i){var n=s(r,i,!1);if(C(n))return!1;if(!n.delete(e))return!1;if(0===n.size){var o=t.get(r);C(o)||(o.delete(i),0===o.size&&t.delete(o))}return!0}};return g.registerProvider(r),r;function s(s,i,n){var o=t.get(s),a=!1;if(C(o)){if(!n)return;o=new u,t.set(s,o),a=!0}var c=o.get(i);if(C(c)){if(!n)return;if(c=new u,o.set(i,c),!e.setProvider(s,i,r))throw o.delete(i),a&&t.delete(s),new Error("Wrong provider for target.")}return c}}(g);function m(e,t,r){if(b(e,t,r))return!0;var s=K(t);return!k(s)&&m(e,s,r)}function b(e,t,r){var s=Q(t,r,!1);return!C(s)&&B(s.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(b(e,t,r))return I(e,t,r);var s=K(t);return k(s)?void 0:A(e,s,r)}function I(e,t,r){var s=Q(t,r,!1);if(!C(s))return s.OrdinaryGetOwnMetadata(e,t,r)}function v(e,t,r,s){Q(r,s,!0).OrdinaryDefineOwnMetadata(e,t,r,s)}function w(e,t){var r=S(e,t),s=K(e);if(null===s)return r;var i=w(s,t);if(i.length<=0)return r;if(r.length<=0)return i;for(var n=new d,o=[],a=0,c=r;a<c.length;a++){var l=c[a];n.has(l)||(n.add(l),o.push(l))}for(var h=0,u=i;h<u.length;h++)l=u[h],n.has(l)||(n.add(l),o.push(l));return o}function S(e,t){var r=Q(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function E(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function C(e){return void 0===e}function k(e){return null===e}function x(e){return"object"==typeof e?null!==e:"function"==typeof e}function _(e,t){switch(E(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var r=3===t?"string":5===t?"number":"default",s=D(e,i);if(void 0!==s){var n=s.call(e,r);if(x(n))throw new TypeError;return n}return function(e,t){if("string"===t){var r=e.toString;if(U(r)&&!x(i=r.call(e)))return i;if(U(s=e.valueOf)&&!x(i=s.call(e)))return i}else{var s;if(U(s=e.valueOf)&&!x(i=s.call(e)))return i;var i,n=e.toString;if(U(n)&&!x(i=n.call(e)))return i}throw new TypeError}(e,"default"===r?"number":r)}function B(e){return!!e}function R(e){var t=_(e,3);return"symbol"==typeof t?t:function(e){return""+e}(t)}function O(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function U(e){return"function"==typeof e}function T(e){return"function"==typeof e}function N(e,t){return e===t||e!=e&&t!=t}function D(e,t){var r=e[t];if(null!=r){if(!U(r))throw new TypeError;return r}}function M(e){var t=D(e,n);if(!U(t))throw new TypeError;var r=t.call(e);if(!x(r))throw new TypeError;return r}function P(e){return e.value}function L(e){var t=e.next();return!t.done&&t}function H(e){var t=e.return;t&&t.call(e)}function K(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===h)return t;if(t!==h)return t;var r=e.prototype,s=r&&Object.getPrototypeOf(r);if(null==s||s===Object.prototype)return t;var i=s.constructor;return"function"!=typeof i||i===e?t:i}function Q(e,t,r){var s=g.getProvider(e,t);if(!C(s))return s;if(r){if(g.setProvider(e,t,y))return y;throw new Error("Illegal state.")}}function V(e){return e.__=void 0,delete e.__,e}e("decorate",function(e,t,r,s){if(C(r)){if(!O(e))throw new TypeError;if(!T(t))throw new TypeError;return function(e,t){for(var r=e.length-1;r>=0;--r){var s=(0,e[r])(t);if(!C(s)&&!k(s)){if(!T(s))throw new TypeError;t=s}}return t}(e,t)}if(!O(e))throw new TypeError;if(!x(t))throw new TypeError;if(!x(s)&&!C(s)&&!k(s))throw new TypeError;return k(s)&&(s=void 0),function(e,t,r,s){for(var i=e.length-1;i>=0;--i){var n=(0,e[i])(t,r,s);if(!C(n)&&!k(n)){if(!x(n))throw new TypeError;s=n}}return s}(e,t,r=R(r),s)}),e("metadata",function(e,t){return function(r,s){if(!x(r))throw new TypeError;if(!C(s)&&!function(e){switch(E(e)){case 3:case 4:return!0;default:return!1}}(s))throw new TypeError;v(e,t,r,s)}}),e("defineMetadata",function(e,t,r,s){if(!x(r))throw new TypeError;return C(s)||(s=R(s)),v(e,t,r,s)}),e("hasMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),m(e,t,r)}),e("hasOwnMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),b(e,t,r)}),e("getMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),A(e,t,r)}),e("getOwnMetadata",function(e,t,r){if(!x(t))throw new TypeError;return C(r)||(r=R(r)),I(e,t,r)}),e("getMetadataKeys",function(e,t){if(!x(e))throw new TypeError;return C(t)||(t=R(t)),w(e,t)}),e("getOwnMetadataKeys",function(e,t){if(!x(e))throw new TypeError;return C(t)||(t=R(t)),S(e,t)}),e("deleteMetadata",function(e,t,r){if(!x(t))throw new TypeError;if(C(r)||(r=R(r)),!x(t))throw new TypeError;C(r)||(r=R(r));var s=Q(t,r,!1);return!C(s)&&s.OrdinaryDeleteMetadata(e,t,r)})}(r,t),void 0===t.Reflect&&(t.Reflect=e)}()}(e||(e={}))},928:e=>{e.exports=t(import.meta.url)("path")},951:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Pool=void 0;const s=r(412),i=r(516);class n{constructor(e){this.backingSet=new o,e.forEach(e=>{this.backingSet.add(e)})}static fromIP(e){let t=e.map(e=>s.RangedSet.fromSingleIP(e));return new n(t)}static fromRangeSet(e){return new n(e)}static fromCidrRanges(e){let t=e.map(e=>e.toRangeSet());return new n(t)}getRanges(){return this.backingSet.asArray()}aggregate(){let e=this.backingSet.asArray().reduce((e,t,r,s)=>{if(0==e.length)return e.push(t),e;{let r=e.pop(),s=r.toCidrRange(),i=t.toCidrRange();if(s.isCidrMergeable(i)){let t=s.merge(i);return e.push(t.toRangeSet()),e}return r.contains(t)?e.push(r):(e.push(r),e.push(t)),e}},[]),t=n.fromRangeSet(e);return t.getRanges().length!==this.getRanges().length?t.aggregate():t}getCidrRange(e){if(e.toRangeSize()>this.getSize())throw new Error(`Not enough IP number in the pool for requested prefix: ${e}`);let t,r;e:for(let s of this.getRanges())for(let i=0n;i+e.toRangeSize()<=s.getSize();i+=1n)try{let r=s.takeSubRange(i,e.toRangeSize());t=r.toCidrRange();let n=s.difference(r);this.removeExact(s),this.add(n);break e}catch(e){if(e instanceof RangeError)continue e;r=e}if(t)return t;throw void 0===r?new Error(`No range big enough in the pool for requested prefix: ${e}`):r}getCidrRanges(e){if(e.toRangeSize()>this.getSize())throw new Error("Prefix greater than pool");let t=(e,r,s)=>{try{let i=this.getCidrRange(r);s.push(i);let n=s.reduce((e,t)=>e+t.getSize(),0n);return e.toRangeSize()===n?s:t(e,r,s)}catch(n){let o=i.isIPv4Prefix(r)?i.IPv4Prefix.fromNumber(r.getValue()+1n):i.IPv6Prefix.fromNumber(r.getValue()+1n);return t(e,o,s)}};return t(e,e,[])}getSize(){return this.aggregate().getRanges().reduce((e,t)=>e+t.getSize(),0n)}resetWith(e){this.backingSet.clear(),this.backingSet=this.backingSet.add(e)}removeExact(e){let t=this.backingSet.removeExact(e),r=!this.backingSet.isEquals(t);return this.backingSet=t,r}removeOverlapping(e){let t=this.backingSet.removeOverlapping(e),r=!this.backingSet.isEquals(t);return this.backingSet=t,r}add(e){this.backingSet=this.backingSet.add(e)}clear(){this.backingSet.clear()}}t.Pool=n;class o{constructor(e){this.backingArray=e?this.sortArray(e):new Array}sortArray(e){return e.sort((e,t)=>e.isLessThan(t)?-1:e.isGreaterThan(t)?1:0),e}asArray(){return this.backingArray}isEquals(e){return this.backingArray.length===e.asArray().length&&this.backingArray.every((t,r)=>t.getSize()===e.asArray()[r].getSize())}add(e){let t=this.backingArray;return"push"in e?t=t.concat(e):t.push(e),new o(this.sortArray(t))}removeExact(e){let t=this.backingArray.filter(t=>"push"in e?void 0!==e.find(e=>e.isEquals(t)):!e.isEquals(t));return new o(this.sortArray(t))}removeOverlapping(e){let t=this.backingArray.flatMap(t=>{if("push"in e)return e.flatMap(e=>t.contains(e)?t.difference(e):t.inside(e)?new Array:t.isOverlapping(e)?[t.subtract(e)]:[e]);try{return t.difference(e)}catch(e){return t}});return new o(this.sortArray(t))}clear(){this.backingArray=[]}}},984:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.hexadectetNotationToBinaryString=t.binaryStringToHexadecimalString=t.colonHexadecimalNotationToBinaryString=t.hexadecimalStringToHexadecatetString=t.hexadecimalStringToBinaryString=t.bigIntToHexadecimalString=void 0;const s=r(872),i=r(8);t.bigIntToHexadecimalString=e=>e.toString(16),t.hexadecimalStringToBinaryString=e=>BigInt(`0x${e}`).toString(2),t.hexadecimalStringToHexadecatetString=e=>{let r=t.hexadecimalStringToBinaryString(e);if(r.length>16)throw new Error("Given decimal in binary contains digits greater than an Hexadecatet");return i.leftPadWithZeroBit(r,16)},t.colonHexadecimalNotationToBinaryString=e=>s.expandIPv6Number(e).split(":").reduce((e,r)=>e.concat(t.hexadecimalStringToHexadecatetString(r)),""),t.binaryStringToHexadecimalString=e=>BigInt(`0b${e}`).toString(16),t.hexadectetNotationToBinaryString=e=>s.expandIPv6Number(e).split(":").reduce((e,r)=>e.concat(i.leftPadWithZeroBit(t.hexadecimalStringToBinaryString(r),16)),"")}},n={};function o(e){var t=n[e];if(void 0!==t)return t.exports;var r=n[e]={exports:{}};return i[e].call(r.exports,r,r.exports,o),r.exports}o.m=i,o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;if("string"==typeof import.meta.url&&(e=import.meta.url),!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o.p=e})(),o.b=new URL("./",import.meta.url);var a={};o.r(a),o.d(a,{Any:()=>Am,BaseBlock:()=>Tg,BaseStringBlock:()=>Dg,BitString:()=>Ty,BmpString:()=>em,Boolean:()=>By,CharacterString:()=>um,Choice:()=>Im,Constructed:()=>Ey,DATE:()=>pm,DateTime:()=>ym,Duration:()=>mm,EndOfContent:()=>ky,Enumerated:()=>Hy,GeneralString:()=>hm,GeneralizedTime:()=>fm,GraphicString:()=>cm,HexBlock:()=>xg,IA5String:()=>am,Integer:()=>Ly,Null:()=>xy,NumericString:()=>sm,ObjectIdentifier:()=>Vy,OctetString:()=>Oy,Primitive:()=>Ay,PrintableString:()=>im,RawData:()=>wm,RelativeObjectIdentifier:()=>jy,Repeated:()=>vm,Sequence:()=>Gy,Set:()=>qy,TIME:()=>bm,TeletexString:()=>nm,TimeOfDay:()=>gm,UTCTime:()=>dm,UniversalString:()=>rm,Utf8String:()=>Xy,ValueBlock:()=>Bg,VideotexString:()=>om,ViewWriter:()=>cg,VisibleString:()=>lm,compareSchema:()=>Sm,fromBER:()=>vy,verifySchema:()=>Em});const c=t(import.meta.url)("node:url");var l;function h(e){const t="debug"===e?"LOG":e.toUpperCase();if(void 0===l[t])throw new Error(`Unknown logging level: "${e}". Use one of "trace", "debug", "log","info", "warn", "error"`);return l[t]}!function(e){e[e.TRACE=1]="TRACE",e[e.LOG=2]="LOG",e[e.INFO=3]="INFO",e[e.WARN=4]="WARN",e[e.ERROR=5]="ERROR"}(l||(l={}));class u{options;static create(e,t){return e===l.TRACE?new d(t):e===l.LOG?new f(t):e===l.INFO?new p(t):new u(t)}constructor(e){this.options=e}trace(e,t,r){}log(e,t,r){}info(e,t,r){}warn(e,t,r){this.push(l.WARN,e,t,r)}error(e,t,r){this.push(l.ERROR,e,t,r)}push(e,t,r,s){const i=r.replace(this.options.workingDir,""),n=t.replace(this.options.workingDir,""),o=function(e,t){let r=t;for(;;){const s=e.modules.get(r);if(void 0!==s)return s;const i=r.lastIndexOf("/");if(-1===i)return e.defaultLevel;r=t.substring(0,i)}}(this.options,t),a=l[e].padEnd(5);if(e<o)return;const c=`${a} [${n}] ${s}\n\t@ ${i}`;e===l.WARN?console.warn(c):e===l.ERROR?console.error(c):console.info(c)}}class d extends u{trace(e,t,r){this.push(l.TRACE,e,t,r)}log(e,t,r){this.push(l.LOG,e,t,r)}info(e,t,r){this.push(l.INFO,e,t,r)}}class f extends u{trace(e,t,r){}log(e,t,r){this.push(l.LOG,e,t,r)}info(e,t,r){this.push(l.INFO,e,t,r)}}class p extends u{trace(e,t,r){}log(e,t,r){}info(e,t,r){this.push(l.INFO,e,t,r)}}const g={workingDir:"",defaultLevel:l.LOG,modules:new Map},y={options:g,transport:u.create(g.defaultLevel,g)};class m{moduleName;fileName;config;static new(e,t){const r=e??"unknown";return new m(t??r,r,y)}static configureAllFromOptions(e){const t=Array.from(e.modules.values()).reduce((e,t)=>e<t?e:t,e.defaultLevel),r=u.create(t,e);y.options=e,y.transport=r}static configureAll(e,t,r){const s=function(e,t,r){const s=new Map,i=e.toLowerCase().split(",");let n=t;for(const e of i){const t=e.trim();if(0!==t.length)if(t.includes("=")){const[e,r]=t.split("=");s.set(e.trim(),h(r.trim()))}else n=h(t)}const o="".split("/");return o.pop(),o.pop(),{defaultLevel:n,modules:s,workingDir:r??o.join("/")}}(e,t,r);m.configureAllFromOptions(s)}constructor(e,t,r){this.moduleName=e,this.fileName=t,this.config=r}trace(e){this.config.transport.trace(this.moduleName,this.fileName,e)}log(e){this.config.transport.log(this.moduleName,this.fileName,e)}info(e){this.config.transport.info(this.moduleName,this.fileName,e)}warn(e){this.config.transport.warn(this.moduleName,this.fileName,e)}error(e){this.config.transport.error(this.moduleName,this.fileName,e)}}const b=t(import.meta.url)("node:os");var A=o.n(b);const I=(E={default:()=>r.default},C={},o.d(C,E),C),v="dev",w={name:A().hostname(),config:v},S=`\n@typeberry/jam 0.0.1 by Fluffy Labs.\n\nUsage:\n jam [options]\n jam [options] import <bin-or-json-blocks>\n\nOptions:\n --name Override node name. Affects networking key and db location.\n [default: ${w.name}]\n --config Path to a config file or '${v}'.\n [default: ${w.config}]\n`;var E,C,k;function x(e,t){const{name:r}=B(e,"name",e=>e,w.name),{config:s}=B(e,"config",e=>e===v?v:t(e),w.config);return{nodeName:r,configPath:s}}function _(e,t){const r=(0,I.default)(e),s=r._.shift()??k.Run;switch(s){case k.Run:{const e=x(r,t);return R(r),{command:k.Run,args:e}}case k.Import:{const e=x(r,t),s=r._.map(e=>t(e));return r._=[],R(r),{command:k.Import,args:{...e,files:s}}}default:r._.unshift(s),R(r)}throw new Error(`Invalid arguments: ${JSON.stringify(r)}`)}function B(e,t,r,s){const i=e[t];if(void 0===i)return{[t]:s};if(delete e[t],"string"!=typeof i)throw new Error(`Option '--${t}' requires an argument.`);try{const e=r(i);return{[t]:e??s}}catch(e){throw new Error(`Invalid value '${i}' for option '${t}': ${e}`)}}function R(e){const t=Object.keys(e).filter(e=>"_"!==e&&"--"!==e);if(e._.length>0)throw new Error(`Unexpected command: '${e._[0]}'`);if((e["--"]?.length??0)>0)throw new Error(`Unexpected parameters: '${e["--"]?.[0]}'...`);if(t.length>0)throw new Error(`Unrecognized options: '${t}'`)}!function(e){e.Run="run",e.Import="import"}(k||(k={}));const O=t(import.meta.url)("node:fs");var U=o.n(O);const T=t(import.meta.url)("node:worker_threads");var N,D;!function(e){e[e.Less=-1]="Less",e[e.Equal=0]="Equal",e[e.Greater=1]="Greater"}(N||(N={}));class M{value;constructor(e){this.value=e}static Less=new M(N.Less);static Greater=new M(N.Greater);static Equal=new M(N.Equal);isLess(){return this.value===N.Less}isGreater(){return this.value===N.Greater}isEqual(){return this.value===N.Equal}isNotEqual(){return!this.isEqual()}isGreaterOrEqual(){return this.isEqual()||this.isGreater()}isLessOrEqual(){return this.isEqual()||this.isLess()}}!function(e){e.V0_6_4="0.6.4",e.V0_6_5="0.6.5",e.V0_6_6="0.6.6",e.V0_6_7="0.6.7",e.V0_7_0="0.7.0"}(D||(D={}));const P=[D.V0_6_4,D.V0_6_5,D.V0_6_6,D.V0_6_7,D.V0_7_0],L=D.V0_6_5;let H=function(e){if(void 0===e)return;const t=e;if(!Object.values(D).includes(t))throw new Error(`Configured environment variable GP_VERSION is unknown: '${e}'. Use one of: ${P}`);return t}(process.env.GP_VERSION);class K{static override(e){H=e}static is(...e){return void 0===H?e.includes(L):e.includes(H)}static isGreaterOrEqual(e){const t=P.indexOf(e);if(-1===t)throw new Error(`Invalid version: ${e}. Not found amongst supported versions: ${P}`);return K.is(...P.slice(t))}}function Q(e,t){if(!e)throw new Error(`Assertion failure: ${t??""}`)}function V(e,t,r){if(function(e,t){return t}(0,t))return e;throw new Error(`Assertion failure: ${r??""}`)}function F(e){throw new Error(`Unexpected value: ${e}`)}function $(e){const t=e=>e.split("\n").map(e=>` ${e}`).join("\n").trim();if(null===e)return"<null>";if(void 0===e)return"<undefined>";if(Array.isArray(e))return`[${e.map(e=>$(e))}]`;if(e instanceof Map)return $(Array.from(e.entries()));if("number"==typeof e)return`${e} (0x${e.toString(16)})`;if("object"!=typeof e)return`${e}`;if("toString"in e&&Object.prototype.toString!==e.toString&&G.prototype.toString!==e.toString)return`${e}`;const r=e.constructor.name;let s="Object"!==r?`${r} {`:"{";const i=Object.keys(e),n=i.length<3;for(const r of i)"string"==typeof r&&(s+=n?"":"\n ",s+=`${r}: ${t($(e[r]))}`,s+=n?",":"");return s+=n?"}":"\n}",s}const j="undefined"==typeof process?e=>{const t=performance.now();return()=>`${e} took ${performance.now()-t}ms`}:e=>{const t=process.hrtime.bigint();return()=>{const r=process.hrtime.bigint()-t,s=Number(r/1000000n).toFixed(2);return`${e} took ${s}ms`}};class G{toString(){return $(this)}}function q(e){return e}function z(e){return e}const W=Symbol("ok");class J{kind;error;enumMapping;constructor(e,t,r){this.kind=e,this.error=t,this.enumMapping=r}toString(){const e=Object.keys(this.enumMapping).find(e=>this.enumMapping[e]===this.kind)??"?";return`${e} (${this.kind}) - ${Y(this.error)}`}}const Y=e=>{return null!==(t=e)&&"object"==typeof t&&"kind"in t&&"error"in t?e instanceof J?e.toString():`${e.kind} - ${Y(e.error)}`:`${e}`;var t};function X(e){return e.isOk?`OK: ${"symbol"==typeof e.ok?e.ok.toString():e.ok}`:`${e.details}\nError: ${Y(e.error)}`}const Z={ok:e=>(Q(void 0!==e,"`Ok` type cannot be undefined."),{isOk:!0,isError:!1,ok:e}),error:(e,t="")=>(Q(void 0!==e,"`Error` type cannot be undefined."),{isOk:!1,isError:!0,error:e,details:t}),taggedError:(e,t,r)=>Z.error(new J(t,r.error,e),r.details)},ee=(t(import.meta.url)("node:assert"),Symbol("compare via string"));class te{[ee]=!0;raw;length=0;constructor(e){this.raw=e,this.length=e.byteLength}toString(){return function(e){const t=e=>e>=he?String.fromCharCode(e+oe-he):String.fromCharCode(e+ie);let r="0x";for(const s of e)r+=t(s>>>4),r+=t(15&s);return r}(this.raw)}asText(){return(new TextDecoder).decode(this.raw)}isEqualTo(e){return this.length===e.length&&de(this.raw,e.raw)}compare(e){const t=Math.min(this.length,e.length),r=this.raw,s=e.raw;for(let e=0;e<t;e++){if(r[e]<s[e])return M.Less;if(r[e]>s[e])return M.Greater}return this.length<e.length?M.Less:this.length>e.length?M.Greater:M.Equal}static empty(){return new te(new Uint8Array)}static blobFromString(e){const t=new TextEncoder;return te.blobFrom(t.encode(e))}static blobFrom(e){return new te(e)}static blobFromParts(e,...t){const r=e instanceof Uint8Array?[e]:e,s=r.reduce((e,t)=>e+t.length,0)+t.reduce((e,t)=>e+t.length,0),i=new Uint8Array(s);let n=0;for(const e of r)i.set(e,n),n+=e.length;for(const e of t)i.set(e,n),n+=e.length;return new te(i)}static blobFromNumbers(e){Q(void 0===e.find(e=>(255&e)!==e),"BytesBlob.blobFromNumbers used with non-byte number array.");const t=new Uint8Array(e);return new te(t)}static parseBlobNoPrefix(e){const t=e.length;if(t%2==1)throw new Error(`Odd number of nibbles. Invalid hex string: ${e}.`);const r=new ArrayBuffer(t/2),s=new Uint8Array(r);for(let r=0;r<t-1;r+=2){const t=e.substring(r,r+2);s[r/2]=se(t)}return new te(s)}static parseBlob(e){if(!e.startsWith("0x"))throw new Error(`Missing 0x prefix: ${e}.`);return te.parseBlobNoPrefix(e.substring(2))}*chunks(e){for(let t=0;t<this.length;t+=e)yield te.blobFrom(this.raw.subarray(t,t+e))}}class re extends te{length;constructor(e,t){super(e),Q(e.byteLength===t,`Given buffer has incorrect size ${e.byteLength} vs expected ${t}`),this.length=t}static fromBlob(e,t){return new re(e,t)}static fromNumbers(e,t){Q(void 0===e.find(e=>(255&e)!==e),"Bytes.fromNumbers used with non-byte number array.");const r=new Uint8Array(e);return new re(r,t)}static zero(e){return new re(new Uint8Array(e),e)}static fill(e,t){Q((255&t)===t,"Input has to be a byte.");const r=re.zero(e);return r.raw.fill(t,0,e),r}static parseBytesNoPrefix(e,t){if(e.length>2*t)throw new Error(`Input string too long. Expected ${t}, got ${e.length/2}`);const r=te.parseBlobNoPrefix(e);return new re(r.raw,t)}static parseBytes(e,t){if(e.length>2*t+2)throw new Error(`Input string too long. Expected ${t}, got ${e.length/2-1}`);const r=te.parseBlob(e);return new re(r.raw,t)}isEqualTo(e){return Q(this.length===e.length,"Comparing incorrectly typed bytes!"),de(this.raw,e.raw)}asOpaque(){return this}}function se(e){return Q(2===e.length,"Two-character string expected"),ue(e.charCodeAt(0))<<4|ue(e.charCodeAt(1))}const ie="0".charCodeAt(0),ne="9".charCodeAt(0),oe="a".charCodeAt(0),ae="f".charCodeAt(0),ce="A".charCodeAt(0),le="F".charCodeAt(0),he=10;function ue(e){if(e>=ie&&e<=ne)return e-ie;if(e>=oe&&e<=ae)return e-oe+he;if(e>=ce&&e<=le)return e-ce+he;throw new Error(`Invalid characters in hex byte string: ${String.fromCharCode(e)}`)}function de(e,t){for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}const fe=(e,t)=>e.compare(t);class pe{data;bitLength;static fromBlob(e,t){return new pe(e,t)}static fromBytes(e,t){return new pe(e.raw,t)}static empty(e){const t=new Uint8Array(Math.ceil(e/8));return new pe(t,e)}byteLength;constructor(e,t){this.data=e,this.bitLength=t,Q(8*e.length>=t,`Not enough bytes in the data array. Need ${8*e.length} has ${t}.`),this.byteLength=Math.ceil(t/8)}get raw(){return this.data.subarray(0,this.byteLength)}sumWith(e){Q(e.bitLength===this.bitLength,`Invalid bit length for sumWith: ${e.bitLength} vs ${this.bitLength}`);const t=e.raw;for(let e=0;e<this.byteLength;e++)this.data[e]|=t[e]}setBit(e,t){Q(e<this.bitLength,`Index out of bounds. Need ${e} has ${this.bitLength}.`);const r=Math.floor(e/8),s=1<<e%8;t?this.data[r]|=s:this.data[r]&=~s}isSet(e){Q(e<this.bitLength,`Index out of bounds. Need ${e} has ${this.bitLength}.`);const t=Math.floor(e/8),r=1<<e%8;return(this.data[t]&r)>0}*indicesOfSetBits(){for(let e=0;e<this.bitLength;e++){const t=e>>3,r=e-(t<<3);1&~(this.data[t]>>r)||(yield e)}}}const ge=e=>V(e,ye(e),`input must have one-byte representation, got ${e}`),ye=e=>(255&e)===e,me=e=>V(e,be(e),`input must have two-byte representation, got ${e}`),be=e=>(65535&e)===e,Ae=e=>V(e,Ie(e),`input must have four-byte representation, got ${e}`),Ie=e=>(4294967295&e)>>>0===e,ve=e=>{const t=BigInt(e);return V(t,we(t),`input must have eight-byte representation, got ${e}`)},we=e=>(18446744073709551615n&e)===e;function Se(...e){let t=0n;for(const r of e)t+=r;const r=!we(t);return t&=0xffffffffffffffffn,{overflow:r,value:ve(t)}}function Ee(e){return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}function Ce(e){return Q(4===e.length,"Input must be a Uint8Array of length 4"),e[0]|e[1]<<8|e[2]<<16|e[3]<<24}const ke=(e,...t)=>t.reduce((e,t)=>t>e?e:t,e);class xe{source;offset;context;static fromBytesBlob(e,t){return new xe(e.raw,t)}static fromBlob(e){return new xe(e)}static decodeObject(e,t,r){const s=t instanceof te?xe.fromBytesBlob(t):xe.fromBlob(t);s.attachContext(r);const i=s.object(e);return s.finish(),i}static decodeSequence(e,t,r){const s=t instanceof te?xe.fromBytesBlob(t):xe.fromBlob(t);s.attachContext(r);const i=[];for(;s.bytesRead()<s.source.length;)i.push(s.object(e));return s.finish(),i}dataView;constructor(e,t=0,r){this.source=e,this.offset=t,this.context=r,this.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)}attachContext(e){this.context=e}getContext(){return this.context}clone(){return new xe(this.source,this.offset,this.context)}bytesRead(){return this.offset}remainingBytes(){const e=this.source.subarray(this.offset),t=e.length;return this.offset+=t,re.fromBlob(e,t)}i8(){return this.getNum(1,()=>this.dataView.getInt8(this.offset))}u8(){return this.getNum(1,()=>this.dataView.getUint8(this.offset))}i16(){return this.getNum(2,()=>this.dataView.getInt16(this.offset,!0))}u16(){return this.getNum(2,()=>this.dataView.getUint16(this.offset,!0))}i24(){const e=this.u24();return e>=2**23?e-2**24:e}u24(){return this.getNum(3,()=>{let e=this.dataView.getUint8(this.offset);return e|=this.dataView.getUint16(this.offset+1,!0)<<8,e})}i32(){return this.getNum(4,()=>this.dataView.getInt32(this.offset,!0))}u32(){return this.getNum(4,()=>this.dataView.getUint32(this.offset,!0))}i64(){return this.getNum(8,()=>this.dataView.getBigInt64(this.offset,!0))}u64(){return this.getNum(8,()=>this.dataView.getBigUint64(this.offset,!0))}bool(){const e=this.u8();if(0===e)return!1;if(1===e)return!0;throw new Error(`Unexpected number when decoding a boolean: ${e}`)}varU32(){this.ensureHasBytes(1);const e=this.source[this.offset],t=Be(e);if(this.offset+=1,0===t)return e;if(t>4)throw new Error(`Unexpectedly large value for u32. l=${t}`);this.ensureHasBytes(t);const r=e+2**(8-t)-256<<8*t;if(1===t)return r+this.u8();if(2===t)return r+this.u16();if(3===t)return r+this.u24();if(0===r)return this.u32();throw new Error(`Unexpectedly large value for u32. l=${t}, mostSignificantByte=${r}`)}varU64(){this.ensureHasBytes(1);const e=this.source[this.offset],t=Be(e);if(this.offset+=1,0===t)return ve(e);if(this.ensureHasBytes(t),this.offset+=t,8===t)return ve(this.dataView.getBigUint64(this.offset-t,!0));let r=BigInt(e+2**(8-t)-256)<<BigInt(8*t);for(let e=0;e<t;e+=1)r|=BigInt(this.source[this.offset-t+e])<<BigInt(8*e);return ve(r)}bytes(e){if(0===e)return re.zero(e);this.ensureHasBytes(e);const t=this.source.subarray(this.offset,this.offset+e);return this.offset+=e,re.fromBlob(t,e)}bytesBlob(){const e=this.varU32();this.ensureHasBytes(e);const t=this.source.subarray(this.offset,this.offset+e);return this.offset+=e,te.blobFrom(t)}bitVecFixLen(e){if(0===e)return pe.empty(0);const t=Math.ceil(e/8),r=this.bytes(t),s=e%8;if(s>0&&r.raw[t-1]>>s>0)throw new Error("Non-zero bits found in the last byte of bitvec encoding.");return pe.fromBytes(r,e)}bitVecVarLen(){const e=this.varU32();return this.bitVecFixLen(e)}object(e){return e.decode(this)}optional(e){return this.bool()?e.decode(this):null}sequenceFixLen(e,t){const r=Array(t);for(let s=0;s<t;s+=1)r[s]=e.decode(this);return r}sequenceVarLen(e){const t=this.varU32();return this.sequenceFixLen(e,t)}resetTo(e){this.offset<e?this.skip(e-this.offset):(Q(e>=0,"The offset has to be positive"),this.offset=e)}skip(e){this.ensureHasBytes(e),this.offset+=e}finish(){if(this.offset<this.source.length)throw new Error(`Expecting end of input, yet there are still ${this.source.length-this.offset} bytes left.`)}getNum(e,t){this.ensureHasBytes(e);const r=t();return this.offset+=e,r}ensureHasBytes(e){if(Q(e>=0,"Negative number of bytes given."),this.offset+e>this.source.length)throw new Error(`Attempting to decode more data than there is left. Need ${e}, left: ${this.source.length-this.offset}.`)}}const _e=[255,254,252,248,240,224,192,128];function Be(e){Q(e>=0&&e<256,`Incorrect byte value: ${e}`);for(let t=0;t<_e.length;t++)if(e>=_e[t])return 8-t;return 0}function Re(e){return Q(e.isExact,"The value is not exact size estimation!"),e.bytes}function Oe(e,t){return{bytes:e.bytes+t.bytes,isExact:e.isExact&&t.isExact}}const Ue=10485760;class Te{destination;buffer;static create(e){if(void 0!==e&&"destination"in e)return new Te(e.destination);const t=e?.expectedLength??512,r=new ArrayBuffer(Math.min(Ue,t),{maxByteLength:Ue}),s=new Uint8Array(r);return new Te(s,r)}static encodeObject(e,t,r){const s=Te.create({expectedLength:e.sizeHint.bytes||512});return s.attachContext(r),s.object(e,t),s.viewResult()}offset=0;context;dataView;constructor(e,t){this.destination=e,this.buffer=t,this.dataView=void 0!==t?new DataView(t):new DataView(e.buffer,e.byteOffset,e.byteLength)}attachContext(e){this.context=e}getContext(){return this.context}viewResult(){return te.blobFrom(this.destination.subarray(0,this.offset))}i32(e){this.prepareIntegerN(e,4),this.dataView.setInt32(this.offset,e,!0),this.offset+=4}i64(e){const t=2n**64n;Q(e<t,"Only for numbers up to 2**64 - 1"),Q(-e<=t/2n,"Only for numbers down to -2**63"),this.ensureBigEnough(8),this.dataView.setBigInt64(this.offset,e,!0),this.offset+=8}i24(e){this.prepareIntegerN(e,3),this.dataView.setInt8(this.offset,255&e),this.dataView.setInt16(this.offset+1,e>>8,!0),this.offset+=3}i16(e){this.prepareIntegerN(e,2),this.dataView.setInt16(this.offset,e,!0),this.offset+=2}i8(e){this.prepareIntegerN(e,1),this.dataView.setInt8(this.offset,e),this.offset+=1}bool(e){this.varU32(Ae(e?1:0))}prepareIntegerN(e,t){const r=2**(8*t);Q(e<r,`Only for numbers up to 2**${8*t} - 1`),Q(-e<=r/2,"Only for numbers down to -2**"+(8*t-1)),this.ensureBigEnough(t)}varU32(e){Q(e>=0,"Only for natural numbers."),Q(e<2**32,"Only for numbers up to 2**32"),this.varU64(BigInt(e))}varU64(e){const t=BigInt(e);if(0n===t)return this.ensureBigEnough(1),this.destination[this.offset]=0,void(this.offset+=1);let r=2n**56n;if(t>=r)return this.ensureBigEnough(9),this.destination[this.offset]=255,this.dataView.setBigUint64(this.offset+1,t,!0),void(this.offset+=9);let s=r>>7n;for(let e=7;e>=0;e-=1){if(t>=s){this.ensureBigEnough(e+1);const r=2n**BigInt(8*e),s=BigInt(256-2**(8-e))+t/r;this.destination[this.offset]=255&Number(s),this.offset+=1;let i=t%r;for(let t=this.offset;t<this.offset+e;t+=1)this.destination[t]=Number(0xffn&i),i>>=8n;return void(this.offset+=e)}r=s,s>>=7n}throw new Error(`Unhandled number encoding: ${t}`)}bytesBlob(e){this.blob(e.raw)}blob(e){this.varU32(Ae(e.length)),this.ensureBigEnough(e.length),this.destination.set(e,this.offset),this.offset+=e.length}bytes(e){this.ensureBigEnough(e.length),this.destination.set(e.raw,this.offset),this.offset+=e.length}bitVecFixLen(e){const t=e.raw;this.bytes(re.fromBlob(t,t.length))}bitVecVarLen(e){const t=e.bitLength;this.varU32(Ae(t)),this.bitVecFixLen(e)}object(e,t){this.applySizeHint(e),e.encode(this,t)}optional(e,t){const r=null!=t;this.bool(r),r&&(this.applySizeHint(e),e.encode(this,t))}sequenceFixLen(e,t){this.applySizeHint(e,t.length);for(const r of t)e.encode(this,r)}sequenceVarLen(e,t){Q(t.length<=2**32,"Wow, that's a nice long sequence you've got here."),this.varU32(Ae(t.length)),this.sequenceFixLen(e,t)}applySizeHint(e,t=1){const r=e.sizeHint.bytes;r>0&&t>0&&this.ensureBigEnough(r*t,{silent:!0})}ensureBigEnough(e,t={silent:!1}){Q(e>=0,"Negative length given");const r=this.offset+e;if(r>Ue){if(t.silent)return;throw new Error("The encoded size would reach the maximum of 10485760.")}if(r>this.destination.length){if(void 0!==this.buffer){const e=Math.max(r,this.buffer.byteLength<<1);this.buffer.resize(Math.min(Ue,e))}if(r>this.destination.length){if(t.silent)return;throw new Error(`Not enough space in the destination array. Needs ${r}, has ${this.destination.length}.`)}}}}class Ne{decoder;constructor(e){this.decoder=e}u64=()=>this.decoder.skip(8);u32=()=>this.decoder.skip(4);u24=()=>this.decoder.skip(3);u16=()=>this.decoder.skip(2);u8=()=>this.decoder.skip(1);bool=()=>this.decoder.skip(1);varU32=()=>this.varU64();varU64(){const e=Be(this.decoder.u8());this.decoder.skip(e)}bytes(e){this.decoder.skip(e)}bytesBlob(){const e=this.decoder.varU32();this.decoder.skip(e)}bitVecFixLen(e){this.decoder.skip(Math.ceil(e/8))}bitVecVarLen(){const e=this.decoder.varU32();this.bitVecFixLen(e)}object(e){e.skip(this)}optional(e){this.decoder.bool()&&e.skip(this)}sequenceFixLen(e,t){for(let r=0;r<t;r+=1)e.skip(this)}sequenceVarLen(e){const t=this.decoder.varU32();return this.sequenceFixLen(e,t)}}function De(e,t,r){if(t<e.minLength)throw new Error(`${r}: length is below minimal. ${t} < ${e.minLength}`);if(t>e.maxLength)throw new Error(`${r}: length is above maximal. ${t} > ${e.maxLength}`)}class Me{getView;getValue;getEncoded;cachedValue;cachedView;cachedBlob;constructor(e,t,r){this.getView=e,this.getValue=t,this.getEncoded=r}materialize(){return void 0===this.cachedValue&&(this.cachedValue=this.getValue()),this.cachedValue}view(){return void 0===this.cachedView&&(this.cachedView=this.getView()),this.cachedView}encoded(){return void 0===this.cachedBlob&&(this.cachedBlob=this.getEncoded()),this.cachedBlob}}class Pe{decoder;materializedConstructor;descriptors;descriptorsKeys;cache=new Map;initialDecoderOffset;lastDecodedFieldIdx=-1;constructor(e,t,r){this.decoder=e,this.materializedConstructor=t,this.descriptors=r,this.descriptorsKeys=Object.keys(r),this.initialDecoderOffset=e.bytesRead()}materialize(){const e=this.descriptorsKeys,t=Object.fromEntries(e.map(e=>[e,this.get(e).materialize()]));return this.materializedConstructor.create(t)}encoded(){const e=this.descriptorsKeys;if(0===e.length)return te.blobFromNumbers([]);if(this.lastDecodedFieldIdx<e.length-1){const t=e[e.length-1];this.decodeUpTo(t)}return te.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset,this.decoder.bytesRead()))}get(e){const t=this.cache.get(e);return void 0!==t?t:this.decodeUpTo(e)}decodeUpTo(e){const t=this.descriptorsKeys.indexOf(e),r=this.descriptorsKeys[this.lastDecodedFieldIdx];Q(this.lastDecodedFieldIdx<t,`Unjustified call to 'decodeUpTo' -\n the index ($Blobindex}, ${String(e)})\n is already decoded (${this.lastDecodedFieldIdx}, ${String(r)}).\n `);let s=this.cache.get(r);const i=new Ne(this.decoder);for(let e=this.lastDecodedFieldIdx+1;e<=t;e++){const t=i.decoder.clone(),r=this.descriptorsKeys[e],n=this.descriptors[r];s=new Me(()=>n.View.decode(t.clone()),()=>n.decode(t.clone()),()=>n.skipEncoded(t.clone())),n.skip(i),this.cache.set(r,s),this.lastDecodedFieldIdx=e}return V(s,void 0!==s,"Last item must be set, since the loop turns at least once.")}}class Le{decoder;descriptor;length;cache=new Map;initialDecoderOffset;lastDecodedIdx=-1;constructor(e,t,r){this.decoder=e,this.descriptor=t,this.initialDecoderOffset=this.decoder.bytesRead(),this.length=r??e.varU32()}*[Symbol.iterator](){for(let e=0;e<this.length;e++){const t=this.get(e),r=V(t,void 0!==t,"We are within 0..this.length so all items are defined.");yield r}}map(e){const t=new Array(this.length);let r=0;for(const s of this)t[r]=e(s),r++;return t}get(e){if(e>=this.length)return;const t=this.cache.get(e);return void 0!==t?t:this.decodeUpTo(e)}encoded(){return 0===this.length?te.blobFromNumbers([]):(this.lastDecodedIdx<this.length-1&&this.decodeUpTo(this.length-1),te.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset,this.decoder.bytesRead())))}decodeUpTo(e){Q(this.lastDecodedIdx<e,`Unjustified call to 'decodeUpTo' - the index (${e}) is already decoded (${this.lastDecodedIdx}).`);let t=this.cache.get(this.lastDecodedIdx);const r=new Ne(this.decoder);for(let s=this.lastDecodedIdx+1;s<=e;s++){const e=r.decoder.clone(),i=this.descriptor;t=new Me(()=>i.View.decode(e.clone()),()=>i.decode(e.clone()),()=>i.skipEncoded(e.clone())),i.skip(r),this.cache.set(s,t),this.lastDecodedIdx=s}return V(t,void 0!==t,"Last item must be set, since the loop turns at least once.")}}class He{name;sizeHint;encode;decode;skip;View;static withView(e,t,r,s,i,n){return new He(e,t,r,s,i,n)}static new(e,t,r,s,i){return new He(e,t,r,s,i,null)}constructor(e,t,r,s,i,n){this.name=e,this.sizeHint=t,this.encode=r,this.decode=s,this.skip=i,this.View=n??this}skipEncoded(e){const t=e.bytesRead();this.skip(new Ne(e));const r=e.bytesRead();return te.blobFrom(e.source.subarray(t,r))}convert(e,t){return new He(this.name,this.sizeHint,(t,r)=>this.encode(t,e(r)),e=>t(this.decode(e)),this.skip,this.View)}asOpaque(){return this.convert(e=>e,e=>e)}}function Ke(e){return e.convert(e=>(Q(Array.isArray(e),`Non-arrays are not supported as 'readonly': got ${typeof e}, ${e}`),e),e=>e)}function Qe(e){return{bytes:e,isExact:!0}}var Ve,Fe;function $e(e,t){for(const r in e)"string"==typeof r&&r in e&&t(r,e[r])}function je(e){return e.View!==e}(Fe=Ve||(Ve={})).bytes=(()=>{const e=new Map;return t=>{let r=e.get(t);return void 0===r&&(r=He.new(`Bytes<${t}>`,Qe(t),(e,t)=>e.bytes(t),e=>e.bytes(t),e=>e.bytes(t)),e.set(t,r)),r}})(),Fe.varU32=He.new("var_u32",{bytes:4,isExact:!1},(e,t)=>e.varU32(t),e=>e.varU32(),e=>e.varU32()),Fe.varU64=He.new("var_u64",{bytes:8,isExact:!1},(e,t)=>e.varU64(t),e=>e.varU64(),e=>e.varU64()),Fe.u64=He.withView("u64",Qe(8),(e,t)=>e.i64(t),e=>e.u64(),e=>e.u64(),Fe.bytes(8)),Fe.u32=He.withView("u32",Qe(4),(e,t)=>e.i32(t),e=>e.u32(),e=>e.u32(),Fe.bytes(4)),Fe.u24=He.withView("u24",Qe(3),(e,t)=>e.i24(t),e=>e.u24(),e=>e.u24(),Fe.bytes(3)),Fe.u16=He.withView("u16",Qe(2),(e,t)=>e.i16(t),e=>e.u16(),e=>e.u16(),Fe.bytes(2)),Fe.u8=He.new("u8",Qe(1),(e,t)=>e.i8(t),e=>e.u8(),e=>e.u8()),Fe.i64=He.withView("u64",Qe(8),(e,t)=>e.i64(t),e=>e.i64(),e=>e.u64(),Fe.bytes(8)),Fe.i32=He.withView("i32",Qe(4),(e,t)=>e.i32(t),e=>e.i32(),e=>e.u32(),Fe.bytes(4)),Fe.i24=He.withView("i24",Qe(3),(e,t)=>e.i24(t),e=>e.i24(),e=>e.u24(),Fe.bytes(3)),Fe.i16=He.withView("i16",Qe(2),(e,t)=>e.i16(t),e=>e.i16(),e=>e.u16(),Fe.bytes(2)),Fe.i8=He.new("i8",Qe(1),(e,t)=>e.i8(t),e=>e.i8(),e=>e.u8()),Fe.bool=He.new("bool",Qe(1),(e,t)=>e.bool(t),e=>e.bool(),e=>e.bool()),Fe.blob=He.new("BytesBlob",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(t),e=>e.bytesBlob(),e=>e.bytesBlob()),Fe.string=He.withView("string",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(te.blobFrom((new TextEncoder).encode(t))),e=>new TextDecoder("utf8",{fatal:!0}).decode(e.bytesBlob().raw),e=>e.bytesBlob(),Fe.blob),Fe.bitVecVarLen=He.new("BitVec[?]",{bytes:8,isExact:!1},(e,t)=>e.bitVecVarLen(t),e=>e.bitVecVarLen(),e=>e.bitVecVarLen()),Fe.bitVecFixLen=e=>He.new(`BitVec[${e}]`,Qe(e>>>3),(e,t)=>e.bitVecFixLen(t),t=>t.bitVecFixLen(e),t=>t.bitVecFixLen(e)),Fe.optional=e=>{const t=He.new(`Optional<${e.name}>`,Oe({bytes:1,isExact:!1},e.sizeHint),(t,r)=>t.optional(e,r),t=>t.optional(e),t=>t.optional(e));return je(e)?He.withView(t.name,t.sizeHint,t.encode,t.decode,t.skip,Fe.optional(e.View)):t},Fe.sequenceVarLen=(e,t={minLength:0,maxLength:2**32-1})=>{const r=`Sequence<${e.name}>[?]`,s=t.typicalLength??64;return He.withView(r,{bytes:s*e.sizeHint.bytes,isExact:!1},(s,i)=>{De(t,i.length,r),s.sequenceVarLen(e,i)},s=>{const i=s.varU32();return De(t,i,r),s.sequenceFixLen(e,i)},s=>{const i=s.decoder.varU32();return De(t,i,r),s.sequenceFixLen(e,i)},function(e,t){const r={bytes:64*e.sizeHint.bytes,isExact:!1},s=e.name!==e.View.name?`, ${e.View.name}`:"",i=`SeqView<${e.name}${s}>[?]`,n=r=>{const s=r.decoder.varU32();return De(t,s,i),r.sequenceFixLen(e,s)};return He.new(i,r,(e,r)=>{De(t,r.length,i);const s=r.encoded();e.bytes(re.fromBlob(s.raw,s.length))},t=>{const r=new Le(t.clone(),e);return n(new Ne(t)),r},n)}(e,t))},Fe.sequenceFixLen=(e,t)=>He.withView(`Sequence<${e.name}>[${t}]`,{bytes:t*e.sizeHint.bytes,isExact:e.sizeHint.isExact},(t,r)=>t.sequenceFixLen(e,r),r=>r.sequenceFixLen(e,t),r=>r.sequenceFixLen(e,t),function(e,{fixedLength:t}){const r={bytes:e.sizeHint.bytes*t,isExact:e.sizeHint.isExact},s=r=>r.sequenceFixLen(e,t),i=e.name!==e.View.name?`, ${e.View.name}`:"",n=`SeqView<${e.name}${i}>[${t}]`;return He.new(n,r,(e,t)=>{const r=t.encoded();e.bytes(re.fromBlob(r.raw,r.length))},r=>{const i=new Le(r.clone(),e,t);return s(new Ne(r)),i},s)}(e,{fixedLength:t})),Fe.dictionary=(e,t,{sortKeys:r,fixedLength:s})=>{const i=He.new(`Dictionary<${e.name}, ${t.name}>[${s??"?"}]`,{bytes:void 0!==s?s*Oe(e.sizeHint,t.sizeHint).bytes:32*(Oe(e.sizeHint,t.sizeHint).bytes??0),isExact:void 0!==s&&e.sizeHint.isExact&&t.sizeHint.isExact},(i,n)=>{const o=Array.from(n.entries());o.sort((e,t)=>r(e[0],t[0])),void 0!==s&&0!==s||i.varU32(Ae(o.length));for(const[r,s]of o)e.encode(i,r),t.encode(i,s)},i=>{const n=new Map,o=s??i.varU32();let a=null;for(let s=0;s<o;s+=1){const s=e.decode(i),o=t.decode(i);if(n.has(s))throw new Error(`Duplicate item in the dictionary encoding: "${s}"!`);if(null!==a&&r(a,s)>=0)throw new Error(`The keys in dictionary encoding are not sorted "${a}" >= "${s}"!`);n.set(s,o),a=s}return n},r=>{const i=s??r.decoder.varU32();r.sequenceFixLen(e,i),r.sequenceFixLen(t,i)});return je(t)?He.withView(i.name,i.sizeHint,i.encode,i.decode,i.skip,Fe.dictionary(e,t.View,{sortKeys:r,fixedLength:s})):i},Fe.custom=({name:e,sizeHint:t={bytes:0,isExact:!1}},r,s,i)=>He.new(e,t,r,s,i),Fe.select=({name:e,sizeHint:t},r)=>He.withView(e,t,(e,t)=>r(e.getContext()).encode(e,t),e=>r(e.getContext()).decode(e),e=>r(e.decoder.getContext()).skip(e),r(null).View),Fe.object=(e,t="object",r=e=>e)=>Fe.Class({name:t,create:r},e),Fe.Class=(e,t)=>{let r=Qe(0);$e(t,(e,t)=>{r=Oe(r,t.sizeHint)});const s=e=>{if(r.isExact)return e.decoder.skip(r.bytes);$e(t,(t,r)=>{r.skip(e)})},i=function(e,t,r,s){class i extends Pe{constructor(r){super(r,e,t)}}return $e(t,e=>{"string"==typeof e&&Object.defineProperty(i.prototype,e,{get:function(){return this.get(e)}})}),He.new(`View<${e.name}>`,r,(e,t)=>{const r=t.encoded();e.bytes(re.fromBlob(r.raw,r.length))},e=>{const t=new i(e.clone());return s(new Ne(e)),t},s)}(e,t,r,s);return He.withView(e.name,r,(e,r)=>{$e(t,(t,s)=>{const i=r[t];s.encode(e,i)})},r=>{const s={};return $e(t,(e,t)=>{const i=t.decode(r);s[e]=i}),e.create(s)},s,i)};const Ge=2n**255n-19n,qe=2n**252n+27742317777372353535851937790883648493n,ze=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,We=0x6666666666666666666666666666666666666666666666666666666666666658n,Je={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Ge,n:qe,h:8,Gx:ze,Gy:We},Ye=(e="")=>{throw new Error(e)},Xe=e=>"string"==typeof e,Ze=(e,t)=>!(e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name)(e)||"number"==typeof t&&t>0&&e.length!==t?Ye("Uint8Array of valid length expected"):e,et=e=>new Uint8Array(e),tt=(e,t=Ge)=>{let r=e%t;return r>=0n?r:t+r},rt=e=>e instanceof st?e:Ye("Point expected");class st{constructor(e,t,r,s){this.ex=e,this.ey=t,this.ez=r,this.et=s}static fromAffine(e){return new st(e.x,e.y,1n,tt(e.x*e.y))}static fromHex(e,t=!1){const{d:r}=Je,s=(n=e,o=32,e=Ze(Xe(n)?lt(n):et(Ze(n)),o)).slice(),i=e[31];var n,o;s[31]=-129&i;const a=ut(s);!t||0n<=a&&a<2n**256n||Ye("bad y coord 1"),t||0n<=a&&a<Ge||Ye("bad y coord 2");const c=tt(a*a),l=tt(c-1n),h=tt(r*c+1n);let{isValid:u,value:d}=yt(l,h);u||Ye("bad y coordinate 3");const f=1n==(1n&d),p=!!(128&i);return!t&&0n===d&&p&&Ye("bad y coord 3"),p!==f&&(d=tt(-d)),new st(d,a,1n,tt(d*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){const{ex:t,ey:r,ez:s}=this,{ex:i,ey:n,ez:o}=rt(e),a=tt(t*o),c=tt(i*s),l=tt(r*o),h=tt(n*s);return a===c&&l===h}is0(){return this.equals(nt)}negate(){return new st(tt(-this.ex),this.ey,this.ez,tt(-this.et))}double(){const{ex:e,ey:t,ez:r}=this,{a:s}=Je,i=tt(e*e),n=tt(t*t),o=tt(2n*tt(r*r)),a=tt(s*i),c=e+t,l=tt(tt(c*c)-i-n),h=a+n,u=h-o,d=a-n,f=tt(l*u),p=tt(h*d),g=tt(l*d),y=tt(u*h);return new st(f,p,y,g)}add(e){const{ex:t,ey:r,ez:s,et:i}=this,{ex:n,ey:o,ez:a,et:c}=rt(e),{a:l,d:h}=Je,u=tt(t*n),d=tt(r*o),f=tt(i*h*c),p=tt(s*a),g=tt((t+r)*(n+o)-u-d),y=tt(p-f),m=tt(p+f),b=tt(d-l*u),A=tt(g*y),I=tt(m*b),v=tt(g*b),w=tt(y*m);return new st(A,I,w,v)}mul(e,t=!0){if(0n===e)return!0===t?Ye("cannot multiply by 0"):nt;if("bigint"==typeof e&&0n<e&&e<qe||Ye("invalid scalar, must be < L"),!t&&this.is0()||1n===e)return this;if(this.equals(it))return vt(e).p;let r=nt,s=it;for(let i=this;e>0n;i=i.double(),e>>=1n)1n&e?r=r.add(i):t&&(s=s.add(i));return r}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(Je.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(qe/2n,!1).double();return e=e.add(this),e.is0()}toAffine(){const{ex:e,ey:t,ez:r}=this;if(this.equals(nt))return{x:0n,y:1n};const s=ft(r,Ge);return 1n!==tt(r*s)&&Ye("invalid inverse"),{x:tt(e*s),y:tt(t*s)}}toRawBytes(){const{x:e,y:t}=this.toAffine(),r=ht(t);return r[31]|=1n&e?128:0,r}toHex(){return at(this.toRawBytes())}}st.BASE=new st(ze,We,1n,tt(ze*We)),st.ZERO=new st(0n,1n,1n,0n);const{BASE:it,ZERO:nt}=st,ot=(e,t)=>e.toString(16).padStart(t,"0"),at=e=>Array.from(Ze(e)).map(e=>ot(e,2)).join(""),ct=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0,lt=e=>{const t="hex invalid";if(!Xe(e))return Ye(t);const r=e.length,s=r/2;if(r%2)return Ye(t);const i=et(s);for(let r=0,n=0;r<s;r++,n+=2){const s=ct(e.charCodeAt(n)),o=ct(e.charCodeAt(n+1));if(void 0===s||void 0===o)return Ye(t);i[r]=16*s+o}return i},ht=e=>lt(ot(e,64)).reverse(),ut=e=>BigInt("0x"+at(et(Ze(e)).reverse())),dt=(...e)=>{const t=et(e.reduce((e,t)=>e+Ze(t).length,0));let r=0;return e.forEach(e=>{t.set(e,r),r+=e.length}),t},ft=(e,t)=>{(0n===e||t<=0n)&&Ye("no inverse n="+e+" mod="+t);let r=tt(e,t),s=t,i=0n,n=1n,o=1n,a=0n;for(;0n!==r;){const e=s/r,t=s%r,c=i-o*e,l=n-a*e;s=r,r=t,i=o,n=a,o=c,a=l}return 1n===s?tt(i,t):Ye("no inverse")},pt=(e,t)=>{let r=e;for(;t-- >0n;)r*=r,r%=Ge;return r},gt=19681161376707505956807079304988542015446066515923890162744021073123829784752n,yt=(e,t)=>{const r=tt(t*t*t),s=(e=>{const t=e*e%Ge*e%Ge,r=pt(t,2n)*t%Ge,s=pt(r,1n)*e%Ge,i=pt(s,5n)*s%Ge,n=pt(i,10n)*i%Ge,o=pt(n,20n)*n%Ge,a=pt(o,40n)*o%Ge,c=pt(a,80n)*a%Ge,l=pt(c,80n)*a%Ge,h=pt(l,10n)*i%Ge;return{pow_p_5_8:pt(h,2n)*e%Ge,b2:t}})(e*tt(r*r*t)).pow_p_5_8;let i=tt(e*r*s);const n=tt(t*i*i),o=i,a=tt(i*gt),c=n===e,l=n===tt(-e),h=n===tt(-e*gt);return c&&(i=o),(l||h)&&(i=a),1n==(1n&tt(i))&&(i=tt(-i)),{isValid:c||l,value:i}};let mt;const bt=()=>"object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,At={bytesToHex:at,hexToBytes:lt,concatBytes:dt,mod:tt,invert:ft,randomBytes:(e=32)=>{const t=bt();return t&&t.getRandomValues||Ye("crypto.getRandomValues must be defined"),t.getRandomValues(et(e))},sha512Async:async(...e)=>{const t=bt(),r=t&&t.subtle;r||Ye("etc.sha512Async or crypto.subtle must be defined");const s=dt(...e);return et(await r.digest("SHA-512",s.buffer))},sha512Sync:void 0};let It;Object.defineProperties(At,{sha512Sync:{configurable:!1,get:()=>mt,set(e){mt||(mt=e)}}});const vt=e=>{const t=It||(It=(()=>{const e=[];let t=it,r=t;for(let s=0;s<33;s++){r=t,e.push(r);for(let s=1;s<128;s++)r=r.add(t),e.push(r);t=r.double()}return e})()),r=(e,t)=>{let r=t.negate();return e?r:t};let s=nt,i=it;const n=BigInt(255),o=BigInt(8);for(let a=0;a<33;a++){const c=128*a;let l=Number(e&n);e>>=o,l>128&&(l-=256,e+=1n);const h=c,u=c+Math.abs(l)-1,d=a%2!=0,f=l<0;0===l?i=i.add(r(d,t[h])):s=s.add(r(f,t[u]))}return{p:s,f:i}};var wt=o(625);const St=32,Et=64;async function Ct(e){if(0===e.length)return Promise.resolve([]);const t=e.reduce((e,{message:t,key:r,signature:s})=>e+r.length+s.length+t.length+1,0),r=new Uint8Array(t);let s=0;for(const{key:t,message:i,signature:n}of e){r.set(t.raw,s),s+=St,r.set(n.raw,s),s+=Et;const e=i.length;Q(e<256,`Message needs to be shorter than 256 bytes. Got: ${e}`),r[s]=e,s+=1,r.set(i.raw,s),s+=e}const i=Array.from((0,wt.verify_ed25519)(r)).map(e=>1===e);return Promise.resolve(i)}var kt=o(405);const xt=32,_t=144,Bt=144,Rt=32;class Ot extends G{hash;data;constructor(e,t){super(),this.hash=e,this.data=t}}class Ut extends Ot{encoded;constructor(e,t,r){super(e,t),this.encoded=r}}class Tt{emptyHash(){return re.zero(Rt)}}const Nt=new Tt;var Dt,Mt=o(675),Pt=o.n(Mt);function Lt(e,t=Nt){const r=t.emptyHash();if(0===e.length)return r.asOpaque();const s=Pt()(Rt);for(const t of e)s?.update(t instanceof te?t.raw:t);return s?.digest(r.raw),r.asOpaque()}function Ht(e,t=Nt){const r=Pt()(Rt),s=e instanceof te?e.raw:e;r?.update(s);const i=t.emptyHash();return r?.digest(i.raw),i}function Kt(e,t=Nt){return Ht(te.blobFromString(e),t)}function Qt(e,t,r,s){return new(r||(r=Promise))(function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class Vt{constructor(){this.mutex=Promise.resolve()}lock(){let e=()=>{};return this.mutex=this.mutex.then(()=>new Promise(e)),new Promise(t=>{e=t})}dispatch(e){return Qt(this,void 0,void 0,function*(){const t=yield this.lock();try{return yield Promise.resolve(e())}finally{t()}})}}const Ft="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,$t=null!==(Dt=Ft.Buffer)&&void 0!==Dt?Dt:null,jt=Ft.TextEncoder?new Ft.TextEncoder:null;function Gt(e,t){return(15&e)+(e>>6|e>>3&8)<<4|(15&t)+(t>>6|t>>3&8)}const qt="a".charCodeAt(0)-10,zt="0".charCodeAt(0);function Wt(e,t,r){let s=0;for(let i=0;i<r;i++){let r=t[i]>>>4;e[s++]=r>9?r+qt:r+zt,r=15&t[i],e[s++]=r>9?r+qt:r+zt}return String.fromCharCode.apply(null,e)}const Jt=null!==$t?e=>{if("string"==typeof e){const t=$t.from(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.length)}if($t.isBuffer(e))return new Uint8Array(e.buffer,e.byteOffset,e.length);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")}:e=>{if("string"==typeof e)return jt.encode(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")},Yt=new Uint8Array(256);for(let e=0;e<64;e++)Yt["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;function Xt(e){const t=function(e){let t=Math.floor(.75*e.length);const r=e.length;return"="===e[r-1]&&(t-=1,"="===e[r-2]&&(t-=1)),t}(e),r=e.length,s=new Uint8Array(t);let i=0;for(let t=0;t<r;t+=4){const r=Yt[e.charCodeAt(t)],n=Yt[e.charCodeAt(t+1)],o=Yt[e.charCodeAt(t+2)],a=Yt[e.charCodeAt(t+3)];s[i]=r<<2|n>>4,i+=1,s[i]=(15&n)<<4|o>>2,i+=1,s[i]=(3&o)<<6|63&a,i+=1}return s}const Zt=16384,er=new Vt,tr=new Map;function rr(e,t){return Qt(this,void 0,void 0,function*(){let r=null,s=null,i=!1;if("undefined"==typeof WebAssembly)throw new Error("WebAssembly is not supported in this environment!");const n=()=>new DataView(r.exports.memory.buffer).getUint32(r.exports.STATE_SIZE,!0),o=er.dispatch(()=>Qt(this,void 0,void 0,function*(){if(!tr.has(e.name)){const t=Xt(e.data),r=WebAssembly.compile(t);tr.set(e.name,r)}const t=yield tr.get(e.name);r=yield WebAssembly.instantiate(t,{})})),a=(e=null)=>{i=!0,r.exports.Hash_Init(e)},c=e=>{if(!i)throw new Error("update() called before init()");(e=>{let t=0;for(;t<e.length;){const i=e.subarray(t,t+Zt);t+=i.length,s.set(i),r.exports.Hash_Update(i.length)}})(Jt(e))},l=new Uint8Array(2*t),h=(e,n=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,r.exports.Hash_Final(n),"binary"===e?s.slice(0,t):Wt(l,s,t)},u=e=>"string"==typeof e?e.length<4096:e.byteLength<Zt;let d=u;switch(e.name){case"argon2":case"scrypt":d=()=>!0;break;case"blake2b":case"blake2s":d=(e,t)=>t<=512&&u(e);break;case"blake3":d=(e,t)=>0===t&&u(e);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":d=()=>!1}return yield(()=>Qt(this,void 0,void 0,function*(){r||(yield o);const e=r.exports.Hash_GetBuffer(),t=r.exports.memory.buffer;s=new Uint8Array(t,e,Zt)}))(),{getMemory:()=>s,writeMemory:(e,t=0)=>{s.set(e,t)},getExports:()=>r.exports,setMemorySize:e=>{r.exports.Hash_SetMemorySize(e);const t=r.exports.Hash_GetBuffer(),i=r.exports.memory.buffer;s=new Uint8Array(i,t,e)},init:a,update:c,digest:h,save:()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");const t=r.exports.Hash_GetState(),s=n(),o=r.exports.memory.buffer,a=new Uint8Array(o,t,s),c=new Uint8Array(4+s);return function(e,t){const r=t.length>>1;for(let s=0;s<r;s++){const r=s<<1;e[s]=Gt(t.charCodeAt(r),t.charCodeAt(r+1))}}(c,e.hash),c.set(a,4),c},load:t=>{if(!(t instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");const s=r.exports.Hash_GetState(),o=n(),a=4+o,c=r.exports.memory.buffer;if(t.length!==a)throw new Error(`Bad state length (expected ${a} bytes, got ${t.length})`);if(!function(e,t){if(e.length!==2*t.length)return!1;for(let r=0;r<t.length;r++){const s=r<<1;if(t[r]!==Gt(e.charCodeAt(s),e.charCodeAt(s+1)))return!1}return!0}(e.hash,t.subarray(0,4)))throw new Error("This state was written by an incompatible hash implementation");const l=t.subarray(4);new Uint8Array(c,s,o).set(l),i=!0},calculate:(e,i=null,n=null)=>{if(!d(e,i))return a(i),c(e),h("hex",n);const o=Jt(e);return s.set(o),r.exports.Hash_Calculate(o.length,i,n),Wt(l,s,t)},hashLength:t}})}new Vt,new Vt,new DataView(new ArrayBuffer(4)),new Vt,new Vt,new Vt,new Vt,new Uint8Array(8),new Vt,new Vt,new Vt;var sr={name:"sha3",data:"AGFzbQEAAAABFARgAAF/YAF/AGACf38AYAN/f38AAwgHAAEBAgEAAwUEAQECAgYOAn8BQZCNBQt/AEGACAsHcAgGbWVtb3J5AgAOSGFzaF9HZXRCdWZmZXIAAAlIYXNoX0luaXQAAQtIYXNoX1VwZGF0ZQACCkhhc2hfRmluYWwABA1IYXNoX0dldFN0YXRlAAUOSGFzaF9DYWxjdWxhdGUABgpTVEFURV9TSVpFAwEKpBwHBQBBgAoL1wMAQQBCADcDgI0BQQBCADcD+IwBQQBCADcD8IwBQQBCADcD6IwBQQBCADcD4IwBQQBCADcD2IwBQQBCADcD0IwBQQBCADcDyIwBQQBCADcDwIwBQQBCADcDuIwBQQBCADcDsIwBQQBCADcDqIwBQQBCADcDoIwBQQBCADcDmIwBQQBCADcDkIwBQQBCADcDiIwBQQBCADcDgIwBQQBCADcD+IsBQQBCADcD8IsBQQBCADcD6IsBQQBCADcD4IsBQQBCADcD2IsBQQBCADcD0IsBQQBCADcDyIsBQQBCADcDwIsBQQBCADcDuIsBQQBCADcDsIsBQQBCADcDqIsBQQBCADcDoIsBQQBCADcDmIsBQQBCADcDkIsBQQBCADcDiIsBQQBCADcDgIsBQQBCADcD+IoBQQBCADcD8IoBQQBCADcD6IoBQQBCADcD4IoBQQBCADcD2IoBQQBCADcD0IoBQQBCADcDyIoBQQBCADcDwIoBQQBCADcDuIoBQQBCADcDsIoBQQBCADcDqIoBQQBCADcDoIoBQQBCADcDmIoBQQBCADcDkIoBQQBCADcDiIoBQQBCADcDgIoBQQBBwAwgAEEBdGtBA3Y2AoyNAUEAQQA2AoiNAQuMAwEIfwJAQQAoAoiNASIBQQBIDQBBACABIABqQQAoAoyNASICcDYCiI0BAkACQCABDQBBgAohAwwBCwJAIAIgAWsiBCAAIAQgAEkbIgNFDQAgA0EDcSEFQQAhBgJAIANBBEkNACABQYCKAWohByADQXxxIQhBACEGA0AgByAGaiIDQcgBaiAGQYAKai0AADoAACADQckBaiAGQYEKai0AADoAACADQcoBaiAGQYIKai0AADoAACADQcsBaiAGQYMKai0AADoAACAIIAZBBGoiBkcNAAsLIAVFDQAgAUHIiwFqIQMDQCADIAZqIAZBgApqLQAAOgAAIAZBAWohBiAFQX9qIgUNAAsLIAAgBEkNAUHIiwEgAhADIAAgBGshACAEQYAKaiEDCwJAIAAgAkkNAANAIAMgAhADIAMgAmohAyAAIAJrIgAgAk8NAAsLIABFDQBBACECQcgBIQYDQCAGQYCKAWogAyAGakG4fmotAAA6AAAgBkEBaiEGIAAgAkEBaiICQf8BcUsNAAsLC+ALAS1+IAApA0AhAkEAKQPAigEhAyAAKQM4IQRBACkDuIoBIQUgACkDMCEGQQApA7CKASEHIAApAyghCEEAKQOoigEhCSAAKQMgIQpBACkDoIoBIQsgACkDGCEMQQApA5iKASENIAApAxAhDkEAKQOQigEhDyAAKQMIIRBBACkDiIoBIREgACkDACESQQApA4CKASETQQApA8iKASEUAkACQCABQcgASw0AQQApA+iKASEVQQApA/iKASEWQQApA/CKASEXQQApA4CLASEYQQApA9CKASEZQQApA+CKASEaQQApA9iKASEbDAELQQApA+CKASAAKQNghSEaQQApA9iKASAAKQNYhSEbQQApA9CKASAAKQNQhSEZIBQgACkDSIUhFEEAKQPoigEhFUEAKQP4igEhFkEAKQPwigEhF0EAKQOAiwEhGCABQekASQ0AIBggACkDgAGFIRggFiAAKQN4hSEWIBcgACkDcIUhFyAVIAApA2iFIRUgAUGJAUkNAEEAQQApA4iLASAAKQOIAYU3A4iLAQsgAyAChSEcIAUgBIUhHSAHIAaFIQcgCSAIhSEIIAsgCoUhHiANIAyFIQkgDyAOhSEKIBEgEIUhCyATIBKFIQxBACkDuIsBIRBBACkDkIsBIRFBACkDoIsBIRJBACkDsIsBIRNBACkDiIsBIQ1BACkDwIsBIQ5BACkDmIsBIR9BACkDqIsBIQ9BwH4hAANAIB4gByALhSAbhSAYhSAPhUIBiYUgFIUgF4UgH4UgDoUhAiAMIB0gCoUgGoUgDYUgE4VCAYmFIAiFIBmFIBaFIBKFIgMgB4UhICAJIAggDIUgGYUgFoUgEoVCAYmFIByFIBWFIBGFIBCFIgQgDoUhISAcIAogFCAehSAXhSAfhSAOhUIBiYUgHYUgGoUgDYUgE4UiBYVCN4kiIiALIBwgCYUgFYUgEYUgEIVCAYmFIAeFIBuFIBiFIA+FIgYgCoVCPokiI0J/hYMgAyAPhUICiSIkhSEOIBYgAoVCKYkiJSAEIBeFQieJIiZCf4WDICKFIQ8gECAFhUI4iSIQIAYgDYVCD4kiJ0J/hYMgAyAbhUIKiSIohSENIAQgHoVCG4kiKSAoIAggAoVCJIkiKkJ/hYOFIRYgBiAdhUIGiSIrIAMgC4VCAYkiLEJ/hYMgEiAChUISiSIthSEXICsgBCAfhUIIiSIuIBUgBYVCGYkiFUJ/hYOFIRsgBiAThUI9iSIdIAQgFIVCFIkiBCAJIAWFQhyJIghCf4WDhSEUIAggHUJ/hYMgAyAYhUItiSIDhSEcIB0gA0J/hYMgGSAChUIDiSIJhSEdIAQgAyAJQn+Fg4UhByAJIARCf4WDIAiFIQggDCAChSICICFCDokiA0J/hYMgESAFhUIViSIEhSEJIAYgGoVCK4kiBSADIARCf4WDhSEKIAQgBUJ/hYMgIEIsiSIEhSELIABB0AlqKQMAIAUgBEJ/hYOFIAKFIQwgJyAoQn+FgyAqhSIFIRggAyAEIAJCf4WDhSICIR4gKiApQn+FgyAQhSIDIR8gLSAuQn+FgyAVhSIEIRogJiAkICVCf4WDhSIGIRMgFSArQn+FgyAshSIoIRkgIyAmICJCf4WDhSIiIRIgLiAsIC1Cf4WDhSImIRUgJyApIBBCf4WDhSInIREgIyAkQn+FgyAlhSIjIRAgAEEIaiIADQALQQAgDzcDqIsBQQAgBTcDgIsBQQAgGzcD2IoBQQAgBzcDsIoBQQAgCzcDiIoBQQAgDjcDwIsBQQAgAzcDmIsBQQAgFzcD8IoBQQAgFDcDyIoBQQAgAjcDoIoBQQAgBjcDsIsBQQAgDTcDiIsBQQAgBDcD4IoBQQAgHTcDuIoBQQAgCjcDkIoBQQAgIjcDoIsBQQAgFjcD+IoBQQAgKDcD0IoBQQAgCDcDqIoBQQAgDDcDgIoBQQAgIzcDuIsBQQAgJzcDkIsBQQAgJjcD6IoBQQAgHDcDwIoBQQAgCTcDmIoBC/gCAQV/QeQAQQAoAoyNASIBQQF2ayECAkBBACgCiI0BIgNBAEgNACABIQQCQCABIANGDQAgA0HIiwFqIQVBACEDA0AgBSADakEAOgAAIANBAWoiAyABQQAoAoiNASIEa0kNAAsLIARByIsBaiIDIAMtAAAgAHI6AAAgAUHHiwFqIgMgAy0AAEGAAXI6AABByIsBIAEQA0EAQYCAgIB4NgKIjQELAkAgAkEESQ0AIAJBAnYiA0EDcSEFQQAhBAJAIANBf2pBA0kNACADQfz///8DcSEBQQAhA0EAIQQDQCADQYAKaiADQYCKAWooAgA2AgAgA0GECmogA0GEigFqKAIANgIAIANBiApqIANBiIoBaigCADYCACADQYwKaiADQYyKAWooAgA2AgAgA0EQaiEDIAEgBEEEaiIERw0ACwsgBUUNACAFQQJ0IQEgBEECdCEDA0AgA0GACmogA0GAigFqKAIANgIAIANBBGohAyABQXxqIgENAAsLCwYAQYCKAQvRBgEDf0EAQgA3A4CNAUEAQgA3A/iMAUEAQgA3A/CMAUEAQgA3A+iMAUEAQgA3A+CMAUEAQgA3A9iMAUEAQgA3A9CMAUEAQgA3A8iMAUEAQgA3A8CMAUEAQgA3A7iMAUEAQgA3A7CMAUEAQgA3A6iMAUEAQgA3A6CMAUEAQgA3A5iMAUEAQgA3A5CMAUEAQgA3A4iMAUEAQgA3A4CMAUEAQgA3A/iLAUEAQgA3A/CLAUEAQgA3A+iLAUEAQgA3A+CLAUEAQgA3A9iLAUEAQgA3A9CLAUEAQgA3A8iLAUEAQgA3A8CLAUEAQgA3A7iLAUEAQgA3A7CLAUEAQgA3A6iLAUEAQgA3A6CLAUEAQgA3A5iLAUEAQgA3A5CLAUEAQgA3A4iLAUEAQgA3A4CLAUEAQgA3A/iKAUEAQgA3A/CKAUEAQgA3A+iKAUEAQgA3A+CKAUEAQgA3A9iKAUEAQgA3A9CKAUEAQgA3A8iKAUEAQgA3A8CKAUEAQgA3A7iKAUEAQgA3A7CKAUEAQgA3A6iKAUEAQgA3A6CKAUEAQgA3A5iKAUEAQgA3A5CKAUEAQgA3A4iKAUEAQgA3A4CKAUEAQcAMIAFBAXRrQQN2NgKMjQFBAEEANgKIjQEgABACQeQAQQAoAoyNASIAQQF2ayEDAkBBACgCiI0BIgFBAEgNACAAIQQCQCAAIAFGDQAgAUHIiwFqIQVBACEBA0AgBSABakEAOgAAIAFBAWoiASAAQQAoAoiNASIEa0kNAAsLIARByIsBaiIBIAEtAAAgAnI6AAAgAEHHiwFqIgEgAS0AAEGAAXI6AABByIsBIAAQA0EAQYCAgIB4NgKIjQELAkAgA0EESQ0AIANBAnYiAUEDcSEFQQAhBAJAIAFBf2pBA0kNACABQfz///8DcSEAQQAhAUEAIQQDQCABQYAKaiABQYCKAWooAgA2AgAgAUGECmogAUGEigFqKAIANgIAIAFBiApqIAFBiIoBaigCADYCACABQYwKaiABQYyKAWooAgA2AgAgAUEQaiEBIAAgBEEEaiIERw0ACwsgBUUNACAFQQJ0IQAgBEECdCEBA0AgAUGACmogAUGAigFqKAIANgIAIAFBBGohASAAQXxqIgANAAsLCwvYAQEAQYAIC9ABkAEAAAAAAAAAAAAAAAAAAAEAAAAAAAAAgoAAAAAAAACKgAAAAAAAgACAAIAAAACAi4AAAAAAAAABAACAAAAAAIGAAIAAAACACYAAAAAAAICKAAAAAAAAAIgAAAAAAAAACYAAgAAAAAAKAACAAAAAAIuAAIAAAAAAiwAAAAAAAICJgAAAAAAAgAOAAAAAAACAAoAAAAAAAICAAAAAAAAAgAqAAAAAAAAACgAAgAAAAICBgACAAAAAgICAAAAAAACAAQAAgAAAAAAIgACAAAAAgA==",hash:"fb24e536"};function ir(e){return[224,256,384,512].includes(e)?null:new Error("Invalid variant! Valid values: 224, 256, 384, 512")}new Vt,new Vt,new Vt,new Vt,new Vt,new Vt,new Vt,new Vt,new Uint8Array(8),new Vt,new Uint8Array(8),new Vt,new Uint8Array(8),new Vt,new Vt,new Vt;class nr{hasher;static async create(){return new nr(await function(e=512){if(ir(e))return Promise.reject(ir(e));const t=e/8;return rr(sr,t).then(r=>{r.init(e);const s={init:()=>(r.init(e),s),update:e=>(r.update(e),s),digest:e=>r.digest(e,1),save:()=>r.save(),load:e=>(r.load(e),s),blockSize:200-2*t,digestSize:t};return s})}(256))}constructor(e){this.hasher=e}}function or(e,t){e.hasher.init();for(const r of t)e.hasher.update(r.raw);return re.fromBlob(e.hasher.digest("binary"),Rt)}class ar{map=new Map;constructor(){}static new(){return new ar}static fromEntries(e){const t=new ar;for(const[r,s]of e)t.set(r,s);return t}get size(){return this.map.size}has(e){return this.map.has(e.toString())}get(e){return this.map.get(e.toString())?.[1]}[Symbol.iterator](){return this.map.values()}entries(){return this.map.values()}*keys(){for(const e of this.map.values())yield e[0]}*values(){for(const e of this.map.values())yield e[1]}toSortedArray(e){const t=Array.from(this.map.values());return t.sort((t,r)=>e(t[0],r[0]).value),t.map(e=>e[1])}set(e,t){this.map.set(e.toString(),[e,t])}delete(e){return this.map.delete(e.toString())}}class cr{map;static viewDictionaryKeys(e){return new cr(e)}static from(e){const t=cr.new();return t.insertAll(e),t}static new(){return new cr}constructor(e=ar.new()){this.map=e}get size(){return this.map.size}has(e){return this.map.has(e)}*intersection(e){const t=this.size<e.size?this:e,r=t===this?e:this;for(const e of t)r.has(e)&&(yield e)}*[Symbol.iterator](){for(const e of this.map)yield e[0]}insert(e){return this.map.set(e,!0)}insertAll(e){for(const t of e)this.map.set(t,!0)}delete(e){return this.map.delete(e)}}function lr(e){return e}class hr extends Array{fixedLength;constructor(...e){super(...e),this.fixedLength=this.length}static new(e,t){Q(e.length===t,`Expected an array of size: ${t}, got: ${e.length}`);const r=new hr(t);for(let s=0;s<t;s++)r[s]=e[s];return Object.seal(r),r}static fill(e,t){const r=[];for(let s=0;s<t;s++)r.push(e(s));return hr.new(r,t)}toString(){return $(Array.from(this))}}class ur{array;comparator;static fromArray(e,t=[]){const r=t.slice();return r.sort((t,r)=>e(t,r).value),new ur(r,e)}static fromSortedArray(e,t=[]){const r=t.length;if(0===r)return new ur([],e);const s=t.slice();for(let t=1;t<r;t++)if(e(s[t-1],s[t]).isGreater())throw new Error(`Expected sorted array, got: ${s}`);return new ur(s,e)}constructor(e,t){this.array=e,this.comparator=t}insert(e){const t=this.binarySearch(e);this.array.splice(t.idx,0,e)}pop(){return this.array.pop()}findIndex(e){const t=this.binarySearch(e);return t.isEqual?t.idx:-1}findExact(e){const t=this.binarySearch(e);if(t.isEqual)return this.array[t.idx]}removeOne(e){const t=this.binarySearch(e);t.isEqual&&this.array.splice(t.idx,1)}has(e){return this.binarySearch(e).isEqual}get length(){return this.array.length}slice(e,t){return this.array.slice(e,t)}binarySearch(e){const t=this.array,r=this.comparator;let s=0,i=t.length;for(;s<i;){const n=i+s>>1,o=r(t[n],e);if(o.isEqual())return{idx:n,isEqual:!0};o.isLess()?s=n+1:i=n}return{idx:s,isEqual:!1}}static fromTwoSortedCollections(e,t){Q(e.comparator===t.comparator,"Cannot merge arrays if they do not use the same comparator");const r=e.comparator,s=e.array,i=s.length,n=t.array,o=n.length,a=new Array(i+o);let c=0,l=0,h=0;for(;c<i&&l<o;)r(s[c],n[l]).isLess()?a[h++]=s[c++]:(r(s[c],n[l]).isGreater()||(a[h++]=s[c++]),a[h++]=n[l++]);for(;c<i;)a[h++]=s[c++];for(;l<o;)a[h++]=n[l++];return ur.fromSortedArray(r,a)}*[Symbol.iterator](){for(const e of this.array)yield e}}class dr extends ur{static fromArray(e,t=[]){const r=t.slice();r.sort((t,r)=>e(t,r).value);const s=r.length;for(let i=1;i<s;i++)if(e(r[i-1],r[i]).isEqual())throw new Error(`Expected array without duplicates, got: ${t}`);return new dr(r,e)}static fromSortedArray(e,t=[]){if(0===t.length)return new dr([],e);const r=t.slice(),s=r.length;for(let t=1;t<s;t++)if(e(r[t-1],r[t]).isGreaterOrEqual())throw new Error(`Expected sorted array without duplicates, got: ${r}`);return new dr(r,e)}insert(e){const t=this.binarySearch(e);t.isEqual||this.array.splice(t.idx,0,e)}static fromTwoSortedCollections(e,t){Q(e.comparator===t.comparator,"Cannot merge arrays if they do not use the same comparator");const r=e.comparator;if(0===e.length)return dr.fromSortedArray(r,t.array);if(0===t.length)return dr.fromSortedArray(r,e.array);const s=ur.fromTwoSortedCollections(e,t).array,i=s.length;let n=1;for(let e=1;e<i;e++)r(s[e-1],s[e]).isNotEqual()&&(s[n++]=s[e]);return s.length=n,dr.fromSortedArray(r,s)}}class fr extends G{validatorsCount;thirdOfValidators;validatorsSuperMajority;coresCount;slotDuration;epochLength;rotationPeriod;contestLength;ticketsPerValidator;maxTicketsPerExtrinsic;numberECPiecesPerSegment;constructor(e){super(),this.validatorsCount=e.validatorsCount,this.thirdOfValidators=Math.floor(e.validatorsCount/3),this.validatorsSuperMajority=2*Math.floor(e.validatorsCount/3)+1,this.coresCount=e.coresCount,this.slotDuration=e.slotDuration,this.epochLength=e.epochLength,this.rotationPeriod=e.rotationPeriod,this.contestLength=e.contestLength,this.ticketsPerValidator=e.ticketsPerValidator,this.maxTicketsPerExtrinsic=e.maxTicketsPerExtrinsic,this.numberECPiecesPerSegment=e.numberECPiecesPerSegment}}const pr=new fr({contestLength:10,coresCount:2,epochLength:12,maxTicketsPerExtrinsic:3,rotationPeriod:4,slotDuration:6,ticketsPerValidator:3,validatorsCount:6,numberECPiecesPerSegment:1026}),gr=new fr({contestLength:500,coresCount:341,epochLength:600,maxTicketsPerExtrinsic:16,rotationPeriod:10,slotDuration:6,ticketsPerValidator:2,validatorsCount:1023,numberECPiecesPerSegment:6});class yr{chainSpec;dbPath;omitSealVerification;static reInit(e){const{chainSpec:t,dbPath:r,omitSealVerification:s}=e;return new yr(new fr(t),r,s)}constructor(e,t,r=!1){this.chainSpec=e,this.dbPath=t,this.omitSealVerification=r}}function mr(e){const t=gr,{name:r,sizeHint:s}=e(t),i=new Map;return Ve.select({name:r,sizeHint:{bytes:s.bytes,isExact:!1}},s=>{if(s instanceof fr){const t=i.get(s);if(void 0!==t)return t;const r=e(s);return i.set(s,r),r}if(null===s)return e(t);if(null!==s)throw new Error(`[${r}] Unexpected context type ${typeof s} while encoding/decoding.`);throw new Error(`[${r}] Missing context while encoding/decoding!`)})}const br=(e,t,r)=>"fixedLength"in t?Ke(Ve.sequenceFixLen(e,t.fixedLength)).convert(z,lr):Ke(Ve.sequenceVarLen(e,t)).convert(z,lr),Ar=(e,t)=>{const r=r=>{if(t!==r)throw new Error(`[${e.name}] Invalid size of fixed-size array. Got ${r}, expected: ${t}`)};return Ve.sequenceFixLen(e,t).convert(e=>(r(e.length),e),e=>(r(e.length),hr.new(e,t)))},Ir=(e,t,{typicalLength:r=32,compare:s=(e,r)=>t(e).compare(t(r))}={})=>He.new(`HashDictionary<${e.name}>[?]`,{bytes:r*e.sizeHint.bytes,isExact:!1},(t,r)=>{const i=Array.from(r.values());i.sort((e,t)=>s(e,t).value),t.varU32(Ae(i.length));for(const r of i)e.encode(t,r)},r=>{const i=ar.new(),n=r.varU32();let o=null;for(let a=0;a<n;a+=1){const n=e.decode(r),a=t(n);if(i.has(a))throw new Error(`Duplicate item in the dictionary encoding: "${a}"!`);if(null!==o&&s(o,n).isGreaterOrEqual())throw new Error(`The keys in dictionary encoding are not sorted "${o}" >= "${n}"!`);i.set(a,n),o=n}return i},t=>{const r=t.decoder.varU32();t.sequenceFixLen(e,r)});class vr extends G{anchor;bitfield;validatorIndex;signature;static Codec=Ve.Class(vr,{anchor:Ve.bytes(Rt).asOpaque(),bitfield:mr(e=>Ve.bitVecFixLen(e.coresCount)),validatorIndex:Ve.u16.asOpaque(),signature:Ve.bytes(Et).asOpaque()});static create({anchor:e,bitfield:t,validatorIndex:r,signature:s}){return new vr(e,t,r,s)}constructor(e,t,r,s){super(),this.anchor=e,this.bitfield=t,this.validatorIndex=r,this.signature=s}}const wr=mr(e=>br(vr.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2}));class Sr extends G{workReportHash;wasConsideredValid;key;signature;static Codec=Ve.Class(Sr,{workReportHash:Ve.bytes(Rt).asOpaque(),wasConsideredValid:Ve.bool,key:Ve.bytes(St).asOpaque(),signature:Ve.bytes(Et).asOpaque()});static create({workReportHash:e,wasConsideredValid:t,key:r,signature:s}){return new Sr(e,t,r,s)}constructor(e,t,r,s){super(),this.workReportHash=e,this.wasConsideredValid=t,this.key=r,this.signature=s}}class Er extends G{workReportHash;key;signature;static Codec=Ve.Class(Er,{workReportHash:Ve.bytes(Rt).asOpaque(),key:Ve.bytes(St).asOpaque(),signature:Ve.bytes(Et).asOpaque()});static create({workReportHash:e,key:t,signature:r}){return new Er(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.key=t,this.signature=r}}class Cr extends G{isWorkReportValid;index;signature;static Codec=Ve.Class(Cr,{isWorkReportValid:Ve.bool,index:Ve.u16.asOpaque(),signature:Ve.bytes(Et).asOpaque()});static create({isWorkReportValid:e,index:t,signature:r}){return new Cr(e,t,r)}constructor(e,t,r){super(),this.isWorkReportValid=e,this.index=t,this.signature=r}}class kr extends G{workReportHash;votesEpoch;votes;static Codec=Ve.Class(kr,{workReportHash:Ve.bytes(Rt).asOpaque(),votesEpoch:Ve.u32.asOpaque(),votes:mr(e=>Ke(Ve.sequenceFixLen(Cr.Codec,e.validatorsSuperMajority)).convert(z,lr))});static create({workReportHash:e,votesEpoch:t,votes:r}){return new kr(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.votesEpoch=t,this.votes=r}}class xr extends G{verdicts;culprits;faults;static Codec=Ve.Class(xr,{verdicts:Ve.sequenceVarLen(kr.Codec),culprits:Ve.sequenceVarLen(Er.Codec),faults:Ve.sequenceVarLen(Sr.Codec)});static create({verdicts:e,culprits:t,faults:r}){return new xr(e,t,r)}constructor(e,t,r){super(),this.verdicts=e,this.culprits=t,this.faults=r}}const _r=e=>Ae(e),Br=e=>me(e),Rr=e=>Ae(e),Or=e=>ve(e),Ur=e=>me(e),Tr=e=>Ae(e);function Nr(e,t){return Q(e.length===t.validatorsCount,`Invalid per-validator array length. Expected ${t.validatorsCount}, got: ${e.length}`),e}const Dr=e=>mr(t=>br(e,{fixedLength:t.validatorsCount}));function Mr(e,t){return Q(e.length===t.epochLength,`Invalid per-epoch-block array length. Expected ${t.epochLength}, got: ${e.length}`),e}const Pr=e=>mr(t=>br(e,{fixedLength:t.epochLength}));class Lr extends G{anchor;stateRoot;beefyRoot;lookupAnchor;lookupAnchorSlot;prerequisites;static Codec=Ve.Class(Lr,{anchor:Ve.bytes(Rt).asOpaque(),stateRoot:Ve.bytes(Rt).asOpaque(),beefyRoot:Ve.bytes(Rt).asOpaque(),lookupAnchor:Ve.bytes(Rt).asOpaque(),lookupAnchorSlot:Ve.u32.asOpaque(),prerequisites:Ve.sequenceVarLen(Ve.bytes(Rt).asOpaque())});static create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n}){return new Lr(e,t,r,s,i,n)}constructor(e,t,r,s,i,n=[]){super(),this.anchor=e,this.stateRoot=t,this.beefyRoot=r,this.lookupAnchor=s,this.lookupAnchorSlot=i,this.prerequisites=n}}class Hr extends G{treeRoot;index;static Codec=Ve.Class(Hr,{treeRoot:Ve.bytes(Rt),index:Ve.u16.asOpaque()});static create({treeRoot:e,index:t}){return new Hr(e,t)}constructor(e,t){super(),this.treeRoot=e,this.index=t}}class Kr extends G{hash;len;static Codec=Ve.Class(Kr,{hash:Ve.bytes(Rt).asOpaque(),len:Ve.u32});static create({hash:e,len:t}){return new Kr(e,t)}constructor(e,t){super(),this.hash=e,this.len=t}}class Qr extends G{service;codeHash;payload;refineGasLimit;accumulateGasLimit;importSegments;extrinsic;exportCount;static Codec=Ve.Class(Qr,{service:Ve.u32.asOpaque(),codeHash:Ve.bytes(Rt).asOpaque(),payload:Ve.blob,refineGasLimit:Ve.u64.asOpaque(),accumulateGasLimit:Ve.u64.asOpaque(),importSegments:br(Hr.Codec,{minLength:0,maxLength:2048,typicalLength:2048}),extrinsic:Ve.sequenceVarLen(Kr.Codec),exportCount:Ve.u16});static create({service:e,codeHash:t,payload:r,refineGasLimit:s,accumulateGasLimit:i,importSegments:n,extrinsic:o,exportCount:a}){return new Qr(e,t,r,s,i,n,o,a)}constructor(e,t,r,s,i,n,o,a){super(),this.service=e,this.codeHash=t,this.payload=r,this.refineGasLimit=s,this.accumulateGasLimit=i,this.importSegments=n,this.extrinsic=o,this.exportCount=a}}function Vr(e){return V(e,e>=Fr&&e<=$r,`WorkItemsCount: Expected '${Fr} <= count <= ${$r}' got ${e}`)}const Fr=1,$r=16;class jr extends G{authorization;authCodeHost;authCodeHash;parametrization;context;items;static Codec=Ve.Class(jr,{authorization:Ve.blob,authCodeHost:Ve.u32.asOpaque(),authCodeHash:Ve.bytes(Rt).asOpaque(),parametrization:Ve.blob,context:Lr.Codec,items:Ve.sequenceVarLen(Qr.Codec).convert(e=>e,e=>hr.new(e,Vr(e.length)))});static create({authorization:e,authCodeHost:t,authCodeHash:r,parametrization:s,context:i,items:n}){return new jr(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){super(),this.authorization=e,this.authCodeHost=t,this.authCodeHash=r,this.parametrization=s,this.context=i,this.items=n}}var Gr,qr;(qr=Gr||(Gr={}))[qr.ok=0]="ok",qr[qr.outOfGas=1]="outOfGas",qr[qr.panic=2]="panic",qr[qr.badCode=3]="badCode",qr[qr.codeOversize=4]="codeOversize";class zr extends G{kind;okBlob;static Codec=Ve.custom({name:"WorkExecResult",sizeHint:{bytes:1,isExact:!1}},(e,t)=>{e.varU32(Ae(t.kind)),t.kind===Gr.ok&&null!==t.okBlob&&e.bytesBlob(t.okBlob)},e=>{const t=e.varU32();if(t===Gr.ok){const r=e.bytesBlob();return new zr(t,r)}if(t>Gr.codeOversize)throw new Error(`Invalid WorkExecResultKind: ${t}`);return new zr(t)},e=>{e.decoder.varU32()===Gr.ok&&e.bytesBlob()});constructor(e,t=null){super(),this.kind=e,this.okBlob=t}}class Wr extends G{gasUsed;importedSegments;extrinsicCount;extrinsicSize;exportedSegments;static Codec=Ve.Class(Wr,{gasUsed:Ve.varU64.asOpaque(),importedSegments:Ve.varU32,extrinsicCount:Ve.varU32,extrinsicSize:Ve.varU32,exportedSegments:Ve.varU32});static create({gasUsed:e,importedSegments:t,extrinsicCount:r,extrinsicSize:s,exportedSegments:i}){return new Wr(e,t,r,s,i)}constructor(e,t,r,s,i){super(),this.gasUsed=e,this.importedSegments=t,this.extrinsicCount=r,this.extrinsicSize=s,this.exportedSegments=i}}class Jr{serviceId;codeHash;payloadHash;gas;result;load;static Codec=Ve.Class(Jr,{serviceId:Ve.u32.asOpaque(),codeHash:Ve.bytes(Rt).asOpaque(),payloadHash:Ve.bytes(Rt),gas:Ve.u64.asOpaque(),result:zr.Codec,load:Wr.Codec});static create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n}){return new Jr(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.serviceId=e,this.codeHash=t,this.payloadHash=r,this.gas=s,this.result=i,this.load=n}}class Yr extends G{hash;length;erasureRoot;exportsRoot;exportsCount;static Codec=Ve.Class(Yr,{hash:Ve.bytes(Rt).asOpaque(),length:Ve.u32,erasureRoot:Ve.bytes(Rt),exportsRoot:Ve.bytes(Rt).asOpaque(),exportsCount:Ve.u16});static create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i}){return new Yr(e,t,r,s,i)}constructor(e,t,r,s,i){super(),this.hash=e,this.length=t,this.erasureRoot=r,this.exportsRoot=s,this.exportsCount=i}}class Xr extends G{workPackageHash;segmentTreeRoot;static Codec=Ve.Class(Xr,{workPackageHash:Ve.bytes(Rt).asOpaque(),segmentTreeRoot:Ve.bytes(Rt).asOpaque()});constructor(e,t){super(),this.workPackageHash=e,this.segmentTreeRoot=t}static create({workPackageHash:e,segmentTreeRoot:t}){return new Xr(e,t)}}class Zr extends G{workPackageSpec;context;coreIndex;authorizerHash;authorizationOutput;segmentRootLookup;results;authorizationGasUsed;static Codec=Ve.Class(Zr,{workPackageSpec:Yr.Codec,context:Lr.Codec,coreIndex:K.isGreaterOrEqual(D.V0_6_5)?Ve.varU32.convert(e=>Ae(e),e=>{if(!be(e))throw new Error(`Core index exceeds U16: ${e}`);return Ur(e)}):Ve.u16.asOpaque(),authorizerHash:Ve.bytes(Rt).asOpaque(),authorizationOutput:Ve.blob,segmentRootLookup:Ke(Ve.sequenceVarLen(Xr.Codec)),results:Ve.sequenceVarLen(Jr.Codec).convert(e=>e,e=>hr.new(e,Vr(e.length))),authorizationGasUsed:Ve.varU64.asOpaque()});static create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:n,results:o,authorizationGasUsed:a}){return new Zr(e,t,r,s,i,n,o,a)}constructor(e,t,r,s,i,n,o,a){super(),this.workPackageSpec=e,this.context=t,this.coreIndex=r,this.authorizerHash=s,this.authorizationOutput=i,this.segmentRootLookup=n,this.results=o,this.authorizationGasUsed=a}}const es=[2,3];class ts extends G{validatorIndex;signature;static Codec=Ve.Class(ts,{validatorIndex:Ve.u16.asOpaque(),signature:Ve.bytes(Et).asOpaque()});static create({validatorIndex:e,signature:t}){return new ts(e,t)}constructor(e,t){super(),this.validatorIndex=e,this.signature=t}}class rs extends G{report;slot;credentials;static Codec=Ve.Class(rs,{report:Zr.Codec,slot:Ve.u32.asOpaque(),credentials:br(ts.Codec,{minLength:es[0],maxLength:es[1],typicalLength:es[1]})});static create({report:e,slot:t,credentials:r}){return new rs(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.credentials=r}}const ss=mr(e=>br(rs.Codec,{minLength:0,maxLength:e.coresCount,typicalLength:e.coresCount}));class is extends G{attempt;signature;static Codec=Ve.Class(is,{attempt:Ve.u8.asOpaque(),signature:Ve.bytes(784).asOpaque()});static create({attempt:e,signature:t}){return new is(e,t)}constructor(e,t){super(),this.attempt=e,this.signature=t}}class ns extends G{id;attempt;static Codec=Ve.Class(ns,{id:Ve.bytes(Rt),attempt:Ve.u8.asOpaque()});static create({id:e,attempt:t}){return new ns(e,t)}constructor(e,t){super(),this.id=e,this.attempt=t}}const os=br(is.Codec,{minLength:0,maxLength:16,typicalLength:16});class as extends G{bandersnatch;ed25519;static Codec=Ve.Class(as,{bandersnatch:Ve.bytes(xt).asOpaque(),ed25519:Ve.bytes(St).asOpaque()});static create({bandersnatch:e,ed25519:t}){return new as(e,t)}constructor(e,t){super(),this.bandersnatch=e,this.ed25519=t}}class cs extends G{entropy;ticketsEntropy;validators;static Codec=Ve.Class(cs,{entropy:Ve.bytes(Rt).asOpaque(),ticketsEntropy:Ve.bytes(Rt).asOpaque(),validators:Dr(as.Codec)});static create({entropy:e,ticketsEntropy:t,validators:r}){return new cs(e,t,r)}constructor(e,t,r){super(),this.entropy=e,this.ticketsEntropy=t,this.validators=r}}const ls=e=>{const t=e.encoded().raw,r=t.length-96;return te.blobFrom(t.subarray(0,r))};class hs extends G{static Codec=Ve.Class(hs,{parentHeaderHash:Ve.bytes(Rt).asOpaque(),priorStateRoot:Ve.bytes(Rt).asOpaque(),extrinsicHash:Ve.bytes(Rt).asOpaque(),timeSlotIndex:Ve.u32.asOpaque(),epochMarker:Ve.optional(cs.Codec),ticketsMarker:Ve.optional(Pr(ns.Codec)),offendersMarker:Ve.sequenceVarLen(Ve.bytes(St).asOpaque()),bandersnatchBlockAuthorIndex:Ve.u16.asOpaque(),entropySource:Ve.bytes(96).asOpaque(),seal:Ve.bytes(96).asOpaque()});static create(e){return Object.assign(hs.empty(),e)}parentHeaderHash=re.zero(Rt).asOpaque();priorStateRoot=re.zero(Rt).asOpaque();extrinsicHash=re.zero(Rt).asOpaque();timeSlotIndex=_r(0);epochMarker=null;ticketsMarker=null;offendersMarker=[];bandersnatchBlockAuthorIndex=Br(0);entropySource=re.zero(96).asOpaque();seal=re.zero(96).asOpaque();constructor(){super()}static empty(){return new hs}}class us extends Ot{static Codec=Ve.Class(us,{hash:Ve.bytes(Rt).asOpaque(),data:hs.Codec.View});static create({hash:e,data:t}){return new Ot(e,t)}}const ds=us.Codec;class fs extends G{requester;blob;static Codec=Ve.Class(fs,{requester:Ve.u32.asOpaque(),blob:Ve.blob});static create({requester:e,blob:t}){return new fs(e,t)}constructor(e,t){super(),this.requester=e,this.blob=t}}const ps=Ve.sequenceVarLen(fs.Codec);class gs extends G{tickets;preimages;guarantees;assurances;disputes;static Codec=Ve.Class(gs,{tickets:os,preimages:ps,guarantees:ss,assurances:wr,disputes:xr.Codec});static create({tickets:e,preimages:t,assurances:r,disputes:s,guarantees:i}){return new gs(e,t,i,r,s)}constructor(e,t,r,s,i){super(),this.tickets=e,this.preimages=t,this.guarantees=r,this.assurances=s,this.disputes=i}}class ys extends G{header;extrinsic;static Codec=Ve.Class(ys,{header:hs.Codec,extrinsic:gs.Codec});static create({header:e,extrinsic:t}){return new ys(e,t)}constructor(e,t){super(),this.header=e,this.extrinsic=t}}const ms=Symbol("no key");function bs(e,t,r="<root>"){const s=typeof e;if("string"===t){if("string"===s)return e;throw new Error(`[${r}] Expected ${t} but got ${s}`)}if("number"===t){if("number"===s)return e;throw new Error(`[${r}] Expected ${t} but got ${s}`)}if("boolean"===t){if("boolean"===s)return e;throw new Error(`[${r}] Expected ${t} but got ${s}`)}if(Array.isArray(t)){const s=t[0];if("array"===s){const s=t[1];if("function"==typeof s)return s(e,r);if(!Array.isArray(e))throw new Error(`[${r}] Expected array, got ${e}`);const i=e,n=[];for(const[e,t]of i.entries())n[e]=bs(t,s,`${r}.${e}`);return n}if("optional"===s)return null==e?e:bs(e,t[1],r);if("object"===s)return As(t[1],e,r);if("string"===s)return As(t[1],bs(e,s,r),r);if("number"===s){const s=t[0];return As(t[1],bs(e,s,r),r)}throw new Error(`[${r}] Invalid parser type: ${s}`)}if("object"!==s)throw new Error(`[${r}] Expected complex type but got ${s}`);if("object"!=typeof t)throw new Error(`[${r}] Unhandled type ${t}`);if(null===e)throw new Error(`[${r}] Unexpected 'null'`);const i={},n=e,o=t;for(const e of Object.keys(n))i[e]=void 0;for(const e of Object.keys(t))if(e in n){const t=n[e];i[e]=bs(t,o[e],`${r}.${e}`)}else Array.isArray(o[e])&&"optional"===o[e][0]&&(i[e]=ms);const a=function(e,t){const r=Object.keys(e),s=Object.keys(t);r.sort(),s.sort();const i={},n=Math.max(s.length,s.length);for(let e=0;e<n;e++)i[r[e]]=(i[r[e]]||0)+1,i[s[e]]=(i[s[e]]||0)+2;const o=[],a=e=>void 0!==e?`"${e}"`:"<missing>";for(const[e,t]of Object.entries(i))3!==t&&"undefined"!==e&&o.push(1===t?[a(e),a(void 0)]:[a(void 0),a(e)]);return o}(i,t);if(a.length>0)throw new Error(`[${r}] Unexpected or missing keys: ${a.join(" | ")}\n Data: ${Object.keys(i)}\n Schema: ${Object.keys(t)}`);for(const e of Object.keys(i))i[e]===ms&&delete i[e];return i}function As(e,t,r){try{return e(t,r)}catch(e){throw new Error(`[${r}] Error while parsing the value: ${e}`)}}var Is,vs;!function(e){function t(e){return["number",e]}function r(e){return["object",e]}e.fromString=function(e){return["string",e]},e.fromNumber=t,e.castNumber=function(){return t(e=>e)},e.fromAny=r,e.optional=function(e){return["optional",e]},e.nullable=function(e){return["optional",e]},e.array=function(e){return["array",e]},e.record=function(e){return r((t,r)=>{if("object"!=typeof t||null===t)throw new Error("Expected object record for parsing");const s={};for(const[i,n]of Object.entries(t))s[i]=bs(n,e,`${r}.${i}`);return s})},e.map=function(e,t){return r((r,s)=>{if("object"!=typeof r||null===r)throw new Error("Expected map for parsing");const i=new Map;for(const[n,o]of Object.entries(r))i.set(bs(n,e,`${s}.key`),bs(o,t,`${s}.value`));return i})},e.object=function(e,t){return r((r,s)=>{const i=bs(r,e,s);return t(i)})}}(Is||(Is={})),function(e){e.bytesN=e=>Is.fromString(t=>re.parseBytes(t,e).asOpaque()),e.bytesNNoPrefix=e=>Is.fromString(t=>re.parseBytesNoPrefix(t,e).asOpaque()),e.bytes32=()=>Is.fromString(e=>re.parseBytes(e,32).asOpaque()),e.bytes32NoPrefix=()=>Is.fromString(e=>re.parseBytesNoPrefix(e,32).asOpaque()),e.bytesBlob=Is.fromString(te.parseBlob),e.bytesBlobNoPrefix=Is.fromString(te.parseBlobNoPrefix),e.ed25519Signature=Is.fromString(e=>re.parseBytes(e,64).asOpaque()),e.ticketAttempt=Is.fromNumber(e=>{if(0!==e&&1!==e&&2!==e)throw new Error("Invalid TicketAttempt value.");return function(e){return ge(e)}(e)}),e.uint8Array=Is.fromAny(e=>{if(Array.isArray(e))return new Uint8Array(e);if(null===e)return new Uint8Array;throw new Error(`Expected an array, got ${typeof e} instead. [uint8Array]`)}),e.bigUint64Array=Is.fromAny(e=>{if(Array.isArray(e))return new BigUint64Array(e.map(e=>BigInt(e)));if(null===e)return new BigUint64Array;throw new Error(`Expected an array, got ${typeof e} instead. [bigUint64Array]`)}),e.bigUint64=Is.fromAny(e=>BigInt(e))}(vs||(vs={}));const ws=e=>Is.array((e=>Is.object({anchor:vs.bytes32(),bitfield:Is.fromString(t=>{const r=Math.ceil(e.coresCount/8);return pe.fromBytes(re.parseBytes(t,r),e.coresCount)}),validator_index:"number",signature:vs.ed25519Signature},({anchor:e,bitfield:t,validator_index:r,signature:s})=>vr.create({anchor:e,bitfield:t,validatorIndex:r,signature:s})))(e)),Ss=Is.object({target:vs.bytes32(),vote:"boolean",key:vs.bytes32(),signature:vs.ed25519Signature},({target:e,vote:t,key:r,signature:s})=>Sr.create({workReportHash:e,wasConsideredValid:t,key:r,signature:s})),Es=Is.object({target:vs.bytes32(),key:vs.bytes32(),signature:vs.ed25519Signature},({target:e,key:t,signature:r})=>Er.create({workReportHash:e,key:t,signature:r})),Cs=Is.object({vote:"boolean",index:"number",signature:vs.ed25519Signature},({vote:e,index:t,signature:r})=>Cr.create({isWorkReportValid:e,index:t,signature:r})),ks=Is.object({target:vs.bytes32(),age:"number",votes:Is.array(Cs)},({target:e,age:t,votes:r})=>kr.create({workReportHash:e,votesEpoch:t,votes:r})),xs=Is.object({verdicts:Is.array(ks),culprits:Is.array(Es),faults:Is.array(Ss)},({verdicts:e,culprits:t,faults:r})=>xr.create({verdicts:e,culprits:t,faults:r})),_s=Is.object({anchor:vs.bytes32(),state_root:vs.bytes32(),beefy_root:vs.bytes32(),lookup_anchor:vs.bytes32(),lookup_anchor_slot:"number",prerequisites:Is.array(vs.bytes32())},({anchor:e,state_root:t,beefy_root:r,lookup_anchor:s,lookup_anchor_slot:i,prerequisites:n})=>Lr.create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n})),Bs=Is.object({ok:Is.optional(Is.fromString(te.parseBlob)),out_of_gas:Is.optional(Is.fromAny(()=>null)),panic:Is.optional(Is.fromAny(()=>null)),bad_code:Is.optional(Is.fromAny(()=>null)),code_oversize:Is.optional(Is.fromAny(()=>null))},e=>{const{ok:t,out_of_gas:r,panic:s,bad_code:i,code_oversize:n}=e;if(void 0!==t)return new zr(Ae(Gr.ok),t);if(null===r)return new zr(Ae(Gr.outOfGas));if(null===s)return new zr(Ae(Gr.panic));if(null===i)return new zr(Ae(Gr.badCode));if(null===n)return new zr(Ae(Gr.codeOversize));throw new Error("Invalid WorkExecResult")}),Rs=Is.object({gas_used:Is.fromNumber(e=>Or(e)),imports:"number",extrinsic_count:"number",extrinsic_size:"number",exports:"number"},({gas_used:e,imports:t,extrinsic_count:r,extrinsic_size:s,exports:i})=>Wr.create({gasUsed:Or(e),importedSegments:Ae(t),extrinsicCount:Ae(r),extrinsicSize:Ae(s),exportedSegments:Ae(i)})),Os=Is.object({service_id:"number",code_hash:vs.bytes32(),payload_hash:vs.bytes32(),accumulate_gas:Is.fromNumber(e=>Or(e)),result:Bs,refine_load:Rs},({service_id:e,code_hash:t,payload_hash:r,accumulate_gas:s,result:i,refine_load:n})=>Jr.create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n})),Us=Is.object({hash:vs.bytes32(),length:"number",erasure_root:vs.bytes32(),exports_root:vs.bytes32(),exports_count:"number"},({hash:e,length:t,erasure_root:r,exports_root:s,exports_count:i})=>Yr.create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i})),Ts=Is.object({work_package_hash:vs.bytes32(),segment_tree_root:vs.bytes32()},({work_package_hash:e,segment_tree_root:t})=>Xr.create({workPackageHash:e,segmentTreeRoot:t})),Ns=Is.object({package_spec:Us,context:_s,core_index:"number",authorizer_hash:vs.bytes32(),auth_output:Is.fromString(te.parseBlob),segment_root_lookup:Is.array(Ts),results:Is.array(Os),auth_gas_used:Is.fromNumber(e=>Or(e))},({package_spec:e,context:t,core_index:r,authorizer_hash:s,auth_output:i,results:n,segment_root_lookup:o,auth_gas_used:a})=>{const c=hr.new(n,Vr(n.length));return Zr.create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:o,results:c,authorizationGasUsed:a})}),Ds=Is.object({validator_index:"number",signature:vs.ed25519Signature},({validator_index:e,signature:t})=>ts.create({validatorIndex:e,signature:t})),Ms=Is.object({report:Ns,slot:"number",signatures:Is.array(Ds)},({report:e,slot:t,signatures:r})=>rs.create({report:e,slot:t,credentials:r})),Ps=Is.array(Ms),Ls=Is.object({requester:"number",blob:Is.fromString(te.parseBlob)},({requester:e,blob:t})=>fs.create({requester:e,blob:t})),Hs=Is.array(Ls),Ks=Is.object({attempt:vs.ticketAttempt,signature:Is.fromString(e=>re.parseBytes(e,784).asOpaque())},e=>is.create({attempt:e.attempt,signature:e.signature})),Qs=Is.array(Ks),Vs=Is.fromString(e=>re.parseBytes(e,96).asOpaque()),Fs=Is.object({bandersnatch:vs.bytes32(),ed25519:vs.bytes32()},as.create),$s=Is.object({entropy:vs.bytes32(),tickets_entropy:vs.bytes32(),validators:Is.array(Fs)},e=>cs.create({entropy:e.entropy,ticketsEntropy:e.tickets_entropy,validators:e.validators})),js=Is.object({id:vs.bytes32(),attempt:vs.ticketAttempt},e=>ns.create({id:e.id,attempt:e.attempt})),Gs=Is.object({parent:vs.bytes32(),parent_state_root:vs.bytes32(),extrinsic_hash:vs.bytes32(),slot:"number",epoch_mark:Is.optional($s),tickets_mark:Is.optional(Is.array(js)),offenders_mark:Is.array(vs.bytes32()),author_index:"number",entropy_source:Vs,seal:Vs},({parent:e,parent_state_root:t,extrinsic_hash:r,slot:s,epoch_mark:i,tickets_mark:n,offenders_mark:o,author_index:a,entropy_source:c,seal:l})=>{const h=hs.empty();return h.parentHeaderHash=e,h.priorStateRoot=t,h.extrinsicHash=r,h.timeSlotIndex=s,h.epochMarker=i??null,h.ticketsMarker=n??null,h.offendersMarker=o,h.bandersnatchBlockAuthorIndex=a,h.entropySource=c,h.seal=l,h});class qs extends G{name;ip;port;static fromString(e){const[t,r]=e.split("@"),s=r.substring(0,r.lastIndexOf(":")),i=r.substring(r.lastIndexOf(":")+1);if(""===t||""===s||""===i)throw new Error(`Invalid bootnode format, expected: <name>@<ip>:<port>, got: "${e}"`);const n=Number.parseInt(i);if(!be(n))throw new Error(`Invalid port number: "${i}"`);return new qs(t,s,n)}constructor(e,t,r){super(),this.name=e,this.ip=t,this.port=r}}class zs extends G{bootnodes;id;genesisHeader;genesisState;static fromJson=Is.object({bootnodes:Is.optional(Is.array(Is.fromString(qs.fromString))),id:"string",genesis_header:vs.bytesBlobNoPrefix,genesis_state:Is.map(vs.bytesNNoPrefix(31),vs.bytesBlobNoPrefix)},e=>zs.create({bootnodes:e.bootnodes,id:e.id,genesisHeader:e.genesis_header,genesisState:e.genesis_state??new Map}));static create({bootnodes:e=[],id:t="",genesisHeader:r=te.empty(),genesisState:s=new Map}){return new zs({bootnodes:e,id:t,genesisHeader:r,genesisState:s})}constructor(e){super(),this.bootnodes=e.bootnodes,this.id=e.id,this.genesisHeader=e.genesisHeader,this.genesisState=e.genesisState}}class Ws{omitSealVerification;static fromJson=Is.object({omit_seal_verification:"boolean"},Ws.new);static new({omit_seal_verification:e}){return new Ws(e)}constructor(e){this.omitSealVerification=e}}var Js;!function(e){e.Tiny="tiny",e.Full="full"}(Js||(Js={}));const Ys=Is.fromString((e,t)=>{switch(e){case Js.Tiny:return Js.Tiny;case Js.Full:return Js.Full;default:throw Error(`unknown network flavor: ${e} at ${t}`)}});class Xs{$schema;version;flavor;chainSpec;databaseBasePath;authorship;static fromJson=Is.object({$schema:"string",version:"number",flavor:Ys,chain_spec:zs.fromJson,database_base_path:"string",authorship:Ws.fromJson},Xs.new);static new({$schema:e,version:t,flavor:r,chain_spec:s,database_base_path:i,authorship:n}){if(1!==t)throw new Error("Only version=1 config is supported.");return new Xs(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.$schema=e,this.version=t,this.flavor=r,this.chainSpec=s,this.databaseBasePath=i,this.authorship=n}}const Zs=e=>He.withView(e.name,e.sizeHint,(t,r)=>e.encode(t,r.data),t=>{const r=t.clone(),s=Ht(e.skipEncoded(r));return new Ot(s.asOpaque(),e.decode(t))},e.skip,e.View);class ei extends G{workReport;timeout;static Codec=Ve.Class(ei,{workReport:Zs(Zr.Codec),timeout:Ve.u32.asOpaque()});static create({workReport:e,timeout:t}){return new ei(e,t)}constructor(e,t){super(),this.workReport=e,this.timeout=t}}class ti extends G{headerHash;mmr;postStateRoot;reported;static Codec=Ve.Class(ti,{headerHash:Ve.bytes(Rt).asOpaque(),mmr:Ve.object({peaks:Ke(Ve.sequenceVarLen(Ve.optional(Ve.bytes(Rt))))}),postStateRoot:Ve.bytes(Rt).asOpaque(),reported:Ir(Xr.Codec,e=>e.workPackageHash)});static create({headerHash:e,mmr:t,postStateRoot:r,reported:s}){return new ti(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.mmr=t,this.postStateRoot=r,this.reported=s}}function ri(e,t){return Q(e.length===t.coresCount,`Invalid per-core array length. Expected ${t.coresCount}, got: ${e.length}`),e}const si=e=>mr(t=>br(e,{fixedLength:t.coresCount})),ii=()=>Ke(Ve.sequenceVarLen(Ve.bytes(Rt))).convert(e=>e.array,e=>{const t=e.map(e=>e.asOpaque());return dr.fromSortedArray(ai,t)}),ni=ii();class oi{goodSet;badSet;wonkySet;punishSet;static Codec=Ve.Class(oi,{goodSet:ni,badSet:ni,wonkySet:ni,punishSet:ii()});static create({goodSet:e,badSet:t,wonkySet:r,punishSet:s}){return new oi(e,t,r,s)}constructor(e,t,r,s){this.goodSet=e,this.badSet=t,this.wonkySet=r,this.punishSet=s}static fromSortedArrays({goodSet:e,badSet:t,wonkySet:r,punishSet:s}){return new oi(dr.fromSortedArray(ai,e),dr.fromSortedArray(ai,t),dr.fromSortedArray(ai,r),dr.fromSortedArray(ai,s))}}function ai(e,t){return e.compare(t)}class ci{service;gasLimit;static Codec=Ve.Class(ci,{service:Ve.u32.asOpaque(),gasLimit:Ve.u64.asOpaque()});static create({service:e,gasLimit:t}){return new ci(e,t)}constructor(e,t){this.service=e,this.gasLimit=t}}class li{manager;authManager;validatorsManager;autoAccumulateServices;static Codec=Ve.Class(li,{manager:Ve.u32.asOpaque(),authManager:Ve.u32.asOpaque(),validatorsManager:Ve.u32.asOpaque(),autoAccumulateServices:Ke(Ve.sequenceVarLen(ci.Codec))});static create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s}){return new li(e,t,r,s)}constructor(e,t,r,s){this.manager=e,this.authManager=t,this.validatorsManager=r,this.autoAccumulateServices=s}}const hi=128;class ui extends G{bandersnatch;ed25519;bls;metadata;static Codec=Ve.Class(ui,{bandersnatch:Ve.bytes(xt).asOpaque(),ed25519:Ve.bytes(St).asOpaque(),bls:Ve.bytes(Bt).asOpaque(),metadata:Ve.bytes(hi)});static create({ed25519:e,bandersnatch:t,bls:r,metadata:s}){return new ui(t,e,r,s)}constructor(e,t,r,s){super(),this.bandersnatch=e,this.ed25519=t,this.bls=r,this.metadata=s}}var di;!function(e){e[e.Tickets=0]="Tickets",e[e.Keys=1]="Keys"}(di||(di={}));const fi=Ve.bytes(xt).asOpaque();class pi extends G{kind;keys;tickets;static Codec=mr(e=>Ve.custom({name:"SafroleSealingKeys",sizeHint:{bytes:1+Rt*e.epochLength,isExact:!1}},(e,t)=>{e.varU32(Ae(t.kind)),t.kind===di.Keys?e.sequenceFixLen(fi,t.keys):e.sequenceFixLen(ns.Codec,t.tickets)},t=>{const r=e.epochLength,s=t.varU32();if(s===di.Keys){const s=t.sequenceFixLen(fi,r);return pi.keys(Mr(s,e))}if(s===di.Tickets){const s=t.sequenceFixLen(ns.Codec,r);return pi.tickets(Mr(s,e))}throw new Error(`Unexpected safrole sealing keys kind: ${s}`)},t=>{const r=t.decoder.varU32();if(r!==di.Keys){if(r!==di.Tickets)throw new Error(`Unexpected safrole sealing keys kind: ${r}`);t.sequenceFixLen(ns.Codec,e.epochLength)}else t.sequenceFixLen(fi,e.epochLength)}));static keys(e){return new pi(di.Keys,e,void 0)}static tickets(e){return new pi(di.Tickets,void 0,e)}constructor(e,t,r){super(),this.kind=e,this.keys=t,this.tickets=r}}class gi{nextValidatorData;epochRoot;sealingKeySeries;ticketsAccumulator;static Codec=Ve.Class(gi,{nextValidatorData:Dr(ui.Codec),epochRoot:Ve.bytes(_t).asOpaque(),sealingKeySeries:pi.Codec,ticketsAccumulator:Ke(Ve.sequenceVarLen(ns.Codec)).convert(z,lr)});static create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s}){return new gi(e,t,r,s)}constructor(e,t,r,s){this.nextValidatorData=e,this.epochRoot=t,this.sealingKeySeries=r,this.ticketsAccumulator=s}}class yi extends G{codeHash;balance;accumulateMinGas;onTransferMinGas;storageUtilisationBytes;storageUtilisationCount;static Codec=Ve.Class(yi,{codeHash:Ve.bytes(Rt).asOpaque(),balance:Ve.u64,accumulateMinGas:Ve.u64.convert(e=>e,Or),onTransferMinGas:Ve.u64.convert(e=>e,Or),storageUtilisationBytes:Ve.u64,storageUtilisationCount:Ve.u32});static create(e){return new yi(e.codeHash,e.balance,e.accumulateMinGas,e.onTransferMinGas,e.storageUtilisationBytes,e.storageUtilisationCount)}static calculateThresholdBalance(e,t){const r=Se(ve(100n),ve(10n*BigInt(e)),ve(1n*t));return r.overflow?ve(2n**64n-1n):r.value}constructor(e,t,r,s,i,n){super(),this.codeHash=e,this.balance=t,this.accumulateMinGas=r,this.onTransferMinGas=s,this.storageUtilisationBytes=i,this.storageUtilisationCount=n}}class mi extends G{hash;blob;static Codec=Ve.Class(mi,{hash:Ve.bytes(Rt).asOpaque(),blob:Ve.blob});static create({hash:e,blob:t}){return new mi(e,t)}constructor(e,t){super(),this.hash=e,this.blob=t}}class bi extends G{key;value;static Codec=Ve.Class(bi,{key:Ve.bytes(Rt).asOpaque(),value:Ve.blob});static create({key:e,value:t}){return new bi(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}function Ai(e){const t=e;if(t.length>3)throw new Error("Lookup history items must contain 0-3 timeslots.");return t}class Ii{hash;length;slots;constructor(e,t,r){this.hash=e,this.length=t,this.slots=r}static isRequested(e){return"slots"in e?0===e.slots.length:0===e.length}}var vi,wi,Si;!function(e){e[e.Provide=0]="Provide",e[e.Remove=1]="Remove",e[e.UpdateOrAdd=2]="UpdateOrAdd"}(vi||(vi={}));class Ei{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static provide({serviceId:e,preimage:t,slot:r}){return new Ei(e,{kind:vi.Provide,preimage:t,slot:r})}static remove({serviceId:e,hash:t,length:r}){return new Ei(e,{kind:vi.Remove,hash:t,length:r})}static updateOrAdd({serviceId:e,lookupHistory:t}){return new Ei(e,{kind:vi.UpdateOrAdd,item:t})}}!function(e){e[e.Update=0]="Update",e[e.Create=1]="Create"}(wi||(wi={}));class Ci{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static update({serviceId:e,serviceInfo:t}){return new Ci(e,{kind:wi.Update,account:t})}static create({serviceId:e,serviceInfo:t,lookupHistory:r}){return new Ci(e,{kind:wi.Create,account:t,lookupHistory:r})}}!function(e){e[e.Set=0]="Set",e[e.Remove=1]="Remove"}(Si||(Si={}));class ki{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static set({serviceId:e,storage:t}){return new ki(e,{kind:Si.Set,storage:t})}static remove({serviceId:e,key:t}){return new ki(e,{kind:Si.Remove,key:t})}get key(){return this.action.kind===Si.Remove?this.action.key:this.action.storage.key}get value(){return this.action.kind===Si.Remove?null:this.action.storage.value}}const xi=Ve.varU32.convert(e=>Ae(e),e=>Rr(e));class _i{blocks;tickets;preImages;preImagesSize;guarantees;assurances;static Codec=Ve.Class(_i,{blocks:Ve.u32,tickets:Ve.u32,preImages:Ve.u32,preImagesSize:Ve.u32,guarantees:Ve.u32,assurances:Ve.u32});static create({blocks:e,tickets:t,preImages:r,preImagesSize:s,guarantees:i,assurances:n}){return new _i(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.blocks=e,this.tickets=t,this.preImages=r,this.preImagesSize=s,this.guarantees=i,this.assurances=n}static empty(){const e=Ae(0);return new _i(e,e,e,e,e,e)}}const Bi=Ve.varU32.convert(e=>Ae(e),e=>me(e)),Ri=Ve.varU64.convert(e=>ve(e),e=>Or(e));class Oi{dataAvailabilityLoad;popularity;imports;exports;extrinsicSize;extrinsicCount;bundleSize;gasUsed;static Codec=Ve.Class(Oi,{dataAvailabilityLoad:Ve.varU32,popularity:Bi,imports:Bi,exports:Bi,extrinsicSize:Ve.varU32,extrinsicCount:Bi,bundleSize:Ve.varU32,gasUsed:Ri});static create(e){return new Oi(e.dataAvailabilityLoad,e.popularity,e.imports,e.exports,e.extrinsicSize,e.extrinsicCount,e.bundleSize,e.gasUsed)}constructor(e,t,r,s,i,n,o,a){this.dataAvailabilityLoad=e,this.popularity=t,this.imports=r,this.exports=s,this.extrinsicSize=i,this.extrinsicCount=n,this.bundleSize=o,this.gasUsed=a}static empty(){const e=Ae(0),t=me(0),r=Or(0);return new Oi(e,t,t,t,e,t,e,r)}}class Ui{providedCount;providedSize;refinementCount;refinementGasUsed;imports;exports;extrinsicSize;extrinsicCount;accumulateCount;accumulateGasUsed;onTransfersCount;onTransfersGasUsed;static Codec=Ve.Class(Ui,{providedCount:Bi,providedSize:Ve.varU32,refinementCount:Ve.varU32,refinementGasUsed:Ri,imports:Bi,exports:Bi,extrinsicSize:Ve.varU32,extrinsicCount:Bi,accumulateCount:Ve.varU32,accumulateGasUsed:Ri,onTransfersCount:Ve.varU32,onTransfersGasUsed:Ri});static create(e){return new Ui(e.providedCount,e.providedSize,e.refinementCount,e.refinementGasUsed,e.imports,e.exports,e.extrinsicSize,e.extrinsicCount,e.accumulateCount,e.accumulateGasUsed,e.onTransfersCount,e.onTransfersGasUsed)}constructor(e,t,r,s,i,n,o,a,c,l,h,u){this.providedCount=e,this.providedSize=t,this.refinementCount=r,this.refinementGasUsed=s,this.imports=i,this.exports=n,this.extrinsicSize=o,this.extrinsicCount=a,this.accumulateCount=c,this.accumulateGasUsed=l,this.onTransfersCount=h,this.onTransfersGasUsed=u}static empty(){const e=Ae(0),t=me(0),r=Or(0);return new Ui(t,e,e,r,t,t,e,t,e,r,e,r)}}class Ti{current;previous;cores;services;static Codec=Ve.Class(Ti,{current:Dr(_i.Codec),previous:Dr(_i.Codec),cores:si(Oi.Codec),services:Ve.dictionary(xi,Ui.Codec,{sortKeys:(e,t)=>e-t})});static create(e){return new Ti(e.current,e.previous,e.cores,e.services)}constructor(e,t,r,s){this.current=e,this.previous=t,this.cores=r,this.services=s}}var Ni,Di;(Di=Ni||(Ni={}))[Di.DuplicateService=0]="DuplicateService",Di[Di.NoService=1]="NoService",Di[Di.PreimageExists=2]="PreimageExists";class Mi extends G{serviceId;data;constructor(e,t){super(),this.serviceId=e,this.data=t}getInfo(){return this.data.info}getStorage(e){return this.data.storage.get(e)?.value??null}hasPreimage(e){return this.data.preimages.has(e)}getPreimage(e){return this.data.preimages.get(e)?.blob??null}getLookupHistory(e,t){const r=this.data.lookupHistory.get(e);return void 0===r?null:r.find(e=>e.length===t)?.slots??null}getEntries(){return{storageKeys:Array.from(this.data.storage.keys()),preimages:Array.from(this.data.preimages.keys()),lookupHistory:Array.from(this.data.lookupHistory.entries()).map(([e,t])=>({hash:e,length:t[0].length}))}}static copyFrom(e,t){const r=e.getInfo(),s=ar.new(),i=ar.new(),n=ar.new();for(const r of t.preimages){const t=e.getPreimage(r);if(null===t)throw new Error(`Service ${e.serviceId} is missing expected preimage: ${r}`);s.set(r,mi.create({hash:r,blob:t}))}for(const{hash:r,length:s}of t.lookupHistory){const t=e.getLookupHistory(r,s);if(null===t)throw new Error(`Service ${e.serviceId} is missing expected lookupHistory: ${r}, ${s}`);const i=n.get(r)??[];i.push(new Ii(r,s,t)),n.set(r,i)}for(const r of t.storageKeys){const t=e.getStorage(r);if(null===t)throw new Error(`Service ${e.serviceId} is missing expected storage: ${r}`);i.set(r,bi.create({key:r,value:t}))}return new Mi(e.serviceId,{info:r,preimages:s,storage:i,lookupHistory:n})}}class Pi extends G{static create(e){return new Pi(e)}static partial(e,t){const r=Pi.empty(e);return Object.assign(r,t),r}static copyFrom(e,t){const r=new Map;for(const[s,i]of t.entries()){const t=e.getService(s);if(null===t)throw new Error(`Expected service ${s} to be part of the state!`);const n=Mi.copyFrom(t,i);r.set(s,n)}return Pi.create({availabilityAssignment:e.availabilityAssignment,accumulationQueue:e.accumulationQueue,designatedValidatorData:e.designatedValidatorData,nextValidatorData:e.nextValidatorData,currentValidatorData:e.currentValidatorData,previousValidatorData:e.previousValidatorData,disputesRecords:e.disputesRecords,timeslot:e.timeslot,entropy:e.entropy,authPools:e.authPools,authQueues:e.authQueues,recentBlocks:e.recentBlocks,statistics:e.statistics,recentlyAccumulated:e.recentlyAccumulated,ticketsAccumulator:e.ticketsAccumulator,sealingKeySeries:e.sealingKeySeries,epochRoot:e.epochRoot,privilegedServices:e.privilegedServices,services:r})}intoServicesData(){const e=new Map;for(const[t,{data:r}]of this.services)e.set(t,{storageKeys:Array.from(r.storage.keys()),preimages:Array.from(r.preimages.keys()),lookupHistory:Array.from(r.lookupHistory).flatMap(([e,t])=>t.map(t=>({hash:e,length:t.length})))});return e}applyUpdate(e){const{servicesRemoved:t,servicesUpdates:r,preimages:s,storage:i,...n}=e;let o;return Object.assign(this,n),o=this.updateServices(r),o.isError?o:(o=this.updatePreimages(s),o.isError?o:(o=this.updateStorage(i),o.isError?o:(this.removeServices(t),Z.ok(W))))}removeServices(e){for(const t of e??[])Q(this.services.has(t),`Attempting to remove non-existing service: ${t}`),this.services.delete(t)}updateStorage(e){for(const{serviceId:t,action:r}of e??[]){const{kind:e}=r,s=this.services.get(t);if(void 0===s)return Z.error(Ni.NoService,`Attempting to update storage of non-existing service: ${t}`);e===Si.Set?s.data.storage.set(r.storage.key,r.storage):e===Si.Remove?(Q(!s.data.storage.has(r.key),`Attempting to remove non-existing storage item at ${t}: ${r.key}`),s.data.storage.delete(r.key)):F(e)}return Z.ok(W)}updatePreimages(e){for(const{serviceId:t,action:r}of e??[]){const e=this.services.get(t);if(void 0===e)return Z.error(Ni.NoService,`Attempting to update preimage of non-existing service: ${t}`);const{kind:s}=r;if(s===vi.Provide){const{preimage:s,slot:i}=r;if(e.data.preimages.has(s.hash))return Z.error(Ni.PreimageExists,`Overwriting existing preimage at ${t}: ${s}`);if(e.data.preimages.set(s.hash,s),null!==i){const t=e.data.lookupHistory.get(s.hash),r=Ae(s.blob.length),n=new Ii(s.hash,r,Ai([i]));if(void 0===t)e.data.lookupHistory.set(s.hash,[n]);else{const e=t.map(e=>e.length).indexOf(r);t.splice(e,-1===e?0:1,n)}}}else if(s===vi.Remove){const{hash:t,length:s}=r;e.data.preimages.delete(t);const i=e.data.lookupHistory.get(t)??[],n=i.map(e=>e.length).indexOf(s);-1!==n&&i.splice(n,1)}else if(s===vi.UpdateOrAdd){const{item:t}=r,s=e.data.lookupHistory.get(t.hash)??[],i=s.map(e=>e.length).indexOf(t.length),n=-1===i?0:1;s.splice(i,n,t),e.data.lookupHistory.set(t.hash,s)}else F(s)}return Z.ok(W)}updateServices(e){for(const{serviceId:t,action:r}of e??[]){const{kind:e,account:s}=r;if(e===wi.Create){const{lookupHistory:e}=r;if(this.services.has(t))return Z.error(Ni.DuplicateService,`${t} already exists!`);this.services.set(t,new Mi(t,{info:s,preimages:ar.new(),storage:ar.new(),lookupHistory:ar.fromEntries(null===e?[]:[[e.hash,[e]]])}))}else if(e===wi.Update){const e=this.services.get(t);if(void 0===e)return Z.error(Ni.NoService,`Cannot update ${t} because it does not exist.`);e.data.info=s}else F(e)}return Z.ok(W)}availabilityAssignment;designatedValidatorData;nextValidatorData;currentValidatorData;previousValidatorData;disputesRecords;timeslot;entropy;authPools;authQueues;recentBlocks;statistics;accumulationQueue;recentlyAccumulated;ticketsAccumulator;sealingKeySeries;epochRoot;privilegedServices;services;recentServiceIds(){return Array.from(this.services.keys())}getService(e){return this.services.get(e)??null}constructor(e){super(),this.availabilityAssignment=e.availabilityAssignment,this.designatedValidatorData=e.designatedValidatorData,this.nextValidatorData=e.nextValidatorData,this.currentValidatorData=e.currentValidatorData,this.previousValidatorData=e.previousValidatorData,this.disputesRecords=e.disputesRecords,this.timeslot=e.timeslot,this.entropy=e.entropy,this.authPools=e.authPools,this.authQueues=e.authQueues,this.recentBlocks=e.recentBlocks,this.statistics=e.statistics,this.accumulationQueue=e.accumulationQueue,this.recentlyAccumulated=e.recentlyAccumulated,this.ticketsAccumulator=e.ticketsAccumulator,this.sealingKeySeries=e.sealingKeySeries,this.epochRoot=e.epochRoot,this.privilegedServices=e.privilegedServices,this.services=e.services}static empty(e){return new Pi({availabilityAssignment:ri(Array.from({length:e.coresCount},()=>null),e),designatedValidatorData:Nr(Array.from({length:e.validatorsCount},()=>ui.create({bandersnatch:re.zero(xt).asOpaque(),bls:re.zero(Bt).asOpaque(),ed25519:re.zero(St).asOpaque(),metadata:re.zero(hi).asOpaque()})),e),nextValidatorData:Nr(Array.from({length:e.validatorsCount},()=>ui.create({bandersnatch:re.zero(xt).asOpaque(),bls:re.zero(Bt).asOpaque(),ed25519:re.zero(St).asOpaque(),metadata:re.zero(hi).asOpaque()})),e),currentValidatorData:Nr(Array.from({length:e.validatorsCount},()=>ui.create({bandersnatch:re.zero(xt).asOpaque(),bls:re.zero(Bt).asOpaque(),ed25519:re.zero(St).asOpaque(),metadata:re.zero(hi).asOpaque()})),e),previousValidatorData:Nr(Array.from({length:e.validatorsCount},()=>ui.create({bandersnatch:re.zero(xt).asOpaque(),bls:re.zero(Bt).asOpaque(),ed25519:re.zero(St).asOpaque(),metadata:re.zero(hi).asOpaque()})),e),disputesRecords:oi.create({goodSet:dr.fromSortedArray(ai,[]),badSet:dr.fromSortedArray(ai,[]),wonkySet:dr.fromSortedArray(ai,[]),punishSet:dr.fromSortedArray(ai,[])}),timeslot:_r(0),entropy:hr.fill(()=>re.zero(Rt).asOpaque(),4),authPools:ri(Array.from({length:e.coresCount},()=>[]),e),authQueues:ri(Array.from({length:e.coresCount},()=>hr.fill(()=>re.zero(Rt).asOpaque(),80)),e),recentBlocks:[],statistics:Ti.create({current:Nr(Array.from({length:e.validatorsCount},()=>_i.empty()),e),previous:Nr(Array.from({length:e.validatorsCount},()=>_i.empty()),e),cores:ri(Array.from({length:e.coresCount},()=>Oi.empty()),e),services:new Map}),accumulationQueue:Mr(Array.from({length:e.epochLength},()=>[]),e),recentlyAccumulated:Mr(Array.from({length:e.epochLength},()=>cr.new()),e),ticketsAccumulator:[],sealingKeySeries:pi.keys(Mr(Array.from({length:e.epochLength},()=>re.zero(xt).asOpaque()),e)),epochRoot:re.zero(_t).asOpaque(),privilegedServices:li.create({manager:Rr(0),authManager:Rr(0),validatorsManager:Rr(0),autoAccumulateServices:[]}),services:new Map})}}const Li=Ve.object({storageKeys:Ve.sequenceVarLen(Ve.bytes(Rt).asOpaque()),preimages:Ve.sequenceVarLen(Ve.bytes(Rt).asOpaque()),lookupHistory:Ve.sequenceVarLen(Ve.object({hash:Ve.bytes(Rt).asOpaque(),length:Ve.u32}))});Ve.dictionary(Ve.u32.asOpaque(),Li,{sortKeys:(e,t)=>e-t});class Hi extends G{report;dependencies;static Codec=Ve.Class(Hi,{report:Zr.Codec,dependencies:br(Ve.bytes(Rt).asOpaque(),{typicalLength:4,maxLength:8,minLength:0})});static create({report:e,dependencies:t}){return new Hi(e,t)}constructor(e,t){super(),this.report=e,this.dependencies=t}}var Ki,Qi,Vi;!function(e){e[e.Unused=0]="Unused",e[e.Alpha=1]="Alpha",e[e.Phi=2]="Phi",e[e.Beta=3]="Beta",e[e.Gamma=4]="Gamma",e[e.Psi=5]="Psi",e[e.Eta=6]="Eta",e[e.Iota=7]="Iota",e[e.Kappa=8]="Kappa",e[e.Lambda=9]="Lambda",e[e.Rho=10]="Rho",e[e.Tau=11]="Tau",e[e.Chi=12]="Chi",e[e.Pi=13]="Pi",e[e.Theta=14]="Theta",e[e.Xi=15]="Xi",e[e.Delta=255]="Delta"}(Ki||(Ki={})),function(e){function t(e,t){const r=re.zero(Rt);let s=0;for(const i of Ee(e))r.raw[s]=i,r.raw[s+1]=t.raw[s/2],s+=2;const i=s/2;return r.raw.set(t.raw.subarray(i,Rt-i),s),r.asOpaque()}e.index=function(e){const t=re.zero(Rt);return t.raw[0]=e,t.asOpaque()},e.serviceInfo=function(e){const t=re.zero(Rt);t.raw[0]=Ki.Delta;let r=1;for(const s of Ee(e))t.raw[r]=s,r+=2;return t.asOpaque()},e.serviceStorage=function(e,r){const s=re.zero(Rt);return s.raw.set(Ee(Ae(2**32-1)),0),s.raw.set(r.raw.subarray(0,28),4),t(e,s)},e.servicePreimage=function(e,r){const s=re.zero(Rt);return s.raw.set(Ee(Ae(2**32-2)),0),s.raw.set(r.raw.subarray(1,29),4),t(e,s)},e.serviceLookupHistory=function(e,r,s){const i=Ht(r),n=re.zero(Rt);return n.raw.set(Ee(s),0),n.raw.set(i.raw.subarray(2,30),4),t(e,n)},e.serviceNested=t}(Qi||(Qi={})),function(e){e.authPools={key:Qi.index(Ki.Alpha),Codec:si(br(Ve.bytes(Rt).asOpaque(),{minLength:0,maxLength:8,typicalLength:8})),extract:e=>e.authPools},e.authQueues={key:Qi.index(Ki.Phi),Codec:si(Ar(Ve.bytes(Rt).asOpaque(),80)),extract:e=>e.authQueues},e.recentBlocks={key:Qi.index(Ki.Beta),Codec:br(ti.Codec,{minLength:0,maxLength:8,typicalLength:8}),extract:e=>e.recentBlocks},e.safrole={key:Qi.index(Ki.Gamma),Codec:gi.Codec,extract:e=>gi.create({nextValidatorData:e.nextValidatorData,epochRoot:e.epochRoot,sealingKeySeries:e.sealingKeySeries,ticketsAccumulator:e.ticketsAccumulator})},e.disputesRecords={key:Qi.index(Ki.Psi),Codec:oi.Codec,extract:e=>e.disputesRecords},e.entropy={key:Qi.index(Ki.Eta),Codec:Ar(Ve.bytes(Rt).asOpaque(),4),extract:e=>e.entropy},e.designatedValidators={key:Qi.index(Ki.Iota),Codec:Dr(ui.Codec),extract:e=>e.designatedValidatorData},e.currentValidators={key:Qi.index(Ki.Kappa),Codec:Dr(ui.Codec),extract:e=>e.currentValidatorData},e.previousValidators={key:Qi.index(Ki.Lambda),Codec:Dr(ui.Codec),extract:e=>e.previousValidatorData},e.availabilityAssignment={key:Qi.index(Ki.Rho),Codec:si(Ve.optional(ei.Codec)),extract:e=>e.availabilityAssignment},e.timeslot={key:Qi.index(Ki.Tau),Codec:Ve.u32.asOpaque(),extract:e=>e.timeslot},e.privilegedServices={key:Qi.index(Ki.Chi),Codec:li.Codec,extract:e=>e.privilegedServices},e.statistics={key:Qi.index(Ki.Pi),Codec:Ti.Codec,extract:e=>e.statistics},e.accumulationQueue={key:Qi.index(Ki.Theta),Codec:Pr(Ke(Ve.sequenceVarLen(Hi.Codec))),extract:e=>e.accumulationQueue},e.recentlyAccumulated={key:Qi.index(Ki.Xi),Codec:Pr(Ve.sequenceVarLen(Ve.bytes(Rt).asOpaque()).convert(e=>Array.from(e),e=>cr.from(e))),extract:e=>e.recentlyAccumulated},e.serviceData=e=>({key:Qi.serviceInfo(e),Codec:yi.Codec}),e.serviceStorage=(e,t)=>({key:Qi.serviceStorage(e,t),Codec:Fi}),e.servicePreimages=(e,t)=>({key:Qi.servicePreimage(e,t),Codec:Fi}),e.serviceLookupHistory=(e,t,r)=>({key:Qi.serviceLookupHistory(e,t,r),Codec:Ke(Ve.sequenceVarLen(Ve.u32))})}(Vi||(Vi={}));const Fi=He.new("Dump",{bytes:64,isExact:!1},(e,t)=>e.bytes(re.fromBlob(t.raw,t.raw.length)),e=>te.blobFrom(e.bytes(e.source.length-e.bytesRead()).raw),e=>e.bytes(e.decoder.source.length-e.decoder.bytesRead()));var $i;!function(e){e[e.Insert=0]="Insert",e[e.Remove=1]="Remove"}($i||($i={}));const ji=te.empty();class Gi{spec;backend;_recentServiceIds;static fromStateEntries(e,t,r=[]){return new Gi(e,t,r)}static new(e,t,r=[]){return new Gi(e,t,r)}constructor(e,t,r){this.spec=e,this.backend=t,this._recentServiceIds=r}updateBackend(e){this.backend=e}recentServiceIds(){return this._recentServiceIds}getService(e){const t=this.retrieveOptional(Vi.serviceData(e));return void 0===t?null:(this._recentServiceIds.includes(e)||this._recentServiceIds.push(e),new qi(e,t,e=>this.retrieveOptional(e)))}retrieve({key:e,Codec:t},r){const s=this.backend.get(e);if(null===s)throw new Error(`Required state entry for ${r} is missing!. Accessing key: ${e}`);return xe.decodeObject(t,s,this.spec)}retrieveOptional({key:e,Codec:t}){const r=this.backend.get(e);if(null!==r)return xe.decodeObject(t,r,this.spec)}get availabilityAssignment(){return this.retrieve(Vi.availabilityAssignment,"availabilityAssignment")}get designatedValidatorData(){return this.retrieve(Vi.designatedValidators,"designatedValidatorData")}get nextValidatorData(){return this.retrieve(Vi.safrole,"safroleData.nextValidatorData").nextValidatorData}get currentValidatorData(){return this.retrieve(Vi.currentValidators,"currentValidators")}get previousValidatorData(){return this.retrieve(Vi.previousValidators,"previousValidators")}get disputesRecords(){return this.retrieve(Vi.disputesRecords,"disputesRecords")}get timeslot(){return this.retrieve(Vi.timeslot,"timeslot")}get entropy(){return this.retrieve(Vi.entropy,"entropy")}get authPools(){return this.retrieve(Vi.authPools,"authPools")}get authQueues(){return this.retrieve(Vi.authQueues,"authQueues")}get recentBlocks(){return this.retrieve(Vi.recentBlocks,"recentBlocks")}get statistics(){return this.retrieve(Vi.statistics,"statistics")}get accumulationQueue(){return this.retrieve(Vi.accumulationQueue,"accumulationQueue")}get recentlyAccumulated(){return this.retrieve(Vi.recentlyAccumulated,"recentlyAccumulated")}get ticketsAccumulator(){return this.retrieve(Vi.safrole,"safroleData.ticketsAccumulator").ticketsAccumulator}get sealingKeySeries(){return this.retrieve(Vi.safrole,"safrole.sealingKeySeries").sealingKeySeries}get epochRoot(){return this.retrieve(Vi.safrole,"safrole.epochRoot").epochRoot}get privilegedServices(){return this.retrieve(Vi.privilegedServices,"privilegedServices")}}class qi{serviceId;accountInfo;retrieveOptional;constructor(e,t,r){this.serviceId=e,this.accountInfo=t,this.retrieveOptional=r}getInfo(){return this.accountInfo}getStorage(e){return this.retrieveOptional(Vi.serviceStorage(this.serviceId,e))??null}hasPreimage(e){return void 0!==this.retrieveOptional(Vi.servicePreimages(this.serviceId,e))}getPreimage(e){return this.retrieveOptional(Vi.servicePreimages(this.serviceId,e))??null}getLookupHistory(e,t){const r=this.retrieveOptional(Vi.serviceLookupHistory(this.serviceId,e,t));return void 0===r?null:Ai(r.map(_r))}}const zi=31;var Wi;!function(e){e[e.Branch=0]="Branch",e[e.Leaf=1]="Leaf",e[e.EmbedLeaf=2]="EmbedLeaf"}(Wi||(Wi={}));class Ji{raw;constructor(e=new Uint8Array(64)){this.raw=e}getNodeType(){return 128&this.raw[0]?192&~this.raw[0]?Wi.EmbedLeaf:Wi.Leaf:Wi.Branch}asBranchNode(){return Q(this.getNodeType()===Wi.Branch),new Yi(this)}asLeafNode(){return Q(this.getNodeType()!==Wi.Branch),new Xi(this)}toString(){return te.blobFrom(this.raw).toString()}}class Yi{node;constructor(e){this.node=e}static fromSubNodes(e,t){const r=new Ji;return r.raw.set(e.raw,0),r.raw.set(t.raw,Rt),r.raw[0]&=127,new Yi(r)}getLeft(){return re.fromBlob(this.node.raw.subarray(0,Rt),Rt).asOpaque()}getRight(){return re.fromBlob(this.node.raw.subarray(Rt),Rt).asOpaque()}}class Xi{node;constructor(e){this.node=e}static fromValue(e,t,r){const s=new Ji;return t.length<=Rt?(s.raw[0]=128|t.length,s.raw.set(e.raw.subarray(0,zi),1),s.raw.set(t.raw,32)):(s.raw[0]=192,s.raw.set(e.raw.subarray(0,zi),1),s.raw.set(r().raw,32)),new Xi(s)}getKey(){return re.fromBlob(this.node.raw.subarray(1,32),zi).asOpaque()}hasEmbeddedValue(){return this.node.getNodeType()===Wi.EmbedLeaf}getValueLength(){return 63&this.node.raw[0]}getValue(){const e=this.getValueLength();return te.blobFrom(this.node.raw.subarray(Rt,Rt+e))}getValueHash(){return re.fromBlob(this.node.raw.subarray(Rt),Rt).asOpaque()}toString(){return`LeafNode {\n key: ${this.getKey()},\n valueHash: ${this.getValueHash()}\n}`}}class Zi{hasher;nodes=ar.new();constructor(e){this.hasher=e}get(e){return Zi.withHashCompat(e,e=>this.nodes.get(e)??null)}hashNode(e){return this.hasher.hashConcat(e.raw)}*leaves(){for(const e of this.nodes.values())e.getNodeType()!==Wi.Branch&&(yield e.asLeafNode())}static withHashCompat(e,t){const r=e.raw[0];e.raw[0]&=127;const s=t(e);return e.raw[0]=r,s}}class en extends Zi{remove(e){return Zi.withHashCompat(e,e=>{this.nodes.delete(e)})}insert(e,t){const r=t??this.hashNode(e);return Zi.withHashCompat(r,t=>{this.nodes.set(t,e)}),r}}class tn{nodes;root;static empty(e){return new tn(new en(e))}static computeStateRoot(e,t){return tn.fromLeaves(e,t).getRootHash()}static fromLeaves(e,t){let r=null;const s=new en(e);for(const e of t)r=rn(r,s,e);return new tn(s,r)}constructor(e,t=null){this.nodes=e,this.root=t}set(e,t,r){const s=Xi.fromValue(e,t,()=>r??this.nodes.hasher.hashConcat(t.raw).asOpaque());return this.root=rn(this.root,this.nodes,s),s}remove(e){throw new Error("Removing from the trie not implemented yet.")}getRootNode(){return this.root}getRootHash(){return null===this.root?re.zero(Rt).asOpaque():this.nodes.hashNode(this.root)}toString(){return on(this.root,this.nodes)}}function rn(e,t,r){if(null===e)return t.insert(r.node),r.node;const s=function(e,t,r){const s=new sn;let i=e,n=t.hashNode(e);for(;;){if(i.getNodeType()!==Wi.Branch){const e=i.asLeafNode();return s.leafToReplace=[e,n],s}const e=i.asBranchNode(),o=nn(r,s.bitIndex),a=o?e.getRight():e.getLeft();s.branchingHistory.push([e,n,o]);const c=t.get(a);if(null===c){if(a.isEqualTo(re.zero(Rt)))return s;throw new Error(`Missing trie node '${a}' with key prefix: ${r}[0..${s.bitIndex}]`)}i=c,n=a,s.bitIndex+=1}}(e,t,r.getKey()),i=void 0!==s.leafToReplace?function(e,t,r,s){const i=s.getKey();let[n,o]=r;const a=n.getKey(),c=t.insert(s.node);if(a.isEqualTo(i))return n.getValueHash().isEqualTo(s.getValueHash())||t.remove(o),[s.node,c];const l=[];let h=nn(i,e.bitIndex);for(;e.bitIndex<248;){h=nn(i,e.bitIndex);const t=nn(a,e.bitIndex);if(h!==t)break;l.push(t),e.bitIndex+=1}const u=re.zero(Rt).asOpaque();(()=>{const t=e.branchingHistory.length;return t>0&&!1===e.branchingHistory[t-1][2]})()&&!h&&(o=t.hashNode(n.node));let d=h?Yi.fromSubNodes(o,c):Yi.fromSubNodes(c,o),f=t.insert(d.node),p=l.pop();for(;void 0!==p;)d=p?Yi.fromSubNodes(u,f):Yi.fromSubNodes(f,u),f=t.insert(d.node),p=l.pop();return[d.node,f]}(s,t,s.leafToReplace,r):[r.node,t.insert(r.node)];let n=s.branchingHistory.pop(),[o,a]=i;for(;void 0!==n;){const[e,r,i]=n;t.remove(r);const c=i?Yi.fromSubNodes(e.getLeft(),a):Yi.fromSubNodes(a,e.getRight());a=t.insert(c.node),o=c.node,n=s.branchingHistory.pop()}return o}class sn{branchingHistory=[];bitIndex=0;leafToReplace}function nn(e,t){Q(t<248);const r=t>>>3,s=128>>>t-(r<<3);return 0!==(e.raw[r]&s)}function on(e,t){if(null===e)return"<empty tree>";if(e.getNodeType()===Wi.Branch){const r=e.asBranchNode(),s=r.getLeft(),i=r.getRight(),n=e=>e.split("\n").map(e=>`\t\t${e}`).join("\n"),o=on(t.get(s),t),a=on(t.get(i),t);return`<branch>\n\t-- ${s}: ${n(o)}\n\t-- ${i}: ${n(a)}\n`}const r=e.asLeafNode(),s=r.getValueLength(),i=s>0?`'${r.getValue()}'(len:${s})`:`'<hash>${r.getValueHash()}'`;return`\nLeaf('${r.getKey().toString()}',${i})`}const an={hashConcat:(e,t=[])=>Lt([e,...t])};class cn{entries;static serializeInMemory(e,t){return new cn({full:!0,data:ln(e,t)})}static fromDictionaryUnsafe(e){return new cn({full:!0,data:e})}static fromTruncatedDictionaryUnsafe(e){return new cn({full:!1,data:e})}trieCache=null;constructor(e){this.entries=e}getTrie(){if(null===this.trieCache){const e=tn.empty(an);for(const[t,r]of this.entries.data)e.set(t.asOpaque(),r);this.trieCache=e}return this.trieCache}get(e){return this.entries.data.get(e)??null}applyUpdate(e){this.trieCache=null;for(const[t,r,s]of e)t===$i.Insert?this.entries.data.set(r,s):t===$i.Remove?this.entries.data.delete(r):F(t)}getRootHash(){return this.getTrie().getRootHash().asOpaque()}}function ln(e,t){const r=ar.new();function s(s){r.set(s.key,Te.encodeObject(s.Codec,s.extract(t),e))}s(Vi.authPools),s(Vi.authQueues),s(Vi.recentBlocks),s(Vi.safrole),s(Vi.disputesRecords),s(Vi.entropy),s(Vi.designatedValidators),s(Vi.currentValidators),s(Vi.previousValidators),s(Vi.availabilityAssignment),s(Vi.timeslot),s(Vi.privilegedServices),s(Vi.statistics),s(Vi.accumulationQueue),s(Vi.recentlyAccumulated);for(const[e,s]of t.services.entries()){const{key:t,Codec:i}=Vi.serviceData(e);r.set(t,Te.encodeObject(i,s.getInfo()));for(const t of s.data.preimages.values()){const{key:s,Codec:i}=Vi.servicePreimages(e,t.hash);r.set(s,Te.encodeObject(i,t.blob))}for(const t of s.data.storage.values()){const{key:s,Codec:i}=Vi.serviceStorage(e,t.key);r.set(s,Te.encodeObject(i,t.value))}for(const t of s.data.lookupHistory.values())for(const s of t){const{key:t,Codec:i}=Vi.serviceLookupHistory(e,s.hash,s.length);r.set(t,Te.encodeObject(i,s.slots.slice()))}}return r}const hn=Ve.object({hash:Ve.bytes(Rt).asOpaque(),length:Ve.u32,slots:Ke(Ve.sequenceVarLen(Ve.u32.asOpaque())).convert(z,Ai)},"LookupHistoryItem",({hash:e,length:t,slots:r})=>new Ii(e,t,r)),un=Ve.object({key:Ve.bytes(Rt).asOpaque(),data:Ve.sequenceVarLen(hn)}),dn=Ve.sequenceVarLen(un).convert(e=>{const t=[];for(const[r,s]of e)t.push({key:r,data:s});return t},e=>{const t=ar.new();for(const{key:r,data:s}of e){const e=t.get(r)??[];e.push(...s),t.set(r,e)}return t});class fn extends Mi{static Codec=Ve.Class(fn,{serviceId:Ve.u32.asOpaque(),data:Ve.object({info:yi.Codec,preimages:Ir(mi.Codec,e=>e.hash),lookupHistory:dn,storage:Ir(bi.Codec,e=>e.key)})});constructor(e,t){super(e,t)}static create({serviceId:e,data:t}){return new fn(e,t)}}var pn,gn,yn;Ve.Class(Pi,{authPools:Vi.authPools.Codec,authQueues:Vi.authQueues.Codec,recentBlocks:Vi.recentBlocks.Codec,nextValidatorData:Dr(ui.Codec),epochRoot:Ve.bytes(_t).asOpaque(),sealingKeySeries:pi.Codec,ticketsAccumulator:Ke(Ve.sequenceVarLen(ns.Codec)).convert(e=>e,lr),disputesRecords:Vi.disputesRecords.Codec,entropy:Vi.entropy.Codec,designatedValidatorData:Vi.designatedValidators.Codec,currentValidatorData:Vi.currentValidators.Codec,previousValidatorData:Vi.previousValidators.Codec,availabilityAssignment:Vi.availabilityAssignment.Codec,timeslot:Vi.timeslot.Codec,privilegedServices:Vi.privilegedServices.Codec,statistics:Vi.statistics.Codec,accumulationQueue:Vi.accumulationQueue.Codec,recentlyAccumulated:Vi.recentlyAccumulated.Codec,services:Ve.dictionary(Ve.u32.asOpaque(),fn.Codec,{sortKeys:(e,t)=>e-t})}),function(e){e[e.Conflict=0]="Conflict",e[e.Commit=1]="Commit"}(pn||(pn={}));class mn{dict;static fromEntries(e){const t=Array.from(e).map(([e,t])=>{const r=re.zero(Rt).asOpaque();return r.raw.set(e.raw.subarray(0,zi)),[r,t]});return new mn(ar.fromEntries(t))}truncatedKey=re.zero(Rt).asOpaque();constructor(e){this.dict=e}get size(){return this.dict.size}get(e){return this.truncatedKey.raw.set(e.raw.subarray(0,zi)),this.dict.get(this.truncatedKey)}has(e){return this.truncatedKey.raw.set(e.raw.subarray(0,zi)),this.dict.has(this.truncatedKey)}set(e,t){const r=re.zero(Rt);r.raw.set(e.raw.subarray(0,zi)),this.dict.set(r.asOpaque(),t)}delete(e){this.truncatedKey.raw.set(e.raw.subarray(0,zi)),this.dict.delete(this.truncatedKey)}values(){return this.dict.values()}[Symbol.iterator](){return this.dict[Symbol.iterator]()}}!function(e){e[e.InvalidLeafData=0]="InvalidLeafData"}(gn||(gn={}));class bn{leaves;db;static fromLeavesBlob(e,t){if(e.length%64!=0)return Z.error(gn.InvalidLeafData,`${e.length} is not a multiply of 64: ${e}`);const r=[];for(const t of e.chunks(64)){const e=new Ji(t.raw);if(e.getNodeType()===Wi.Branch)return Z.error(gn.InvalidLeafData,`Branch node detected: ${t}`);r.push(e.asLeafNode())}return Z.ok(new bn(r,t))}lookup;constructor(e,t){this.leaves=e,this.db=t,this.lookup=mn.fromEntries(e.map(e=>[e.getKey().asOpaque(),e.hasEmbeddedValue()?{kind:yn.EmbeddedValue,value:e.getValue()}:{kind:yn.DbKey,key:e.getValueHash().raw}]))}get(e){const t=this.lookup.get(e);return void 0===t?null:t.kind===yn.EmbeddedValue?t.value:t.kind===yn.DbKey?te.blobFrom(this.db.get(t.key)):void F(t)}getStateRoot(){return tn.computeStateRoot(an,this.leaves).asOpaque()}}!function(e){e[e.EmbeddedValue=0]="EmbeddedValue",e[e.DbKey=1]="DbKey"}(yn||(yn={}));const An="best hash and posterior state root";class In{chainSpec;root;extrinsics;headers;postStateRoots;constructor(e,t){this.chainSpec=e,this.root=t,this.extrinsics=this.root.subDb("extrinsics"),this.headers=this.root.subDb("headers"),this.postStateRoots=this.root.subDb("postStateRoots")}async setPostStateRoot(e,t){await this.postStateRoots.put(e.raw,t.raw)}getPostStateRoot(e){const t=this.postStateRoots.get(e.raw);return void 0===t?null:re.fromBlob(t,Rt).asOpaque()}async insertBlock(e){const t=e.data.header.view().encoded(),r=e.data.extrinsic.view().encoded();await this.root.db.transaction(()=>{this.headers.put(e.hash.raw,t.raw),this.extrinsics.put(e.hash.raw,r.raw)})}async setBestHeaderHash(e){await this.root.db.put(An,e.raw)}getBestHeaderHash(){const e=this.root.db.get(An);return void 0===e?re.zero(Rt).asOpaque():re.fromBlob(e,Rt).asOpaque()}getHeader(e){const t=this.headers.get(e.raw);return void 0===t?null:xe.decodeObject(hs.Codec.View,t,this.chainSpec)}getExtrinsic(e){const t=this.extrinsics.get(e.raw);return void 0===t?null:xe.decodeObject(gs.Codec.View,t,this.chainSpec)}}const vn=(e=>{var t={};return o.d(t,e),t})({open:()=>s.open});class wn{db;constructor(e,t=!1){this.db=vn.open(e,{compression:!0,keyEncoding:"binary",encoding:"binary",readOnly:t})}subDb(e){return this.db.openDB({name:e})}}class Sn{spec;root;states;values;constructor(e,t){this.spec=e,this.root=t,this.states=this.root.subDb("states"),this.values=this.root.subDb("values")}async insertState(e,t){const r=tn.empty(an);return await this.updateAndCommit(e,r,Array.from(t.entries.data).map(e=>[$i.Insert,e[0],e[1]]))}async updateAndCommit(e,t,r){const s=[];for(const[e,i,n]of r)if(e===$i.Insert){const e=t.set(i.asOpaque(),n);e.hasEmbeddedValue()||s.push([e.getValueHash(),n])}else e===$i.Remove?t.remove(i.asOpaque()):F(e);const i=te.blobFromParts(Array.from(t.nodes.leaves()).map(e=>e.node.raw)),n=this.states.put(e.raw,i.raw),o=this.values.transaction(()=>{for(const[e,t]of s)this.values.put(e.raw,t.raw)});try{await Promise.all([o,n])}catch(e){return console.error(e),Z.error(pn.Commit)}return Z.ok(W)}async updateAndSetState(e,t,r){const s=tn.fromLeaves(an,t.backend.leaves),i=function*(e,t){yield*function*(e,t){function r(t,r){return[$i.Insert,r.key,Te.encodeObject(r.Codec,t,e)]}void 0!==t.authPools&&(yield r(t.authPools,Vi.authPools)),void 0!==t.authQueues&&(yield r(t.authQueues,Vi.authQueues)),void 0!==t.recentBlocks&&(yield r(t.recentBlocks,Vi.recentBlocks));const s=function(e,t,r,s){if(void 0!==e&&void 0!==t&&void 0!==r&&void 0!==s)return gi.create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s});if([e,t,r,s].some(e=>void 0!==e))throw new Error("SafroleData needs to be updated all at once!")}(t.nextValidatorData,t.epochRoot,t.sealingKeySeries,t.ticketsAccumulator);void 0!==s&&(yield r(s,Vi.safrole)),void 0!==t.disputesRecords&&(yield r(t.disputesRecords,Vi.disputesRecords)),void 0!==t.entropy&&(yield r(t.entropy,Vi.entropy)),void 0!==t.designatedValidatorData&&(yield r(t.designatedValidatorData,Vi.designatedValidators)),void 0!==t.currentValidatorData&&(yield r(t.currentValidatorData,Vi.currentValidators)),void 0!==t.previousValidatorData&&(yield r(t.previousValidatorData,Vi.previousValidators)),void 0!==t.availabilityAssignment&&(yield r(t.availabilityAssignment,Vi.availabilityAssignment)),void 0!==t.timeslot&&(yield r(t.timeslot,Vi.timeslot)),void 0!==t.privilegedServices&&(yield r(t.privilegedServices,Vi.privilegedServices)),void 0!==t.statistics&&(yield r(t.statistics,Vi.statistics)),void 0!==t.accumulationQueue&&(yield r(t.accumulationQueue,Vi.accumulationQueue)),void 0!==t.recentlyAccumulated&&(yield r(t.recentlyAccumulated,Vi.recentlyAccumulated))}(e,t);const r=(t,r)=>Te.encodeObject(t,r,e);yield*function*(e,t){for(const{action:r,serviceId:s}of e??[]){const e=Vi.serviceData(s);if(yield[$i.Insert,e.key,t(e.Codec,r.account)],r.kind===wi.Create&&null!==r.lookupHistory){const{lookupHistory:e}=r,i=Vi.serviceLookupHistory(s,e.hash,e.length);yield[$i.Insert,i.key,t(i.Codec,e.slots)]}}}(t.servicesUpdates,r),yield*function*(e,t){for(const{action:r,serviceId:s}of e??[])switch(r.kind){case vi.Provide:{const{hash:e,blob:i}=r.preimage,n=Vi.servicePreimages(s,e);if(yield[$i.Insert,n.key,i],null!==r.slot){const n=Vi.serviceLookupHistory(s,e,Ae(i.length));yield[$i.Insert,n.key,t(n.Codec,Ai([r.slot]))]}break}case vi.UpdateOrAdd:{const{hash:e,length:i,slots:n}=r.item,o=Vi.serviceLookupHistory(s,e,i);yield[$i.Insert,o.key,t(o.Codec,n)];break}case vi.Remove:{const{hash:e,length:t}=r,i=Vi.servicePreimages(s,e);yield[$i.Remove,i.key,ji];const n=Vi.serviceLookupHistory(s,e,t);yield[$i.Remove,n.key,ji];break}default:F(r)}}(t.preimages,r),yield*function*(e){for(const{action:t,serviceId:r}of e??[])switch(t.kind){case Si.Set:{const e=Vi.serviceStorage(r,t.storage.key);yield[$i.Insert,e.key,t.storage.value];break}case Si.Remove:{const e=Vi.serviceStorage(r,t.key);yield[$i.Remove,e.key,ji];break}default:F(t)}}(t.storage),yield*function*(e){for(const t of e??[]){const e=Vi.serviceData(t);yield[$i.Remove,e.key,ji]}}(t.servicesRemoved)}(this.spec,r);return await this.updateAndCommit(e,s,i)}async getStateRoot(e){return e.backend.getStateRoot()}getState(e){const t=this.states.get(e.raw);if(void 0===t)return null;const r=this.values,s=bn.fromLeavesBlob(te.blobFrom(t),{get(e){const t=r.get(e);if(void 0===t)throw new Error(`Missing required value: ${te.blobFrom(e)} in the DB`);return t}});if(s.isError)throw new Error(`Inconsistent DB. Invalid leaf nodes for ${e}: ${X(s)}`);return Gi.new(this.spec,s.ok)}}const En=t(import.meta.url)("node:events"),Cn=2**32,kn=m.new(void 0,"state-machine/port");class xn{port;listeners=new En.EventEmitter;responseListeners=new En.EventEmitter;messageId=0;constructor(e){this.port=e,e.on("message",e=>{try{this.dispatchPortMessage(e)}catch(t){throw kn.error(`[${this.constructor.name}] Failed to dispatch a message: ${t}: ${JSON.stringify(e)}`),t}})}async sendRequest(e,t,r,s){const[i,n]=this.prepareRequest(e,t,r);return this.postMessage(i,s),n}sendSignal(e,t,r,s){this.messageId=(this.messageId+1)%Cn,this.messageId>>>=0,this.postMessage({kind:"signal",name:t,id:this.messageId,localState:e,data:r},s)}prepareRequest(e,t,r){this.messageId+=1;const s=new Promise((e,t)=>{this.responseListeners.once(_n(this.messageId),(r,s)=>null!==r?t(r):e(s))});return[{kind:"request",id:this.messageId,name:t,localState:e,data:r},s]}respond(e,t,r){Q("request"===t.kind),this.postMessage({kind:"response",id:t.id,name:t.name,data:r,localState:e})}close(){this.cleanup("closing"),this.listeners.removeAllListeners(),this.port.close()}postMessage(e,t){try{this.port.postMessage(e,t)}catch(t){throw kn.error(`[${this.constructor.name}] Failed to post a message: ${t}: ${JSON.stringify(e)}`),t}}dispatchPortMessage(e){if(!function(e){return null!==e&&"object"==typeof e&&"kind"in e&&"string"==typeof e.kind&&"id"in e&&"number"==typeof e.id&&"name"in e&&"string"==typeof e.name&&"data"in e&&"localState"in e&&"string"==typeof e.localState}(e))throw new Error(`Invalid message: ${JSON.stringify(e)}.`);switch(e.kind){case"response":Q(-1!==this.responseListeners.eventNames().indexOf(_n(e.id))),this.responseListeners.emit(_n(e.id),null,e.data,e.name,e.localState,e);break;case"signal":this.listeners.emit("signal",e.name,e.data,e.localState,e);break;case"request":this.listeners.emit("request",e.name,e.data,e.localState,e);break;case"subscription":case"subscribe":throw new Error("unimplemented");default:throw new Error(`Unexpected message: "${e.kind}"`)}}cleanup(e){const t=this.responseListeners.eventNames();for(const r in t)this.responseListeners.emit(r,new Error(`port is ${e}`))}}function _n(e){return`req:${e}`}const Bn=m.new(void 0,"state-machine"),Rn="channel";class On{machine;port;constructor(e,t){this.machine=e,this.port=t,t.listeners.on("signal",(e,t,r)=>{try{this.dispatchSignal(e,t)}catch(t){throw Bn.error(`[${this.constructor.name}] Unable to dispatch signal (${e}): ${t}. ${this.stateInfo(r)}`),t}}),t.listeners.on("request",async(e,t,r,s)=>{try{await this.dispatchRequest(e,t,s)}catch(t){throw Bn.error(`[${this.constructor.name}] Unable to dispatch request (${e}): ${t}. ${this.stateInfo(r)}`),t}})}sendSignal(e,t){this.port.sendSignal(this.currentState().stateName,e,t)}async sendRequest(e,t){return this.port.sendRequest(this.currentState().stateName,e,t)}close(){this.port.close()}getState(e){return this.machine.getState(e)}currentState(){return this.machine.currentState()}async waitForState(e){return await this.machine.waitForState(e),this.transitionTo()}async doUntil(e,t){const r={isDone:!1},s=this.waitForState(e).then(()=>{r.isDone=!0});return await t(this.currentState(),this,()=>r.isDone),await s,this.transitionTo()}transition(e){const t=e(this.currentState(),this);return this.machine.transition(t.state,t.data),this.transitionTo()}stateInfo(e){return` (local state: "${this.currentState()}", remote state: "${e}")`}async dispatchRequest(e,t,r){const s=this.currentState(),i=s.requestHandlers.get(e);if(void 0===i)throw new Error(`Missing request handler for "${e}"`);const n=await i(t),o=this.currentState()!==s;if(void 0!==n.transitionTo&&this.machine.transition(n.transitionTo.state,n.transitionTo.data),!o)return this.port.respond(s.stateName,r,n.response);Bn.warn(`Ignoring obsolete response for an old request: "${e}"`)}dispatchSignal(e,t){const r=this.currentState().signalListeners.get(e);if(void 0===r)throw new Error(`Unexpected signal "${e}"`);const s=r(t);void 0!==s&&this.machine.transition(s.state,s.data)}transitionTo(){return Bn.trace(`[${this.machine.name}] transitioned to ${this.currentState()}`),this}static async createAndTransferChannel(e,t){const r=new T.MessageChannel,s=new xn(r.port2),i=e.currentState().stateName,[n,o]=s.prepareRequest(i,Rn,r.port1);t.postMessage(n,[r.port1]);try{await o}catch(e){Bn.error(JSON.stringify(e))}return new On(e,s)}static async receiveChannel(e,t){if(null===t)throw new Error("This code is expected to be run in a worker.");const r=new Promise((r,s)=>{t.once("message",t=>{try{Q("request"===t.kind,"The initial message should be a request with channel."),Q(t.name===Rn),Q(t.data instanceof T.MessagePort);const s=new xn(t.data);s.respond(e.currentState().stateName,t,"OK"),r(s)}catch(e){s(e)}})}),s=await r;return new On(e,s)}}const Un=Symbol(),Tn=Symbol();class Nn{emitter=new En.EventEmitter;emit(e){this.emitter.emit(Un,e)}on(e){return this.emitter.on(Un,e),this}once(e){return this.emitter.once(Un,e),this}onceDone(e){return this.emitter.once(Tn,e),this}markDone(){this.emitter.emit(Tn),this.emitter.removeAllListeners(Un),this.emitter.removeAllListeners(Tn)}}class Dn{name;state;allStates;stateListeners=new En.EventEmitter;constructor(e,t,r){this.name=e,this.state=t,this.allStates=new Map;for(const e of r)this.allStates.set(e.stateName,e)}getState(e){const t=this.allStates.get(e);return Q(void 0!==t,`Unable to retrieve state object for ${e}.`),t}currentState(){return this.state}waitForState(e){if(this.state.stateName===e)throw new Error(`Attempting to await a state that is already active: ${e}`);return new Promise(t=>{this.stateListeners.once(e,t)})}transition(e,t){if(this.state.stateName===e)throw new Error("Attempting transition to already active state!");if(!this.state.canTransitionTo(e))throw new Error(`Unallowed transition from ${this.state} to ${e}`);const r=this.allStates.get(e);if(void 0===r)throw new Error(`Unavailable state: ${e}`);r.onActivation(t);const s=this.transitionTo(r);return s.stateListeners.emit(e,s),s}transitionTo(e){return this.state=e,this}}const Mn=m.new(void 0,"state-machine/state");class Pn{stateName;signalListeners;requestHandlers;allowedTransitions;data=null;constructor({name:e,signalListeners:t={},requestHandlers:r={},allowedTransitions:s=[]}){this.stateName=e,this.allowedTransitions=s,this.signalListeners=new Map(Object.entries(t)),this.requestHandlers=new Map(Object.entries(r))}onActivation(e){Mn.trace(`[${this.constructor.name}] Changing state to: ${this}`),this.data=e}canTransitionTo(e){return-1!==this.allowedTransitions.indexOf(e)}toString(){return`<State ${this.stateName}>`}}class Ln extends Pn{constructor(){super({name:"finished"})}close(e){e.close()}async waitForWorkerToFinish(){return this.data}}class Hn extends Pn{readyName;constructor(e){super({name:"init(main)",allowedTransitions:[e]}),this.readyName=e}sendConfig(e,t){return e.sendSignal("config",t),{state:this.readyName,data:t}}}class Kn extends Pn{workerReadyName;handleConfig;constructor(e,t){super({name:"init(worker)",allowedTransitions:[e],signalListeners:{config:e=>this.onConfig(e)}}),this.workerReadyName=e,this.handleConfig=t}onConfig(e){return{state:this.workerReadyName,data:this.handleConfig(e)}}}async function Qn(e,t,r,s){const i=new T.Worker(e),n=function(e,t,r){const s=new Hn(t),i=new Ln;return new Dn(e,s,[s,r,i])}(`main->${r}`,r,s),o=await On.createAndTransferChannel(n,i);return t.trace(`[${n.name}] Worker spawned ${o.currentState()}`),o}const Vn=4294967295,Fn=4294967296,$n=4096,jn=(Q(!0,"incorrect minimal allocation shift"),7),Gn=$n>>jn,qn=1048575,zn=1048576,Wn=e=>V(e,e>=0&&e<=Vn,`Incorrect memory index: ${e}!`),Jn=e=>V(e,e>=0&&e<=4294967296,`Incorrect sbrk index: ${e}!`);var Yn,Xn;(Xn=Yn||(Yn={}))[Xn.OK=255]="OK",Xn[Xn.HALT=0]="HALT",Xn[Xn.PANIC=1]="PANIC",Xn[Xn.FAULT=2]="FAULT",Xn[Xn.HOST=3]="HOST",Xn[Xn.OOG=4]="OOG";const Zn=e=>Ae(e);var eo,to;!function(e){e[e.Halt=0]="Halt",e[e.Panic=1]="Panic"}(eo||(eo={}));class ro{lookupTableForward;constructor(e){this.lookupTableForward=this.buildLookupTableForward(e)}isInstruction(e){return 0===this.lookupTableForward[e]}getNoOfBytesToNextInstruction(e){return Q(e>=0,`index (${e}) cannot be a negative number`),Math.min(this.lookupTableForward[e]??0,25)}buildLookupTableForward(e){const t=new Uint8Array(e.bitLength);let r=0;for(let s=e.bitLength-1;s>=0;s--)e.isSet(s)?r=0:r++,t[s]=r;return t}static empty(){return new ro(pe.empty(0))}}!function(e){e[e.NO_ARGUMENTS=0]="NO_ARGUMENTS",e[e.ONE_IMMEDIATE=1]="ONE_IMMEDIATE",e[e.TWO_IMMEDIATES=2]="TWO_IMMEDIATES",e[e.ONE_OFFSET=3]="ONE_OFFSET",e[e.ONE_REGISTER_ONE_IMMEDIATE=4]="ONE_REGISTER_ONE_IMMEDIATE",e[e.ONE_REGISTER_TWO_IMMEDIATES=5]="ONE_REGISTER_TWO_IMMEDIATES",e[e.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET=6]="ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET",e[e.TWO_REGISTERS=7]="TWO_REGISTERS",e[e.TWO_REGISTERS_ONE_IMMEDIATE=8]="TWO_REGISTERS_ONE_IMMEDIATE",e[e.TWO_REGISTERS_ONE_OFFSET=9]="TWO_REGISTERS_ONE_OFFSET",e[e.TWO_REGISTERS_TWO_IMMEDIATES=10]="TWO_REGISTERS_TWO_IMMEDIATES",e[e.THREE_REGISTERS=11]="THREE_REGISTERS",e[e.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE=12]="ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE"}(to||(to={}));class so{u32;i32;u64;i64;view;bytes;constructor(){const e=new ArrayBuffer(8);this.u32=new Uint32Array(e),this.i32=new Int32Array(e),this.u64=new BigUint64Array(e),this.i64=new BigInt64Array(e),this.view=new DataView(e),this.bytes=new Uint8Array(e)}setBytes(e){const t=e.length,r=t>0?128&e[t-1]:0,s=Math.min(t,8),i=0!==r?255:0;for(let t=0;t<s;t++)this.view.setUint8(t,e[t]);for(let e=t;e<8;e++)this.view.setUint8(e,i)}getUnsigned(){return this.u32[0]}getSigned(){return this.i32[0]}getU32(){return this.u32[0]}getI32(){return this.i32[0]}getU64(){return this.u64[0]}getI64(){return this.i64[0]}getBytesAsLittleEndian(){return this.bytes.subarray(0,4)}getExtendedBytesAsLittleEndian(){return this.bytes}}class io{bytes;asSigned;asUnsigned;constructor(e=new Uint8Array(104)){this.bytes=e,Q(104===e.length,"Invalid size of registers array."),this.asSigned=new BigInt64Array(e.buffer,e.byteOffset),this.asUnsigned=new BigUint64Array(e.buffer,e.byteOffset)}static fromBytes(e){return Q(104===e.length,"Invalid size of registers array."),new io(e)}getBytesAsLittleEndian(e,t){const r=e<<3;return this.bytes.subarray(r,r+t)}getAllBytesAsLittleEndian(){return this.bytes}copyFrom(e){const t=e instanceof BigUint64Array?e:e.asUnsigned;this.asUnsigned.set(t)}reset(){for(let e=0;e<13;e++)this.asUnsigned[e]=0n}getLowerU32(e){return Number(0xffffffffn&this.asUnsigned[e])}getLowerI32(e){return 0|Number(this.getLowerU32(e))}setU32(e,t){this.asUnsigned[e]=no(t)}setI32(e,t){this.asSigned[e]=no(t)}getU64(e){return this.asUnsigned[e]}getI64(e){return this.asSigned[e]}setU64(e,t){this.asUnsigned[e]=t}setI64(e,t){this.asSigned[e]=t}getAllU64(){return this.asUnsigned}}function no(e){const t="number"==typeof e?BigInt(e):e,r=BigInt(4294967295),s=t&r;return(s&BigInt(2147483648))!==BigInt(0)?s|~r:s}class oo{byte=new Int8Array(1);setByte(e){this.byte[0]=e}getHighNibble(){return(240&this.byte[0])>>>4}getLowNibble(){return 15&this.byte[0]}getHighNibbleAsRegisterIndex(){return Math.min(this.getHighNibble(),12)}getLowNibbleAsRegisterIndex(){return Math.min(this.getLowNibble(),12)}getHighNibbleAsLength(){return Math.min(this.getHighNibble(),4)}getLowNibbleAsLength(){return Math.min(this.getLowNibble(),4)}}class ao{nibblesDecoder=new oo;offsetDecoder=new so;code=new Uint8Array;mask=ro.empty();reset(e,t){this.code=e,this.mask=t}fillArgs(e,t){const r=1+this.mask.getNoOfBytesToNextInstruction(e+1);switch(t.noOfBytesToSkip=r,t.type){case to.NO_ARGUMENTS:break;case to.ONE_IMMEDIATE:{const s=Math.min(4,r-1),i=e+1;t.immediateDecoder.setBytes(this.code.subarray(i,i+s));break}case to.THREE_REGISTERS:{const r=this.code[e+1],s=this.code[e+2];this.nibblesDecoder.setByte(r),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex(),this.nibblesDecoder.setByte(s),t.thirdRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();break}case to.TWO_REGISTERS_ONE_IMMEDIATE:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex();const i=e+2,n=i+Math.min(4,Math.max(0,r-2));t.immediateDecoder.setBytes(this.code.subarray(i,n));break}case to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const i=this.nibblesDecoder.getHighNibbleAsLength(),n=e+2,o=n+i;t.immediateDecoder.setBytes(this.code.subarray(n,o));const a=e+2+i,c=a+Math.min(4,Math.max(0,r-2-i));this.offsetDecoder.setBytes(this.code.subarray(a,c)),t.nextPc=e+this.offsetDecoder.getSigned();break}case to.TWO_REGISTERS_ONE_OFFSET:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex();const i=e+2,n=i+Math.min(4,Math.max(0,r-2));this.offsetDecoder.setBytes(this.code.subarray(i,n)),t.nextPc=e+this.offsetDecoder.getSigned();break}case to.TWO_REGISTERS:{const r=this.code[e+1];this.nibblesDecoder.setByte(r),t.firstRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();break}case to.ONE_OFFSET:{const s=e+1,i=s+Math.min(4,r-1),n=this.code.subarray(s,i);this.offsetDecoder.setBytes(n);const o=this.offsetDecoder.getSigned();t.nextPc=e+o;break}case to.ONE_REGISTER_ONE_IMMEDIATE:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const i=e+2,n=i+Math.min(4,Math.max(0,r-2)),o=this.code.subarray(i,n);t.immediateDecoder.setBytes(o);break}case to.TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s);const i=this.nibblesDecoder.getLowNibbleAsLength(),n=e+2,o=n+i,a=this.code.subarray(n,o);t.firstImmediateDecoder.setBytes(a);const c=o,l=c+Math.min(4,Math.max(0,r-2-i)),h=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(h);break}case to.ONE_REGISTER_TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const i=this.nibblesDecoder.getHighNibbleAsLength(),n=e+2,o=n+i,a=this.code.subarray(n,o);t.firstImmediateDecoder.setBytes(a);const c=o,l=c+Math.min(4,Math.max(0,r-2-i)),h=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(h);break}case to.TWO_REGISTERS_TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s),t.firstRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex();const i=this.code[e+2];this.nibblesDecoder.setByte(i);const n=this.nibblesDecoder.getLowNibbleAsLength(),o=e+3,a=o+n,c=this.code.subarray(o,a);t.firstImmediateDecoder.setBytes(c);const l=a,h=l+Math.min(4,Math.max(0,r-3-n)),u=this.code.subarray(l,h);t.secondImmediateDecoder.setBytes(u);break}case to.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE:{const r=this.code[e+1];this.nibblesDecoder.setByte(r),t.registerIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();const s=e+2,i=s+8,n=this.code.subarray(s,i);t.immediateDecoder.setBytes(n);break}}}}class co{unsignedImmediate;bytes;constructor(){const e=new ArrayBuffer(8);this.unsignedImmediate=new BigUint64Array(e),this.bytes=new Uint8Array(e)}setBytes(e){let t=0;for(;t<e.length;t++)this.bytes[t]=e[t];for(;t<8;t++)this.bytes[t]=0}getValue(){return this.unsignedImmediate[0]}getBytesAsLittleEndian(){return this.bytes.subarray(0,8)}}const lo=Object.keys(to).length/2;var ho;!function(e){e[e.TRAP=0]="TRAP",e[e.FALLTHROUGH=1]="FALLTHROUGH",e[e.ECALLI=10]="ECALLI",e[e.LOAD_IMM_64=20]="LOAD_IMM_64",e[e.STORE_IMM_U8=30]="STORE_IMM_U8",e[e.STORE_IMM_U16=31]="STORE_IMM_U16",e[e.STORE_IMM_U32=32]="STORE_IMM_U32",e[e.STORE_IMM_U64=33]="STORE_IMM_U64",e[e.JUMP=40]="JUMP",e[e.JUMP_IND=50]="JUMP_IND",e[e.LOAD_IMM=51]="LOAD_IMM",e[e.LOAD_U8=52]="LOAD_U8",e[e.LOAD_I8=53]="LOAD_I8",e[e.LOAD_U16=54]="LOAD_U16",e[e.LOAD_I16=55]="LOAD_I16",e[e.LOAD_U32=56]="LOAD_U32",e[e.LOAD_I32=57]="LOAD_I32",e[e.LOAD_U64=58]="LOAD_U64",e[e.STORE_U8=59]="STORE_U8",e[e.STORE_U16=60]="STORE_U16",e[e.STORE_U32=61]="STORE_U32",e[e.STORE_U64=62]="STORE_U64",e[e.STORE_IMM_IND_U8=70]="STORE_IMM_IND_U8",e[e.STORE_IMM_IND_U16=71]="STORE_IMM_IND_U16",e[e.STORE_IMM_IND_U32=72]="STORE_IMM_IND_U32",e[e.STORE_IMM_IND_U64=73]="STORE_IMM_IND_U64",e[e.LOAD_IMM_JUMP=80]="LOAD_IMM_JUMP",e[e.BRANCH_EQ_IMM=81]="BRANCH_EQ_IMM",e[e.BRANCH_NE_IMM=82]="BRANCH_NE_IMM",e[e.BRANCH_LT_U_IMM=83]="BRANCH_LT_U_IMM",e[e.BRANCH_LE_U_IMM=84]="BRANCH_LE_U_IMM",e[e.BRANCH_GE_U_IMM=85]="BRANCH_GE_U_IMM",e[e.BRANCH_GT_U_IMM=86]="BRANCH_GT_U_IMM",e[e.BRANCH_LT_S_IMM=87]="BRANCH_LT_S_IMM",e[e.BRANCH_LE_S_IMM=88]="BRANCH_LE_S_IMM",e[e.BRANCH_GE_S_IMM=89]="BRANCH_GE_S_IMM",e[e.BRANCH_GT_S_IMM=90]="BRANCH_GT_S_IMM",e[e.MOVE_REG=100]="MOVE_REG",e[e.SBRK=101]="SBRK",e[e.COUNT_SET_BITS_64=102]="COUNT_SET_BITS_64",e[e.COUNT_SET_BITS_32=103]="COUNT_SET_BITS_32",e[e.LEADING_ZERO_BITS_64=104]="LEADING_ZERO_BITS_64",e[e.LEADING_ZERO_BITS_32=105]="LEADING_ZERO_BITS_32",e[e.TRAILING_ZERO_BITS_64=106]="TRAILING_ZERO_BITS_64",e[e.TRAILING_ZERO_BITS_32=107]="TRAILING_ZERO_BITS_32",e[e.SIGN_EXTEND_8=108]="SIGN_EXTEND_8",e[e.SIGN_EXTEND_16=109]="SIGN_EXTEND_16",e[e.ZERO_EXTEND_16=110]="ZERO_EXTEND_16",e[e.REVERSE_BYTES=111]="REVERSE_BYTES",e[e.STORE_IND_U8=120]="STORE_IND_U8",e[e.STORE_IND_U16=121]="STORE_IND_U16",e[e.STORE_IND_U32=122]="STORE_IND_U32",e[e.STORE_IND_U64=123]="STORE_IND_U64",e[e.LOAD_IND_U8=124]="LOAD_IND_U8",e[e.LOAD_IND_I8=125]="LOAD_IND_I8",e[e.LOAD_IND_U16=126]="LOAD_IND_U16",e[e.LOAD_IND_I16=127]="LOAD_IND_I16",e[e.LOAD_IND_U32=128]="LOAD_IND_U32",e[e.LOAD_IND_I32=129]="LOAD_IND_I32",e[e.LOAD_IND_U64=130]="LOAD_IND_U64",e[e.ADD_IMM_32=131]="ADD_IMM_32",e[e.AND_IMM=132]="AND_IMM",e[e.XOR_IMM=133]="XOR_IMM",e[e.OR_IMM=134]="OR_IMM",e[e.MUL_IMM_32=135]="MUL_IMM_32",e[e.SET_LT_U_IMM=136]="SET_LT_U_IMM",e[e.SET_LT_S_IMM=137]="SET_LT_S_IMM",e[e.SHLO_L_IMM_32=138]="SHLO_L_IMM_32",e[e.SHLO_R_IMM_32=139]="SHLO_R_IMM_32",e[e.SHAR_R_IMM_32=140]="SHAR_R_IMM_32",e[e.NEG_ADD_IMM_32=141]="NEG_ADD_IMM_32",e[e.SET_GT_U_IMM=142]="SET_GT_U_IMM",e[e.SET_GT_S_IMM=143]="SET_GT_S_IMM",e[e.SHLO_L_IMM_ALT_32=144]="SHLO_L_IMM_ALT_32",e[e.SHLO_R_IMM_ALT_32=145]="SHLO_R_IMM_ALT_32",e[e.SHAR_R_IMM_ALT_32=146]="SHAR_R_IMM_ALT_32",e[e.CMOV_IZ_IMM=147]="CMOV_IZ_IMM",e[e.CMOV_NZ_IMM=148]="CMOV_NZ_IMM",e[e.ADD_IMM_64=149]="ADD_IMM_64",e[e.MUL_IMM_64=150]="MUL_IMM_64",e[e.SHLO_L_IMM_64=151]="SHLO_L_IMM_64",e[e.SHLO_R_IMM_64=152]="SHLO_R_IMM_64",e[e.SHAR_R_IMM_64=153]="SHAR_R_IMM_64",e[e.NEG_ADD_IMM_64=154]="NEG_ADD_IMM_64",e[e.SHLO_L_IMM_ALT_64=155]="SHLO_L_IMM_ALT_64",e[e.SHLO_R_IMM_ALT_64=156]="SHLO_R_IMM_ALT_64",e[e.SHAR_R_IMM_ALT_64=157]="SHAR_R_IMM_ALT_64",e[e.ROT_R_64_IMM=158]="ROT_R_64_IMM",e[e.ROT_R_64_IMM_ALT=159]="ROT_R_64_IMM_ALT",e[e.ROT_R_32_IMM=160]="ROT_R_32_IMM",e[e.ROT_R_32_IMM_ALT=161]="ROT_R_32_IMM_ALT",e[e.BRANCH_EQ=170]="BRANCH_EQ",e[e.BRANCH_NE=171]="BRANCH_NE",e[e.BRANCH_LT_U=172]="BRANCH_LT_U",e[e.BRANCH_LT_S=173]="BRANCH_LT_S",e[e.BRANCH_GE_U=174]="BRANCH_GE_U",e[e.BRANCH_GE_S=175]="BRANCH_GE_S",e[e.LOAD_IMM_JUMP_IND=180]="LOAD_IMM_JUMP_IND",e[e.ADD_32=190]="ADD_32",e[e.SUB_32=191]="SUB_32",e[e.MUL_32=192]="MUL_32",e[e.DIV_U_32=193]="DIV_U_32",e[e.DIV_S_32=194]="DIV_S_32",e[e.REM_U_32=195]="REM_U_32",e[e.REM_S_32=196]="REM_S_32",e[e.SHLO_L_32=197]="SHLO_L_32",e[e.SHLO_R_32=198]="SHLO_R_32",e[e.SHAR_R_32=199]="SHAR_R_32",e[e.ADD_64=200]="ADD_64",e[e.SUB_64=201]="SUB_64",e[e.MUL_64=202]="MUL_64",e[e.DIV_U_64=203]="DIV_U_64",e[e.DIV_S_64=204]="DIV_S_64",e[e.REM_U_64=205]="REM_U_64",e[e.REM_S_64=206]="REM_S_64",e[e.SHLO_L_64=207]="SHLO_L_64",e[e.SHLO_R_64=208]="SHLO_R_64",e[e.SHAR_R_64=209]="SHAR_R_64",e[e.AND=210]="AND",e[e.XOR=211]="XOR",e[e.OR=212]="OR",e[e.MUL_UPPER_S_S=213]="MUL_UPPER_S_S",e[e.MUL_UPPER_U_U=214]="MUL_UPPER_U_U",e[e.MUL_UPPER_S_U=215]="MUL_UPPER_S_U",e[e.SET_LT_U=216]="SET_LT_U",e[e.SET_LT_S=217]="SET_LT_S",e[e.CMOV_IZ=218]="CMOV_IZ",e[e.CMOV_NZ=219]="CMOV_NZ",e[e.ROT_L_64=220]="ROT_L_64",e[e.ROT_L_32=221]="ROT_L_32",e[e.ROT_R_64=222]="ROT_R_64",e[e.ROT_R_32=223]="ROT_R_32",e[e.AND_INV=224]="AND_INV",e[e.OR_INV=225]="OR_INV",e[e.XNOR=226]="XNOR",e[e.MAX=227]="MAX",e[e.MAX_U=228]="MAX_U",e[e.MIN=229]="MIN",e[e.MIN_U=230]="MIN_U"}(ho||(ho={}));const uo=ho.MIN_U,fo=(()=>{const e=new Array(uo+1);return e[ho.TRAP]=to.NO_ARGUMENTS,e[ho.FALLTHROUGH]=to.NO_ARGUMENTS,e[ho.ECALLI]=to.ONE_IMMEDIATE,e[ho.LOAD_IMM_64]=to.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,e[ho.STORE_IMM_U8]=to.TWO_IMMEDIATES,e[ho.STORE_IMM_U16]=to.TWO_IMMEDIATES,e[ho.STORE_IMM_U32]=to.TWO_IMMEDIATES,e[ho.STORE_IMM_U64]=to.TWO_IMMEDIATES,e[ho.JUMP]=to.ONE_OFFSET,e[ho.JUMP_IND]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_U8]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_I8]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_U16]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_I16]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_U32]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_I32]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.LOAD_U64]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.STORE_U8]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.STORE_U16]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.STORE_U32]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.STORE_U64]=to.ONE_REGISTER_ONE_IMMEDIATE,e[ho.STORE_IMM_IND_U8]=to.ONE_REGISTER_TWO_IMMEDIATES,e[ho.STORE_IMM_IND_U16]=to.ONE_REGISTER_TWO_IMMEDIATES,e[ho.STORE_IMM_IND_U32]=to.ONE_REGISTER_TWO_IMMEDIATES,e[ho.STORE_IMM_IND_U64]=to.ONE_REGISTER_TWO_IMMEDIATES,e[ho.LOAD_IMM_JUMP]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_EQ_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_NE_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_LT_U_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_LE_U_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_GE_U_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_GT_U_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_LT_S_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_LE_S_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_GE_S_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.BRANCH_GT_S_IMM]=to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[ho.MOVE_REG]=to.TWO_REGISTERS,e[ho.SBRK]=to.TWO_REGISTERS,e[ho.COUNT_SET_BITS_64]=to.TWO_REGISTERS,e[ho.COUNT_SET_BITS_32]=to.TWO_REGISTERS,e[ho.LEADING_ZERO_BITS_64]=to.TWO_REGISTERS,e[ho.LEADING_ZERO_BITS_32]=to.TWO_REGISTERS,e[ho.TRAILING_ZERO_BITS_64]=to.TWO_REGISTERS,e[ho.TRAILING_ZERO_BITS_32]=to.TWO_REGISTERS,e[ho.SIGN_EXTEND_8]=to.TWO_REGISTERS,e[ho.SIGN_EXTEND_16]=to.TWO_REGISTERS,e[ho.ZERO_EXTEND_16]=to.TWO_REGISTERS,e[ho.REVERSE_BYTES]=to.TWO_REGISTERS,e[ho.STORE_IND_U8]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.STORE_IND_U16]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.STORE_IND_U32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.STORE_IND_U64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_U8]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_I8]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_U16]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_I16]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_U32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_I32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.LOAD_IND_U64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.ADD_IMM_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.ADD_IMM_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.AND_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.XOR_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.OR_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.MUL_IMM_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.MUL_IMM_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SET_LT_U_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SET_LT_S_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_L_IMM_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_R_IMM_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHAR_R_IMM_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.NEG_ADD_IMM_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_L_IMM_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_R_IMM_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHAR_R_IMM_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.NEG_ADD_IMM_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SET_GT_U_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SET_GT_S_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_L_IMM_ALT_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_R_IMM_ALT_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHAR_R_IMM_ALT_32]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_L_IMM_ALT_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHLO_R_IMM_ALT_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.SHAR_R_IMM_ALT_64]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.CMOV_IZ_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.CMOV_NZ_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.ROT_R_64_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.ROT_R_64_IMM_ALT]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.ROT_R_32_IMM]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.ROT_R_32_IMM_ALT]=to.TWO_REGISTERS_ONE_IMMEDIATE,e[ho.BRANCH_EQ]=to.TWO_REGISTERS_ONE_OFFSET,e[ho.BRANCH_NE]=to.TWO_REGISTERS_ONE_OFFSET,e[ho.BRANCH_LT_U]=to.TWO_REGISTERS_ONE_OFFSET,e[ho.BRANCH_LT_S]=to.TWO_REGISTERS_ONE_OFFSET,e[ho.BRANCH_GE_U]=to.TWO_REGISTERS_ONE_OFFSET,e[ho.BRANCH_GE_S]=to.TWO_REGISTERS_ONE_OFFSET,e[ho.LOAD_IMM_JUMP_IND]=to.TWO_REGISTERS_TWO_IMMEDIATES,e[ho.ADD_32]=to.THREE_REGISTERS,e[ho.ADD_64]=to.THREE_REGISTERS,e[ho.SUB_32]=to.THREE_REGISTERS,e[ho.SUB_64]=to.THREE_REGISTERS,e[ho.AND]=to.THREE_REGISTERS,e[ho.XOR]=to.THREE_REGISTERS,e[ho.OR]=to.THREE_REGISTERS,e[ho.MUL_32]=to.THREE_REGISTERS,e[ho.MUL_64]=to.THREE_REGISTERS,e[ho.MUL_UPPER_S_S]=to.THREE_REGISTERS,e[ho.MUL_UPPER_U_U]=to.THREE_REGISTERS,e[ho.MUL_UPPER_S_U]=to.THREE_REGISTERS,e[ho.DIV_U_32]=to.THREE_REGISTERS,e[ho.DIV_S_32]=to.THREE_REGISTERS,e[ho.REM_U_32]=to.THREE_REGISTERS,e[ho.REM_S_32]=to.THREE_REGISTERS,e[ho.DIV_U_64]=to.THREE_REGISTERS,e[ho.DIV_S_64]=to.THREE_REGISTERS,e[ho.REM_U_64]=to.THREE_REGISTERS,e[ho.REM_S_64]=to.THREE_REGISTERS,e[ho.SET_LT_U]=to.THREE_REGISTERS,e[ho.SET_LT_S]=to.THREE_REGISTERS,e[ho.SHLO_L_32]=to.THREE_REGISTERS,e[ho.SHLO_R_32]=to.THREE_REGISTERS,e[ho.SHAR_R_32]=to.THREE_REGISTERS,e[ho.SHLO_L_64]=to.THREE_REGISTERS,e[ho.SHLO_R_64]=to.THREE_REGISTERS,e[ho.SHAR_R_64]=to.THREE_REGISTERS,e[ho.CMOV_IZ]=to.THREE_REGISTERS,e[ho.CMOV_NZ]=to.THREE_REGISTERS,e[ho.ROT_L_64]=to.THREE_REGISTERS,e[ho.ROT_L_32]=to.THREE_REGISTERS,e[ho.ROT_R_64]=to.THREE_REGISTERS,e[ho.ROT_R_32]=to.THREE_REGISTERS,e[ho.AND_INV]=to.THREE_REGISTERS,e[ho.OR_INV]=to.THREE_REGISTERS,e[ho.XNOR]=to.THREE_REGISTERS,e[ho.MAX]=to.THREE_REGISTERS,e[ho.MAX_U]=to.THREE_REGISTERS,e[ho.MIN]=to.THREE_REGISTERS,e[ho.MIN_U]=to.THREE_REGISTERS,e})(),po=e=>Ae(e),go=e=>ve(e),yo=e=>"number"==typeof e&&e<2**32?po(e):go(e);function mo(e){return new bo(ve(e))}class bo{gas;constructor(e){this.gas=e}set(e){this.gas=ve(e)}get(){return yo(this.gas)}sub(e){return this.gas=ve(this.gas-ve(e)),this.gas<0n}}const Ao=[[ho.TRAP,1],[ho.FALLTHROUGH,1],[ho.ECALLI,1],[ho.LOAD_IMM_64,1],[ho.STORE_IMM_U8,1],[ho.STORE_IMM_U16,1],[ho.STORE_IMM_U32,1],[ho.STORE_IMM_U64,1],[ho.JUMP,1],[ho.JUMP_IND,1],[ho.LOAD_IMM,1],[ho.LOAD_U8,1],[ho.LOAD_I8,1],[ho.LOAD_U16,1],[ho.LOAD_I16,1],[ho.LOAD_U32,1],[ho.LOAD_I32,1],[ho.LOAD_U64,1],[ho.STORE_U8,1],[ho.STORE_U16,1],[ho.STORE_U32,1],[ho.STORE_U64,1],[ho.STORE_IMM_IND_U8,1],[ho.STORE_IMM_IND_U16,1],[ho.STORE_IMM_IND_U32,1],[ho.STORE_IMM_IND_U64,1],[ho.LOAD_IMM_JUMP,1],[ho.BRANCH_EQ_IMM,1],[ho.BRANCH_NE_IMM,1],[ho.BRANCH_LT_U_IMM,1],[ho.BRANCH_LE_U_IMM,1],[ho.BRANCH_GE_U_IMM,1],[ho.BRANCH_GT_U_IMM,1],[ho.BRANCH_LT_S_IMM,1],[ho.BRANCH_LE_S_IMM,1],[ho.BRANCH_GE_S_IMM,1],[ho.BRANCH_GT_S_IMM,1],[ho.MOVE_REG,1],[ho.SBRK,1],[ho.COUNT_SET_BITS_64,1],[ho.COUNT_SET_BITS_32,1],[ho.LEADING_ZERO_BITS_64,1],[ho.LEADING_ZERO_BITS_32,1],[ho.TRAILING_ZERO_BITS_64,1],[ho.TRAILING_ZERO_BITS_32,1],[ho.SIGN_EXTEND_8,1],[ho.SIGN_EXTEND_16,1],[ho.ZERO_EXTEND_16,1],[ho.REVERSE_BYTES,1],[ho.STORE_IND_U8,1],[ho.STORE_IND_U16,1],[ho.STORE_IND_U32,1],[ho.STORE_IND_U64,1],[ho.LOAD_IND_U8,1],[ho.LOAD_IND_I8,1],[ho.LOAD_IND_U16,1],[ho.LOAD_IND_I16,1],[ho.LOAD_IND_U32,1],[ho.LOAD_IND_I32,1],[ho.LOAD_IND_U64,1],[ho.ADD_IMM_32,1],[ho.AND_IMM,1],[ho.XOR_IMM,1],[ho.OR_IMM,1],[ho.MUL_IMM_32,1],[ho.SET_LT_U_IMM,1],[ho.SET_LT_S_IMM,1],[ho.SHLO_L_IMM_32,1],[ho.SHLO_R_IMM_32,1],[ho.SHAR_R_IMM_32,1],[ho.NEG_ADD_IMM_32,1],[ho.SET_GT_U_IMM,1],[ho.SET_GT_S_IMM,1],[ho.SHLO_L_IMM_ALT_32,1],[ho.SHLO_R_IMM_ALT_32,1],[ho.SHAR_R_IMM_ALT_32,1],[ho.CMOV_IZ_IMM,1],[ho.CMOV_NZ_IMM,1],[ho.ADD_IMM_64,1],[ho.MUL_IMM_64,1],[ho.SHLO_L_IMM_64,1],[ho.SHLO_R_IMM_64,1],[ho.SHAR_R_IMM_64,1],[ho.NEG_ADD_IMM_64,1],[ho.SHLO_L_IMM_ALT_64,1],[ho.SHLO_R_IMM_ALT_64,1],[ho.SHAR_R_IMM_ALT_64,1],[ho.ROT_R_64_IMM,1],[ho.ROT_R_64_IMM_ALT,1],[ho.ROT_R_32_IMM,1],[ho.ROT_R_32_IMM_ALT,1],[ho.BRANCH_EQ,1],[ho.BRANCH_NE,1],[ho.BRANCH_LT_U,1],[ho.BRANCH_LT_S,1],[ho.BRANCH_GE_U,1],[ho.BRANCH_GE_S,1],[ho.LOAD_IMM_JUMP_IND,1],[ho.ADD_32,1],[ho.SUB_32,1],[ho.MUL_32,1],[ho.DIV_U_32,1],[ho.DIV_S_32,1],[ho.REM_U_32,1],[ho.REM_S_32,1],[ho.SHLO_L_32,1],[ho.SHLO_R_32,1],[ho.SHAR_R_32,1],[ho.ADD_64,1],[ho.SUB_64,1],[ho.MUL_64,1],[ho.DIV_U_64,1],[ho.DIV_S_64,1],[ho.REM_U_64,1],[ho.REM_S_64,1],[ho.SHLO_L_64,1],[ho.SHLO_R_64,1],[ho.SHAR_R_64,1],[ho.AND,1],[ho.XOR,1],[ho.OR,1],[ho.MUL_UPPER_S_S,1],[ho.MUL_UPPER_U_U,1],[ho.MUL_UPPER_S_U,1],[ho.SET_LT_U,1],[ho.SET_LT_S,1],[ho.CMOV_IZ,1],[ho.CMOV_NZ,1],[ho.ROT_L_64,1],[ho.ROT_L_32,1],[ho.ROT_R_64,1],[ho.ROT_R_32,1],[ho.AND_INV,1],[ho.OR_INV,1],[ho.XNOR,1],[ho.MAX,1],[ho.MAX_U,1],[ho.MIN,1],[ho.MIN_U,1]].reduce((e,t)=>{const[r,s]=(([e,t])=>[e,{gas:po(t)}])(t);return e[r]=s,e},{}),Io=(()=>{const e=new Array(uo+1);return e.fill(!1),e[ho.TRAP]=!0,e[ho.FALLTHROUGH]=!0,e[ho.JUMP]=!0,e[ho.JUMP_IND]=!0,e[ho.LOAD_IMM_JUMP]=!0,e[ho.LOAD_IMM_JUMP_IND]=!0,e[ho.BRANCH_EQ]=!0,e[ho.BRANCH_NE]=!0,e[ho.BRANCH_GE_U]=!0,e[ho.BRANCH_GE_S]=!0,e[ho.BRANCH_LT_U]=!0,e[ho.BRANCH_LT_S]=!0,e[ho.BRANCH_EQ_IMM]=!0,e[ho.BRANCH_NE_IMM]=!0,e[ho.BRANCH_LT_U_IMM]=!0,e[ho.BRANCH_LT_S_IMM]=!0,e[ho.BRANCH_LE_U_IMM]=!0,e[ho.BRANCH_LE_S_IMM]=!0,e[ho.BRANCH_GE_U_IMM]=!0,e[ho.BRANCH_GE_S_IMM]=!0,e[ho.BRANCH_GT_U_IMM]=!0,e[ho.BRANCH_GT_S_IMM]=!0,e})();class vo{basicBlocks=new Set;reset(e,t){this.basicBlocks.clear(),this.basicBlocks.add(0);const r=e.length,s=r=>t.isInstruction(r)&&Io[e[r]];for(let e=0;e<r;e++)t.isInstruction(e)&&s(e)&&this.basicBlocks.add(e+1+t.getNoOfBytesToNextInstruction(e+1))}isBeginningOfBasicBlock(e){return this.basicBlocks.has(e)}}const wo=(()=>{const e=new Array(uo+1);for(let t=0;t<uo+1;t++){const r=Ao[t]?.gas;e[t]=r}return e})();class So{nextPc=0;status=null;exitParam=null;reset(){this.nextPc=0,this.status=null,this.exitParam=null}}const Eo=e=>V(e,e>=0&&e<$n,`Incorect page index: ${e}!`),Co=e=>V(e,e>=0&&e<=qn,`Incorrect page number: ${e}!`);function ko(e){return Co(e===qn?0:e+1)}function xo(e){return $n*Math.ceil(e/$n)}function _o(e){return Co(e>>>12)}function Bo(e){return Wn(e>>>12<<12)}function Ro(e){return Wn(e<<12>>>0)}class Oo{address;isAccessFault;constructor(e,t=!0){this.address=e,this.isAccessFault=t}static fromPageNumber(e,t=!1){const r=Ro(Co(e));return new Oo(r,t)}static fromMemoryIndex(e,t=!1){const r=Bo(Wn(e%Fn));return new Oo(r,t)}}class Uo extends Error{constructor(){super("Out of bounds")}}Error,Error;class To extends Error{constructor(){super("Space between sbrk index and max heap index should be empty!")}}class No extends Error{constructor(){super("MemoryBuilder was finalized and cannot be changed!")}}class Do extends Error{constructor(){super("You are trying to access reserved memory!")}}class Mo extends Error{constructor(){super("You try to fill data on memory page that does not exist!")}}Error;class Po extends Error{constructor(){super("Out of memory")}}class Lo{start;length;end;lastIndex=null;constructor(e,t){this.start=e,this.length=t,this.end=Wn((this.start+this.length)%Fn),t>0&&(this.lastIndex=Wn((this.end-1+Fn)%Fn))}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>Fn)throw new TypeError(`length must be a non-negative integer and less than 4294967296, got ${t}`);return new Lo(e,t)}isEmpty(){return 0===this.length}isWrapped(){return this.start>=this.end&&!this.isEmpty()}isInRange(e){return this.isWrapped()?e>=this.start||e<this.end:e>=this.start&&e<this.end}overlapsWith(e){return null!==this.lastIndex&&null!==e.lastIndex&&(this.isInRange(e.start)||this.isInRange(e.lastIndex)||e.isInRange(this.start)||e.isInRange(this.lastIndex))}}const Ho=Lo.fromStartAndLength(Wn(0),65536);class Ko{start;length;end;constructor(e,t){this.start=e,this.length=t,this.end=Co((this.start+this.length)%zn)}static fromMemoryRange(e){const t=_o(e.start);if(e.isEmpty())return new Ko(t,0);const r=_o(e.lastIndex??e.end),s=ko(r);if((t===s||t===r)&&e.length>$n)return new Ko(t,zn);const i=t<s?s-t:zn-t+s;return Ko.fromStartAndLength(t,i)}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>zn)throw new TypeError(`length must be a non-negative integer and less than 1048576, got ${t}`);return new Ko(e,t)}isEmpty(){return 0===this.length}*[Symbol.iterator](){if(this.isEmpty())return;const e=this.end;let t=this.start;do{yield t,t=ko(t)}while(t!==e)}}class Qo{start;constructor(e){this.start=Ro(e)}}class Vo extends Qo{data;constructor(e,t){super(e),this.data=t}loadInto(e,t,r){const s=t+r;if(s>$n)return Z.error(Oo.fromMemoryIndex(this.start+$n));const i=this.data.subarray(t,s);return e.fill(0,i.length,r),e.set(i),Z.ok(W)}storeFrom(e,t){return Z.error(Oo.fromMemoryIndex(this.start,!0))}setData(e,t){this.data.set(t,e)}isWriteable(){return!1}getPageDump(){return this.data}}class Fo extends Qo{buffer;view;constructor(e,t){super(e);const r=t?.length??0,s=Math.min($n,Math.max(r,Gn));this.buffer=new ArrayBuffer(s,{maxByteLength:$n}),this.view=new Uint8Array(this.buffer),void 0!==t&&this.view.set(t)}loadInto(e,t,r){const s=t+r;if(s>$n)return Z.error(Oo.fromMemoryIndex(this.start+$n));const i=this.view.subarray(t,s);return e.fill(0,i.length,r),e.set(i),Z.ok(W)}storeFrom(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<$n){const r=Math.min($n,Math.max(Gn,e+t.length));this.buffer.resize(r)}return this.view.set(t,e),Z.ok(W)}setData(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<$n){const r=Math.min($n,Math.max(Gn,e+t.length));this.buffer.resize(r)}this.view.set(t,e)}isWriteable(){return!0}getPageDump(){return this.view}}var $o;!function(e){e[e.READ=0]="READ",e[e.WRITE=1]="WRITE"}($o||($o={}));class jo{sbrkIndex;virtualSbrkIndex;endHeapIndex;memory;static fromInitialMemory(e){return new jo(e?.sbrkIndex,e?.sbrkIndex,e?.endHeapIndex,e?.memory)}constructor(e=Jn(Ho.end),t=Jn(Ho.end),r=Jn(Vn),s=new Map){this.sbrkIndex=e,this.virtualSbrkIndex=t,this.endHeapIndex=r,this.memory=s}reset(){this.sbrkIndex=Jn(Ho.end),this.virtualSbrkIndex=Jn(Ho.end),this.endHeapIndex=Jn(Vn),this.memory=new Map}copyFrom(e){this.sbrkIndex=e.sbrkIndex,this.virtualSbrkIndex=e.virtualSbrkIndex,this.endHeapIndex=e.endHeapIndex,this.memory=e.memory}storeFrom(e,t){if(0===t.length)return Z.ok(W);const r=this.getPages(e,t.length,$o.WRITE);if(r.isError)return Z.error(r.error);const s=r.ok;let i=e,n=t.length;for(const r of s){const s=Eo(i%$n),o=Math.min($n-s,n),a=i-e,c=t.subarray(a,a+o);r.storeFrom(s,c),i+=o,n-=o}return Z.ok(W)}getPages(e,t,r){if(0===t)return Z.ok([]);const s=Lo.fromStartAndLength(e,t),i=Ko.fromMemoryRange(s),n=[];for(const e of i){if(e<16)return Z.error(Oo.fromPageNumber(e,!0));const t=this.memory.get(e);if(void 0===t)return Z.error(Oo.fromPageNumber(e));if(r===$o.WRITE&&!t.isWriteable())return Z.error(Oo.fromPageNumber(e,!0));n.push(t)}return Z.ok(n)}loadInto(e,t){if(0===e.length)return Z.ok(W);const r=this.getPages(t,e.length,$o.READ);if(r.isError)return Z.error(r.error);const s=r.ok;let i=t,n=e.length;for(const r of s){const s=Eo(i%$n),o=Math.min($n-s,n),a=i-t,c=e.subarray(a);r.loadInto(c,s,o),i+=o,n-=o}return Z.ok(W)}sbrk(e){const t=this.sbrkIndex,r=this.virtualSbrkIndex;if(Vn<r+e||r+e>this.endHeapIndex)throw new Po;const s=Jn(this.virtualSbrkIndex+e);if(s<=t)return this.virtualSbrkIndex=s,r;const i=Jn(xo(s)),n=_o(t),o=(i-t)/$n,a=Ko.fromStartAndLength(n,o);for(const e of a){const t=new Fo(e);this.memory.set(e,t)}return this.virtualSbrkIndex=s,this.sbrkIndex=i,r}getPageDump(e){const t=this.memory.get(e);return t?.getPageDump()??null}getDirtyPages(){return this.memory.keys()}}class Go{initialMemory=new Map;isFinalized=!1;ensureNotFinalized(){if(this.isFinalized)throw new No}ensureNoReservedMemoryUsage(e){if(e.overlapsWith(Ho))throw new Do}setReadablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),Q(e<t,"end has to be bigger than start"),Q(e%$n===0,"start needs to be a multiple of page size (4096)"),Q(t%$n===0,"end needs to be a multiple of page size (4096)"),Q(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=Lo.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(Ko.fromMemoryRange(i)),o=n.length;for(let e=0;e<o;e++){const t=n[e],s=r.subarray(e*$n,(e+1)*$n),i=new Vo(t,s);this.initialMemory.set(t,i)}return this}setWriteablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),Q(e<t,"end has to be bigger than start"),Q(e%$n===0,"start needs to be a multiple of page size (4096)"),Q(t%$n===0,"end needs to be a multiple of page size (4096)"),Q(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=Lo.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(Ko.fromMemoryRange(i)),o=n.length;for(let e=0;e<o;e++){const t=n[e],s=r.subarray(e*$n,(e+1)*$n),i=new Fo(t,s);this.initialMemory.set(t,i)}return this}setData(e,t){this.ensureNotFinalized();const r=$n-e%$n;Q(t.length<=r,"The data has to fit into a single page.");const s=t.length,i=Lo.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=_o(e),o=this.initialMemory.get(n);if(void 0===o)throw new Mo;const a=Eo(e-o.start);return o.setData(a,t),this}finalize(e,t){Q(e<=t,`startHeapIndex (${e}) has to be less than or equal to endHeapIndex (${t})`),this.ensureNotFinalized();const r=Lo.fromStartAndLength(e,t-e),s=Ko.fromMemoryRange(r);for(const e of s)if(this.initialMemory.has(e))throw new To;const i=jo.fromInitialMemory({memory:this.initialMemory,sbrkIndex:Jn(e),endHeapIndex:t});return this.isFinalized=!0,i}}class qo{mathOps;shiftOps;bitOps;booleanOps;moveOps;bitRotationOps;constructor(e,t,r,s,i,n){this.mathOps=e,this.shiftOps=t,this.bitOps=r,this.booleanOps=s,this.moveOps=i,this.bitRotationOps=n}dispatch(e,t){switch(e){case ho.ADD_32:this.mathOps.addU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.ADD_64:this.mathOps.addU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MUL_32:this.mathOps.mulU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MUL_64:this.mathOps.mulU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MUL_UPPER_U_U:this.mathOps.mulUpperUU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MUL_UPPER_S_S:this.mathOps.mulUpperSS(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MUL_UPPER_S_U:this.mathOps.mulUpperSU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SUB_32:this.mathOps.subU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SUB_64:this.mathOps.subU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.DIV_S_32:this.mathOps.divSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.DIV_S_64:this.mathOps.divSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.DIV_U_32:this.mathOps.divUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.DIV_U_64:this.mathOps.divUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.REM_S_32:this.mathOps.remSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.REM_S_64:this.mathOps.remSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.REM_U_32:this.mathOps.remUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.REM_U_64:this.mathOps.remUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SHLO_L_32:this.shiftOps.shiftLogicalLeftU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SHLO_L_64:this.shiftOps.shiftLogicalLeftU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SHLO_R_32:this.shiftOps.shiftLogicalRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SHLO_R_64:this.shiftOps.shiftLogicalRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SHAR_R_32:this.shiftOps.shiftArithmeticRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SHAR_R_64:this.shiftOps.shiftArithmeticRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.OR:this.bitOps.or(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.AND:this.bitOps.and(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.XOR:this.bitOps.xor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SET_LT_S:this.booleanOps.setLessThanSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.SET_LT_U:this.booleanOps.setLessThanUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.CMOV_IZ:this.moveOps.cmovIfZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.CMOV_NZ:this.moveOps.cmovIfNotZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.ROT_L_64:this.bitRotationOps.rotL64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.ROT_L_32:this.bitRotationOps.rotL32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.ROT_R_64:this.bitRotationOps.rotR64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.ROT_R_32:this.bitRotationOps.rotR32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.AND_INV:this.bitOps.andInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.OR_INV:this.bitOps.orInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.XNOR:this.bitOps.xnor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MAX:this.mathOps.max(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MAX_U:this.mathOps.maxU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MIN:this.mathOps.min(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case ho.MIN_U:this.mathOps.minU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex)}}}class zo{mathOps;shiftOps;bitOps;booleanOps;moveOps;storeOps;loadOps;bitRotationOps;constructor(e,t,r,s,i,n,o,a){this.mathOps=e,this.shiftOps=t,this.bitOps=r,this.booleanOps=s,this.moveOps=i,this.storeOps=n,this.loadOps=o,this.bitRotationOps=a}dispatch(e,t){switch(e){case ho.ADD_IMM_32:this.mathOps.addImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.ADD_IMM_64:this.mathOps.addImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.MUL_IMM_32:this.mathOps.mulImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.MUL_IMM_64:this.mathOps.mulImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.NEG_ADD_IMM_32:this.mathOps.negAddImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.NEG_ADD_IMM_64:this.mathOps.negAddImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_L_IMM_32:this.shiftOps.shiftLogicalLeftImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_L_IMM_64:this.shiftOps.shiftLogicalLeftImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_L_IMM_ALT_32:this.shiftOps.shiftLogicalLeftImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_L_IMM_ALT_64:this.shiftOps.shiftLogicalLeftImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_R_IMM_32:this.shiftOps.shiftLogicalRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_R_IMM_64:this.shiftOps.shiftLogicalRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_R_IMM_ALT_32:this.shiftOps.shiftLogicalRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHLO_R_IMM_ALT_64:this.shiftOps.shiftLogicalRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHAR_R_IMM_32:this.shiftOps.shiftArithmeticRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHAR_R_IMM_64:this.shiftOps.shiftArithmeticRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHAR_R_IMM_ALT_32:this.shiftOps.shiftArithmeticRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SHAR_R_IMM_ALT_64:this.shiftOps.shiftArithmeticRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.OR_IMM:this.bitOps.orImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.AND_IMM:this.bitOps.andImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.XOR_IMM:this.bitOps.xorImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SET_LT_S_IMM:this.booleanOps.setLessThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SET_LT_U_IMM:this.booleanOps.setLessThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SET_GT_S_IMM:this.booleanOps.setGreaterThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.SET_GT_U_IMM:this.booleanOps.setGreaterThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.CMOV_IZ_IMM:this.moveOps.cmovIfZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.CMOV_NZ_IMM:this.moveOps.cmovIfNotZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.STORE_IND_U8:this.storeOps.storeIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.STORE_IND_U16:this.storeOps.storeIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.STORE_IND_U32:this.storeOps.storeIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.STORE_IND_U64:this.storeOps.storeIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_U8:this.loadOps.loadIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_U16:this.loadOps.loadIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_U32:this.loadOps.loadIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_U64:this.loadOps.loadIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_I8:this.loadOps.loadIndI8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_I16:this.loadOps.loadIndI16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.LOAD_IND_I32:this.loadOps.loadIndI32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case ho.ROT_R_64_IMM:this.bitRotationOps.rotR64Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.ROT_R_64_IMM_ALT:this.bitRotationOps.rotR64ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.ROT_R_32_IMM:this.bitRotationOps.rotR32Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case ho.ROT_R_32_IMM_ALT:this.bitRotationOps.rotR32ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex)}}}class Wo{moveOps;memoryOps;bitOps;bitRotationOps;constructor(e,t,r,s){this.moveOps=e,this.memoryOps=t,this.bitOps=r,this.bitRotationOps=s}dispatch(e,t){switch(e){case ho.MOVE_REG:this.moveOps.moveRegister(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.SBRK:this.memoryOps.sbrk(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.COUNT_SET_BITS_64:this.bitOps.countSetBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.COUNT_SET_BITS_32:this.bitOps.countSetBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.LEADING_ZERO_BITS_64:this.bitOps.leadingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.LEADING_ZERO_BITS_32:this.bitOps.leadingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.TRAILING_ZERO_BITS_64:this.bitOps.trailingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.TRAILING_ZERO_BITS_32:this.bitOps.trailingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.SIGN_EXTEND_8:this.bitOps.signExtend8(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.SIGN_EXTEND_16:this.bitOps.signExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.ZERO_EXTEND_16:this.bitOps.zeroExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case ho.REVERSE_BYTES:this.bitRotationOps.reverseBytes(t.firstRegisterIndex,t.secondRegisterIndex)}}}class Jo{branchOps;loadOps;constructor(e,t){this.branchOps=e,this.loadOps=t}dispatch(e,t){switch(e){case ho.LOAD_IMM_JUMP:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder),this.branchOps.jump(t.nextPc);break;case ho.BRANCH_EQ_IMM:this.branchOps.branchEqImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_NE_IMM:this.branchOps.branchNeImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_LT_U_IMM:this.branchOps.branchLtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_LE_U_IMM:this.branchOps.branchLeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_GE_U_IMM:this.branchOps.branchGeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_GT_U_IMM:this.branchOps.branchGtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_LT_S_IMM:this.branchOps.branchLtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_LE_S_IMM:this.branchOps.branchLeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_GE_S_IMM:this.branchOps.branchGeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case ho.BRANCH_GT_S_IMM:this.branchOps.branchGtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc)}}}class Yo{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){switch(e){case ho.BRANCH_EQ:this.branchOps.branchEq(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case ho.BRANCH_NE:this.branchOps.branchNe(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case ho.BRANCH_LT_U:this.branchOps.branchLtUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case ho.BRANCH_LT_S:this.branchOps.branchLtSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case ho.BRANCH_GE_U:this.branchOps.branchGeUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case ho.BRANCH_GE_S:this.branchOps.branchGeSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc)}}}class Xo{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){e===ho.JUMP&&this.branchOps.jump(t.nextPc)}}class Zo{loadOps;storeOps;dynamicJumpOps;constructor(e,t,r){this.loadOps=e,this.storeOps=t,this.dynamicJumpOps=r}dispatch(e,t){switch(e){case ho.LOAD_IMM:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder);break;case ho.STORE_U8:this.storeOps.storeU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.STORE_U16:this.storeOps.storeU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.STORE_U32:this.storeOps.storeU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.STORE_U64:this.storeOps.storeU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_U8:this.loadOps.loadU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_U16:this.loadOps.loadU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_U32:this.loadOps.loadU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_U64:this.loadOps.loadU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_I8:this.loadOps.loadI8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_I16:this.loadOps.loadI16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.LOAD_I32:this.loadOps.loadI32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case ho.JUMP_IND:{const e=this.dynamicJumpOps.caluclateJumpAddress(t.immediateDecoder,t.registerIndex);this.dynamicJumpOps.jumpInd(e);break}}}}class ea{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case ho.STORE_IMM_IND_U8:this.storeOps.storeImmediateIndU8(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case ho.STORE_IMM_IND_U16:this.storeOps.storeImmediateIndU16(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case ho.STORE_IMM_IND_U32:this.storeOps.storeImmediateIndU32(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case ho.STORE_IMM_IND_U64:this.storeOps.storeImmediateIndU64(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder)}}}class ta{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case ho.STORE_IMM_U8:this.storeOps.storeImmediateU8(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case ho.STORE_IMM_U16:this.storeOps.storeImmediateU16(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case ho.STORE_IMM_U32:this.storeOps.storeImmediateU32(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case ho.STORE_IMM_U64:this.storeOps.storeImmediateU64(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder)}}}class ra{noArgsOps;constructor(e){this.noArgsOps=e}dispatch(e){switch(e){case ho.TRAP:this.noArgsOps.trap();break;case ho.FALLTHROUGH:this.noArgsOps.fallthrough()}}}class sa{loadOps;dynamicJumpOps;constructor(e,t){this.loadOps=e,this.dynamicJumpOps=t}dispatch(e,t){switch(e){case ho.LOAD_IMM_JUMP_IND:{const e=this.dynamicJumpOps.caluclateJumpAddress(t.secondImmediateDecoder,t.secondRegisterIndex);this.loadOps.loadImmediate(t.firstRegisterIndex,t.firstImmediateDecoder),this.dynamicJumpOps.jumpInd(e);break}}}}class ia{hostCallOps;constructor(e){this.hostCallOps=e}dispatch(e,t){e===ho.ECALLI&&this.hostCallOps.hostCall(t.immediateDecoder)}}class na{loadOps;constructor(e){this.loadOps=e}dispatch(e,t){e===ho.LOAD_IMM_64&&this.loadOps.loadImmediateU64(t.registerIndex,t.immediateDecoder)}}class oa{regs;constructor(e){this.regs=e}or(e,t,r){this.regs.setU64(r,this.regs.getU64(e)|this.regs.getU64(t))}orImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)|t.getU64())}and(e,t,r){this.regs.setU64(r,this.regs.getU64(e)&this.regs.getU64(t))}andImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)&t.getU64())}xor(e,t,r){this.regs.setU64(r,this.regs.getU64(e)^this.regs.getU64(t))}xorImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)^t.getU64())}andInv(e,t,r){this.regs.setU64(r,this.regs.getU64(e)&~this.regs.getU64(t))}orInv(e,t,r){this.regs.setU64(r,this.regs.getU64(e)|~this.regs.getU64(t))}xnor(e,t,r){this.regs.setU64(r,this.regs.getU64(e)^~this.regs.getU64(t))}countSetBits64(e,t){this.regs.setU32(t,function(e){let t=e;return t-=t>>1n&0x5555555555555555n,t=(0x3333333333333333n&t)+(t>>2n&0x3333333333333333n),t=t+(t>>4n)&0x0f0f0f0f0f0f0f0fn,t+=t>>8n,t+=t>>16n,t+=t>>32n,Number(0x7fn&t)}(this.regs.getU64(e)))}countSetBits32(e,t){this.regs.setU32(t,function(e){let t=e;return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,63&t}(this.regs.getLowerU32(e)))}leadingZeroBits64(e,t){this.regs.setU32(t,function(e){const t=Number(e>>32n),r=Number(0xffffffffn&e),s=Math.clz32(t);return s<32?s:s+Math.clz32(r)}(this.regs.getU64(e)))}leadingZeroBits32(e,t){this.regs.setU32(t,Math.clz32(this.regs.getLowerU32(e)))}trailingZeroBits64(e,t){this.regs.setU32(t,function(e){if(0n===e)return 64;let t=e,r=0;for(;0n==(1n&t);)r++,t>>=1n;return r}(this.regs.getU64(e)))}trailingZeroBits32(e,t){this.regs.setU32(t,function(e){if(0===e)return 32;let t=e,r=0;for(;!(1&t);)r++,t>>>=1;return r}(this.regs.getLowerU32(e)))}signExtend(e,t){const r=2**t-1,s=e&r;return(s&1<<t-1)>0?~BigInt(r)|BigInt(s):BigInt(s)}signExtend8(e,t){const r=this.signExtend(this.regs.getLowerU32(e),8);this.regs.setU64(t,r)}signExtend16(e,t){const r=this.signExtend(this.regs.getLowerU32(e),16);this.regs.setU64(t,r)}zeroExtend16(e,t){const r=0x000000000000ffffn&this.regs.getU64(e);this.regs.setU64(t,r)}}const aa=4294967295,ca=-(2**31),la=32,ha=64n;function ua(e,t){return e>aa-t?aa-(aa-e+(aa-t))-1:e+t}function da(e,t){return(e+t)%2n**64n}function fa(e,t){return t>e?aa-t+e+1:e-t}function pa(e,t){return(2n**64n+e-t)%2n**64n}function ga(e,t){if(e>65536||t>65536){const r=65535&e,s=65535&t,i=r*s;return 65535&i|(i>>16)+(65535&r*(t>>16))+(65535&(e>>16)*s)<<16}return e*t}function ya(e,t){return e*t%2n**64n}function ma(e){return e>=1n<<63n?e-(1n<<64n):e}function ba(e,t){return(0xffffffffffffffffn&e)*(0xffffffffffffffffn&t)>>64n&0xffffffffffffffffn}function Aa(e,t){return ma(0xffffffffffffffffn&e*t>>64n)}function Ia(e,t){Q(t>=0,"Shift count must be non-negative");const r=e<0?"1":"0",s=e.toString(2).padStart(64,r);return(e<0n?(1n<<BigInt(s.length))+e:e)>>t}function va(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t>e?t:e)}function wa(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t<e?t:e)}class Sa{regs;constructor(e){this.regs=e}shiftLogicalLeftU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<this.regs.getLowerU32(t)%la)}shiftLogicalLeftU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<this.regs.getU64(t)%ha)}shiftLogicalRightU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>this.regs.getLowerU32(t)%la)}shiftLogicalRightU64(e,t,r){this.regs.setU64(r,Ia(this.regs.getU64(e),this.regs.getU64(t)%ha))}shiftArithmeticRightU32(e,t,r){this.regs.setI32(r,this.regs.getLowerI32(e)>>this.regs.getLowerU32(t)%la)}shiftArithmeticRightU64(e,t,r){this.regs.setI64(r,this.regs.getI64(e)>>this.regs.getU64(t)%ha)}shiftLogicalLeftImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<t.getU32()%la)}shiftLogicalLeftImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<t.getU64()%ha)}shiftLogicalRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>t.getU32()%la)}shiftLogicalRightImmediateU64(e,t,r){this.regs.setU64(r,Ia(this.regs.getU64(e),t.getU64()%ha))}shiftArithmeticRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerI32(e)>>t.getU32()%la)}shiftArithmeticRightImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getI64(e)>>t.getU64()%ha)}shiftLogicalLeftImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()<<this.regs.getLowerU32(e)%la)}shiftLogicalLeftImmediateAlternativeU64(e,t,r){this.regs.setU64(r,t.getU64()<<this.regs.getU64(e)%ha)}shiftLogicalRightImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()>>>this.regs.getLowerU32(e)%la)}shiftLogicalRightImmediateAlternativeU64(e,t,r){this.regs.setU64(r,Ia(t.getU64(),this.regs.getU64(e)%ha))}shiftArithmeticRightImmediateAlternativeU32(e,t,r){this.regs.setI32(r,t.getU32()>>this.regs.getLowerU32(e)%la)}shiftArithmeticRightImmediateAlternativeU64(e,t,r){this.regs.setI64(r,t.getI64()>>this.regs.getU64(e)%ha)}}class Ea{regs;constructor(e){this.regs=e}addU32(e,t,r){this.regs.setU64(r,no(ua(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}addU64(e,t,r){this.regs.setU64(r,da(this.regs.getU64(e),this.regs.getU64(t)))}addImmediateU32(e,t,r){this.regs.setU64(r,no(ua(this.regs.getLowerU32(e),t.getU32())))}addImmediateU64(e,t,r){this.regs.setU64(r,da(this.regs.getU64(e),t.getU64()))}mulU32(e,t,r){this.regs.setU64(r,no(ga(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}mulU64(e,t,r){this.regs.setU64(r,ya(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperUU(e,t,r){this.regs.setU64(r,ba(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperSS(e,t,r){this.regs.setI64(r,Aa(this.regs.getI64(e),this.regs.getI64(t)))}mulUpperSU(e,t,r){this.regs.setI64(r,ma(0xffffffffffffffffn&this.regs.getI64(e)*(0xffffffffffffffffn&this.regs.getU64(t))>>64n))}mulImmediateU32(e,t,r){this.regs.setU64(r,no(ga(this.regs.getLowerU32(e),t.getU32())))}mulImmediateU64(e,t,r){this.regs.setU64(r,ya(this.regs.getU64(e),t.getU64()))}mulUpperSSImmediate(e,t,r){this.regs.setI64(r,Aa(this.regs.getI64(e),t.getI64()))}mulUpperUUImmediate(e,t,r){this.regs.setU64(r,ba(this.regs.getU64(e),t.getU64()))}subU32(e,t,r){this.regs.setU64(r,no(fa(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}subU64(e,t,r){this.regs.setU64(r,pa(this.regs.getU64(e),this.regs.getU64(t)))}negAddImmediateU32(e,t,r){this.regs.setU64(r,no(fa(t.getU32(),this.regs.getLowerU32(e))))}negAddImmediateU64(e,t,r){this.regs.setU64(r,pa(t.getU64(),this.regs.getU64(e)))}divSignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,2n**64n-1n):-1===this.regs.getLowerI32(t)&&this.regs.getLowerI32(e)===ca?this.regs.setU64(r,no(this.regs.getLowerU32(e))):this.regs.setI64(r,no(~~(this.regs.getLowerI32(e)/this.regs.getLowerI32(t))))}divSignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,2n**64n-1n):-1n===this.regs.getI64(t)&&this.regs.getI64(e)===-(2n**63n)?this.regs.setU64(r,this.regs.getU64(e)):this.regs.setI64(r,~~(this.regs.getI64(e)/this.regs.getI64(t)))}divUnsignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,2n**64n-1n):this.regs.setU64(r,no(~~(this.regs.getLowerU32(e)/this.regs.getLowerU32(t))))}divUnsignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,2n**64n-1n):this.regs.setU64(r,~~(this.regs.getU64(e)/this.regs.getU64(t)))}remSignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,BigInt(this.regs.getLowerI32(e))):-1===this.regs.getLowerI32(t)&&this.regs.getLowerI32(e)===ca?this.regs.setU64(r,0n):this.regs.setI64(r,no(this.regs.getLowerI32(e)%this.regs.getLowerI32(t)))}remSignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,this.regs.getU64(e)):-1n===this.regs.getI64(t)&&this.regs.getI64(e)===-(2n**63n)?this.regs.setU64(r,0n):this.regs.setI64(r,this.regs.getI64(e)%this.regs.getI64(t))}remUnsignedU32(e,t,r){0===this.regs.getLowerU32(t)?this.regs.setU64(r,no(this.regs.getLowerU32(e))):this.regs.setU64(r,no(this.regs.getLowerU32(e)%this.regs.getLowerU32(t)))}remUnsignedU64(e,t,r){0n===this.regs.getU64(t)?this.regs.setU64(r,this.regs.getU64(e)):this.regs.setU64(r,this.regs.getU64(e)%this.regs.getU64(t))}max(e,t,r){this.regs.setI64(r,va(this.regs.getI64(e),this.regs.getI64(t)))}maxU(e,t,r){this.regs.setU64(r,va(this.regs.getU64(e),this.regs.getU64(t)))}min(e,t,r){this.regs.setI64(r,wa(this.regs.getI64(e),this.regs.getI64(t)))}minU(e,t,r){this.regs.setU64(r,wa(this.regs.getU64(e),this.regs.getU64(t)))}}class Ca{regs;constructor(e){this.regs=e}setLessThanSignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getI64(e)<t.getI64()?1n:0n)}setLessThanUnsignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<t.getU64()?1n:0n)}setLessThanSigned(e,t,r){this.regs.setU64(r,this.regs.getI64(e)<this.regs.getI64(t)?1n:0n)}setLessThanUnsigned(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<this.regs.getU64(t)?1n:0n)}setGreaterThanSignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getI64(e)>t.getI64()?1n:0n)}setGreaterThanUnsignedImmediate(e,t,r){this.regs.setU64(r,this.regs.getU64(e)>t.getU64()?1n:0n)}}class ka{regs;constructor(e){this.regs=e}cmovIfZeroImmediate(e,t,r){0n===this.regs.getU64(e)&&this.regs.setU64(r,t.getU64())}cmovIfNotZeroImmediate(e,t,r){0n!==this.regs.getU64(e)&&this.regs.setU64(r,t.getU64())}cmovIfZero(e,t,r){0n===this.regs.getU64(t)&&this.regs.setU64(r,this.regs.getU64(e))}cmovIfNotZero(e,t,r){0n!==this.regs.getU64(t)&&this.regs.setU64(r,this.regs.getU64(e))}moveRegister(e,t){this.regs.setU64(t,this.regs.getU64(e))}}var xa,_a;(_a=xa||(xa={}))[_a.HALT=0]="HALT",_a[_a.PANIC=1]="PANIC",_a[_a.FAULT_ACCESS=2]="FAULT_ACCESS",_a[_a.FAULT=3]="FAULT",_a[_a.HOST=4]="HOST";class Ba{regs;instructionResult;basicBlocks;constructor(e,t,r){this.regs=e,this.instructionResult=t,this.basicBlocks=r}setBasicBlocks(e){this.basicBlocks=e}branch(e,t){t&&(this.basicBlocks.isBeginningOfBasicBlock(e)?this.instructionResult.nextPc=e:this.instructionResult.status=xa.PANIC)}jump(e){this.branch(e,!0)}branchEqImmediate(e,t,r){this.branch(r,this.regs.getU64(e)===t.getU64())}branchEq(e,t,r){this.branch(r,this.regs.getU64(e)===this.regs.getU64(t))}branchNeImmediate(e,t,r){this.branch(r,this.regs.getU64(e)!==t.getU64())}branchNe(e,t,r){this.branch(r,this.regs.getU64(e)!==this.regs.getU64(t))}branchLtUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)<t.getU64())}branchLtUnsigned(e,t,r){this.branch(r,this.regs.getU64(e)<this.regs.getU64(t))}branchLeUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)<=t.getU64())}branchGtUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)>t.getU64())}branchGeUnsignedImmediate(e,t,r){this.branch(r,this.regs.getU64(e)>=t.getU64())}branchGeUnsigned(e,t,r){this.branch(r,this.regs.getU64(e)>=this.regs.getU64(t))}branchLtSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)<t.getI64())}branchLtSigned(e,t,r){this.branch(r,this.regs.getI64(e)<this.regs.getI64(t))}branchLeSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)<=t.getI64())}branchGtSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)>t.getI64())}branchGeSignedImmediate(e,t,r){this.branch(r,this.regs.getI64(e)>=t.getI64())}branchGeSigned(e,t,r){this.branch(r,this.regs.getI64(e)>=this.regs.getI64(t))}}class Ra{regs;memory;instructionResult;constructor(e,t,r){this.regs=e,this.memory=t,this.instructionResult=r}loadImmediate(e,t){this.regs.setU64(e,t.getU64())}loadImmediateU64(e,t){this.regs.setU64(e,t.getValue())}loadNumber(e,t,r){const s=this.regs.getBytesAsLittleEndian(t,8),i=this.memory.loadInto(s.subarray(0,r),Wn(e));i.isError?i.error.isAccessFault?this.instructionResult.status=xa.FAULT_ACCESS:(this.instructionResult.status=xa.FAULT,this.instructionResult.exitParam=e):s.fill(0,r)}loadSignedNumber(e,t,r){const s=this.regs.getBytesAsLittleEndian(t,8),i=this.memory.loadInto(s.subarray(0,r),Wn(e));i.isError?i.error.isAccessFault?this.instructionResult.status=xa.FAULT_ACCESS:(this.instructionResult.status=xa.FAULT,this.instructionResult.exitParam=e):(128&s[r-1])>0?s.fill(255,r):s.fill(0,r)}loadU8(e,t){this.loadNumber(e,t,1)}loadU16(e,t){this.loadNumber(e,t,2)}loadU32(e,t){this.loadNumber(e,t,4)}loadU64(e,t){this.loadNumber(e,t,8)}loadI8(e,t){this.loadSignedNumber(e,t,1)}loadI16(e,t){this.loadSignedNumber(e,t,2)}loadI32(e,t){this.loadSignedNumber(e,t,4)}loadIndU8(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,1)}loadIndU16(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,2)}loadIndU32(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,4)}loadIndU64(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,8)}loadIndI8(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,1)}loadIndI16(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,2)}loadIndI32(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,4)}}class Oa{regs;memory;instructionResult;constructor(e,t,r){this.regs=e,this.memory=t,this.instructionResult=r}storeU8(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,1))}storeU16(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,2))}storeU32(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,4))}storeU64(e,t){this.store(e,this.regs.getBytesAsLittleEndian(t,8))}storeIndU8(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,1))}storeIndU16(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,2))}storeIndU32(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,4))}storeIndU64(e,t,r){const s=ua(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,8))}storeImmediateU8(e,t){this.store(e,t.getBytesAsLittleEndian().subarray(0,1))}storeImmediateU16(e,t){this.store(e,t.getBytesAsLittleEndian().subarray(0,2))}storeImmediateU32(e,t){this.store(e,t.getBytesAsLittleEndian().subarray(0,4))}storeImmediateU64(e,t){this.store(e,t.getExtendedBytesAsLittleEndian())}storeImmediateIndU8(e,t,r){const s=ua(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,1))}storeImmediateIndU16(e,t,r){const s=ua(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,2))}storeImmediateIndU32(e,t,r){const s=ua(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,4))}storeImmediateIndU64(e,t,r){const s=ua(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getExtendedBytesAsLittleEndian())}store(e,t){const r=this.memory.storeFrom(Wn(e),t);r.isOk||(r.error.isAccessFault?this.instructionResult.status=xa.FAULT_ACCESS:(this.instructionResult.status=xa.FAULT,this.instructionResult.exitParam=Bo(r.error.address)))}}class Ua{instructionResult;constructor(e){this.instructionResult=e}trap(){this.instructionResult.status=xa.PANIC}fallthrough(){}}class Ta{regs;jumpTable;instructionResult;basicBlocks;constructor(e,t,r,s){this.regs=e,this.jumpTable=t,this.instructionResult=r,this.basicBlocks=s}djump(e){if(4294901760===e)return void(this.instructionResult.status=xa.HALT);if(0===e||e%2!=0)return void(this.instructionResult.status=xa.PANIC);const t=e/2-1;if(!this.jumpTable.hasIndex(t))return void(this.instructionResult.status=xa.PANIC);const r=this.jumpTable.getDestination(t);this.basicBlocks.isBeginningOfBasicBlock(r)?this.instructionResult.nextPc=r:this.instructionResult.status=xa.PANIC}caluclateJumpAddress(e,t){return ua(this.regs.getLowerU32(t),e.getU32())}jumpInd(e){this.djump(e)}}class Na{instructionResult;constructor(e){this.instructionResult=e}hostCall(e){this.instructionResult.status=xa.HOST,this.instructionResult.exitParam=e.getUnsigned()}}class Da{regs;memory;instructionResult;constructor(e,t,r){this.regs=e,this.memory=t,this.instructionResult=r}sbrk(e,t){try{this.regs.setU32(t,this.memory.sbrk(this.regs.getLowerU32(e)))}catch{this.instructionResult.status=xa.FAULT}}}class Ma{regs;constructor(e){this.regs=e}reverseBytes(e,t){const r=this.regs.getU64(e);let s=0n;for(let e=0;e<8;e++)s=s<<8n|r>>BigInt(8*e)&0xffn;this.regs.setU64(t,s)}rotate32Left(e,t){const r=t%32,s=2**32-1;return(e<<r&s|e>>>32-r)>>>0&s}rotate64Left(e,t){const r=t%64,s=(1n<<64n)-1n;return(e<<BigInt(r)&s|Ia(e,BigInt(64-r)))&s}rotate32Right(e,t){const r=t%32,s=2**32-1;return(e>>>r|e<<32-r&s)&s}rotate64Right(e,t){const r=t%64,s=(1n<<64n)-1n;return(Ia(e,BigInt(r))|e<<BigInt(64-r)&s)&s}rotR64Imm(e,t,r){const s=t.getU32(),i=this.regs.getU64(e);this.regs.setU64(r,this.rotate64Right(i,s))}rotR64ImmAlt(e,t,r){const s=this.regs.getLowerU32(e),i=t.getU64();this.regs.setU64(r,this.rotate64Right(i,s))}rotR32Imm(e,t,r){const s=t.getU32(),i=this.regs.getLowerU32(e);this.regs.setU32(r,this.rotate32Right(i,s))}rotR32ImmAlt(e,t,r){const s=this.regs.getLowerU32(e),i=t.getU32();this.regs.setU32(r,this.rotate32Right(i,s))}rotL64(e,t,r){const s=this.regs.getU64(e),i=this.regs.getLowerU32(t);this.regs.setU64(r,this.rotate64Left(s,i))}rotL32(e,t,r){const s=this.regs.getLowerU32(e),i=this.regs.getLowerU32(t);this.regs.setU32(r,this.rotate32Left(s,i))}rotR64(e,t,r){const s=this.regs.getU64(e),i=this.regs.getLowerU32(t);this.regs.setU64(r,this.rotate64Right(s,i))}rotR32(e,t,r){const s=this.regs.getLowerU32(e),i=this.regs.getLowerU32(t);this.regs.setU32(r,this.rotate32Right(s,i))}}class Pa{indices;constructor(e,t){Q(0===e||t.length%e===0,`Length of jump table (${t.length}) should be a multiple of item lenght (${e})!`);const r=0===e?0:t.length/e;this.indices=new Uint32Array(r);for(let s=0;s<r;s++)this.indices[s]=this.decodeNext(t.subarray(s*e,(s+1)*e))}decodeNext(e){const t=e.length;let r=0;for(let s=0;s<t;s++){if((4278190080&r)>0)return 2**32-1;r<<=8,r|=e[t-s-1]}return r}hasIndex(e){return e<this.indices.length&&e>=0}getDestination(e){return this.indices[e]}static empty(){return new Pa(0,new Uint8Array)}copyFrom(e){this.indices=e.indices}}const La=m.new(void 0,"pvm-interpreter");var Ha;!function(e){e[e.InvalidProgramError=0]="InvalidProgramError"}(Ha||(Ha={}));class Ka{code;mask;jumpTable;constructor(e){const{code:t,mask:r,jumpTable:s,jumpTableItemLength:i}=this.decodeProgram(e);this.code=new Uint8Array(t),this.mask=new ro(r),this.jumpTable=new Pa(i,s)}decodeProgram(e){const t=xe.fromBlob(e),r=t.varU32(),s=t.u8(),i=t.varU32(),n=r*s,o=t.bytes(n).raw,a=t.bytes(i).raw,c=t.bitVecFixLen(i);return t.finish(),{mask:c,code:a,jumpTableItemLength:s,jumpTable:o}}getMask(){return this.mask}getCode(){return this.code}getJumpTable(){return this.jumpTable}static deblob(e){try{return Z.ok(new Ka(e))}catch(e){return La.error(`Invalid program: ${e}`),Z.error(Ha.InvalidProgramError)}}}class Qa{useSbrkGas;registers=new io;code=new Uint8Array;mask=ro.empty();pc=0;gas=mo(yo(0));initialGas=mo(yo(0));argsDecoder;threeRegsDispatcher;twoRegsOneImmDispatcher;twoRegsDispatcher;oneRegOneImmOneOffsetDispatcher;twoRegsOneOffsetDispatcher;oneOffsetDispatcher;oneRegOneImmDispatcher;instructionResult=new So;memory=new jo;twoImmsDispatcher;oneRegTwoImmsDispatcher;noArgsDispatcher;twoRegsTwoImmsDispatcher;oneImmDispatcher;oneRegOneExtImmDispatcher;status=Yn.OK;argsDecodingResults=(()=>{const e=new Array(lo);return e[to.NO_ARGUMENTS]={type:to.NO_ARGUMENTS,noOfBytesToSkip:1},e[to.ONE_IMMEDIATE]={type:to.ONE_IMMEDIATE,noOfBytesToSkip:1,immediateDecoder:new so},e[to.TWO_REGISTERS]={type:to.TWO_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0},e[to.THREE_REGISTERS]={type:to.THREE_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,thirdRegisterIndex:0},e[to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET]={type:to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new so,nextPc:0},e[to.TWO_REGISTERS_ONE_OFFSET]={type:to.TWO_REGISTERS_ONE_OFFSET,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,nextPc:0},e[to.TWO_REGISTERS_ONE_IMMEDIATE]={type:to.TWO_REGISTERS_ONE_IMMEDIATE,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,immediateDecoder:new so},e[to.ONE_REGISTER_ONE_IMMEDIATE]={type:to.ONE_REGISTER_ONE_IMMEDIATE,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new so},e[to.ONE_REGISTER_TWO_IMMEDIATES]={type:to.ONE_REGISTER_TWO_IMMEDIATES,noOfBytesToSkip:1,registerIndex:0,firstImmediateDecoder:new so,secondImmediateDecoder:new so},e[to.ONE_OFFSET]={type:to.ONE_OFFSET,noOfBytesToSkip:1,nextPc:0},e[to.TWO_IMMEDIATES]={type:to.TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new so,secondImmediateDecoder:new so},e[to.TWO_REGISTERS_TWO_IMMEDIATES]={type:to.TWO_REGISTERS_TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new so,secondImmediateDecoder:new so,firstRegisterIndex:0,secondRegisterIndex:0},e[to.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE]={type:to.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,noOfBytesToSkip:9,registerIndex:0,immediateDecoder:new co},e})();basicBlocks;jumpTable=Pa.empty();constructor(e=!1){this.useSbrkGas=e,this.argsDecoder=new ao,this.basicBlocks=new vo;const t=new Ea(this.registers),r=new Sa(this.registers),s=new oa(this.registers),i=new Ca(this.registers),n=new ka(this.registers),o=new Ba(this.registers,this.instructionResult,this.basicBlocks),a=new Ra(this.registers,this.memory,this.instructionResult),c=new Oa(this.registers,this.memory,this.instructionResult),l=new Ua(this.instructionResult),h=new Ta(this.registers,this.jumpTable,this.instructionResult,this.basicBlocks),u=new Na(this.instructionResult),d=new Da(this.registers,this.memory,this.instructionResult),f=new Ma(this.registers);this.threeRegsDispatcher=new qo(t,r,s,i,n,f),this.twoRegsOneImmDispatcher=new zo(t,r,s,i,n,c,a,f),this.twoRegsDispatcher=new Wo(n,d,s,f),this.oneRegOneImmOneOffsetDispatcher=new Jo(o,a),this.twoRegsOneOffsetDispatcher=new Yo(o),this.oneOffsetDispatcher=new Xo(o),this.oneRegOneImmDispatcher=new Zo(a,c,h),this.twoImmsDispatcher=new ta(c),this.oneRegTwoImmsDispatcher=new ea(c),this.noArgsDispatcher=new ra(l),this.twoRegsTwoImmsDispatcher=new sa(a,h),this.oneImmDispatcher=new ia(u),this.oneRegOneExtImmDispatcher=new na(a)}reset(e,t,r,s,i){const n=new Ka(e);this.code=n.getCode(),this.mask=n.getMask(),this.jumpTable.copyFrom(n.getJumpTable()),this.pc=t,this.gas=mo(r),this.initialGas=mo(r),this.status=Yn.OK,this.argsDecoder.reset(this.code,this.mask),this.basicBlocks.reset(this.code,this.mask),this.instructionResult.reset(),void 0!==s?this.registers.copyFrom(s):this.registers.reset(),void 0!==i?this.memory.copyFrom(i):this.memory.reset()}printProgram(){const e=(t=this.code,r=this.mask,t.reduce((e,t,s)=>(r.isInstruction(s)?e.push([ho[t]]):e[e.length-1].push(t),e),[]));var t,r;return console.table(e),e}runProgram(){for(;this.nextStep()===Yn.OK;);}nextStep(){this.status===Yn.HOST&&(this.status=Yn.OK,this.pc=this.instructionResult.nextPc,this.instructionResult.reset());const e=this.code[this.pc]??ho.TRAP,t=void 0!==ho[e],r=wo[e]??wo[ho.TRAP];if(this.gas.sub(r))return this.status=Yn.OOG,this.status;const s=fo[e]??to.NO_ARGUMENTS,i=this.argsDecodingResults[s];if(this.argsDecoder.fillArgs(this.pc,i),t)switch(this.instructionResult.nextPc=this.pc+i.noOfBytesToSkip,i.type){case to.NO_ARGUMENTS:this.noArgsDispatcher.dispatch(e);break;case to.ONE_IMMEDIATE:this.oneImmDispatcher.dispatch(e,i);break;case to.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET:this.oneRegOneImmOneOffsetDispatcher.dispatch(e,i);break;case to.TWO_REGISTERS:if(this.useSbrkGas&&e===ho.SBRK){const e=e=>xo(e)/$n*16;if(this.gas.sub(yo(e(this.registers.getLowerU32(i.firstRegisterIndex)))))return this.status=Yn.OOG,this.status}this.twoRegsDispatcher.dispatch(e,i);break;case to.THREE_REGISTERS:this.threeRegsDispatcher.dispatch(e,i);break;case to.TWO_REGISTERS_ONE_IMMEDIATE:this.twoRegsOneImmDispatcher.dispatch(e,i);break;case to.TWO_REGISTERS_ONE_OFFSET:this.twoRegsOneOffsetDispatcher.dispatch(e,i);break;case to.ONE_OFFSET:this.oneOffsetDispatcher.dispatch(e,i);break;case to.ONE_REGISTER_ONE_IMMEDIATE:this.oneRegOneImmDispatcher.dispatch(e,i);break;case to.TWO_IMMEDIATES:this.twoImmsDispatcher.dispatch(e,i);break;case to.ONE_REGISTER_TWO_IMMEDIATES:this.oneRegTwoImmsDispatcher.dispatch(e,i);break;case to.TWO_REGISTERS_TWO_IMMEDIATES:this.twoRegsTwoImmsDispatcher.dispatch(e,i);break;case to.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE:this.oneRegOneExtImmDispatcher.dispatch(e,i)}else this.instructionResult.status=xa.PANIC;if(null!==this.instructionResult.status){switch(this.instructionResult.status!==xa.FAULT&&this.instructionResult.status!==xa.FAULT_ACCESS||this.gas.sub(wo[ho.TRAP]),this.instructionResult.status){case xa.FAULT:this.status=Yn.FAULT;break;case xa.HALT:this.status=Yn.HALT;break;case xa.PANIC:case xa.FAULT_ACCESS:this.status=Yn.PANIC;break;case xa.HOST:this.status=Yn.HOST}return this.status}return this.pc=this.instructionResult.nextPc,this.status}getRegisters(){return this.registers}getPC(){return this.pc}setNextPC(e){this.pc=e}getGas(){return this.gas.get()}getGasConsumed(){const e=go(this.initialGas.get())-go(this.gas.get());return e<0?this.initialGas.get():go(e)}getGasCounter(){return this.gas}getStatus(){return this.status}getExitParam(){const e=this.instructionResult.exitParam;return null!==e?Ae(e):e}getMemory(){return this.memory}getMemoryPage(e){return this.memory.getPageDump(Co(e))}}class Va{memory;constructor(e){this.memory=e}storeFrom(e,t){return 0===t.length?Z.ok(W):e+ve(t.length)>Fn?Z.error(new Uo):this.memory.storeFrom(Wn(Number(e)),t)}loadInto(e,t){return 0===e.length?Z.ok(W):t+ve(e.length)>Fn?Z.error(new Uo):this.memory.loadInto(e,Wn(Number(t)))}getMemory(){return this.memory}}class Fa{registers;constructor(e){this.registers=e}get(e){return ve(this.registers.getU64(e))}set(e,t){this.registers.setU64(e,t)}}class $a{consumedGas;status;memorySlice;constructor(e,t,r){this.consumedGas=e,this.status=t,this.memorySlice=r,Q(null===t&&null!==r||null!==t&&null===r,"`status` and `memorySlice` must not both be null or both be non-null — exactly one must be provided")}static fromStatus(e,t){return new $a(e,t,null)}static fromMemorySlice(e,t){return new $a(e,null,t)}hasMemorySlice(){return this.memorySlice instanceof Uint8Array&&null===this.status}hasStatus(){return!this.hasMemorySlice()}}class ja{pvmInstanceManager;hostCalls;constructor(e,t){this.pvmInstanceManager=e,this.hostCalls=t}getReturnValue(e,t){const r=t.getGasConsumed();if(e===Yn.OOG)return $a.fromStatus(r,e);if(e===Yn.HALT){const e=t.getMemory(),s=t.getRegisters(),i=s.getLowerU32(10),n=s.getLowerU32(11),o=new Uint8Array(n),a=Wn(i);return null!==e.loadInto(o,a)?$a.fromMemorySlice(r,new Uint8Array):$a.fromMemorySlice(r,o)}return $a.fromStatus(r,Yn.PANIC)}async execute(e){for(e.runProgram();;){let t=e.getStatus();if(t!==Yn.HOST)return this.getReturnValue(t,e);Q(null!==e.getExitParam(),"We know that the exit param is not null, because the status is `Status.HOST`");const r=e.getExitParam()??-1,s=e.getGasCounter(),i=new Fa(e.getRegisters()),n=new Va(e.getMemory()),o=this.hostCalls.get(Zn(r)),a="number"==typeof o.gasCost?o.gasCost:o.gasCost(i);if(s.sub(a))return $a.fromStatus(e.getGasConsumed(),Yn.OOG);if(await o.execute(s,i,n)===eo.Halt)return t=Yn.HALT,this.getReturnValue(t,e);e.runProgram(),t=e.getStatus()}}async runProgram(e,t,r,s,i){const n=await this.pvmInstanceManager.getInstance();n.reset(e,t,r,s,i);try{return await this.execute(n)}finally{this.pvmInstanceManager.releaseInstance(n)}}}class Ga{instances=[];waitingQueue=[];constructor(e){for(let t=0;t<e;t++)this.instances.push(new Qa)}async getInstance(){const e=this.instances.pop();return void 0!==e?Promise.resolve(e):new Promise(e=>{this.waitingQueue.push(e)})}releaseInstance(e){const t=this.waitingQueue.shift();if(void 0!==t)return t(e);this.instances.push(e)}}const qa={NONE:ve(0xffffffffffffffffn),WHAT:ve(0xfffffffffffffffen),OOB:ve(0xfffffffffffffffdn),WHO:ve(0xfffffffffffffffcn),FULL:ve(0xfffffffffffffffbn),CORE:ve(0xfffffffffffffffan),CASH:ve(0xfffffffffffffff9n),LOW:ve(0xfffffffffffffff8n),HUH:ve(0xfffffffffffffff7n),OK:ve(0n)},za=Ae(2**32-1),Wa=ve(za),Ja=Rr(2**32-1);function Ya(e,t,r){const s=t.get(e);return s===2n**64n-1n?r:Xa(s)}function Xa(e){const{lower:t,upper:r}=(e=>{const t=e>>32n;return{lower:Number(e&2n**32n-1n),upper:Number(t)}})(e);return 0===r?Rr(t):null}function Za(e,t){Q(t.length>=4,"Not enough space in the destination."),t.set(Ee(e))}function ec(e){return e>Wa?za:Ae(Number(e))}const tc=m.new(void 0,"host-calls");class rc{hostCalls=new Map;missing=new sc;constructor(...e){for(const t of e)Q(void 0===this.hostCalls.get(t.index),`Overwriting host call handler at index ${t.index}`),this.hostCalls.set(t.index,t)}get(e){const t=this.hostCalls.get(e)??this.missing;return tc.trace(`[${t.currentServiceId}] PVM invoking ${e} (${t.constructor.name}:${t.index})`),t}}class sc{index=Zn(2**32-1);gasCost=po(10);currentServiceId=Ja;execute(e,t,r){return t.set(7,qa.WHAT),Promise.resolve(void 0)}}const ic=4096,nc=65536,oc=2**24,ac=4278059008,cc=4278124544;function lc(e){return ic*Math.ceil(e/ic)}class hc extends G{start;end;data;static from({start:e,end:t,data:r}){return new hc(e,t,r)}constructor(e,t,r){super(),this.start=e,this.end=t,this.data=r}}class uc extends G{readable;writeable;sbrkIndex;heapEnd;constructor(e,t,r,s){super(),this.readable=e,this.writeable=t,this.sbrkIndex=r,this.heapEnd=s}}class dc extends G{code;memory;registers;constructor(e,t,r){super(),this.code=e,this.memory=t,this.registers=r}}function fc(e,t,r=null){return new hc(e,t,r)}class pc{code;registers;memory;metadata;static fromSpi(e,t,r){const{code:s,metadata:i}=r?gc(e):{code:e},{code:n,memory:o,registers:a}=function(e,t){const r=xe.fromBlob(e),s=r.u24(),i=r.u24(),n=V(t.length,t.length<=oc,"Incorrect arguments length"),o=V(s,s<=oc,"Incorrect readonly segment length"),a=V(i,i<=oc,"Incorrect heap segment length"),c=r.u16(),l=r.u24(),h=r.bytes(o).raw,u=r.bytes(a).raw,d=r.u32(),f=r.bytes(d).raw;r.finish();const p=nc+lc(o),g=131072+(y=o,nc*Math.ceil(y/nc));var y;const m=g+lc(a),b=g+lc(a)+c*ic,A=ac-lc(l),I=ac,v=cc,w=v+lc(n),S=w+lc(n);function E(e){return!1!==e}const C=[o>0&&fc(65536,p,h),n>0&&fc(v,w,t),w<S&&fc(w,S)].filter(E),k=[a>0&&fc(g,m,u),m<b&&fc(m,b),A<I&&fc(A,I)].filter(E);return new dc(f,new uc(C,k,b,A),function(e){const t=new BigUint64Array(13);return t[0]=BigInt(4294901760),t[1]=BigInt(ac),t[7]=BigInt(cc),t[8]=BigInt(e),t}(t.length))}(s,t),c=new io;c.copyFrom(a);const l=new Go;for(const{start:e,end:t,data:r}of o.readable){const s=Wn(e),i=Wn(t);l.setReadablePages(s,i,r??new Uint8Array)}for(const{start:e,end:t,data:r}of o.writeable){const s=Wn(e),i=Wn(t);l.setWriteablePages(s,i,r??new Uint8Array)}const h=Wn(o.sbrkIndex),u=Jn(o.heapEnd),d=l.finalize(h,u);return new pc(n,c,d,i)}static fromGeneric(e,t){const{code:r,metadata:s}=t?gc(e):{code:e},i=new io,n=new jo;return new pc(r,i,n,s)}constructor(e,t,r,s=new Uint8Array){this.code=e,this.registers=t,this.memory=r,this.metadata=s}}function gc(e){const t=xe.fromBlob(e);return{metadata:t.bytesBlob().raw,code:t.remainingBytes().raw}}var yc,mc,bc;!function(e){e[e.NoLookup=0]="NoLookup",e[e.NoState=1]="NoState",e[e.NoServiceCode=2]="NoServiceCode",e[e.ServiceCodeMismatch=3]="ServiceCodeMismatch"}(yc||(yc={}));class Ac{context;keccakHasher;allocator;constructor(e,t,r){this.context=e,this.keccakHasher=t,this.allocator=r}hashConcat(e,t){return or(this.keccakHasher,[e,t])}hashConcatPrepend(e,t,r){return or(this.keccakHasher,[e,t,r])}header(e){return new Ot(Ht(e.encoded(),this.allocator).asOpaque(),e)}extrinsic(e){const t=e.guarantees.view().map(e=>e.view()).map(e=>{const t=Ht(e.report.encoded(),this.allocator).asOpaque();return te.blobFromParts([t.raw,e.slot.encoded().raw,e.credentials.encoded().raw])}),r=Te.encodeObject(Ve.sequenceVarLen(Fi),t,this.context),s=Ht(e.tickets.encoded(),this.allocator).asOpaque(),i=Ht(e.preimages.encoded(),this.allocator).asOpaque(),n=Ht(r,this.allocator).asOpaque(),o=Ht(e.assurances.encoded(),this.allocator).asOpaque(),a=Ht(e.disputes.encoded(),this.allocator).asOpaque(),c=te.blobFromParts([s.raw,i.raw,n.raw,o.raw,a.raw]);return new Ut(Ht(c,this.allocator).asOpaque(),e,c)}workPackage(e){return this.encode(jr.Codec,e)}encode(e,t){const r=Te.encodeObject(e,t,this.context);return new Ut(Ht(r,this.allocator).asOpaque(),t,r)}}!function(e){e.PreimageUnneeded="preimage_unneeded",e.PreimagesNotSortedUnique="preimages_not_sorted_unique",e.AccountNotFound="account_not_found"}(mc||(mc={}));class Ic{state;constructor(e){this.state=e}integrate(e){for(let t=1;t<e.preimages.length;t++){const r=e.preimages[t-1],s=e.preimages[t];if(!(r.requester<s.requester)&&(r.requester>s.requester||s.blob.compare(r.blob).isLessOrEqual()))return Z.error(mc.PreimagesNotSortedUnique)}const{preimages:t,slot:r}=e,s=[];for(const e of t){const{requester:t,blob:i}=e,n=Ht(i).asOpaque(),o=this.state.getService(t);if(null===o)return Z.error(mc.AccountNotFound);const a=o.hasPreimage(n),c=o.getLookupHistory(n,Ae(i.length));if(a||null===c||!Ii.isRequested(c))return Z.error(mc.PreimageUnneeded);s.push(Ei.provide({serviceId:t,preimage:mi.create({hash:n,blob:i}),slot:r}))}return Z.ok({preimages:s})}}class vc{spec;importer;toImport=ur.fromSortedArray((e,t)=>{const r=e.timeSlot-t.timeSlot;return r<0?M.Greater:r>0?M.Less:M.Equal});lastEpoch=Tr(2**32-1);constructor(e,t){this.spec=e,this.importer=t}tryToReadTimeSlot(e){try{return e.header.view().timeSlotIndex.materialize()}catch{return null}}isCurrentEpoch(e){const t=Math.floor(e/this.spec.epochLength);return this.lastEpoch===t}startPreverification(){for(const e of this.toImport)this.isCurrentEpoch(e.timeSlot)&&(e.seal=this.importer.preverifySeal(e.timeSlot,e.block))}push(e){const t=this.tryToReadTimeSlot(e);if(null===t)return null;const r={timeSlot:t,block:e,seal:this.isCurrentEpoch(t)?this.importer.preverifySeal(t,e):Promise.resolve(null)};return this.toImport.insert(r),t}shift(){const e=this.toImport.pop();if(void 0!==e){const t=Math.floor(e.timeSlot/this.spec.epochLength),r=this.lastEpoch!==t;this.lastEpoch=Tr(t),r&&this.startPreverification()}return e}}!function(e){e[e.ParentNotFound=0]="ParentNotFound",e[e.InvalidTimeSlot=1]="InvalidTimeSlot",e[e.InvalidExtrinsic=2]="InvalidExtrinsic",e[e.StateRootNotFound=3]="StateRootNotFound",e[e.InvalidStateRoot=4]="InvalidStateRoot",e[e.AlreadyImported=5]="AlreadyImported"}(bc||(bc={}));const wc=re.zero(Rt).asOpaque();class Sc{hasher;blocks;constructor(e,t){this.hasher=e,this.blocks=t}async verifyBlock(e){const t=e.header.view(),r=this.hasher.header(t);if(null!==this.blocks.getHeader(r.hash))return Z.error(bc.AlreadyImported,`Block ${r.hash} is already imported.`);const s=t.parentHeaderHash.materialize();if(!s.isEqualTo(wc)){const e=this.blocks.getHeader(s);if(null===e)return Z.error(bc.ParentNotFound,`Parent ${s.toString()} not found`);const r=t.timeSlotIndex.materialize(),i=e.timeSlotIndex.materialize();if(r<=i)return Z.error(bc.InvalidTimeSlot,`Invalid time slot index: ${r}, expected > ${i}`)}const i=t.extrinsicHash.materialize(),n=this.hasher.extrinsic(e.extrinsic.view());if(!i.isEqualTo(n.hash))return Z.error(bc.InvalidExtrinsic,`Invalid extrinsic hash: ${i.toString()}, expected ${n.hash.toString()}`);const o=t.priorStateRoot.materialize(),a=this.blocks.getPostStateRoot(s);return null===a?Z.error(bc.StateRootNotFound,`Posterior state root ${s.toString()} not found`):o.isEqualTo(a)?Z.ok(r.hash):Z.error(bc.InvalidStateRoot,`Invalid prior state root: ${o.toString()}, expected ${a.toString()} (ours)`)}hashHeader(e){return this.hasher.header(e.header.view())}}var Ec;function Cc(e,t){for(let r=1;r<e.length;r++)if(e[r-1][t].compare(e[r][t]).isGreaterOrEqual())return!1;return!0}!function(e){e.AlreadyJudged="already_judged",e.BadVoteSplit="bad_vote_split",e.VerdictsNotSortedUnique="verdicts_not_sorted_unique",e.JudgementsNotSortedUnique="judgements_not_sorted_unique",e.CulpritsNotSortedUnique="culprits_not_sorted_unique",e.FaultsNotSortedUnique="faults_not_sorted_unique",e.NotEnoughCulprits="not_enough_culprits",e.NotEnoughFaults="not_enough_faults",e.CulpritsVerdictNotBad="culprits_verdict_not_bad",e.FaultVerdictWrong="fault_verdict_wrong",e.OffenderAlreadyReported="offender_already_reported",e.BadJudgementAge="bad_judgement_age",e.BadValidatorIndex="bad_validator_index",e.BadSignature="bad_signature",e.BadGuarantorKey="bad_guarantor_key",e.BadAuditorKey="bad_auditor_key"}(Ec||(Ec={}));const kc=te.blobFromString("jam_valid").raw,xc=te.blobFromString("jam_invalid").raw,_c=te.blobFromString("jam_guarantee").raw;function Bc({key:e,signature:t,workReportHash:r}){return{key:e,signature:t,message:te.blobFromParts(_c,r.raw)}}function Rc({workReportHash:e,wasConsideredValid:t,signature:r,key:s}){const i=t?kc:xc;return{key:s,signature:r,message:te.blobFromParts(i,e.raw)}}function Oc(e,t,r){const{isWorkReportValid:s,signature:i}=e,n=s?kc:xc;return{key:r,signature:i,message:te.blobFromParts(n,t.raw)}}class Uc{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}verifyCulprits(e,t,r,s){if(!Cc(e.culprits,"key"))return Z.error(Ec.CulpritsNotSortedUnique);const i=e.culprits.length;for(let n=0;n<i;n++){const{key:i,workReportHash:o}=e.culprits[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return Z.error(Ec.OffenderAlreadyReported);if(!s.has(i))return Z.error(Ec.BadGuarantorKey);if(void 0===t.toAddToBadSet.findExact(o))return Z.error(Ec.CulpritsVerdictNotBad);const a=r.culprits[n];if(!a?.isValid)return Z.error(Ec.BadSignature)}return Z.ok(null)}verifyFaults(e,t,r,s){if(!Cc(e.faults,"key"))return Z.error(Ec.FaultsNotSortedUnique);const i=e.faults.length;for(let n=0;n<i;n++){const{key:i,workReportHash:o,wasConsideredValid:a}=e.faults[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return Z.error(Ec.OffenderAlreadyReported);if(!s.has(i))return Z.error(Ec.BadAuditorKey);if(a){const e=t.toAddToGoodSet.findExact(o),r=t.toAddToBadSet.findExact(o);if(void 0!==e||void 0===r)return Z.error(Ec.FaultVerdictWrong)}if(!r.faults[n].isValid)return Z.error(Ec.BadSignature)}return Z.ok(null)}verifyVerdicts(e,t){if(!Cc(e.verdicts,"workReportHash"))return Z.error(Ec.VerdictsNotSortedUnique);if(e.verdicts.some(e=>!function(e){for(let t=1;t<e.length;t++)if(e[t-1].index>=e[t].index)return!1;return!0}(e.votes)))return Z.error(Ec.JudgementsNotSortedUnique);const r=Math.floor(this.state.timeslot/this.chainSpec.epochLength);let s=0;for(const{votesEpoch:i,votes:n}of e.verdicts){if(i!==r&&i+1!==r)return Z.error(Ec.BadJudgementAge);const e=i===r?this.state.currentValidatorData:this.state.previousValidatorData;for(const{index:r}of n){const i=e[r]?.ed25519;if(void 0===i)return Z.error(Ec.BadValidatorIndex);if(!t.judgements[s].isValid)return Z.error(Ec.BadSignature);s+=1}}return Z.ok(null)}verifyIfAlreadyJudged(e){for(const t of e.verdicts){const e=this.state.disputesRecords.goodSet.findExact(t.workReportHash),r=this.state.disputesRecords.badSet.findExact(t.workReportHash),s=this.state.disputesRecords.wonkySet.findExact(t.workReportHash);if(void 0!==e||void 0!==r||void 0!==s)return Z.error(Ec.AlreadyJudged)}return Z.ok(null)}calculateVotesForWorkReports(e){const t=ar.new();for(const r of e.verdicts){const e=r.votes,s=r.workReportHash;let i=0;for(const{isWorkReportValid:t}of e)t&&(i+=1);t.set(s,i)}return t}verifyVotesForWorkReports(e,t){for(const[r,s]of e)if(s===this.chainSpec.validatorsSuperMajority){const e=t.faults.find(e=>e.workReportHash.isEqualTo(r));if(void 0===e)return Z.error(Ec.NotEnoughFaults)}else if(0===s){const e=t.culprits.find(e=>e.workReportHash.isEqualTo(r)),s=t.culprits.findLast(e=>e.workReportHash.isEqualTo(r));if(e===s)return Z.error(Ec.NotEnoughCulprits)}else if(s!==this.chainSpec.thirdOfValidators)return Z.error(Ec.BadVoteSplit);return Z.ok(null)}getDisputesRecordsNewItems(e){const t=[],r=[],s=[];for(const[i,n]of e)n>=this.chainSpec.validatorsSuperMajority?t.push(i):0===n?r.push(i):n>=this.chainSpec.thirdOfValidators&&s.push(i);return{toAddToGoodSet:dr.fromArray(ai,t),toAddToBadSet:dr.fromArray(ai,r),toAddToWonkySet:dr.fromArray(ai,s)}}getClearedCoreAssignment(e){const t=this.state.availabilityAssignment.slice();for(let r=0;r<t.length;r++){const s=t[r];if(null!==s){const i=e.get(s.workReport.hash);void 0!==i&&i<this.chainSpec.validatorsSuperMajority&&(t[r]=null)}}return ri(t,this.chainSpec)}getOffenders(e){const t=[];for(const{key:r}of e.culprits)t.push(r);for(const{key:r}of e.faults)t.push(r);return t}getUpdatedDisputesRecords(e,t){const r=ur.fromArray(ai,t);return oi.create({goodSet:dr.fromTwoSortedCollections(this.state.disputesRecords.goodSet,e.toAddToGoodSet),badSet:dr.fromTwoSortedCollections(this.state.disputesRecords.badSet,e.toAddToBadSet),wonkySet:dr.fromTwoSortedCollections(this.state.disputesRecords.wonkySet,e.toAddToWonkySet),punishSet:dr.fromTwoSortedCollections(this.state.disputesRecords.punishSet,r)})}prepareSignaturesToVerification(e){const t={culprits:[],judgements:[],faults:[]},r=Math.floor(this.state.timeslot/this.chainSpec.epochLength);for(const{votesEpoch:s,votes:i,workReportHash:n}of e.verdicts){const e=s===r?this.state.currentValidatorData:this.state.previousValidatorData;for(const r of i){const s=e[r.index];if(void 0===s)return Z.error(Ec.BadValidatorIndex);const i=s.ed25519;t.judgements.push(Oc(r,n,i))}}return t.culprits=e.culprits.map(Bc),t.faults=e.faults.map(Rc),Z.ok(t)}getValidatorKeys(){const e=this.state.disputesRecords.punishSet,t=this.state.currentValidatorData.map(e=>e.ed25519),r=this.state.previousValidatorData.map(e=>e.ed25519),s=t.concat(r).filter(t=>!e.has(t));return cr.from(s)}async transition(e){const t=this.prepareSignaturesToVerification(e);if(t.isError)return Z.error(t.error);const r=async function(e){const t={culprits:[],faults:[],judgements:[]},r=Object.entries(e);for(const[e,s]of r)t[e]=(await Ct(s)).map((e,t)=>({isValid:e,signature:s[t].signature}));return Promise.resolve(t)}(t.ok),s=this.calculateVotesForWorkReports(e),i=this.getDisputesRecordsNewItems(s),n=await r,o=this.getValidatorKeys(),a=[this.verifyVerdicts(e,n),this.verifyVotesForWorkReports(s,e),this.verifyCulprits(e,i,n,o),this.verifyFaults(e,i,n,o),this.verifyIfAlreadyJudged(e)].find(e=>e.isError);if(a?.isError)return Z.error(a.error);const c=this.getOffenders(e),l=this.getUpdatedDisputesRecords(i,c),h=this.getClearedCoreAssignment(s);return Z.ok({offendersMark:c,stateUpdate:{disputesRecords:l,availabilityAssignment:h}})}}const Tc=te.blobFromString("jam_entropy").raw,Nc=te.blobFromString("jam_fallback_seal").raw,Dc=te.blobFromString("jam_ticket_seal").raw;var Mc;!function(e){e[e.Ok=0]="Ok",e[e.Error=1]="Error"}(Mc||(Mc={}));const Pc=async function(e,t,r,s,i,n){const o=te.blobFromParts(t.map(e=>e.raw)).raw,a=await e.verifySeal(o,r,s.raw,i.raw,n.raw);return a[0]===Mc.Error?Z.error(null):Z.ok(re.fromBlob(a.subarray(1),Rt).asOpaque())},Lc=async function(e,t,r,s){const i=s.length+Dc.length+1,n=te.blobFromParts(r.map(e=>te.blobFromParts([e.signature.raw,Dc,s.raw,Uint8Array.of(e.attempt)]).raw)).raw,o=te.blobFromParts(t.map(e=>e.raw)).raw;try{const t=await e.batchVerifyTicket(o,n,i);return Array.from(te.blobFrom(t).chunks(33)).map(e=>({isValid:e.raw[0]===Mc.Ok,entropyHash:re.fromBlob(e.raw.subarray(1,33),Rt).asOpaque()}))}catch(e){if("RuntimeError: unreachable"==`${e}`)return Array.from({length:r.length},()=>({isValid:!1,entropyHash:re.zero(Rt).asOpaque()}));throw e}},Hc=async function(e,t){const r=te.blobFromParts(t.map(e=>e.raw)).raw,s=await e.getRingCommitment(r);return s[0]===Mc.Error?Z.error(null):Z.ok(re.fromBlob(s.subarray(1),_t).asOpaque())};class Kc{runInternal;state;static new(e,t){return new Kc(e,t)}constructor(e,t){this.runInternal=e,this.state=t}listenToParentPort(){if(null===T.parentPort)throw new Error("This method is meant to be run inside a worker thread!");T.parentPort.once("close",()=>{process.exit(0)}),T.parentPort.once("message",e=>{this.listenTo(e),T.parentPort?.postMessage("ready")})}listenTo(e){e.once("close",()=>{e.removeAllListeners(),process.exit(0)}),e.on("message",t=>{const{params:r}=t;this.run(r).then(t=>{const r=Z.ok(t);e.postMessage(r,t.getTransferList())}).catch(t=>{const r=Z.error(`${t}`);e.postMessage(r,[])})})}async run(e){return await this.runInternal(e,this.state)}async destroy(){}}class Qc{workers;maxWorkers;workerPath;static async initialize(e,t){Q(t.maxWorkers>0,"Max workers has to be positive."),Q(t.minWorkers<=t.maxWorkers,"Min workers has to be lower or equal to max workers.");const r=[];for(let s=0;s<t.minWorkers;s++)r.push(await Vc(e));return new Qc(r,t.maxWorkers,e)}freeWorkerIndices=[];taskQueue=[];isDestroyed=!1;isWorkerInitializing=!1;constructor(e,t,r){this.workers=e,this.maxWorkers=t,this.workerPath=r;for(let t=0;t<e.length;t++)this.freeWorkerIndices.push(t)}async initNewWorker(e=()=>{}){this.workers.length>=this.maxWorkers?console.warn(`Task queue has ${this.taskQueue.length} pending items and we can't init any more workers.`):this.isWorkerInitializing||(this.isWorkerInitializing=!0,this.workers.push(await Vc(this.workerPath)),this.freeWorkerIndices.push(this.workers.length-1),this.isWorkerInitializing=!1,e())}async destroy(){for(const e of this.workers)e.port.close(),await e.worker.terminate();this.workers.length=0,this.isDestroyed=!0}async run(e){return new Promise((t,r)=>{this.isDestroyed?r("pool destroyed"):(this.taskQueue.push({params:e,resolve:t,reject:r}),this.processEntryFromTaskQueue())})}processEntryFromTaskQueue(){const e=this.freeWorkerIndices.pop();if(void 0===e)return void(this.taskQueue.length>5&&this.initNewWorker(()=>{this.processEntryFromTaskQueue()}));const t=this.taskQueue.pop();void 0!==t?this.workers[e].runTask(t,()=>{this.freeWorkerIndices.push(e),this.processEntryFromTaskQueue()}):this.freeWorkerIndices.push(e)}}async function Vc(e){const{port1:t,port2:r}=new MessageChannel,s=new T.Worker(e,{});return s.postMessage(t,[t]),await new Promise((e,t)=>{s.once("message",e),s.once("error",t)}),s.unref(),new Fc(s,r)}class Fc{worker;port;constructor(e,t){this.worker=e,this.port=t}runTask(e,t){const r={params:e.params};this.port.once("message",r=>{r.isOk?e.resolve(r.ok):e.reject(new Error(r.error)),t()}),this.port.postMessage(r,r.params.getTransferList())}}var $c;!function(e){e[e.RingCommitment=0]="RingCommitment",e[e.BatchVerifyTickets=1]="BatchVerifyTickets",e[e.VerifySeal=2]="VerifySeal"}($c||($c={}));class jc{data;constructor(e){this.data=e}getTransferList(){return[]}}class Gc{params;constructor(e){this.params=e}getTransferList(){return[]}}const qc=Kc.new(e=>{const t=e.params,r=t.method;return r===$c.RingCommitment?Promise.resolve(new jc((0,kt.hc)(t.keys))):r===$c.BatchVerifyTickets?Promise.resolve(new jc((0,kt.ZJ)(t.keys,t.ticketsData,t.contextLength))):r===$c.VerifySeal?Promise.resolve(new jc((0,kt.KG)(t.keys,t.authorIndex,t.signature,t.payload,t.auxData))):void F(r)},null);class zc{executor;constructor(e){this.executor=e}destroy(){return this.executor.destroy()}static async new({synchronous:e}){const t=A().cpus().length;return new zc(e?qc:await Qc.initialize(new URL(o(884),o.b),{minWorkers:Math.max(1,Math.floor(t/2)),maxWorkers:t}))}async verifySeal(e,t,r,s,i){return(await this.executor.run(new Gc({method:$c.VerifySeal,keys:e,authorIndex:t,signature:r,payload:s,auxData:i}))).data}async getRingCommitment(e){return(await this.executor.run(new Gc({method:$c.RingCommitment,keys:e}))).data}async batchVerifyTicket(e,t,r){return(await this.executor.run(new Gc({method:$c.BatchVerifyTickets,keys:e,ticketsData:t,contextLength:r}))).data}}const Wc=(e,t)=>fe(e.id,t.id);var Jc,Yc,Xc,Zc,el,tl,rl;!function(e){e[e.IncorrectData=1]="IncorrectData",e[e.BadSlot=2]="BadSlot",e[e.UnexpectedTicket=3]="UnexpectedTicket",e[e.BadTicketOrder=4]="BadTicketOrder",e[e.BadTicketProof=5]="BadTicketProof",e[e.BadTicketAttempt=6]="BadTicketAttempt",e[e.DuplicateTicket=7]="DuplicateTicket"}(Jc||(Jc={}));class sl{chainSpec;state;bandersnatch;constructor(e,t,r=zc.new({synchronous:!0})){this.chainSpec=e,this.state=t,this.bandersnatch=r}isEpochChanged(e){const t=Math.floor(this.state.timeslot/this.chainSpec.epochLength);return Math.floor(e/this.chainSpec.epochLength)>t}isSameEpoch(e){const t=Math.floor(this.state.timeslot/this.chainSpec.epochLength);return Math.floor(e/this.chainSpec.epochLength)===t}isNextEpoch(e){const t=Math.floor(this.state.timeslot/this.chainSpec.epochLength);return Math.floor(e/this.chainSpec.epochLength)===t+1}getSlotPhaseIndex(e){return e%this.chainSpec.epochLength}getEntropy(e,t){const[r,...s]=this.state.entropy,i=Lt([r.raw,t]).asOpaque();return this.isEpochChanged(e)?hr.new([i,r,s[0],s[1]],4):hr.new([i,...s],4)}async getValidatorKeys(e){if(!this.isEpochChanged(e)){const{nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s}=this.state;return Z.ok({nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s})}const t=this.state.disputesRecords.punishSet,r=this.state.designatedValidatorData.map(e=>!1!==t.has(e.ed25519)?ui.create({bandersnatch:re.zero(xt).asOpaque(),ed25519:re.zero(St).asOpaque(),bls:e.bls,metadata:e.metadata}):e),{nextValidatorData:s,currentValidatorData:i}=this.state,n=await Hc(await this.bandersnatch,r.map(e=>e.bandersnatch));return n.isOk?Z.ok({nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n.ok}):Z.error(Jc.IncorrectData)}outsideInSequencer(e){const t=e.length,r=new Array(t),s=Math.floor(t/2);t%2==1&&(r[s]=e[s]);for(let i=0;i<s;i+=1)r[2*i]=e[i],r[2*i+1]=e[t-i-1];return Mr(r,this.chainSpec)}fallbackKeySequencer(e,t){const r=this.chainSpec.epochLength,s=[],i=t.length;for(let n=Ae(0);n<r;n++){const r=Ee(n),o=Lt([e.raw,r]).raw,a=xe.fromBlob(o).u32()%i;s.push(t[a].bandersnatch)}return Mr(s,this.chainSpec)}getSlotKeySequence(e,t,r){const s=this.getSlotPhaseIndex(this.state.timeslot);return this.isNextEpoch(e)&&s>=this.chainSpec.contestLength&&this.state.ticketsAccumulator.length===this.chainSpec.epochLength?pi.tickets(this.outsideInSequencer(this.state.ticketsAccumulator)):this.isSameEpoch(e)?this.state.sealingKeySeries:pi.keys(this.fallbackKeySequencer(r,t))}getEpochMark(e,t){if(!this.isEpochChanged(e))return null;const r=this.state.entropy;return cs.create({entropy:r[0],ticketsEntropy:r[1],validators:t.map(e=>as.create(e))})}verifyTickets(e){const t=e.length;for(let r=1;r<t;r++){const t=e[r-1].id.compare(e[r].id);if(t.isEqual())return Z.error(Jc.DuplicateTicket);if(t.isGreater())return Z.error(Jc.BadTicketOrder)}return Z.ok(null)}async getNewTicketAccumulator(e,t,r,s){const i=0===t.length?[]:await Lc(await this.bandersnatch,r.map(e=>e.bandersnatch),t,s),n=t.map((e,t)=>({id:i[t].entropyHash,attempt:e.attempt}));if(!i.every(e=>e.isValid))return Z.error(Jc.BadTicketProof);const o=this.verifyTickets(n);if(o.isError)return Z.error(o.error);if(this.isEpochChanged(e))return Z.ok(n);const a=dr.fromSortedArray(Wc,this.state.ticketsAccumulator),c=dr.fromSortedArray(Wc,n),l=dr.fromTwoSortedCollections(a,c);return a.length+c.length!==l.length?Z.error(Jc.DuplicateTicket):Z.ok(l.array.slice(0,this.chainSpec.epochLength))}getTicketsMark(e){const t=this.getSlotPhaseIndex(this.state.timeslot),r=this.getSlotPhaseIndex(e);return this.isSameEpoch(e)&&t<this.chainSpec.contestLength&&this.chainSpec.contestLength<=r&&this.state.ticketsAccumulator.length===this.chainSpec.epochLength?this.outsideInSequencer(this.state.ticketsAccumulator):null}isExtrinsicLengthValid(e,t){return this.getSlotPhaseIndex(e)<this.chainSpec.contestLength?t.length<=this.chainSpec.maxTicketsPerExtrinsic:0===t.length}areTicketAttemptsValid(e){const t=e.length;for(let r=0;r<t;r++)if(e[r].attempt>=this.chainSpec.ticketsPerValidator)return!1;return!0}getSafroleSealState(e){const t=this.isEpochChanged(e),r=t?this.state.nextValidatorData:this.state.currentValidatorData,s=this.state.entropy[t?1:2];return{currentValidatorData:r,currentEntropy:this.state.entropy[t?2:3],sealingKeySeries:this.getSlotKeySequence(e,r,s)}}async transition(e){if(this.state.timeslot>=e.slot)return Z.error(Jc.BadSlot);if(!this.isExtrinsicLengthValid(e.slot,e.extrinsic))return Z.error(Jc.UnexpectedTicket);if(!this.areTicketAttemptsValid(e.extrinsic))return Z.error(Jc.BadTicketAttempt);const t=await this.getValidatorKeys(e.slot);if(t.isError)return Z.error(t.error);const{nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n}=t.ok,o=this.getEntropy(e.slot,e.entropy),a=this.getSlotKeySequence(e.slot,s,o[2]),c=await this.getNewTicketAccumulator(e.slot,e.extrinsic,this.state.nextValidatorData,o[2]);if(c.isError)return Z.error(c.error);const l={nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n,timeslot:e.slot,entropy:o,sealingKeySeries:a,ticketsAccumulator:c.ok},h={epochMark:this.getEpochMark(e.slot,r),ticketsMark:this.getTicketsMark(e.slot),stateUpdate:l};return Z.ok(h)}}!function(e){e[e.InvalidValidatorIndex=0]="InvalidValidatorIndex",e[e.InvalidValidator=1]="InvalidValidator",e[e.InvalidTicket=2]="InvalidTicket",e[e.IncorrectSeal=3]="IncorrectSeal",e[e.IncorrectEntropySource=4]="IncorrectEntropySource"}(Yc||(Yc={}));class il{bandersnatch;constructor(e=zc.new({synchronous:!0})){this.bandersnatch=e}async verifyHeaderSeal(e,t){const r=await this.verifySeal(e,t);if(r.isError)return r;const s=te.blobFromParts(Tc,r.ok.raw),i=await Pc(await this.bandersnatch,t.currentValidatorData.map(e=>e.bandersnatch),e.bandersnatchBlockAuthorIndex.materialize(),e.entropySource.materialize(),s,te.blobFromNumbers([]));return i.isError?Z.error(Yc.IncorrectEntropySource):Z.ok(i.ok)}async verifySeal(e,t){const r=t.currentValidatorData,s=e.bandersnatchBlockAuthorIndex.materialize(),i=r[s];if(void 0===i)return Z.error(Yc.InvalidValidatorIndex);const n=e.timeSlotIndex.materialize(),o=t.sealingKeySeries,a=t.currentEntropy;return o.kind===di.Tickets?await this.verifySealWithTicket(o.tickets,n,a,r,s,e):await this.verifySealWithKeys(o.keys,i,n,a,r,s,e)}async verifySealWithTicket(e,t,r,s,i,n){const o=t%e.length,{id:a,attempt:c}=e[o],l=te.blobFromParts(Dc,r.raw,new Uint8Array([c])),h=await Pc(await this.bandersnatch,s.map(e=>e.bandersnatch),i,n.seal.materialize(),l,ls(n));return h.isError?Z.error(Yc.IncorrectSeal):a.isEqualTo(h.ok)?Z.ok(h.ok):Z.error(Yc.InvalidTicket)}async verifySealWithKeys(e,t,r,s,i,n,o){if(!e[r%e.length].isEqualTo(t.bandersnatch))return Z.error(Yc.InvalidValidator);const a=te.blobFromParts(Nc,s.raw),c=await Pc(await this.bandersnatch,i.map(e=>e.bandersnatch),n,o.seal.materialize(),a,ls(o));return c.isError?Z.error(Yc.IncorrectSeal):Z.ok(c.ok)}}function nl(e){if(e.length===Xc.Requested)return{status:Xc.Requested};if(e.length===Xc.Available)return{status:Xc.Available,data:[e[0]]};if(e.length===Xc.Unavailable)return{status:Xc.Unavailable,data:[e[0],e[1]]};if(e.length===Xc.Reavailable)return{status:Xc.Reavailable,data:[e[0],e[1],e[2]]};throw new Error(`Invalid slots length: ${e.length}`)}!function(e){e[e.Requested=0]="Requested",e[e.Available=1]="Available",e[e.Unavailable=2]="Unavailable",e[e.Reavailable=3]="Reavailable"}(Xc||(Xc={})),function(e){e[e.AlreadyRequested=0]="AlreadyRequested",e[e.AlreadyAvailable=1]="AlreadyAvailable",e[e.InsufficientFunds=2]="InsufficientFunds"}(Zc||(Zc={})),function(e){e[e.DestinationNotFound=0]="DestinationNotFound",e[e.GasTooLow=1]="GasTooLow",e[e.BalanceBelowThreshold=2]="BalanceBelowThreshold"}(el||(el={})),function(e){e[e.InvalidService=0]="InvalidService",e[e.InvalidPreimage=1]="InvalidPreimage"}(tl||(tl={})),function(e){e[e.ServiceNotFound=0]="ServiceNotFound",e[e.WasNotRequested=1]="WasNotRequested",e[e.AlreadyProvided=2]="AlreadyProvided"}(rl||(rl={}));class ol{source;destination;amount;memo;gas;constructor(e,t,r,s,i){this.source=e,this.destination=t,this.amount=r,this.memo=s,this.gas=i}static create({source:e,destination:t,amount:r,memo:s,gas:i}){return new ol(e,t,r,s,i)}}class al{serviceId;static copyFrom(e){const t=new al(e.serviceId);t.newServices.push(...e.newServices),t.ejectedServices.push(...e.ejectedServices),t.transfers.push(...e.transfers),t.lookupHistory.push(...e.lookupHistory),t.providedPreimages.push(...e.providedPreimages);for(const[r,s]of e.authorizationQueues)t.authorizationQueues.set(r,s);return t.storage.push(...e.storage),t.updatedServiceInfo=null===e.updatedServiceInfo?null:yi.create(e.updatedServiceInfo),t.validatorsData=null===e.validatorsData?null:[...e.validatorsData],t.yieldedRoot=e.yieldedRoot,t.privilegedServices=null===e.privilegedServices?null:{...e.privilegedServices},t}intoServicesUpdate(e){return{servicesRemoved:this.ejectedServices,servicesUpdates:this.newServices.map(e=>Ci.create({serviceId:e.serviceId,serviceInfo:e.data.info,lookupHistory:e.data.lookupHistory.values().next().value?.[0]??null})).concat(null===this.updatedServiceInfo?[]:[Ci.update({serviceId:this.serviceId,serviceInfo:this.updatedServiceInfo})]),preimages:this.providedPreimages.map(t=>Ei.provide({serviceId:t.serviceId,preimage:t.item,slot:e})).concat(this.lookupHistory.map(e=>e.forgotten?Ei.remove({serviceId:this.serviceId,hash:e.hash,length:e.length}):Ei.updateOrAdd({serviceId:this.serviceId,lookupHistory:e}))),storage:this.storage}}newServices=[];ejectedServices=[];transfers=[];lookupHistory=[];providedPreimages=[];authorizationQueues=new Map;updatedServiceInfo=null;yieldedRoot=null;validatorsData=null;privilegedServices=null;storage=[];constructor(e){this.serviceId=e}}class cl extends Ii{forgotten;constructor(e,t){super(e.hash,e.length,e.slots),this.forgotten=t}static forget(e){return new cl(e,!0)}static update(e){return new cl(e,!1)}}class ll{serviceId;item;static create({serviceId:e,item:t}){return new ll(e,t)}constructor(e,t){this.serviceId=e,this.item=t}}const hl=19200;class ul{state;currentServiceId;updatedState;checkpointedState=null;nextNewServiceId;constructor(e,t,r){if(this.state=e,this.currentServiceId=t,this.updatedState=new al(t),this.nextNewServiceId=this.getNextAvailableServiceId(r),null===this.state.getService(this.currentServiceId))throw new Error(`Invalid state initialization. Service info missing for ${this.currentServiceId}.`)}getStateUpdates(){return[this.updatedState,this.checkpointedState]}getNextNewServiceId(){return this.nextNewServiceId}getCurrentServiceInfo(){if(null!==this.updatedState.updatedServiceInfo)return this.updatedState.updatedServiceInfo;const e=this.state.getService(this.currentServiceId);return V(e,null!==e,"Service existence in state validated in constructor.").getInfo()}getServiceInfo(e){if(null===e)return null;if(e===this.currentServiceId)return this.getCurrentServiceInfo();const t=this.updatedState.ejectedServices.some(t=>t===e);if(t)return null;const r=this.updatedState.newServices.find(({serviceId:t})=>t===e);if(void 0!==r)return r.data.info;const s=this.state.getService(e);return null===s?null:s.getInfo()}getPreimageStatus(e,t){const r=this.updatedState.lookupHistory.find(r=>r.hash.isEqualTo(e)&&BigInt(r.length)===t);if(void 0!==r)return r;const s=this.state.getService(this.currentServiceId),i=dl(t);if(null===i||null===s)return null;const n=s.getLookupHistory(e,i);return null===n?null:cl.update(new Ii(e,i,n))}isPreviousCodeExpired(e,t,r){const s=this.state.getService(e),i=dl(r),n=null===s||null===i?null:s.getLookupHistory(t,i),o=null===n?null:nl(n);if(o?.status!==Xc.Unavailable)return[!1,"wrong status"];const a=this.state.timeslot,c=o.data[1]<a-hl;return[c,c?"":"not expired"]}hasExistingPreimage(e,t){if(null===e)return!1;if(void 0!==this.updatedState.providedPreimages.find(r=>r.serviceId===e&&r.item.hash.isEqualTo(t)))return!0;const r=this.state.getService(e);return void 0!==r&&(r?.hasPreimage(t)??!1)}replaceOrAddPreimageUpdate(e,t){const r=this.updatedState.lookupHistory.indexOf(e),s=-1===r?0:1;this.updatedState.lookupHistory.splice(r,s,t)}getNextAvailableServiceId(e){let t=e;const r=2**32-512;for(;;){if(null===this.getServiceInfo(t))return t;t=Rr((t-256+1+r)%r+256)}}checkPreimageStatus(e,t){const r=this.getPreimageStatus(e,t);return null===r||r.forgotten?null:nl(r.slots)}requestPreimage(e,t){const r=this.getPreimageStatus(e,t);if(null!==r&&!r.forgotten){const e=r.slots.length;if(e===Xc.Requested)return Z.error(Zc.AlreadyRequested);if(e===Xc.Available||e===Xc.Reavailable)return Z.error(Zc.AlreadyAvailable);Q(e===Xc.Unavailable)}const s=this.getCurrentServiceInfo(),i=function(...e){let t=0,r=!1;for(const s of e){const e=t;t=t+s>>>0,r||=e>t}return{overflow:r,value:Ae(t)}}(s.storageUtilisationCount,Ae(1)),n=Se(s.storageUtilisationBytes,t),o=this.updateServiceStorageUtilisation(i,n,s);if(o.isError)return Z.error(Zc.InsufficientFunds,o.details);const a=ec(t);return null===r||r.forgotten?this.updatedState.lookupHistory.push(cl.update(new Ii(e,a,Ai([])))):this.replaceOrAddPreimageUpdate(r,cl.update(new Ii(e,a,Ai([...r.slots,this.state.timeslot])))),Z.ok(W)}updateServiceStorageUtilisation(e,t,r){if(e.overflow||t.overflow)return Z.error("insufficient funds");const s=yi.calculateThresholdBalance(e.value,t.value);return r.balance<s?Z.error("insufficient funds"):(this.updatedState.updatedServiceInfo=yi.create({...r,storageUtilisationBytes:t.value,storageUtilisationCount:e.value}),Z.ok(W))}forgetPreimage(e,t){const r=this.getPreimageStatus(e,t);if(null===r||r.forgotten)return Z.error(null);const s=nl(r.slots);if(s.status===Xc.Requested)return this.replaceOrAddPreimageUpdate(r,cl.forget(r)),Z.ok(W);const i=this.state.timeslot;return s.status===Xc.Unavailable?s.data[1]<i-hl?(this.replaceOrAddPreimageUpdate(r,cl.forget(r)),Z.ok(W)):Z.error(null):s.status===Xc.Available?(this.replaceOrAddPreimageUpdate(r,cl.update(new Ii(r.hash,r.length,Ai([s.data[0],i])))),Z.ok(W)):s.status===Xc.Reavailable?s.data[1]<i-hl?(this.replaceOrAddPreimageUpdate(r,cl.update(new Ii(r.hash,r.length,Ai([s.data[2],i])))),Z.ok(W)):Z.error(null):void F(s)}transfer(e,t,r,s){const i=this.getCurrentServiceInfo(),n=this.getServiceInfo(e);if(null===n||null===e)return Z.error(el.DestinationNotFound);if(r<n.onTransferMinGas)return Z.error(el.GasTooLow);const o=i.balance-t;return o<yi.calculateThresholdBalance(i.storageUtilisationCount,i.storageUtilisationBytes)?Z.error(el.BalanceBelowThreshold):(this.updatedState.transfers.push(ol.create({source:this.currentServiceId,destination:e,amount:t,memo:s,gas:r})),this.updatedState.updatedServiceInfo=yi.create({...i,balance:ve(o)}),Z.ok(W))}newService(e,t,r,s){const i=this.nextNewServiceId,n=Ae(2),o=Se(ve(81),t),a=ec(t),c=yi.calculateThresholdBalance(n,o.value),l=this.getCurrentServiceInfo(),h=yi.calculateThresholdBalance(l.storageUtilisationCount,l.storageUtilisationBytes),u=l.balance-c;if(u<h||o.overflow)return Z.error("insufficient funds");const d=new Mi(i,{info:yi.create({codeHash:e,balance:c,accumulateMinGas:r,onTransferMinGas:s,storageUtilisationBytes:o.value,storageUtilisationCount:n}),preimages:ar.new(),lookupHistory:ar.fromEntries([[e.asOpaque(),[new Ii(e.asOpaque(),a,Ai([]))]]]),storage:ar.new()});return this.updatedState.newServices.push(d),this.updatedState.updatedServiceInfo=yi.create({...l,balance:ve(u)}),this.nextNewServiceId=this.getNextAvailableServiceId(function(e){const t=2**32-512;return Rr(256+(e-256+42+t)%t)}(i)),Z.ok(i)}upgradeService(e,t,r){const s=this.getCurrentServiceInfo();this.updatedState.updatedServiceInfo=yi.create({...s,codeHash:e,accumulateMinGas:Or(t),onTransferMinGas:Or(r)})}updateValidatorsData(e){this.updatedState.validatorsData=e}checkpoint(){this.checkpointedState=al.copyFrom(this.updatedState)}updateAuthorizationQueue(e,t){this.updatedState.authorizationQueues.set(e,t)}updatePrivilegedServices(e,t,r,s){this.updatedState.privilegedServices={manager:e,authorizer:t,validators:r,autoAccumulate:s}}yield(e){this.updatedState.yieldedRoot=e}providePreimage(e,t){const r=null===e?null:this.state.getService(e);if(null===r||null===e)return Z.error(rl.ServiceNotFound);const s=Ht(t).asOpaque();if(e===this.currentServiceId){const e=this.getPreimageStatus(s,ve(t.length));if(null===e||!Ii.isRequested(e)||e.forgotten)return Z.error(rl.WasNotRequested)}else{const e=r.getLookupHistory(s,Ae(t.length));if(null===e||!Ii.isRequested(e))return Z.error(rl.WasNotRequested)}return this.hasExistingPreimage(e,s)?Z.error(rl.AlreadyProvided):(this.updatedState.providedPreimages.push(ll.create({serviceId:e,item:mi.create({hash:s,blob:t})})),Z.ok(W))}eject(e,t){const r=this.getServiceInfo(e);if(null===r||null===e)return Z.error(tl.InvalidService,"Service missing");const s=this.getCurrentServiceInfo(),i=re.zero(Rt).asOpaque();if(Za(this.currentServiceId,i.raw),!r.codeHash.isEqualTo(i))return Z.error(tl.InvalidService,"Invalid code hash");if(2!==r.storageUtilisationCount)return Z.error(tl.InvalidPreimage,"Too many storage items");const n=ve(81),o=ve(((e,...t)=>t.reduce((e,t)=>t<e?e:t,e))(r.storageUtilisationBytes,n)-n),[a,c]=this.isPreviousCodeExpired(e,t,o);if(!a)return Z.error(tl.InvalidPreimage,`Previous code available: ${c}`);const l=Se(s.balance,r.balance);return l.overflow?Z.error(tl.InvalidService,"Balance overflow"):(this.updatedState.updatedServiceInfo=yi.create({...s,balance:l.value}),this.updatedState.ejectedServices.push(e),Z.ok(W))}replaceOrAddStorageUpdate(e,t){const r=null===t?ki.remove({serviceId:this.currentServiceId,key:e}):ki.set({serviceId:this.currentServiceId,storage:bi.create({key:e,value:t})}),s=this.updatedState.storage.findIndex(t=>t.serviceId===r.serviceId&&t.key.isEqualTo(e)),i=-1===s?0:1;this.updatedState.storage.splice(s,i,r)}read(e,t){if(null===e)return null;if(this.currentServiceId===e){const r=this.updatedState.storage.find(r=>r.serviceId===e&&r.key.isEqualTo(t));if(void 0!==r)return r.value}const r=this.state.getService(e);return r?.getStorage(t)??null}write(e,t){const r=this.read(this.currentServiceId,e),s=null===r&&null!==t?1:null!==r&&null===t?-1:0,i=(t?.length??0)-(r?.length??0),n=this.getCurrentServiceInfo(),o=n.storageUtilisationCount+s,a=n.storageUtilisationBytes+BigInt(i);Q(o>=0,`storageUtilisationCount has to be a positive number, got: ${o}`),Q(a>=0,`storageUtilisationBytes has to be a positive number, got: ${a}`);const c=!Ie(o),l=!we(a),h=this.updateServiceStorageUtilisation({overflow:c,value:c?Ae(0):o},{overflow:l,value:l?ve(0):a},n);return h.isError?Z.error("full",h.details):(this.replaceOrAddStorageUpdate(e,t),Z.ok(W))}readSnapshotLength(e){const t=this.state.getService(this.currentServiceId);return t?.getStorage(e)?.length??null}lookup(e,t){if(null===e)return null;const r=this.updatedState.providedPreimages.find(r=>r.serviceId===e&&r.item.hash.isEqualTo(t));if(void 0!==r)return r.item.blob;const s=this.state.getService(e);return s?.getPreimage(t)??null}}function dl(e){return e>=2n**32n?null:Ae(Number(e))}function fl(e){const t=e.map(e=>e.workPackageSpec.hash);return cr.from(t)}const pl=Ve.object({serviceId:Ve.u32.asOpaque(),entropy:Ve.bytes(Rt).asOpaque(),timeslot:Ve.u32.asOpaque()});class gl{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}getWorkReportsToAccumulateImmediately(e){return e.filter(e=>0===e.context.prerequisites.length&&0===e.segmentRootLookup.length)}getWorkReportDependencies(e){return Array.from(cr.from(e.context.prerequisites.concat(e.segmentRootLookup.map(e=>e.workPackageHash))))}getWorkReportsToAccumulateLater(e){const t=this.state.recentlyAccumulated.flatMap(e=>Array.from(e));return yl(e.filter(e=>e.context.prerequisites.length>0||e.segmentRootLookup.length>0).map(e=>Hi.create({report:e,dependencies:this.getWorkReportDependencies(e)})),cr.from(t))}enqueueReports(e){const t=[];let r=[...e];for(;r.length>0;){const e=r.filter(({dependencies:e})=>0===e.length).map(({report:e})=>e);if(0===e.length)return t;t.push(...e),r=yl(r,fl(e))}return t}getQueueFromState(e){const t=e%this.chainSpec.epochLength,r=this.state.accumulationQueue.slice(t),s=this.state.accumulationQueue.slice(0,t);return r.concat(s).flat()}}function yl(e,t){return e.filter(({report:e})=>!t.has(e.workPackageSpec.hash)).map(e=>{const{report:r,dependencies:s}=e;return Hi.create({report:r,dependencies:s.filter(e=>!t.has(e))})})}var ml;!function(e){e[e.InvalidAnchor=0]="InvalidAnchor",e[e.InvalidOrder=1]="InvalidOrder",e[e.InvalidSignature=2]="InvalidSignature",e[e.NoReportPending=3]="NoReportPending",e[e.InvalidValidatorIndex=4]="InvalidValidatorIndex"}(ml||(ml={}));class bl{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}async transition(e){const t=this.chainSpec.coresCount,r=this.verifySignatures(e.assurances),s=e.assurances.map(e=>e.materialize()),i=hr.new(Array(t).fill(0),t);let n=-1;for(const r of s){const{anchor:s,validatorIndex:o,bitfield:a}=r;if(!s.isEqualTo(e.parentHash))return Z.error(ml.InvalidAnchor,`anchor: expected: ${e.parentHash}, got ${s}`);if(n>=o)return Z.error(ml.InvalidOrder,`order: expected: ${n+1}, got: ${o}`);n=r.validatorIndex,Q(a.bitLength===t,`Invalid bitfield length of ${a.bitLength}`);const c=a.indicesOfSetBits();for(const e of c)i[e]+=1}const o=[],a=[],c=this.chainSpec.validatorsSuperMajority;for(let r=0;r<t;r++){const t=i[r],s=this.state.availabilityAssignment[r],n=null!==s;if(t>0&&!n)return Z.error(ml.NoReportPending,`no report pending for core ${r} yet we got an assurance`);n&&(e.slot>=s.timeout+5&&a.push(r),t>=c&&(o.push(s.workReport.data),a.push(r)))}const l=await r;if(l.isError)return l;const h=this.state.availabilityAssignment.slice();for(const e of a)h[e]=null;return Z.ok({availableReports:o,stateUpdate:{availabilityAssignment:h}})}async verifySignatures(e){const t=this.state.currentValidatorData,r=[];for(const s of e){const e=s.view(),i=t[e.validatorIndex.materialize()];if(void 0===i)return Z.error(ml.InvalidValidatorIndex);r.push({signature:e.signature.materialize(),key:i.ed25519,message:Il(e.anchor.encoded(),e.bitfield.encoded())})}const s=await Ct(r),i=s.every(e=>e);if(!i){const e=s.reduce((e,t,r)=>t?e:e.concat(r),[]);return Z.error(ml.InvalidSignature,`invalid signatures at ${e.join(", ")}`)}return Z.ok(W)}}const Al=te.blobFromString("jam_available").raw;function Il(e,t){return te.blobFromParts(Al,Ht(te.blobFromParts(e.raw,t.raw)).raw)}const vl=te.blobFromString("peak");class wl{hasher;mountains;static empty(e){return new wl(e)}static fromPeaks(e,t){return new wl(e,t.peaks.reduce((e,t,r)=>(null!==t&&e.push(Sl.fromPeak(t,2**r)),e),[]).reverse())}constructor(e,t=[]){this.hasher=e,this.mountains=t}append(e){let t=Sl.fromPeak(e,1);for(;;){const e=this.mountains.pop();if(void 0===e)return void this.mountains.push(t);if(e.size!==t.size)return this.mountains.push(e),void this.mountains.push(t);t=e.mergeWith(this.hasher,t)}}getSuperPeakHash(){if(0===this.mountains.length)return re.zero(Rt).asOpaque();const e=this.mountains.slice().reverse(),t=e.length;let r=e[0].peak;for(let s=1;s<t;s++){const t=e[s];r=this.hasher.hashConcatPrepend(vl,r,t.peak)}return r}getPeaks(){const e=[],t=this.mountains;let r=1,s=t.length-1;for(;s>=0;){const i=t[s];i.size>=r&&i.size<2*r?(e.push(i.peak),s-=1):e.push(null),r<<=1}return{peaks:e}}}class Sl{peak;size;constructor(e,t){this.peak=e,this.size=t}static fromPeak(e,t){return new Sl(e,t)}static fromChildren(e,t){const[r,s]=t,i=e.hashConcat(r.peak,s.peak),n=r.size+s.size;return new Sl(i,n)}mergeWith(e,t){return Sl.fromChildren(e,[this,t])}toString(){return`${this.size} @ ${this.peak}`}}var El;!function(e){e[e.BadCoreIndex=0]="BadCoreIndex",e[e.FutureReportSlot=1]="FutureReportSlot",e[e.ReportEpochBeforeLast=2]="ReportEpochBeforeLast",e[e.InsufficientGuarantees=3]="InsufficientGuarantees",e[e.OutOfOrderGuarantee=4]="OutOfOrderGuarantee",e[e.NotSortedOrUniqueGuarantors=5]="NotSortedOrUniqueGuarantors",e[e.WrongAssignment=6]="WrongAssignment",e[e.CoreEngaged=7]="CoreEngaged",e[e.AnchorNotRecent=8]="AnchorNotRecent",e[e.BadServiceId=9]="BadServiceId",e[e.BadCodeHash=10]="BadCodeHash",e[e.DependencyMissing=11]="DependencyMissing",e[e.DuplicatePackage=12]="DuplicatePackage",e[e.BadStateRoot=13]="BadStateRoot",e[e.BadBeefyMmrRoot=14]="BadBeefyMmrRoot",e[e.CoreUnauthorized=15]="CoreUnauthorized",e[e.BadValidatorIndex=16]="BadValidatorIndex",e[e.WorkReportGasTooHigh=17]="WorkReportGasTooHigh",e[e.ServiceItemGasTooLow=18]="ServiceItemGasTooLow",e[e.TooManyDependencies=19]="TooManyDependencies",e[e.SegmentRootLookupInvalid=20]="SegmentRootLookupInvalid",e[e.BadSignature=21]="BadSignature",e[e.WorkReportTooBig=22]="WorkReportTooBig"}(El||(El={}));class Cl extends G{static Codec=Ve.Class(Cl,{hash:Ve.bytes(Rt).asOpaque(),exportsRoot:Ve.bytes(Rt).asOpaque(),authorizerHash:Ve.bytes(Rt).asOpaque(),payloadHash:Ve.bytes(Rt),gas:Ve.varU64.asOpaque(),result:zr.Codec,authorizationOutput:Ve.blob});hash;exportsRoot;authorizerHash;payloadHash;gas;result;authorizationOutput;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,gas:s,hash:i,payloadHash:n,result:o}){return new Cl({gas:Or(s),payloadHash:n.asOpaque(),result:o,authorizationOutput:te.blobFrom(e.raw),exportsRoot:r.asOpaque(),hash:i.asOpaque(),authorizerHash:t.asOpaque()})}constructor(e){super(),this.gas=e.gas,this.payloadHash=e.payloadHash,this.result=e.result,this.authorizationOutput=e.authorizationOutput,this.exportsRoot=e.exportsRoot,this.hash=e.hash,this.authorizerHash=e.authorizerHash}static new(e){return new Cl(e)}}class kl{static Codec=Ve.Class(kl,{hash:Ve.bytes(Rt).asOpaque(),exportsRoot:Ve.bytes(Rt).asOpaque(),authorizerHash:Ve.bytes(Rt).asOpaque(),authorizationOutput:Ve.blob,payloadHash:Ve.bytes(Rt),result:zr.Codec});hash;exportsRoot;authorizerHash;authorizationOutput;payloadHash;result;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,hash:s,payloadHash:i,result:n}){return new kl({payloadHash:i,result:n,authorizationOutput:e,exportsRoot:r,hash:s,authorizerHash:t})}constructor(e){this.payloadHash=e.payloadHash,this.result=e.result,this.authorizationOutput=e.authorizationOutput,this.exportsRoot=e.exportsRoot,this.hash=e.hash,this.authorizerHash=e.authorizerHash}static new(e){return new kl(e)}}const xl=Ve.object({B_I:Ve.u64,B_L:Ve.u64,B_S:Ve.u64,C:Ve.u16,D:Ve.u32,E:Ve.u32,G_A:Ve.u64,G_I:Ve.u64,G_R:Ve.u64,G_T:Ve.u64,H:Ve.u16,I:Ve.u16,J:Ve.u16,L:Ve.u32,O:Ve.u16,P:Ve.u16,Q:Ve.u16,R:Ve.u16,S:Ve.u16,T:Ve.u16,U:Ve.u16,V:Ve.u16,W_A:Ve.u16,W_B:Ve.u32,W_C:Ve.u32,W_E:Ve.u32,W_G:Ve.u32,W_M:Ve.u32,W_P:Ve.u32,W_R:Ve.u32,W_T:Ve.u32,W_X:Ve.u32,Y:Ve.u32}),_l=new Map;class Bl{entropyHash;operands;chainSpec;constructor(e,t,r){this.entropyHash=e,this.operands=t,this.chainSpec=r}constants(){return function(e){const t=_l.get(e);if(void 0!==t)return t;const r=Te.encodeObject(xl,{B_I:ve(10n),B_L:ve(1n),B_S:ve(100n),C:me(e.coresCount),D:Ae(hl),E:Ae(e.epochLength),G_A:ve(Jl),G_I:ve(5e7),G_R:ve(5e9),G_T:ve(Yl),H:me(8),I:me($r),J:me(8),L:Ae(14400),O:me(8),P:me(e.slotDuration),Q:me(80),R:me(0),S:me(1024),T:me(e.rotationPeriod),U:me(5),V:me(0),W_A:me(e.validatorsCount),W_B:Ae(13794305),W_C:Ae(4e6),W_E:Ae(684),W_G:Ae(4104),W_M:Ae(3072),W_P:Ae(6),W_R:Ae(49152),W_T:Ae(128),W_X:Ae(3072),Y:Ae(e.contestLength)});return _l.set(e,r),r}(this.chainSpec)}entropy(){return this.entropyHash.asOpaque()}authorizerTrace(){return null}workItemExtrinsic(e,t){return null}workItemImport(e,t){return null}workPackage(){return null}authorizer(){return null}authorizationToken(){return null}refineContext(){return null}allWorkItems(){return null}oneWorkItem(e){return null}workItemPayload(e){return null}allOperands(){return K.is(D.V0_6_4)?Te.encodeObject(Ve.sequenceVarLen(kl.Codec),this.operands,this.chainSpec):Te.encodeObject(Ve.sequenceVarLen(Cl.Codec),this.operands,this.chainSpec)}oneOperand(e){if(e>=2n**32n)return null;const t=this.operands[Number(e)];return void 0===t?null:K.isGreaterOrEqual(D.V0_6_5)?Te.encodeObject(Cl.Codec,t,this.chainSpec):Te.encodeObject(kl.Codec,t,this.chainSpec)}allTransfers(){return null}oneTransfer(e){return null}}const Rl=Ve.object({serviceId:Ve.u32.convert(e=>e,e=>e),gas:Ve.u64.convert(e=>ve(e),e=>Or(e))});class Ol{currentServiceId;index=Zn(0);gasCost=po(10);constructor(e){this.currentServiceId=e}execute(e,t){return t.set(7,ve(e.get())),Promise.resolve(void 0)}}const Ul=Re(ui.Codec.sizeHint),Tl=e=>ve(e);var Nl,Dl,Ml;!function(e){e[e.SourcePageFault=0]="SourcePageFault",e[e.DestinationPageFault=1]="DestinationPageFault",e[e.NoMachine=2]="NoMachine"}(Nl||(Nl={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidPage=1]="InvalidPage"}(Dl||(Dl={})),Symbol("Machine index not found."),Symbol("Too many segments already exported.");class Pl{currentServiceId;fetch;index=Zn(18);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.fetch=t}async execute(e,t,r){const s=this.getValue(t),i=t.get(7),n=ve(s?.length??0),o=ke(t.get(8),n),a=ke(t.get(9),ve(n-o)),c=null===s?new Uint8Array:s.raw.subarray(Number(o),Number(o+a));if(r.storeFrom(i,c).isError)return eo.Panic;t.set(7,null===s?qa.NONE:n)}getValue(e){const t=ec(e.get(10));if(t===Ml.Constants)return this.fetch.constants();if(t===Ml.Entropy)return this.fetch.entropy();if(t===Ml.AuthorizerTrace)return this.fetch.authorizerTrace();if(t===Ml.OtherWorkItemExtrinsics){const t=e.get(11),r=e.get(12);return this.fetch.workItemExtrinsic(t,r)}if(t===Ml.MyExtrinsics){const t=e.get(11);return this.fetch.workItemExtrinsic(null,t)}if(t===Ml.OtherWorkItemImports){const t=e.get(11),r=e.get(12);return this.fetch.workItemImport(t,r)}if(t===Ml.MyImports){const t=e.get(11);return this.fetch.workItemImport(null,t)}if(t===Ml.WorkPackage)return this.fetch.workPackage();if(t===Ml.Authorizer)return this.fetch.authorizer();if(t===Ml.AuthorizationToken)return this.fetch.authorizationToken();if(t===Ml.RefineContext)return this.fetch.refineContext();if(t===Ml.AllWorkItems)return this.fetch.allWorkItems();if(t===Ml.OneWorkItem){const t=e.get(11);return this.fetch.oneWorkItem(t)}if(t===Ml.WorkItemPayload){const t=e.get(11);return this.fetch.workItemPayload(t)}if(t===Ml.AllOperands)return this.fetch.allOperands();if(t===Ml.OneOperand){const t=e.get(11);return this.fetch.oneOperand(t)}if(t===Ml.AllTransfers)return this.fetch.allTransfers();if(t===Ml.OneTransfer){const t=e.get(11);return this.fetch.oneTransfer(t)}return null}}!function(e){e[e.Constants=0]="Constants",e[e.Entropy=1]="Entropy",e[e.AuthorizerTrace=2]="AuthorizerTrace",e[e.OtherWorkItemExtrinsics=3]="OtherWorkItemExtrinsics",e[e.MyExtrinsics=4]="MyExtrinsics",e[e.OtherWorkItemImports=5]="OtherWorkItemImports",e[e.MyImports=6]="MyImports",e[e.WorkPackage=7]="WorkPackage",e[e.Authorizer=8]="Authorizer",e[e.AuthorizationToken=9]="AuthorizationToken",e[e.RefineContext=10]="RefineContext",e[e.AllWorkItems=11]="AllWorkItems",e[e.OneWorkItem=12]="OneWorkItem",e[e.WorkItemPayload=13]="WorkItemPayload",e[e.AllOperands=14]="AllOperands",e[e.OneOperand=15]="OneOperand",e[e.AllTransfers=16]="AllTransfers",e[e.OneTransfer=17]="OneTransfer"}(Ml||(Ml={}));class Ll{currentServiceId;account;index=Zn(4);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=Ya(7,t,this.currentServiceId),i=t.get(8),n=this.account.getServiceInfo(s),o=null===n?te.empty():Te.encodeObject(Hl,{...n,thresholdBalance:yi.calculateThresholdBalance(n.storageUtilisationCount,n.storageUtilisationBytes)});if(r.storeFrom(i,o.raw).isError)return eo.Panic;null!==n?t.set(7,qa.OK):t.set(7,qa.NONE)}}const Hl=Ve.object({codeHash:Ve.bytes(Rt),balance:Ve.u64,thresholdBalance:Ve.u64,accumulateMinGas:Ve.u64.convert(e=>e,Or),onTransferMinGas:Ve.u64.convert(e=>e,Or),storageUtilisationBytes:Ve.u64,storageUtilisationCount:Ve.u32},"ServiceAccountInfoWithThresholdBalance"),Kl=m.new(void 0,"host-calls"),Ql=new TextDecoder("utf8");class Vl{currentServiceId;index=Zn(100);gasCost=po(0);constructor(e){this.currentServiceId=e}execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),o=t.get(10),a=t.get(11),c=new Uint8Array(ec(n)),l=new Uint8Array(ec(a));return 0n!==i&&r.loadInto(c,i),r.loadInto(l,o),Kl.trace(`[${this.currentServiceId}] [${s}] ${Ql.decode(c)} ${Ql.decode(l)}`),Promise.resolve(void 0)}}class Fl{currentServiceId;account;index=Zn(1);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=Ya(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),o=re.zero(Rt);if(r.loadInto(o.raw,i).isError)return eo.Panic;const a=this.account.lookup(s,o),c=ve(null===a?0:a.raw.length),l=t.get(10),h=t.get(11),u=ke(l,c),d=ke(h,ve(c-u)),f=null===a?new Uint8Array(0):a.raw.subarray(Number(u),Number(u+d));if(r.storeFrom(n,f).isError)return eo.Panic;null!==a?t.set(7,c):t.set(7,qa.NONE)}}class $l{currentServiceId;account;index=Zn(2);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=Ya(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),o=t.get(10),a=ec(n),c=new Uint8Array(4+a);if(null!==s&&Za(s,c),r.loadInto(c.subarray(4),i).isError)return eo.Panic;const l=Ht(c),h=this.account.read(s,l),u=ve(null===h?0:h.raw.length),d=t.get(11),f=t.get(12),p=ke(d,u),g=ke(f,ve(u-p)),y=null===h?new Uint8Array(0):h.raw.subarray(Number(p),Number(p+g));if(r.storeFrom(o,y).isError)return eo.Panic;null!==h?t.set(7,u):t.set(7,qa.NONE)}}class jl{currentServiceId;account;index=Zn(3);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),o=t.get(10),a=ec(i),c=new Uint8Array(4+a);if(Za(this.currentServiceId,c),r.loadInto(c.subarray(4),s).isError)return eo.Panic;const l=Ht(c),h=ec(o),u=new Uint8Array(h);if(r.loadInto(u,n).isError)return eo.Panic;const d=0n===o?null:te.blobFrom(u);if(this.account.write(l,d).isError)return void t.set(7,qa.FULL);const f=this.account.readSnapshotLength(l);t.set(7,null===f?qa.NONE:ve(f))}}const Gl=[class{currentServiceId;partialState;index=Zn(5);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=Xa(t.get(7)),i=Xa(t.get(8)),n=Xa(t.get(9)),o=t.get(10),a=t.get(11),c=new Array,l=new Uint8Array(Re(Rl.sizeHint)),h=xe.fromBlob(l);let u=o;for(let e=0n;e<a;e+=1n){if(h.resetTo(0),r.loadInto(l,u).isError)return eo.Panic;const{serviceId:e,gas:t}=h.object(Rl);c.push([e,t]),u=ve(u+ve(h.bytesRead()))}null!==s&&null!==i&&null!==n?(this.partialState.updatePrivilegedServices(s,i,n,c),t.set(7,qa.OK)):t.set(7,qa.WHO)}},class{currentServiceId;partialState;chainSpec;index=Zn(6);gasCost=po(10);constructor(e,t,r){this.currentServiceId=e,this.partialState=t,this.chainSpec=r}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=new Uint8Array(2560);if(r.loadInto(n,i).isError)return eo.Panic;if(s>=this.chainSpec.coresCount)return void t.set(7,qa.CORE);const o=xe.fromBlob(n).sequenceFixLen(Ve.bytes(Rt),80),a=hr.new(o,80);t.set(7,qa.OK),this.partialState.updateAuthorizationQueue(Ur(Number(s)),a)}},class{currentServiceId;partialState;chainSpec;index=Zn(7);gasCost=po(10);constructor(e,t,r){this.currentServiceId=e,this.partialState=t,this.chainSpec=r}async execute(e,t,r){const s=t.get(7),i=new Uint8Array(Ul*this.chainSpec.validatorsCount);if(r.loadInto(i,s).isError)return eo.Panic;const n=xe.fromBlob(i).sequenceFixLen(ui.Codec,this.chainSpec.validatorsCount);t.set(7,qa.OK),this.partialState.updateValidatorsData(Nr(n,this.chainSpec))}},class{currentServiceId;partialState;index=Zn(8);gasCost=po(10);gasHostCall;constructor(e,t){this.currentServiceId=e,this.partialState=t,this.gasHostCall=new Ol(e)}async execute(e,t){await this.gasHostCall.execute(e,t),this.partialState.checkpoint()}},class{currentServiceId;partialState;index=Zn(9);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=Or(t.get(9)),o=Or(t.get(10)),a=re.zero(Rt);if(r.loadInto(a.raw,s).isError)return eo.Panic;const c=this.partialState.newService(a.asOpaque(),i,n,o);c.isOk?t.set(7,ve(c.ok)):t.set(7,qa.CASH)}},class{currentServiceId;partialState;index=Zn(10);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),o=re.zero(Rt);if(r.loadInto(o.raw,s).isError)return eo.Panic;this.partialState.upgradeService(o.asOpaque(),i,n),t.set(7,qa.OK)}},class{currentServiceId;partialState;index=Zn(11);gasCost=e=>{const t=10n+e.get(9);return yo(t)};constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=Xa(t.get(7)),i=t.get(8),n=Or(t.get(9)),o=t.get(10),a=re.zero(128);if(r.loadInto(a.raw,o).isError)return eo.Panic;const c=this.partialState.transfer(s,i,n,a);if(c.isOk)return void t.set(7,qa.OK);const l=c.error;l!==el.DestinationNotFound?l!==el.GasTooLow?l!==el.BalanceBelowThreshold?F(l):t.set(7,qa.CASH):t.set(7,qa.LOW):t.set(7,qa.WHO)}},class{currentServiceId;partialState;index=Zn(12);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=Xa(t.get(7)),i=t.get(8),n=re.zero(Rt).asOpaque();if(r.loadInto(n.raw,i).isError)return eo.Panic;if(s===this.currentServiceId)return void t.set(7,qa.WHO);const o=this.partialState.eject(s,n);if(o.isOk)return void t.set(7,qa.OK);const a=o.error;a===tl.InvalidService?t.set(7,qa.WHO):a===tl.InvalidPreimage?t.set(7,qa.HUH):F(a)}},class{currentServiceId;partialState;index=Zn(13);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=re.zero(Rt);if(r.loadInto(n.raw,s).isError)return eo.Panic;const o=this.partialState.checkPreimageStatus(n.asOpaque(),i),a=ve(0n);if(null===o)return t.set(7,qa.NONE),void t.set(8,a);switch(o.status){case Xc.Requested:return t.set(7,a),void t.set(8,a);case Xc.Available:return t.set(7,ve(1n+(BigInt(o.data[0])<<32n))),void t.set(8,a);case Xc.Unavailable:return t.set(7,ve(2n+(BigInt(o.data[0])<<32n))),void t.set(8,ve(o.data[1]));case Xc.Reavailable:return t.set(7,ve(3n+(BigInt(o.data[0])<<32n))),void t.set(8,ve((BigInt(o.data[2])<<32n)+BigInt(o.data[1])))}}},class{currentServiceId;partialState;index=Zn(14);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=re.zero(Rt);if(r.loadInto(n.raw,s).isError)return eo.Panic;const o=this.partialState.requestPreimage(n.asOpaque(),i);if(o.isOk)return void t.set(7,qa.OK);const a=o.error;a!==Zc.AlreadyAvailable&&a!==Zc.AlreadyRequested?a!==Zc.InsufficientFunds?F(a):t.set(7,qa.FULL):t.set(7,qa.HUH)}},class{currentServiceId;partialState;index=Zn(15);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=re.zero(Rt);if(r.loadInto(n.raw,s).isError)return eo.Panic;this.partialState.forgetPreimage(n.asOpaque(),i).isOk?t.set(7,qa.OK):t.set(7,qa.HUH)}},class{currentServiceId;partialState;index=Zn(16);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=re.zero(Rt);if(r.loadInto(i.raw,s).isError)return eo.Panic;this.partialState.yield(i),t.set(7,qa.OK)}},class{currentServiceId;partialState;index=Zn(27);gasCost=po(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=Ya(7,t,this.currentServiceId),i=t.get(8),n=ec(t.get(9)),o=te.blobFrom(new Uint8Array(n));if(r.loadInto(o.raw,i).isError)return eo.Panic;const a=this.partialState.providePreimage(s,o);if(a.isOk)return void t.set(7,qa.OK);const c=a.error;c!==rl.ServiceNotFound?c!==rl.WasNotRequested&&c!==rl.AlreadyProvided?F(c):t.set(7,qa.HUH):t.set(7,qa.WHO)}}];var ql,zl;!function(e){e.IS_AUTHORIZED=Tl(0),e.REFINE=Tl(0),e.ACCUMULATE=Tl(5),e.ON_TRANSFER=Tl(10)}(ql||(ql={}));class Wl{serviceCode;entrypoint;pvm;hostCalls;pvmInstanceManager=new Ga(4);constructor(e,t,r){this.serviceCode=e,this.entrypoint=r,this.hostCalls=new rc(...t),this.pvm=new ja(this.pvmInstanceManager,this.hostCalls)}static prepareAccumulateHostCalls(e,t,r){const s=Gl.map(s=>new s(e,t.partialState,r)),i=[new Ol(e),new Vl(e),new $l(e,t.serviceExternalities),new jl(e,t.serviceExternalities),new Pl(e,t.fetchExternalities),new Fl(e,t.serviceExternalities),new Ll(e,t.serviceExternalities)];return s.concat(i)}async run(e,t){const r=pc.fromSpi(this.serviceCode.raw,e.raw,!0);return this.pvm.runProgram(r.code,Number(this.entrypoint),t,r.registers,r.memory)}static createAccumulateExecutor(e,t,r,s){const i=Wl.prepareAccumulateHostCalls(e,r,s);return new Wl(t,i,ql.ACCUMULATE)}}!function(e){e[e.NoService=0]="NoService",e[e.NoPreimage=1]="NoPreimage"}(zl||(zl={}));const Jl=10000000n,Yl=3500000000n,Xl=m.new(void 0,"accumulate"),Zl=Ve.object({slot:Ve.u32.asOpaque(),serviceId:Ve.u32.asOpaque(),operands:Ve.sequenceVarLen(kl.Codec)}),eh=Ve.object({slot:Ve.u32.asOpaque(),serviceId:Ve.u32.asOpaque(),operands:Ve.sequenceVarLen(Cl.Codec)}),th=Ve.object({slot:Ve.varU32.asOpaque(),serviceId:Ve.varU32.asOpaque(),operands:Ve.varU32});class rh{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}findReportCutoffIndex(e,t){const r=t.length;let s=0n;for(let i=0;i<r;i++){const r=t[i].results.map(e=>e.gas).reduce((e,t)=>e+t,0n);if(s+r>e)return i;s+=r}return r}async pvmAccumulateInvocation(e,t,r,s,i){const n=this.state.getService(t);if(null===n)return Xl.log(`Service with id ${t} not found.`),Z.error(zl.NoService);const o=n.getInfo().codeHash,a=n.getPreimage(o.asOpaque());if(null===a)return Xl.log(`Code with hash ${o} not found for service ${t}.`),Z.error(zl.NoPreimage);const c=function({serviceId:e,entropy:t,timeslot:r},s){const i=Ce(Ht(Te.encodeObject(pl,{serviceId:e,entropy:t,timeslot:r},s)).raw.subarray(0,4))>>>0;return Rr(i%(2**32-512)+256)}({serviceId:t,entropy:i,timeslot:e},this.chainSpec),l=new ul(this.state,t,c),h={partialState:l,serviceExternalities:l,fetchExternalities:new Bl(i,r,this.chainSpec)},u=Wl.createAccumulateExecutor(t,a,h,this.chainSpec);let d=te.empty();d=K.is(D.V0_6_4)?Te.encodeObject(Zl,{slot:e,serviceId:t,operands:r},this.chainSpec):K.is(D.V0_6_5)?Te.encodeObject(eh,{slot:e,serviceId:t,operands:r},this.chainSpec):Te.encodeObject(th,{slot:e,serviceId:t,operands:Ae(r.length)});const f=await u.run(d,yo(s)),[p,g]=l.getStateUpdates();if(f.hasStatus()){const e=f.status;if(e===Yn.OOG||e===Yn.PANIC)return Z.ok({stateUpdate:g,consumedGas:Or(f.consumedGas)})}if(f.hasMemorySlice()&&f.memorySlice.length===Rt){const e=re.fromBlob(f.memorySlice,Rt);p.yieldedRoot=e.asOpaque()}return Z.ok({stateUpdate:p,consumedGas:Or(f.consumedGas)})}getOperandsAndGasCost(e,t){let r=this.state.privilegedServices.autoAccumulateServices.find(t=>t.service===e)?.gasLimit??Or(0n);const s=[];for(const i of t){const t=i.results.filter(t=>t.serviceId===e);for(const e of t)r=Or(r+e.gas),s.push(Cl.new({gas:e.gas,payloadHash:e.payloadHash,result:e.result,authorizationOutput:i.authorizationOutput,exportsRoot:i.workPackageSpec.exportsRoot,hash:i.workPackageSpec.hash,authorizerHash:i.authorizerHash}))}return{operands:s,gasCost:r}}async accumulateSingleService(e,t,r,s){const{operands:i,gasCost:n}=this.getOperandsAndGasCost(e,t);Xl.trace(`Accumulating service ${e}, items: ${i.length} at slot: ${r}.`);const o=await this.pvmAccumulateInvocation(r,e,i,n,s);return o.isError?(Xl.trace(`Accumulation failed for ${e}.`),{stateUpdate:null,consumedGas:n}):(Xl.trace(`Accumulation successful for ${e}.`),o.ok)}async accumulateSequentially(e,t,r,s){const i=this.findReportCutoffIndex(e,t);if(0===i)return{accumulatedReports:Ae(0),gasCosts:[],yieldedRoots:[],pendingTransfers:[],stateUpdates:[]};const n=t.slice(0,i),o=t.slice(i),{gasCosts:a,yieldedRoots:c,pendingTransfers:l,stateUpdates:h,...u}=await this.accumulateInParallel(n,r,s),d=a.reduce((e,[t,r])=>e+r,0n),{accumulatedReports:f,gasCosts:p,yieldedRoots:g,pendingTransfers:y,stateUpdates:m,...b}=await this.accumulateSequentially(Or(e-d),o,r,s);return{accumulatedReports:Ae(i+f),gasCosts:a.concat(p),yieldedRoots:c.concat(g),pendingTransfers:l.concat(y),stateUpdates:h.concat(m)}}async accumulateInParallel(e,t,r){const s=this.state.privilegedServices.autoAccumulateServices.map(({service:e})=>e),i=e.flatMap(e=>e.results.map(e=>e.serviceId)).concat(Array.from(s)),n=function(e){const t=new Set;for(const r of e)t.add(r);return Array.from(t)}(s.concat(i)),o=[],a=[],c=[],l=[];for(const s of n){const{consumedGas:i,stateUpdate:n}=await this.accumulateSingleService(s,e,t,r);a.push([s,Or(i)]),null!==n&&(o.push([s,n]),l.push([s,n.transfers]),null!==n.yieldedRoot&&c.push([s,n.yieldedRoot]))}return{stateUpdates:o,pendingTransfers:l,yieldedRoots:c,gasCosts:a}}mergeServiceStateUpdates(e,t){const{authManager:r,manager:s,validatorsManager:i}=this.state.privilegedServices;let n=null;const o=this.state.authQueues.slice();let a=!1,c=null;const l=[];for(const[h,u]of e){if(h===s&&null!==u.privilegedServices){const{manager:e,authorizer:t,validators:r,autoAccumulate:s}=u.privilegedServices;Q(null===n,"Only one service can update privileged services!"),n=li.create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s.map(([e,t])=>ci.create({gasLimit:t,service:e}))})}if(h===r&&null!==u.authorizationQueues)for(const[e,t]of u.authorizationQueues)o[e]=t,a=!0;h===i&&null!==u.validatorsData&&(Q(null===c,"Only one service can update designated validators!"),c=u.validatorsData),l.push(u.intoServicesUpdate(t))}const h=l.reduce((e,t)=>(e.servicesRemoved.push(...t.servicesRemoved),e.servicesUpdates.push(...t.servicesUpdates),e.preimages.push(...t.preimages),e.storage.push(...t.storage),e),{servicesRemoved:[],servicesUpdates:[],preimages:[],storage:[]}),u=new Set;for(const e of h.servicesUpdates)if(e.action.kind===wi.Create){if(u.has(e.serviceId))return Z.error("duplicate service created",`duplicate service ${e.serviceId} has been created!`);u.add(e.serviceId)}return Z.ok({...h,...null!==n?{privilegedServices:n}:{},...a?{authQueues:o}:{},...null!==c?{designatedValidatorData:c}:{}})}getAccumulationStateUpdate(e,t,r){const s=this.chainSpec.epochLength,i=r%s,n=fl(e),o=Array.from(n).sort((e,t)=>ai(e,t).value),a=Mr(this.state.recentlyAccumulated.slice(1).concat(cr.from(o)),this.chainSpec),c=this.state.accumulationQueue.slice();c[i]=yl(t,n);for(let e=1;e<s;e++)if(e<r-this.state.timeslot)c[(i+s-e)%s]=[];else{const t=(i+s-e)%s;c[t]=yl(c[t],n)}return{recentlyAccumulated:a,accumulationQueue:Mr(c,this.chainSpec),timeslot:r}}getGasLimit(){const e=Jl*BigInt(this.chainSpec.coresCount)+this.state.privilegedServices.autoAccumulateServices.reduce((e,{gasLimit:t})=>e+t,0n),t=Or(Yl>e?Yl:e);return Or(t)}async transition({reports:e,slot:t,entropy:r}){const s=new gl(this.chainSpec,this.state),i=s.getWorkReportsToAccumulateImmediately(e),n=s.getWorkReportsToAccumulateLater(e),o=yl(s.getQueueFromState(t).concat(n),fl(i)),a=s.enqueueReports(o),c=i.concat(a),l=this.getGasLimit(),{accumulatedReports:h,yieldedRoots:u,gasCosts:d,pendingTransfers:f,stateUpdates:p,...g}=await this.accumulateSequentially(l,c,t,r),y=c.slice(0,h),m=this.getAccumulationStateUpdate(y,n,t),b=this.mergeServiceStateUpdates(p,t);if(b.isError)return b;const A=await async function(e){const t=await nr.create(),r=(n=t,{hashConcat:(e,t=[])=>or(n,[e,...t].map(te.blobFrom)).asOpaque()}),s=tn.empty(r),i=e.sort((e,t)=>e[0]-t[0]);var n;for(const[e,t]of i){const r=te.blobFromParts([Ee(e),t.raw]);s.set(re.fromBlob(r.raw,36).asOpaque(),r)}return s.getRootHash().asOpaque()}(u);return Z.ok({root:A,stateUpdate:{...m,...b.ok}})}}class sh{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}transition(e){const t=this.state.authPools.slice();for(let r=Ur(0);r<this.chainSpec.coresCount;r++){let s=t[r].slice();const i=this.state.authQueues[r],n=e.used.get(r);for(void 0!==n&&(s=s.filter(e=>!n.delete(e))),s.push(i[e.slot%80]);s.length>8;)s.shift();t[r]=lr(s)}return{authPools:ri(t,this.chainSpec)}}}class ih{hasher;state;constructor(e,t){this.hasher=e,this.state=t}transition(e){const t=this.state.recentBlocks.slice(),r=t.length>0?t[t.length-1]:null;null!==r&&(r.postStateRoot=e.priorStateRoot);const s=null!==r?wl.fromPeaks(this.hasher,r.mmr):wl.empty(this.hasher);return s.append(e.accumulateRoot),t.push({headerHash:e.headerHash,mmr:s.getPeaks(),postStateRoot:re.zero(Rt).asOpaque(),reported:e.workPackages}),t.length>8&&t.shift(),{recentBlocks:t}}}function nh(e,t,r){return function(e,t,r){const s=oh(_r(t%r.epochLength),r.rotationPeriod),i=(n=function(e,t){Q(32===t.length,`Expected entropy of length 32, got ${t.length}`);const r=e.length,s=function(e,t){const r=new Array(t),s=new Uint8Array(36);s.set(e.raw);for(let e=0;e<t;e++){s.set(Ee(Ae(Math.floor(e/8))),32);const t=4*e%32,i=t+4,n=Ce(Ht(s).raw.subarray(t,i))>>>0;r[e]=n}return r}(t,e.length),i=new Array(r);let n=r;for(let t=0;t<r;t++){const r=s[t]%n;i[t]=e[r],n--,e[r]=e[n],e.length=n}return i}(Array(r.validatorsCount).fill(0).map((e,t)=>Ur(Math.floor(t*r.coresCount/r.validatorsCount))),e),o=s,a=r.coresCount,n.map(e=>(e+o)%a));var n,o,a;return i}(t,r,e)}function oh(e,t){return Math.floor(e/t)}const ah=te.blobFromString("jam_guarantee").raw;function ch(e){return te.blobFromParts(ah,e.raw)}const lh=1e7;class hh{chainSpec;state;mmrHasher;headerChain;constructor(e,t,r,s){this.chainSpec=e,this.state=t,this.mmrHasher=r,this.headerChain=s}async transition(e){const t=function(e,t){const r=t.coresCount;let s=-1;for(const t of e){const e=t.view().report.view().coreIndex.materialize();if(s>=e)return Z.error(El.OutOfOrderGuarantee,`Core indices of work reports are not unique or in order. Got: ${e}, expected at least: ${s+1}`);if(e>=r)return Z.error(El.BadCoreIndex,`Invalid core index. Got: ${e}, max: ${r}`);s=e}return Z.ok(W)}(e.guarantees,this.chainSpec);if(t.isError)return t;const r=function(e){for(const t of e){const e=t.view().report.view(),r=e.context.view().prerequisites.view().length,s=e.segmentRootLookup.view().length;if(r+s>8)return Z.error(El.TooManyDependencies,`Report at ${e.coreIndex.materialize()} has too many dependencies. Got ${r} + ${s}, max: 8`);const i=e.authorizationOutput.view().length;let n=0;for(const t of e.results.view())n+=t.view().result.view().okBlob?.raw.length??0;if(i+n>49152)return Z.error(El.WorkReportTooBig,`Work report at ${e.coreIndex.materialize()} too big. Got ${i} + ${n}, max: 49152`)}return Z.ok(W)}(e.guarantees);if(r.isError)return r;const s=this.workReportHashes(e.guarantees),i=this.verifyCredentials(e,s);if(i.isError)return i;const n=Ct(i.ok),o=this.verifyPostSignatureChecks(e.guarantees);if(o.isError)return o;const a=this.verifyContextualValidity(e);if(a.isError)return a;const c=this.checkSignatures(i.ok,await n);if(c.isError)return c;let l=0;const h=this.state.availabilityAssignment.slice();for(const t of e.guarantees){const r=t.view().report.materialize(),i=s[l];h[r.coreIndex]=ei.create({workReport:new Ot(i,r),timeout:e.slot}),l+=1}return Z.ok({stateUpdate:{availabilityAssignment:ri(h,this.chainSpec)},reported:a.ok,reporters:dr.fromArray(fe,i.ok.map(e=>e.key)).slice()})}workReportHashes(e){const t=[];for(const r of e)t.push(q(Ht(r.view().report.encoded())));return t}verifyCredentials(e,t){return function(e,t,r,s){const i=[],n=r;let o=0;for(const r of e){const e=r.view(),a=e.report.view().coreIndex.materialize(),c=t[o];o+=1;const l=e.credentials.view();if(l.length<es[0]||l.length>es[1])return Z.error(El.InsufficientGuarantees,`Invalid number of credentials. Expected ${es}, got ${l.length}`);const h=s(n,e.slot.materialize());if(h.isError)return h;const u=h.ok;let d=-1;for(const e of l){const t=e.view(),r=t.validatorIndex.materialize();if(d>=r)return Z.error(El.NotSortedOrUniqueGuarantors,`Credentials must be sorted by validator index. Got ${r}, expected at least ${d+1}`);d=r;const s=t.signature.materialize(),n=u[r];if(void 0===n)return Z.error(El.BadValidatorIndex,`Invalid validator index: ${r}`);if(n.core!==a)return Z.error(El.WrongAssignment,`Invalid core assignment for validator ${r}. Expected: ${n.core}, got: ${a}`);i.push({signature:s,key:n.ed25519,message:ch(c)})}}return Z.ok(i)}(e.guarantees,t,e.slot,(e,t)=>this.getGuarantorAssignment(e,t))}verifyPostSignatureChecks(e){return function(e,t,r,s){for(const i of e){const e=i.materialize().report,n=e.coreIndex;if(null!==t[n])return Z.error(El.CoreEngaged,`Report pending availability at core: ${n}`);const o=e.authorizerHash;if(void 0===r[n].find(e=>e.isEqualTo(o)))return Z.error(El.CoreUnauthorized,`Authorizer hash not found in the pool of core ${n}: ${o}`);for(const t of e.results){const e=s(t.serviceId);if(null===e)return Z.error(El.BadServiceId,`No service with id: ${t.serviceId}`);const r=e.getInfo();if(t.gas<r.accumulateMinGas)return Z.error(El.ServiceItemGasTooLow,`Service (${t.serviceId}) gas is less than minimal. Got: ${t.gas}, expected at least: ${r.accumulateMinGas}`)}const a=Se(...e.results.map(e=>e.gas));if(a.overflow||a.value>lh)return Z.error(El.WorkReportGasTooHigh,`Total gas too high. Got: ${a.value} (ovfl: ${a.overflow}), maximal: ${lh}`)}return Z.ok(W)}(e,this.state.availabilityAssignment,this.state.authPools,e=>this.state.getService(e))}verifyContextualValidity(e){return function(e,t,r,s){const i=[],n=ar.new(),o=cr.new(),a=cr.new();for(const r of e.guarantees){const e=r.materialize();i.push(e.report.context);const s=Xr.create({workPackageHash:e.report.workPackageSpec.hash,segmentTreeRoot:e.report.workPackageSpec.exportsRoot});n.set(s.workPackageHash,s),o.insertAll(e.report.context.prerequisites),a.insertAll(e.report.segmentRootLookup.map(e=>e.workPackageHash));for(const r of e.report.results){const e=t.getService(r.serviceId);if(null===e)return Z.error(El.BadServiceId,`No service with id: ${r.serviceId}`);if(!r.codeHash.isEqualTo(e.getInfo().codeHash))return Z.error(El.BadCodeHash,`Service (${r.serviceId}) code hash mismatch. Got: ${r.codeHash}, expected: ${e.getInfo().codeHash}`)}}if(n.size!==e.guarantees.length)return Z.error(El.DuplicatePackage,"Duplicate work package detected.");const c=function(e,t,r,s,i){const n=ar.new();for(const e of r.recentBlocks)n.set(e.headerHash,e);for(const r of t){const t=n.get(r.anchor);if(void 0===t)return Z.error(El.AnchorNotRecent,`Anchor block ${r.anchor} not found in recent blocks.`);if(!t.postStateRoot.isEqualTo(r.stateRoot))return Z.error(El.BadStateRoot,`Anchor state root mismatch. Got: ${r.stateRoot}, expected: ${t.postStateRoot}.`);const o=wl.fromPeaks(s,t.mmr).getSuperPeakHash();if(!o.isEqualTo(r.beefyRoot))return Z.error(El.BadBeefyMmrRoot,`Invalid BEEFY super peak hash. Got: ${r.beefyRoot}, expected: ${o}. Anchor: ${t.headerHash}`);if(r.lookupAnchorSlot<e)return Z.error(El.SegmentRootLookupInvalid,`Lookup anchor slot's too old. Got: ${r.lookupAnchorSlot}, minimal: ${e}`);if(!i.isInChain(r.lookupAnchor))return Z.error(El.SegmentRootLookupInvalid,`Lookup anchor is not found in chain. Hash: ${r.lookupAnchor} (slot: ${r.lookupAnchorSlot})`)}return Z.ok(W)}(Math.max(0,e.slot-14400),i,t,r,s);if(c.isError)return c;const l=function(e,t){const r=cr.new();for(const e of t.recentBlocks)r.insertAll(Array.from(e.reported.keys()));for(const e of t.recentlyAccumulated)r.insertAll(Array.from(e));for(const e of t.accumulationQueue)r.insertAll(e.map(e=>e.report.workPackageSpec.hash));for(const e of t.availabilityAssignment)null!==e&&r.insert(e.workReport.data.workPackageSpec.hash);const s=r.intersection(e);for(const e of s)return Z.error(El.DuplicatePackage,`The same work package hash found in the pipeline (workPackageHash: ${e})`);return Z.ok(W)}(cr.viewDictionaryKeys(n),t);if(l.isError)return l;const h=ar.new();for(const e of t.recentBlocks)for(const t of e.reported.values())h.set(t.workPackageHash,t.segmentTreeRoot);const u=function({currentWorkPackages:e,recentlyReported:t,prerequisiteHashes:r,segmentRootLookupHashes:s}){const i=(r,s=!1)=>{for(const i of r)if(!e.has(i)&&!t.has(i))return Z.error(s?El.SegmentRootLookupInvalid:El.DependencyMissing,`Missing work package ${i} in current extrinsic or recent history.`);return Z.ok(W)},n=i(r);if(n.isError)return n;const o=i(s,!0);return o.isError?o:Z.ok(W)}({currentWorkPackages:n,recentlyReported:h,prerequisiteHashes:o,segmentRootLookupHashes:a});if(u.isError)return u;for(const t of e.guarantees){const e=t.materialize().report;for(const t of e.segmentRootLookup){let e=n.get(t.workPackageHash);if(void 0===e){const r=h.get(t.workPackageHash);e=void 0!==r?Xr.create({workPackageHash:t.workPackageHash,segmentTreeRoot:r}):void 0}if(void 0===e||!e.segmentTreeRoot.isEqualTo(t.segmentTreeRoot))return Z.error(El.SegmentRootLookupInvalid,`Mismatching segment tree root for package ${t.workPackageHash}. Got: ${t.segmentTreeRoot}, expected: ${e?.segmentTreeRoot}`)}}return Z.ok(n)}(e,this.state,this.mmrHasher,this.headerChain)}checkSignatures(e,t){if(t.every(e=>e))return Z.ok(W);const r=t.map((t,r)=>t?null:e[r].key).filter(e=>null!==e);return Z.error(El.BadSignature,`Invalid signatures for validators with keys: ${r.join(", ")}`)}getGuarantorAssignment(e,t){const r=this.chainSpec.epochLength,s=this.chainSpec.rotationPeriod,i=oh(e,s),n=oh(t,s),o=Math.max(0,i-1)*s;if(t>e)return Z.error(El.FutureReportSlot,`Report slot is in future. Block ${e}, Report: ${t}`);if(t<o)return Z.error(El.ReportEpochBeforeLast,`Report slot is too old. Block ${e}, Report: ${t}`);let a=this.state.entropy[2],c=this.state.currentValidatorData,l=e;i>n&&(l=_r(e-s),function(e,t,r){const s=Math.floor(t/r);return Math.floor(e/r)!==s}(l,e,r)&&(a=this.state.entropy[3],c=this.state.previousValidatorData));const h=nh(this.chainSpec,a,l);return Z.ok((u=c,d=(e,t)=>({core:e,ed25519:t.ed25519}),h.map((e,t)=>d(e,u[t]))));var u,d}}class uh{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}getStatistics(e){if(Math.floor(this.state.timeslot/this.chainSpec.epochLength)===Math.floor(e/this.chainSpec.epochLength))return this.state.statistics;const t=Nr(Array.from({length:this.chainSpec.validatorsCount},()=>_i.empty()),this.chainSpec);return Ti.create({...this.state.statistics,current:t,previous:this.state.statistics.current})}calculateDAScoreCore(e){if(void 0===e)return Ae(0);let t=0;return t+=e.workPackageSpec.length+4104*Math.ceil(65*e.workPackageSpec.exportsCount/64),Ae(t)}calculateRefineScore(e){const t={gasUsed:0n,imported:0,extrinsicCount:0,extrinsicSize:0,exported:0};for(const r of e)t.gasUsed+=r.load.gasUsed,t.imported+=r.load.importedSegments,t.extrinsicCount+=r.load.extrinsicCount,t.extrinsicSize+=r.load.extrinsicSize,t.exported+=r.load.exportedSegments;return{gasUsed:Or(t.gasUsed),exported:me(t.exported),imported:me(t.imported),extrinsicCount:me(t.extrinsicCount),extrinsicSize:Ae(t.extrinsicSize)}}calculateProvidedScoreService(e){const t={count:0,size:0};for(const r of e)t.count+=1,t.size+=r.blob.length;return{count:me(t.count),size:Ae(t.size)}}collectServiceIds(e,t,r,s){const i=new Set;for(const t of e)i.add(t.requester);for(const e of t)i.add(e.serviceId);for(const e of r)i.add(e);for(const e of s)i.add(e);return i}transition(e){const{slot:t,authorIndex:r,extrinsic:s,incomingReports:i,availableReports:n}=e,o=this.getStatistics(t),{current:a,cores:c,services:l}=o;Q(void 0!==a[r],"authorIndex is out of bounds");const h=a[r].blocks+1;a[r].blocks=Ae(h);const u=a[r].tickets+s.tickets.length;a[r].tickets=Ae(u);const d=a[r].preImages+s.preimages.length;a[r].preImages=Ae(d);const f=s.preimages.reduce((e,t)=>e+t.blob.length,0),p=a[r].preImagesSize+f;a[r].preImagesSize=Ae(p);for(const{credentials:e}of s.guarantees)for(const{validatorIndex:t}of e){const e=a[t].guarantees+1;a[t].guarantees=Ae(e)}for(const{validatorIndex:e}of s.assurances){const t=a[e].assurances+1;a[e].assurances=Ae(t)}for(let e=0;e<this.chainSpec.coresCount;e++){const t=Ur(e),r=i.find(e=>e.coreIndex===t),{imported:o,extrinsicCount:a,extrinsicSize:l,exported:h,gasUsed:u}=void 0!==r?this.calculateRefineScore(r.results.map(e=>e)):{imported:me(0),extrinsicCount:me(0),extrinsicSize:Ae(0),exported:me(0),gasUsed:Or(0n)},d=n.find(e=>e.coreIndex===t),f=s.assurances.reduce((t,{bitfield:r})=>t+(r.isSet(e)?1:0),0);c[t].imports=o,c[t].extrinsicCount=a,c[t].extrinsicSize=l,c[t].exports=h,c[t].gasUsed=u,c[t].bundleSize=Ae(r?.workPackageSpec.length??0),c[t].dataAvailabilityLoad=this.calculateDAScoreCore(d),c[t].popularity=me(f)}l.clear();const g=this.collectServiceIds(s.preimages,i.flatMap(e=>e.results),e.accumulationStatistics.keys(),e.transferStatistics.keys());for(const t of g){const r=i.flatMap(e=>e.results.filter(e=>e.serviceId===t)),{gasUsed:n,imported:o,extrinsicCount:a,extrinsicSize:c,exported:h}=this.calculateRefineScore(r),u=s.preimages.filter(e=>e.requester===t),{count:d,size:f}=this.calculateProvidedScoreService(u),{count:p,gasUsed:g}=e.accumulationStatistics.get(t)??{count:Ae(0),gasUsed:Or(0n)},{count:y,gasUsed:m}=e.transferStatistics.get(t)??{count:Ae(0),gasUsed:Or(0n)},b=Ui.empty();b.refinementCount=Ae(r.length),b.refinementGasUsed=n,b.imports=o,b.extrinsicCount=a,b.extrinsicSize=c,b.exports=h,b.providedCount=d,b.providedSize=f,b.providedCount=d,b.providedSize=f,b.accumulateCount=p,b.accumulateGasUsed=g,b.onTransfersCount=y,b.onTransfersGasUsed=m,l.set(t,b)}return{statistics:o}}}class dh{blocks;constructor(e){this.blocks=e}isInChain(e){return null!==this.blocks.getHeader(e)}}var fh;!function(e){e[e.Assurances=0]="Assurances",e[e.Disputes=1]="Disputes",e[e.Safrole=2]="Safrole",e[e.Reports=3]="Reports",e[e.Preimages=4]="Preimages",e[e.SafroleSeal=5]="SafroleSeal",e[e.Accumulate=6]="Accumulate"}(fh||(fh={}));const ph=(e,t)=>Z.taggedError(fh,e,t);class gh{chainSpec;state;hasher;safrole;safroleSeal;disputes;reports;assurances;accumulate;preimages;recentHistory;authorization;statistics;constructor(e,t,r,s,{enableParallelSealVerification:i}){this.chainSpec=e,this.state=t,this.hasher=s;const n=zc.new({synchronous:!i});this.statistics=new uh(e,t),this.safrole=new sl(e,t,n),this.safroleSeal=new il(n),this.recentHistory=new ih(s,t),this.disputes=new Uc(e,t),this.reports=new hh(e,t,s,new dh(r)),this.assurances=new bl(e,t),this.accumulate=new rh(e,t),this.preimages=new Ic(t),this.authorization=new sh(e,t)}async verifySeal(e,t){const r=this.safrole.getSafroleSealState(e);return await this.safroleSeal.verifyHeaderSeal(t.header.view(),r)}async transition(e,t,r=null,s=!1){const i=e.header.materialize(),n=i.timeSlotIndex;let o=r;if(s&&(o=Ht(i.seal).asOpaque()),null===o){const t=await this.verifySeal(n,e);if(t.isError)return ph(fh.SafroleSeal,t);o=t.ok}const a=await this.disputes.transition(e.extrinsic.view().disputes.materialize());if(a.isError)return ph(fh.Disputes,a);const{disputesRecords:c,availabilityAssignment:l,...h}=a.ok.stateUpdate,u=await this.reports.transition({slot:n,guarantees:e.extrinsic.view().guarantees.view(),knownPackages:[]});if(u.isError)return ph(fh.Reports,u);const{availabilityAssignment:d,...f}=u.ok.stateUpdate,p=await this.assurances.transition({assurances:e.extrinsic.view().assurances.view(),slot:n,parentHash:i.parentHeaderHash});if(p.isError)return ph(fh.Assurances,p);const{availabilityAssignment:g,...y}=p.ok.stateUpdate,m=await this.safrole.transition({slot:n,entropy:o,extrinsic:e.extrinsic.view().tickets.materialize()});if(m.isError)return ph(fh.Safrole,m);const{timeslot:b,ticketsAccumulator:A,sealingKeySeries:I,epochRoot:v,entropy:w,nextValidatorData:S,currentValidatorData:E,previousValidatorData:C,...k}=m.ok.stateUpdate,x=this.preimages.integrate({slot:n,preimages:e.extrinsic.view().preimages.materialize()});if(x.isError)return ph(fh.Preimages,x);const{preimages:_,...B}=x.ok,R=await this.accumulate.transition({slot:n,reports:p.ok.availableReports,entropy:w[0]});if(R.isError)return ph(fh.Accumulate,R);const{root:O,stateUpdate:U,...T}=R.ok,{privilegedServices:N,authQueues:D,designatedValidatorData:M,timeslot:P,preimages:L,...H}=U,K=this.recentHistory.transition({headerHash:t,priorStateRoot:i.priorStateRoot,accumulateRoot:O,workPackages:u.ok.reported}),{recentBlocks:Q,...V}=K,F=this.authorization.transition({slot:n,used:this.getUsedAuthorizerHashes(e.extrinsic.view().guarantees.view())}),{authPools:$,...j}=F,G=e.extrinsic.materialize(),q=this.statistics.transition({slot:n,authorIndex:i.bandersnatchBlockAuthorIndex,extrinsic:G,incomingReports:G.guarantees.map(e=>e.report),availableReports:p.ok.availableReports,accumulationStatistics:new Map,transferStatistics:new Map}),{statistics:z,...W}=q;return Z.ok({...void 0!==D?{authQueues:D}:{},...void 0!==M?{designatedValidatorData:M}:{},...void 0!==N?{privilegedServices:N}:{},authPools:$,preimages:_.concat(L),disputesRecords:c,availabilityAssignment:yh(this.state.availabilityAssignment,d,l,g),recentBlocks:Q,statistics:z,timeslot:b,epochRoot:v,entropy:w,currentValidatorData:E,nextValidatorData:S,previousValidatorData:C,sealingKeySeries:I,ticketsAccumulator:A,...H})}getUsedAuthorizerHashes(e){const t=new Map;for(const r of e){const e=r.view().report.view(),s=e.coreIndex.materialize(),i=t.get(s)??cr.new();i.insert(e.authorizerHash.materialize()),t.set(s,i)}return t}}function yh(e,t,r,s){const i=e.slice();for(const n of t.keys())null!==r[n]&&null!==s[n]||(i[n]=null),null!==t[n]&&e[n]!==t[n]&&(i[n]=t[n]);return i}var mh;!function(e){e[e.Verifier=0]="Verifier",e[e.Stf=1]="Stf",e[e.Update=2]="Update"}(mh||(mh={}));const bh=(e,t)=>Z.taggedError(mh,e,t);class Ah{logger;blocks;states;verifier;stf;state;constructor(e,t,r,s,i){this.logger=r,this.blocks=s,this.states=i;const n=this.blocks.getBestHeaderHash(),o=i.getState(n);if(null===o)throw new Error(`Unable to load best state from header hash: ${n}.`);this.verifier=new Sc(t,s),this.stf=new gh(e,o,s,t,{enableParallelSealVerification:!0}),this.state=o,r.info(`😎 Best time slot: ${o.timeslot} (header hash: ${n})`)}async preverifySeal(e,t){try{const r=await this.stf.verifySeal(e,t);return r.isOk?r.ok:(this.logger.warn(`Unable to pre-verify the seal: ${X(r)}`),null)}catch(e){return this.logger.warn(`Error while trying to pre-verify the seal: ${e}`),null}}async importBlock(e,t,r=!1){const s=this.logger;s.log("🧱 Attempting to import a new block "+(null!==t?"(seal preverified)":""));const i=j("import:verify"),n=await this.verifier.verifyBlock(e);if(s.log(i()),n.isError)return bh(mh.Verifier,n);const o=e.header.view().timeSlotIndex.materialize(),a=n.ok;s.log(`🧱 Verified block: Got hash ${a} for block at slot ${o}.`);const c=j("import:stf"),l=await this.stf.transition(e,a,t,r);if(s.log(c()),l.isError)return bh(mh.Stf,l);const h=l.ok,u=j("import:state"),d=await this.states.updateAndSetState(a,this.state,h);if(d.isError)return s.error(`🧱 Unable to update state: ${X(d)}`),bh(mh.Update,d);const f=this.states.getState(a);if(null===f)throw new Error("Freshly updated state not in the DB?");this.state.updateBackend(f.backend),s.log(u());const p=j("import:db"),g=this.blocks.insertBlock(new Ot(a,e)),y=await this.states.getStateRoot(f);s.log(`🧱 Storing post-state-root for ${a}: ${y}.`);const m=this.blocks.setPostStateRoot(a,y);return await Promise.all([g,m]),s.log(p()),await this.blocks.setBestHeaderHash(a),Z.ok(new Ot(a,e.header.view()))}bestBlockHash(){return this.blocks.getBestHeaderHash()}}const Ih=m.new(void 0,"importer");class vh extends Pn{onBestBlock=new Nn;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{bestBlock:e=>this.triggerBestBlock(e)}})}getConfig(){if(null===this.data)throw new Error("Did not receive chain spec config!");return this.data}triggerBestBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=xe.decodeObject(ds,e,t.chainSpec);this.onBestBlock.emit(r)}}sendBlock(e,t){e.sendSignal("block",t,[t.buffer])}finish(e){return this.onBestBlock.markDone(),{state:"finished",data:e.sendRequest("finish",null)}}}class wh extends Pn{onBlock=new Nn;constructor(){super({name:"ready(importer)",allowedTransitions:["finished"],requestHandlers:{finish:async()=>this.endWork()},signalListeners:{block:e=>this.triggerOnBlock(e)}})}getConfig(){if(null===this.data)throw new Error("Did not receive chain spec config!");return this.data}announce(e,t){const r=this.getConfig(),s=Te.encodeObject(ds,t,r.chainSpec).raw;e.sendSignal("bestBlock",s,[s.buffer])}triggerOnBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=xe.decodeObject(ys.Codec.View,e,t.chainSpec);this.onBlock.emit(r)}else Ih.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}async endWork(){return this.onBlock.markDone(),{response:null,transitionTo:{state:"finished",data:Promise.resolve(null)}}}}const Sh=m.new(void 0,"importer");if(!T.isMainThread){m.configureAll(process.env.JAM_LOG??"",l.LOG);const e=function(){const e=new Kn("ready(importer)",yr.reInit),t=new wh,r=new Ln;return new Dn("importer",e,[e,t,r])}();On.receiveChannel(e,T.parentPort).then(e=>async function(e){Sh.info(`📥 Importer starting ${e.currentState()}`);const t=await e.waitForState("ready(importer)"),r=await t.doUntil("finished",async(e,t)=>{Sh.info("📥 Importer waiting for blocks.");const r=e.getConfig(),s=new wn(r.dbPath),i=new In(r.chainSpec,s),n=new Sn(r.chainSpec,s),o=new Ah(r.chainSpec,new Ac(r.chainSpec,await Eh,new Tt),Sh,i,n);let a=!1;const c=new vc(r.chainSpec,o);e.onBlock.on(async s=>{const i=c.push(s)??_r(0);if(Sh.log(`🧊 Got block: #${i}`),!a){a=!0;try{for(;;){const s=c.shift();if(void 0===s)return;const{block:i,seal:n,timeSlot:a}=s,l=j("importBlock"),h=await o.importBlock(i,await n,r.omitSealVerification);if(h.isOk){const r=h.ok;e.announce(t,r),Sh.info(`🧊 Best block: #${r.data.timeSlotIndex.materialize()} (${r.hash})`)}else Sh.log(`❌ Rejected block #${a}: ${X(h)}`);Sh.log(l())}}finally{a=!1}}})});Sh.info("📥 Importer finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>Sh.error(e))}const Eh=nr.create(),Ch=t(import.meta.url)("node:timers/promises");class kh{chainSpec;keccakHasher;blocks;states;hashAllocator=new Tt;lastHeaderHash;lastHeader;lastState;constructor(e,t,r,s){this.chainSpec=e,this.keccakHasher=t,this.blocks=r,this.states=s;const{lastHeaderHash:i,lastHeader:n,lastState:o}=kh.getLastHeaderAndState(r,s);this.lastHeaderHash=i,this.lastHeader=n,this.lastState=o}refreshLastHeaderAndState(){const{lastHeaderHash:e,lastHeader:t,lastState:r}=kh.getLastHeaderAndState(this.blocks,this.states);this.lastHeaderHash=e,this.lastHeader=t,this.lastState=r}static getLastHeaderAndState(e,t){const r=e.getBestHeaderHash(),s=e.getHeader(r)?.materialize()??null,i=t.getState(r);if(null===s)throw new Error(`Missing best header: ${r}! Make sure DB is initialized.`);if(null===i)throw new Error(`Missing last state at ${r}! Make sure DB is initialized.`);return{lastHeaderHash:r,lastHeader:s,lastState:i}}async nextEncodedBlock(){const e=await this.nextBlock();return Te.encodeObject(ys.Codec,e,this.chainSpec)}async nextBlock(){this.refreshLastHeaderAndState();const e=this.lastHeader.timeSlotIndex+1,t=Br(e%6),r=new Ac(this.chainSpec,this.keccakHasher,this.hashAllocator),s=this.lastHeaderHash,i=this.states.getStateRoot(this.lastState),n=gs.create({tickets:[],preimages:[],guarantees:[],assurances:[],disputes:xr.create({verdicts:[],culprits:[],faults:[]})}),o=Te.encodeObject(gs.Codec,n,this.chainSpec),a=xe.decodeObject(gs.Codec.View,o,this.chainSpec),c=r.extrinsic(a).hash,l=Te.create();l.i32(e),l.i16(t),l.bytes(re.fill(90,0));const h=re.fromBlob(l.viewResult().raw,96),u=hs.create({parentHeaderHash:s,priorStateRoot:await i,extrinsicHash:c,timeSlotIndex:_r(e),epochMarker:null,ticketsMarker:null,offendersMarker:[],bandersnatchBlockAuthorIndex:t,entropySource:re.fill(96,42*e%256).asOpaque(),seal:h.asOpaque()}),d=Te.encodeObject(hs.Codec,u,this.chainSpec),f=xe.decodeObject(hs.Codec.View,d,this.chainSpec);return this.lastHeaderHash=r.header(f).hash,this.lastHeader=u,ys.create({header:u,extrinsic:n})}}const xh=m.new(void 0,"block-generator");class _h extends Pn{onBlock=new Nn;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{block:e=>this.triggerOnBlock(e)}})}triggerOnBlock(e){e instanceof Uint8Array?this.onBlock.emit(e):xh.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}finish(e){return this.onBlock.markDone(),{state:"finished",data:e.sendRequest("finish",null)}}}class Bh extends Pn{constructor(){super({name:"ready(generator)",allowedTransitions:["finished"],requestHandlers:{finish:async()=>this.endWork()}})}sendBlock(e,t){e.sendSignal("block",t.raw,[t.raw.buffer])}getConfig(){if(null===this.data)throw new Error("Config not received.");return this.data}async endWork(){return{response:null,transitionTo:{state:"finished",data:Promise.resolve(null)}}}}const Rh=m.new(void 0,"block-generator");if(!T.isMainThread){m.configureAll(process.env.JAM_LOG??"",l.LOG);const e=function(){const e=new Kn("ready(generator)",yr.reInit),t=new Bh,r=new Ln;return new Dn("block-generator",e,[e,t,r])}();On.receiveChannel(e,T.parentPort).then(e=>async function(e){Rh.info(`🎁 Block Generator running ${e.currentState()}`);const t=await e.waitForState("ready(generator)"),r=t.currentState().getConfig(),s=new wn(r.dbPath),i=new In(r.chainSpec,s),n=new Sn(r.chainSpec,s),o=await t.doUntil("finished",async(e,t,s)=>{let o=0;const a=new kh(r.chainSpec,await nr.create(),i,n);for(;!s();){o+=1;const r=await a.nextEncodedBlock();Rh.trace(`Sending block ${o}`),e.sendBlock(t,r),await(0,Ch.setTimeout)(3e3)}});Rh.info("Block Generator finished. Closing channel."),o.currentState().close(e)}(e)).catch(e=>{Rh.error(e),void 0!==e.stack&&Rh.error(e.stack),void 0!==e.cause&&Rh.error(e.cause)})}const Oh=t(import.meta.url)("dgram");var Uh,Th;(Th=Uh||(Uh={}))[Th.NOTSET=0]="NOTSET",Th[Th.DEBUG=1]="DEBUG",Th[Th.INFO=2]="INFO",Th[Th.WARN=3]="WARN",Th[Th.ERROR=4]="ERROR",Th[Th.SILENT=100]="SILENT";const Nh="captureStackTrace"in Error,Dh="stackTraceLimit"in Error;function Mh(e){switch(e){case Uh.NOTSET:return"NOTSET";case Uh.DEBUG:return"DEBUG";case Uh.INFO:return"INFO";case Uh.WARN:return"WARN";case Uh.ERROR:return"ERROR";case Uh.SILENT:return"SILENT"}}function Ph(e,t){return"function"==typeof t?t():t}function Lh(e){return JSON.stringify(e,Ph)}const Hh=Symbol("level"),Kh=Symbol("key"),Qh=Symbol("keys"),Vh=Symbol("date"),Fh=Symbol("msg"),$h=Symbol("stack"),jh=Symbol("data"),Gh=(function(e,...t){return r=>{let s=e[0];for(let i=0;i<t.length;i++){const n=t[i];if(n===Kh)s+=r.key;else if(n===Qh)s+=r.keys;else if(n===Vh)s+=r.date().toISOString();else if(n===Fh)null!=r.msg&&(s+=r.msg);else if(n===Hh)s+=Mh(r.level);else if(n===jh)s+=Lh(r.data);else if(n===$h){const e=r.stack();""!==e&&(s+="\n"+e)}else s+=n.toString();s+=e[i+1]}return s}})`${Hh}:${Kh}:${Fh}`,qh=class{formatter;constructor(e=Gh){this.formatter=e}setFormatter(e){this.formatter=e}handle(e,t){const r=null!=t?t(e):this.format(e);this.emit(r)}format(e){return this.formatter(e)}},zh=class extends qh{emit(e){console.error(e)}};class Wh{key;level;filter;keys;handlers;parent;_loggers=new Map;loggersRegistry;constructor(e="root",t=Uh.NOTSET,r=[new zh],s){this.key=e,this.level=t,this.handlers=new Set(r),this.parent=s,this.keys=null!=s?`${s.keys}.${e}`:e,this.loggersRegistry=new FinalizationRegistry(e=>{this._loggers.delete(e)})}get loggers(){return new Map([...this._loggers.entries()].map(([e,t])=>{const r=t.deref();return null!=r?[e,r]:void 0}).filter(e=>null!=e))}getChild(e){let t=this._loggers.get(e),r=t?.deref();return null!=r||(r=new Wh(e,Uh.NOTSET,[],this),t=new WeakRef(r),this._loggers.set(e,t),this.loggersRegistry.register(r,e)),r}getParent(){return this.parent}setLevel(e){this.level=e}getEffectiveLevel(){return this.level!==Uh.NOTSET?this.level:this.parent?this.parent.getEffectiveLevel():this.level}isEnabledFor(e){return e>=this.level}addHandler(e){this.handlers.add(e)}removeHandler(e){this.handlers.delete(e)}clearHandlers(){this.handlers.clear()}hasHandlers(){return!!this.handlers.size||(this.parent?.hasHandlers()??!1)}setFilter(e){this.filter=e}unsetFilter(){delete this.filter}debug(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Uh.DEBUG,t):this.log(e,t,Uh.DEBUG,r)}info(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Uh.INFO,t):this.log(e,t,Uh.INFO,r)}warn(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Uh.WARN,t):this.log(e,t,Uh.WARN,r)}error(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Uh.ERROR,t):this.log(e,t,Uh.ERROR,r)}log(e,t,r,s){if(r<this.getEffectiveLevel())return;const i=this.makeRecord(e,t,r);this.callHandlers(i,r,s)}makeRecord(e,t,r){return{logger:this,key:this.key,keys:this.keys,level:r,msg:e?.toString(),data:t,date:()=>new Date,stack:()=>{let e;if(Nh&&Dh){Error.stackTraceLimit++;const t={};Error.captureStackTrace(t,Wh.prototype.log),Error.stackTraceLimit--,e=t.stack,e=e.slice(e.indexOf("\n",e.indexOf("\n")+1)+1)}else e=(new Error).stack??"",e=e.slice(e.indexOf("\n")+1);return e}}}callHandlers(e,t,r,s=""){if(!(t<this.getEffectiveLevel())&&(s=`${this.key}.${s}`,null==this.filter||this.filter.test(s))){for(const t of this.handlers)t.handle(e,r);this.parent&&this.parent.callHandlers(e,t,r,s)}}}const Jh=Wh;t(import.meta.url)("node:process");class Yh extends Event{detail;constructorParams;constructor(e=new.target.name,t,r){"string"==typeof e?(super(e,t),this.detail=t?.detail):(super(new.target.name,e),this.detail=e.detail,r=t),this.constructorParams=r??arguments}clone(){try{return new this.constructor(...this.constructorParams)}catch(e){if("TypeError"===e.name)throw new TypeError(`Cloning ${this.constructor.name} requires the original constructor arguments to be passed into super`);throw e}}}const Xh=Yh;class Zh extends Xh{constructor(e){super(Zh.name,e,arguments)}}const eu=Zh;class tu extends Xh{constructor(e){super(tu.name,e,arguments)}}const ru=tu;class su extends Xh{constructor(e){super(su.name,e,arguments)}}const iu=su,nu=Symbol("_eventTarget"),ou=Symbol("eventTarget"),au=Symbol("_eventHandlers"),cu=Symbol("eventHandlers"),lu=Symbol("_eventHandled"),hu=Symbol("eventHandled"),uu=Symbol("_handleEventError"),du=Symbol("handleEventError");function fu(e){return{capture:!1,once:!1,passive:!1,..."boolean"==typeof e?{capture:e}:"object"==typeof e?e:void 0}}function pu(e,t){return e.capture===t.capture}function gu(){return e=>{const t=class extends e{[nu]=new EventTarget;[au]=new Map;[lu]=new WeakSet;[uu]=e=>{throw e.detail};constructor(...e){super(...e),this[nu].addEventListener(iu.name,this[uu])}get[ou](){return this[nu]}get[cu](){return this[au]}get[hu](){return this[lu]}get[du](){return this[uu]}addEventListener(e,t,r){r=fu(r);const s=this;let i,n,o=!1;if("function"==typeof t||"function"==typeof t?.handleEvent){n=this[au].get(e),void 0===n&&(n=new Set,this[au].set(e,n));for(const e of n)if(e.callback===t&&(i=e.handler,pu(e.options,r))){o=!0;break}}"function"==typeof t?null==i?(i=async function(e){let r;s[lu].add(e);try{r=t.call(s,e)}catch(e){this.dispatchEvent(new iu({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new iu({detail:e}))}},n.add({callback:t,options:r,handler:i})):o||n.add({callback:t,options:r,handler:i}):"function"==typeof t?.handleEvent?null==i?(i=async function(e){let r;s[lu].add(e);try{r=t.handleEvent(e)}catch(e){this.dispatchEvent(new iu({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new iu({detail:e}))}return r},n.add({callback:t,options:r,handler:i})):o||n.add({callback:t,options:r,handler:i}):i=t,this[nu].addEventListener(e,i,r),e===iu.name&&1===n?.size&&this[nu].removeEventListener(iu.name,this[uu])}removeEventListener(e,t,r){let s,i,n;if(r=fu(r),null!=t){if(i=this[au].get(e),void 0===i)return;for(const e of i)if(e.callback===t&&pu(e.options,r)){s=e.handler,n=e;break}if(null==s)return}else s=t;this[nu].removeEventListener(e,s,r),null!=i&&null!=n&&(i.delete(n),e===iu.name&&0===i.size&&this[nu].addEventListener(iu.name,this[uu]))}dispatchEvent(e){if(Object.defineProperties(e,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),e instanceof iu)return this[nu].dispatchEvent(e);{let t=this[nu].dispatchEvent(e);if(t&&!this[lu].has(e)){const r=new eu({bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed,detail:e});Object.defineProperties(r,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),t=this[nu].dispatchEvent(r)}if(t){const r=new ru({bubbles:e.bubbles,cancelable:e.cancelable,composed:e.composed,detail:e});Object.defineProperties(r,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),t=this[nu].dispatchEvent(r)}return t}}};return Object.defineProperty(t,"name",Object.getOwnPropertyDescriptor(e,"name")),t}}async function yu(e,t){const r=[],s=[];let i;try{for(const t of e){const[e,i]=await t(s);r.push(e),s.push(i)}return await t(s)}catch(e){throw i=e,e}finally{r.reverse();for(const e of r)await e(i)}}async function*mu(e,t){const r=[],s=[];let i;try{for(const t of e){const[e,i]=await t(s);r.push(e),s.push(i)}return yield*t(s)}catch(e){throw i=e,e}finally{r.reverse();for(const e of r)await e(i)}}class bu extends Promise{static get[Symbol.species](){return Promise}static resolve(e){return e instanceof bu?e:super.resolve(e)}static reject(e){return super.reject(e)}static all(e,t){const r=super.all(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static allSettled(e,t){const r=super.allSettled(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static race(e,t){const r=super.race(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static any(e,t){const r=super.any(e);return"function"==typeof t?(r.abortController=new AbortController,t(r.abortController.signal)):null!=t&&(r.abortController=t),r}static from(e,t){return new this((t,r)=>{e.then(t,r)},t)}reject;abortController;constructor(e,t){let r,s,i,n;"function"==typeof t?(r=new AbortController,t(r.signal),s=r.signal,i=!0):null!=t?(r=t,s=t.signal,i=!0):(r=new AbortController,s=new Proxy(r.signal,{get:(e,t,r)=>"addEventListener"===t?function(...r){return i=!0,e[t].apply(this,r)}:Reflect.get(e,t,r),set:(e,t,r)=>("onabort"===t&&(i=!0),Reflect.set(e,t,r)),deleteProperty:(e,t)=>("onabort"===t&&(i=!0),Reflect.deleteProperty(e,t))}),i=!1),super((t,r)=>{n=e=>{e instanceof DOMException&&"AbortError"===e.name&&(e=void 0),r(e)},e(t,n,s)}),i||r.signal.addEventListener("abort",()=>{n(r.signal.reason)},{once:!0}),this.reject=n,this.abortController=r}get[Symbol.toStringTag](){return this.constructor.name}cancel(e){this.abortController.abort(e)}then(e,t,r){let s,i,n;"function"==typeof e&&(i=t=>e(t,s)),"function"==typeof t&&(n=e=>t(e,s));const o=super.then(i,n),a=bu.from(o,r);return s=a.abortController.signal,a}catch(e,t){let r,s;"function"==typeof e&&(s=t=>e(t,r));const i=super.catch(s);return"function"==typeof t?(i.abortController=new AbortController,t(i.abortController.signal)):null!=t&&(i.abortController=t),r=i.abortController.signal,i}finally(e,t){let r,s;"function"==typeof e&&(s=()=>e(r));const i=super.finally(s);return"function"==typeof t?(i.abortController=new AbortController,t(i.abortController.signal)):null!=t&&(i.abortController=t),r=i.abortController.signal,i}}const Au=bu,Iu=t(import.meta.url)("node:perf_hooks");var vu,wu=(vu=function(e,t){return vu=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},vu(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}vu(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),Su=function(e){function t(t){var r,s,i,n=this.constructor,o=e.call(this,t)||this;return Object.defineProperty(o,"name",{value:n.name,enumerable:!1,configurable:!0}),r=o,s=n.prototype,(i=Object.setPrototypeOf)?i(r,s):r.__proto__=s,function(e,t){void 0===t&&(t=e.constructor);var r=Error.captureStackTrace;r&&r(e,t)}(o),o}return wu(t,e),t}(Error);const Eu=class extends Su{static description="";static fromJSON(e){if("object"!=typeof e||e.type!==this.name||"object"!=typeof e.data||"string"!=typeof e.data.message||isNaN(Date.parse(e.data.timestamp))||"object"!=typeof e.data.data||"stack"in e.data&&"string"!=typeof e.data.stack)throw new TypeError(`Cannot decode JSON to ${this.name}`);const t=new this(e.data.message,{timestamp:new Date(e.data.timestamp),data:e.data.data,cause:e.data.cause});return t.stack=e.data.stack,t}data;cause;timestamp;constructor(e="",t={}){super(e),this.timestamp=t.timestamp??new Date(Iu.performance.timeOrigin+Iu.performance.now()),this.data=t.data??{},this.cause=t.cause}get description(){return this.constructor.description}toJSON(){return{type:this.constructor.name,description:this.description,data:{message:this.message,timestamp:this.timestamp,data:this.data,cause:this.cause,stack:this.stack}}}};function Cu(e,t,r=new Set){if(r.has(e))return!1;if(r.add(e),t(e))return!0;if(e instanceof AggregateError){for(const s of e.errors){const e=Cu(s,t,r);if(e)return e}return Cu(e.cause,t,r)}return e instanceof Error&&Cu(e.cause,t,r)}class ku extends Eu{static description="Timer error"}class xu extends ku{static description="The timer has already ended"}class _u{_delay;lazy;timestamp;_scheduled;handler;p;resolveP;rejectP;abortController;timeoutRef;_status=null;constructor(e,t=0,r=!1,s){let i,n;"function"==typeof e?i=e:"object"==typeof e&&null!==e&&(i=e.handler,t=e.delay??t,r=e.lazy??r,s=e.controller??s),isNaN(t)?t=0:(t=Math.max(t,0),isFinite(t)&&(t=Math.min(t,2**31-1))),this.handler=i,this._delay=t,this.lazy=r,"function"==typeof s?(n=new AbortController,s(n.signal)):null!=s?n=s:(n=new AbortController,n.signal.addEventListener("abort",()=>{this.reject(n.signal.reason)})),this.p=new Au((e,t)=>{this.resolveP=e.bind(this.p),this.rejectP=t.bind(this.p)},n),this.abortController=n,isFinite(t)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},t),this.timestamp=new Date(Iu.performance.timeOrigin+Iu.performance.now()),this._scheduled=new Date(this.timestamp.getTime()+t)):(this.timeoutRef=setInterval(()=>{},2**31-1),this.timestamp=new Date(Iu.performance.timeOrigin+Iu.performance.now()))}get[Symbol.toStringTag](){return this.constructor.name}get status(){return this._status}get scheduled(){return this._scheduled}get delay(){return this._delay}getTimeout(){return null!==this._status?0:null==this._scheduled?1/0:Math.max(Math.trunc(this._scheduled.getTime()-(Iu.performance.timeOrigin+Iu.performance.now())),0)}toString(){return this.getTimeout().toString()}valueOf(){return this.getTimeout()}cancel(e){this.p.catch(()=>{}),this.p.cancel(e)}then(e,t,r){return this.p.then(e,t,r)}catch(e,t){return this.p.catch(e,t)}finally(e,t){return this.p.finally(e,t)}refresh(){if(null!=this._status)throw new xu;return this.reset(this._delay)}reset(e){if(null!=this._status)throw new xu;clearTimeout(this.timeoutRef),this._delay=e,isFinite(e)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},e),this._scheduled=new Date(Iu.performance.timeOrigin+Iu.performance.now()+e)):(this.timeoutRef=setInterval(()=>{},2**31-1),delete this._scheduled)}async fulfill(){if(this._status="settling",clearTimeout(this.timeoutRef),delete this.timeoutRef,null!=this.handler)try{const e=await this.handler(this.abortController.signal);this.resolveP(e)}catch(e){this.rejectP(e)}else this.resolveP();delete this.handler,this._status="settled"}async reject(e){this.lazy&&"settling"===this._status||"settled"===this._status||(this._status="settling",clearTimeout(this.timeoutRef),delete this.timeoutRef,this.rejectP(e),delete this.handler,this._status="settled")}}const Bu=_u;function Ru(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Ou(e,t,r,s,i,n){let o,a;if(void 0!==i.timer&&"number"!=typeof i.timer||void 0!==i.signal)if((void 0===i.timer||"number"==typeof i.timer)&&i.signal instanceof AbortSignal){o=new AbortController;const e=new s,t=new Bu(()=>{o.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),o.abort(n.reason)};n.aborted?(t.cancel(),o.abort(n.reason)):n.addEventListener("abort",c),i.signal=o.signal,i.timer=t,a=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof Bu&&void 0===i.signal){o=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||o.abort(e),r),()=>{}),i.signal=o.signal,a=()=>{t=!0}}else{o=new AbortController;const e=i.signal,t=()=>{o.abort(e.reason)};e.aborted?o.abort(e.reason):e.addEventListener("abort",t),i.signal=o.signal,a=()=>{e.removeEventListener("abort",t)}}else{o=new AbortController;const e=new s,t=new Bu(()=>{o.abort(e)},i.timer??r);o.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=o.signal,i.timer=t,a=()=>{t.cancel()}}const c=e(i,...n);return new Au((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},o).finally(()=>{a()},o)}class Uu extends Eu{static description="Async locks error"}class Tu extends Uu{static description="Async locks timeout"}const Nu=class{limit;priority;_count=0;currentWeight=0;queue=[];abortQueueMap=new WeakMap;constructor(e,t=!1){if(e<1)throw new RangeError("Semaphore must be constructed with `limit` >= 1");this.limit=e,this.priority=t}get count(){return this._count}isLocked(){return this._count>0}lock(...e){const t=(2===e.length||"number"==typeof e[0]?e[0]:void 0)??1;let r=2===e.length?e[1]:"number"!=typeof e[0]?e[0]:void 0;if(t<1)throw new RangeError("Semaphore must be locked with `weight` >= 1");return r=null!=r?{...r}:{},()=>Ou((e,t)=>{this._count++;const{p:r,resolveP:s,rejectP:i}=Ru();if(e.signal.aborted)return this._count--,i(e.signal.reason),r;const n=()=>{this._count--;const t=this.abortQueueMap.get(n);null!=t&&(t.aborted=!0),i(e.signal.reason)};let o=!1;const a={task:()=>{this.currentWeight+=t,e.signal.removeEventListener("abort",n),s([async()=>{o||(o=!0,this._count--,this.currentWeight-=t,this.processQueue())},this])},weight:t,abortHandler:n,aborted:!1};return e.signal.addEventListener("abort",n,{once:!0}),this.abortQueueMap.set(n,a),this.insertQueue(a),this.processQueue(),r},!0,1/0,Tu,r,[t])}waitForUnlock(...e){const t=(2===e.length||"number"==typeof e[0]?e[0]:void 0)??1;let r=2===e.length?e[1]:"number"!=typeof e[0]?e[0]:void 0;if(t<1)throw new RangeError("Semaphore must be locked with `weight` >= 1");return r=null!=r?{...r}:{},Ou((e,t)=>{const{p:r,resolveP:s,rejectP:i}=Ru();if(e.signal.aborted)return i(e.signal.reason),r;const n=()=>{const t=this.abortQueueMap.get(n);null!=t&&(t.aborted=!0),i(e.signal.reason)},o={task:()=>{e.signal.removeEventListener("abort",n),s()},weight:t,abortHandler:n,aborted:!1};return e.signal.addEventListener("abort",n,{once:!0}),this.abortQueueMap.set(n,o),this.insertQueue(o),this.processQueue(),r},!0,1/0,Tu,r,[t])}withF(...e){const t=e.pop();return yu([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return mu([this.lock(...e)],([e])=>t(e))}insertQueue(e){if(this.priority){let t=this.queue.length;for(;t>0&&this.queue[t-1].weight<e.weight;)t--;this.queue.splice(t,0,e)}else this.queue.unshift(e)}processQueue(){for(;this.queue.length>0&&this.currentWeight+this.queue[this.queue.length-1].weight<=this.limit;){const e=this.queue.pop();e.aborted||e.task()}}},Du=class{semaphore=new Nu(1);get count(){return this.semaphore.count}isLocked(){return this.semaphore.isLocked()}lock(e){const t=this.semaphore.lock(1,e);return()=>{const e=t();return e.then(([e])=>[e,this],void 0,t=>{t.addEventListener("abort",()=>{e.cancel(t.reason)},{once:!0})})}}waitForUnlock(e){return this.semaphore.waitForUnlock(1,e)}withF(...e){const t=e.pop();return yu([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return mu([this.lock(...e)],([e])=>t(e))}},Mu=class{readersLock=new Du;writersLock=new Du;readersRelease;readerCountBlocked=0;acquireReadersLockP;_readerCount=0;_writerCount=0;get count(){return this.readerCount+this.writerCount}get readerCount(){return this._readerCount+this.readerCountBlocked}get writerCount(){return this._writerCount}isLocked(e){return"read"===e?0===this._writerCount&&this.readersLock.isLocked():"write"===e?this.writersLock.isLocked():this.readersLock.isLocked()||this.writersLock.isLocked()}lock(...e){const t=(2===e.length||"string"==typeof e[0]?e[0]:void 0)??"write",r=2===e.length?e[1]:"string"!=typeof e[0]?e[0]:void 0;switch(t){case"read":return this.read(r);case"write":return this.write(r)}}read(e){return e=null!=e?{...e}:{},()=>Ou(async e=>{if(this._writerCount>0){++this.readerCountBlocked;const t=this.writersLock.waitForUnlock(e);try{await t}finally{--this.readerCountBlocked}}if(1===++this._readerCount){const t=this.readersLock.lock(e);this.acquireReadersLockP=t();try{[this.readersRelease]=await this.acquireReadersLockP}catch(e){throw--this._readerCount,e}}else await this.acquireReadersLockP.catch(()=>{});let t=!1;return[async()=>{t||(t=!0,0===--this._readerCount&&await this.readersRelease())},this]},!0,1/0,Tu,e,[])}write(e){return e=null!=e?{...e}:{},()=>Ou(async e=>{++this._writerCount;const t=this.writersLock.lock(e)();let r;try{[r]=await t}catch(e){throw--this._writerCount,e}const s=this.readersLock.lock(e)();try{[this.readersRelease]=await s}catch(e){throw await r(),--this._writerCount,e}let i=!1;return[async()=>{i||(i=!0,await this.readersRelease(),await r(),--this._writerCount)},this]},!0,1/0,Tu,e,[])}waitForUnlock(e){const t=this.readersLock.waitForUnlock(e),r=this.writersLock.waitForUnlock(e);return Au.all([t,r]).then(()=>{},void 0,e=>{e.addEventListener("abort",()=>{t.cancel(e.reason),r.cancel(e.reason)},{once:!0})})}withF(...e){let t;switch(2===e.length||"string"==typeof e[0]?t=e.shift():null==typeof e[0]&&e.shift(),t=t??"write",t){case"read":return this.withReadF(...e);case"write":return this.withWriteF(...e)}}withReadF(...e){const t=e.pop();return yu([this.read(...e)],([e])=>t(e))}withWriteF(...e){const t=e.pop();return yu([this.write(...e)],([e])=>t(e))}withG(...e){let t;switch(2===e.length||"string"==typeof e[0]?t=e.shift():null==typeof e[0]&&e.shift(),t=t??"write",t){case"read":return this.withReadG(...e);case"write":return this.withWriteG(...e)}}withReadG(...e){const t=e.pop();return mu([this.read(...e)],([e])=>t(e))}withWriteG(...e){const t=e.pop();return mu([this.write(...e)],([e])=>t(e))}},Pu=Symbol("_running"),Lu=Symbol("running"),Hu=Symbol("_destroyed"),Ku=Symbol("destroyed"),Qu=Symbol("_status"),Vu=Symbol("status"),Fu=Symbol("_statusP"),$u=Symbol("statusP"),ju=Symbol("resolveStatusP"),Gu=Symbol("initLock"),qu=(async()=>{}).constructor,zu=function*(){}.constructor,Wu=async function*(){}.constructor,Ju="captureStackTrace"in Error;function Yu(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Xu(e,t){if(null!=e.stack){const r=e.stack.slice(0,e.stack.indexOf("\n")+1);Ju?Error.captureStackTrace(e,t):e.stack=(new Error).stack??"",e.stack=e.stack.replace(/[^\n]+\n/,r)}}class Zu extends Xh{}class ed extends Zu{}class td extends Zu{}class rd extends Zu{}class sd extends Zu{}class id extends Zu{}class nd extends Zu{}class od extends Eu{static description="Async init error"}class ad extends od{static description="Async init is not running"}class cd extends od{static description="Async init is destroyed"}function ld({eventDestroy:e=id,eventDestroyed:t=nd}={}){return r=>{const{p:s,resolveP:i}=Yu(),n=class extends(gu()(r)){[Hu]=!1;[Qu]=null;[Fu]=s;[ju]=i;[Gu]=new Mu;get[Ku](){return this[Hu]}get[Vu](){return this[Qu]}get[$u](){return this[Fu]}async destroy(...r){return this[Gu].withWriteF(async()=>{if(this[Hu])return;this[Qu]="destroying",this[ju]("destroying");const{p:s,resolveP:i}=Yu();let n;return this[Fu]=s,this[ju]=i,this.dispatchEvent(new e),"function"==typeof super.destroy&&(n=await super.destroy(...r)),this[Hu]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[Qu]=null,this[ju](null);const{p:e,resolveP:t}=Yu();this[Fu]=e,this[ju]=t})}};return Object.defineProperty(n,"name",Object.getOwnPropertyDescriptor(r,"name")),n}}function hd(e=new cd,t=!1,r=[]){return(s,i,n)=>{let o;null!=n.value?o="value":null!=n.get?o="get":null!=n.set&&(o="set");const a=n[o];if("function"!=typeof a)throw new TypeError(`${i} is not a function`);return n[o]=a instanceof qu?async function(...s){if(this[Gu].isLocked("write")&&null===this[Qu]&&await this[Fu],r.includes(this[Qu]))return a.apply(this,s);if(t)return this[Gu].withReadF(async()=>{if(this[Hu])throw Xu(e,n[o]),e;return a.apply(this,s)});if(this[Gu].isLocked("write")||this[Hu])throw Xu(e,n[o]),e;return a.apply(this,s)}:a instanceof zu?function*(...t){if(r.includes(this[Qu]))return yield*a.apply(this,t);if(this[Gu].isLocked("write")&&null!==this[Vu]||this[Hu])throw Xu(e,n[o]),e;return yield*a.apply(this,t)}:a instanceof Wu?async function*(...s){if(this[Gu].isLocked("write")&&null===this[Qu]&&await this[Fu],r.includes(this[Qu]))return yield*a.apply(this,s);if(t)return yield*this[Gu].withReadG(()=>{if(this[Hu])throw Xu(e,n[o]),e;return a.apply(this,s)});if(this[Gu].isLocked("write")||this[Hu])throw Xu(e,n[o]),e;return yield*a.apply(this,s)}:function(...t){if(r.includes(this[Qu]))return a.apply(this,t);if(this[Gu].isLocked("write")&&null!==this[Vu]||this[Hu])throw Xu(e,n[o]),e;return a.apply(this,t)},Object.defineProperty(n[o],"name",{value:i}),n}}function ud({eventStart:e=ed,eventStarted:t=td,eventStop:r=rd,eventStopped:s=sd}={}){return i=>{const{p:n,resolveP:o}=Yu(),a=class extends(gu()(i)){[Pu]=!1;[Qu]=null;[Fu]=n;[ju]=o;[Gu]=new Mu;get[Lu](){return this[Pu]}get[Vu](){return this[Qu]}get[$u](){return this[Fu]}async start(...r){return this[Gu].withWriteF(async()=>{if(this[Pu])return;this[Qu]="starting",this[ju]("starting");const{p:s,resolveP:i}=Yu();let n;return this[Fu]=s,this[ju]=i,this.dispatchEvent(new e),"function"==typeof super.start&&(n=await super.start(...r)),this[Pu]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[Qu]=null,this[ju](null);const{p:e,resolveP:t}=Yu();this[Fu]=e,this[ju]=t})}async stop(...e){return this[Gu].withWriteF(async()=>{if(!this[Pu])return;this[Qu]="stopping",this[ju]("stopping");const{p:t,resolveP:i}=Yu();let n;return this[Fu]=t,this[ju]=i,this.dispatchEvent(new r),"function"==typeof super.stop&&(n=await super.stop(...e)),this[Pu]=!1,this.dispatchEvent(new s),n}).finally(()=>{this[Qu]=null,this[ju](null);const{p:e,resolveP:t}=Yu();this[Fu]=e,this[ju]=t})}};return Object.defineProperty(a,"name",Object.getOwnPropertyDescriptor(i,"name")),a}}function dd(e=new ad,t=!1,r=[]){return(s,i,n)=>{let o;null!=n.value?o="value":null!=n.get?o="get":null!=n.set&&(o="set");const a=n[o];if("function"!=typeof a)throw new TypeError(`${i} is not a function`);return n[o]=a instanceof qu?async function(...s){if(this[Gu].isLocked("write")&&null===this[Qu]&&await this[Fu],r.includes(this[Qu]))return a.apply(this,s);if(t)return this[Gu].withReadF(async()=>{if(!this[Pu])throw Xu(e,n[o]),e;return a.apply(this,s)});if(this[Gu].isLocked("write")||!this[Pu])throw Xu(e,n[o]),e;return a.apply(this,s)}:a instanceof zu?function*(...t){if(r.includes(this[Qu]))return yield*a.apply(this,t);if(this[Gu].isLocked("write")&&null!==this[Vu]||!this[Pu])throw Xu(e,n[o]),e;return yield*a.apply(this,t)}:a instanceof Wu?async function*(...s){if(this[Gu].isLocked("write")&&null===this[Qu]&&await this[Fu],r.includes(this[Qu]))return yield*a.apply(this,s);if(t)return yield*this[Gu].withReadG(()=>{if(!this[Pu])throw Xu(e,n[o]),e;return a.apply(this,s)});if(this[Gu].isLocked("write")||!this[Pu])throw Xu(e,n[o]),e;return yield*a.apply(this,s)}:function(...t){if(r.includes(this[Qu]))return a.apply(this,t);if(this[Gu].isLocked("write")&&null!==this[Vu]||!this[Pu])throw Xu(e,n[o]),e;return a.apply(this,t)},Object.defineProperty(n[o],"name",{value:i}),n}}class fd extends Uint8Array{string;static fromString(e){const t=Buffer.from(e,"hex");return new this(t.buffer,t.byteOffset,t.byteLength)}static fromBuffer(e){return new this(e.buffer,e.byteOffset,e.byteLength)}constructor(...e){super(...e),this.string=this.toBuffer().toString("hex")}toString(){return this.string}toBuffer(){return Buffer.from(this.buffer,this.byteOffset,this.byteLength)}[Symbol.toPrimitive](e){return this.toString()}}const pd=fd;class gd{[Symbol.toStringTag]="QUICConnectionMap";_serverConnections=new Map;_clientConnections=new Map;constructor(e){if(null!=e)for(const[t,r]of e)this.set(t,r)}get size(){return this._serverConnections.size+this._clientConnections.size}get serverConnections(){return this._serverConnections}get clientConnections(){return this._clientConnections}has(e){return this._serverConnections.has(e.toString())||this._clientConnections.has(e.toString())}get(e){return this._serverConnections.get(e.toString())??this._clientConnections.get(e.toString())}set(e,t){return"server"===t.type?this._serverConnections.set(e.toString(),t):"client"===t.type&&this._clientConnections.set(e.toString(),t),this}delete(e){return this._serverConnections.delete(e.toString())||this._clientConnections.delete(e.toString())}clear(){this._serverConnections.clear(),this._clientConnections.clear()}forEach(e,t){this._serverConnections.forEach((r,s)=>{e.bind(t)(r,pd.fromString(s),this)}),this._clientConnections.forEach((r,s)=>{e.bind(t)(r,pd.fromString(s),this)})}[Symbol.iterator](){const e=this._serverConnections[Symbol.iterator](),t=this._clientConnections[Symbol.iterator](),r={next:()=>{const r=e.next();if(!r.done){const[e,t]=r.value;return{done:!1,value:[pd.fromString(e),t]}}const s=t.next();if(!s.done){const[e,t]=s.value;return{done:!1,value:[pd.fromString(e),t]}}return{done:!0,value:void 0}},[Symbol.iterator]:()=>r};return r}entries(){return this[Symbol.iterator]()}keys(){const e={next:()=>{const e=this[Symbol.iterator]().next();return e.done?{done:!0,value:void 0}:{done:!1,value:e.value[0]}},[Symbol.iterator]:()=>e};return e}values(){const e={next:()=>{const e=this[Symbol.iterator]().next();return e.done?{done:!0,value:void 0}:{done:!1,value:e.value[1]}},[Symbol.iterator]:()=>e};return e}}const yd=gd,md=t(import.meta.url)("process");var bd=o(928);const Ad=t(import.meta.url)("url"),Id=t(import.meta.url)("node:module").createRequire("file:///home/runner/work/typeberry/typeberry/node_modules/@matrixai/quic/dist/native/quiche.js"),vd=Ad.fileURLToPath(new URL(o(810),o.b)),wd=bd.join(vd,"../../"),Sd=bd.join(wd,"prebuild");function Ed(e){const t=e.map(e=>bd.join(Sd,`quic-${e}.node`));for(const e of t){try{return Id(e)}catch(e){if("MODULE_NOT_FOUND"!==e.code)throw e}try{return Id(Ad.pathToFileURL(e).href)}catch(e){if("MODULE_NOT_FOUND"!==e.code)throw e}}const r=e.map(e=>`@matrixai/quic-${e}`);for(const e of r){try{return Id(e)}catch(e){if("MODULE_NOT_FOUND"!==e.code)throw e}try{return Id(Ad.pathToFileURL(e).href)}catch(e){if("MODULE_NOT_FOUND"!==e.code)throw e}}throw new Error(`Failed requiring possible native bindings: ${t.concat(r)}`)}let Cd;switch(md.platform){case"win32":switch(md.arch){case"x64":Cd=Ed(["win32-x64"]);break;case"ia32":Cd=Ed(["win32-ia32"]);break;case"arm64":Cd=Ed(["win32-arm64"]);break;default:throw new Error(`Unsupported architecture on Windows: ${md.arch}`)}break;case"darwin":switch(md.arch){case"x64":Cd=Ed(["darwin-x64","darwin-x64+arm64","darwin-arm64+x64","darwin-universal"]);break;case"arm64":Cd=Ed(["darwin-arm64","darwin-arm64+x64","darwin-x64+arm64","darwin-universal"]);break;default:throw new Error(`Unsupported architecture on macOS: ${md.arch}`)}break;case"linux":switch(md.arch){case"x64":Cd=Ed(["linux-x64"]);break;case"arm64":Cd=Ed(["linux-arm64"]);break;case"arm":Cd=Ed(["linux-arm"]);break;default:throw new Error(`Unsupported architecture on Linux: ${md.arch}`)}break;default:throw new Error(`Unsupported OS: ${md.platform}, architecture: ${md.arch}`)}const kd=Cd,xd=t(import.meta.url)("dns");var _d=o(618);class Bd extends Eu{static description="QUIC error"}class Rd extends Eu{static description="You should never see this error"}class Od extends Eu{static description="Host provided was not valid"}class Ud extends Eu{static description="Port provided was not valid"}class Td extends Bd{static description="QUIC config error"}class Nd extends Bd{static description="QUIC Socket error"}class Dd extends Nd{static description="QUIC Socket is not running"}class Md extends Nd{static description="QUIC Socket has active connections"}class Pd extends Nd{static description="QUIC Socket cannot bind to the specified address"}class Ld extends Nd{static description="QUIC Socket cannot send to the specified address"}class Hd extends Nd{static description="QUIC Socket internal error"}class Kd extends Bd{static description="QUIC Client error"}class Qd extends Kd{static description="QUIC Client is destroyed"}class Vd extends Kd{static description="QUIC Client cannot be created with an unstarted shared QUIC socket"}class Fd extends Kd{static description="QUIC Client had a failure relating to an invalid argument"}class $d extends Kd{static description="QUIC Client cannot be created with the specified host"}class jd extends Kd{static description="QUIC Client internal error"}class Gd extends Bd{static description="QUIC Server error"}class qd extends Gd{static description="QUIC Server is not running"}class zd extends Gd{static description="QUIC Server cannot start with an unstarted shared QUIC socket"}class Wd extends Gd{static description="QUIC Server creating a new connection"}class Jd extends Gd{static description="QUIC Server internal error"}class Yd extends Gd{static description="QUIC Server is stopping"}class Xd extends Bd{static description="QUIC Connection error"}class Zd extends Xd{static description="QUIC Connection is stopping"}class ef extends Xd{static description="QUIC Connection is not running"}class tf extends Xd{static description="QUIC Connection cannot be restarted because it has already been closed"}class rf extends Bd{static description="QUIC Connection start requires data when it is a server connection"}class sf extends Xd{static description="QUIC connection invalid configuration"}class nf extends Xd{static description="QUIC Connection local error";constructor(e="",t){super(e,t)}}class of extends nf{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class af extends Xd{static description="QUIC Connection peer error";constructor(e="",t){super(e,t)}}class cf extends nf{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class lf extends Xd{static description="QUIC Connection max idle timeout exhausted"}class hf extends Xd{static description="QUIC Connection internal error"}class uf extends Bd{static description="QUIC Stream error"}class df extends uf{static description="QUIC Stream is destroyed"}class ff extends uf{static description="QUIC Stream locally closed readable side";constructor(e="",t){super(e,t)}}class pf extends uf{static description="QUIC Stream locally closed writable side";constructor(e="",t){super(e,t)}}class gf extends uf{static description="QUIC Stream peer closed readable side";constructor(e="",t){super(e,t)}}class yf extends uf{static description="QUIC Stream peer closed writable side";constructor(e="",t){super(e,t)}}class mf extends uf{static description="QUIC Stream internal error"}class bf extends uf{static description="QUIC Stream limit has been reached"}const Af=new TextEncoder,If=new TextDecoder("utf-8");function vf(e){throw new Rd(e)}function wf(e){return function(...t){return new Promise((r,s)=>{t.push((e,...t)=>{if(null!=e)return s(e);0===t.length?r():1===t.length?r(t[0]):r(t)}),e.apply(this,t)})}}function Sf(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Ef(e){const[t]=_d.Validator.isValidIPv4String(e);return t}function Cf(e){const[t]=_d.Validator.isValidIPv6String(e);return!!t||kf(e)}function kf(e){if(e.startsWith("::ffff:"))try{return _d.IPv6.fromString(e),!0}catch{if(Ef(e.slice(7)))return!0}return!1}function xf(e){if(!Ef(e))throw new TypeError("Invalid IPv4 address");return"::ffff:"+e}function _f(e){const t=e.slice(7);if(Ef(t))return t;const r=t.match(/^([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/);if(null==r)throw new TypeError("Invalid IPv4 mapped IPv6 address");return(r[1].padStart(4,"0")+r[2].padStart(4,"0")).match(/.{1,2}/g).map(e=>parseInt(e,16)).join(".")}function Bf(e){const t=new _d.IPv4("0.0.0.0"),r=new _d.IPv6("::");if(kf(e)){const r=_f(e);return new _d.IPv4(r).isEquals(t)?xf("127.0.0.1"):e}return Ef(e)&&new _d.IPv4(e).isEquals(t)?"127.0.0.1":Cf(e)&&new _d.IPv6(e).isEquals(r)?"::1":e}async function Rf(e){return(await xd.promises.lookup(e,{family:0,all:!1,verbatim:!0})).address}async function Of(e,t){if(Ef(e))return[e,"udp4"];if(Cf(e))return[e,"udp6"];try{return Of(e=await t(e),t)}catch{throw new Od}}function Uf(e){if(!function(e){return"number"==typeof e&&e>=0&&e<=65535}(e))throw new Ud;return e}function Tf(e,t=0){let r;return r=Ef(e)?`${e}:${t}`:Cf(e)?`[${e}]:${t}`:`${e}:${t}`,r}function Nf(e,t,r,s,i){if("0.0.0.0"===(n=r)||"::"===n||"::0"===n||"::ffff:0.0.0.0"===n||"::ffff:0:0"===n)throw new i(`Invalid wildcard target host ${r}`);var n;const o=kf(e),a=kf(r);if("ipv4&ipv6"===t&&"udp4"===s)return xf(r);if("ipv4"===t){if(o){if("udp4"===s)return xf(r);if("udp6"===s&&!a)throw new i(`Invalid target host ${r} from an IPv4 socket`)}else if("udp6"===s){if(a)return _f(r);throw new i(`Invalid target host ${r} from an IPv4 socket`)}return r}if("ipv6"===t){if("udp4"===s||a)throw new i(`Invalid target host ${r} from an IPv6 socket`);return r}return r}function Df(e){const t=[];if("string"==typeof e)t.push(e.trim()+"\n");else if(e instanceof Uint8Array)t.push(If.decode(e).trim()+"\n");else if(Array.isArray(e))for(const r of e)"string"==typeof r?t.push(r.trim()+"\n"):t.push(If.decode(r).trim()+"\n");return t}function Mf(e){const t=e.replace(/-----BEGIN .*-----/,"").replace(/-----END .*-----/,"").replace(/\s+/g,""),r=Buffer.from(t,"base64");return new Uint8Array(r)}function Pf(e){return`${e.name}${"description"in e?`: ${e.description}`:""}${void 0!==e.message?` - ${e.message}`:""}`}function Lf(e){let t;return null!=(t=e.message.match(/StreamStopped\((\d{1,16})\)/))&&parseInt(t[1])}function Hf(e){let t;return null!=(t=e.message.match(/StreamReset\((\d{1,16})\)/))&&parseInt(t[1])}function Kf(e,t=1e5){En.setMaxListeners(t,e)}class Qf extends Xh{}class Vf extends Qf{}class Ff extends Vf{}class $f extends Vf{}class jf extends Vf{}class Gf extends Qf{}class qf extends Gf{}class zf extends Vf{}class Wf extends Gf{}class Jf extends Qf{}class Yf extends Jf{}class Xf extends Jf{}class Zf extends Jf{}class ep extends Qf{}class tp extends ep{}class rp extends ep{}class sp extends ep{}class ip extends ep{}class np extends ep{}class op extends Qf{}class ap extends op{}class cp extends op{}class lp extends op{}class hp extends op{}class up extends op{}var dp=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let fp=class{connectionMap=new yd;logger;server;resolveHostname;_host;_port;_type;_closed=!1;_closedP;resolveClosedP;socket;socketBind;socketClose;socketSend;handleEventQUICSocketError=e=>{const t=e.detail;this.logger.debug(Pf(t))};handleEventQUICSocketClose=async()=>{await this.socketClose(),this._closed=!0,this.resolveClosedP(),this[Lu]&&await this.stop({force:!0})};handleSocketMessage=async(e,t)=>{let r;try{r=kd.Header.fromSlice(e,kd.MAX_CONN_ID_LEN)}catch(e){if("BufferTooShort"===e.message||"InvalidPacket"===e.message)return;throw e}const s=new pd(r.dcid),i={host:t.address,port:t.port},n=this.connectionMap.get(s);if(null!=n)await n.recv(e,i);else{if(null==this.server)return;try{await this.server.acceptConnection(i,r,s,e)}catch(e){if(Cu(e,e=>e instanceof Nd)){const t=new Hd("Failed to call accept connection due to socket send",{cause:e});return this.dispatchEvent(new $f({detail:t})),void this.dispatchEvent(new jf)}if(e instanceof Wd)return;throw e}}};constructor({resolveHostname:e=Rf,logger:t}){this.logger=t??new Jh(this.constructor.name),this.resolveHostname=e;const{p:r,resolveP:s}=Sf();this._closedP=r,this.resolveClosedP=s}get host(){return this._host}get port(){return this._port}get type(){return this._type}get closed(){return this._closed}get closedP(){return this._closedP}async start({host:e="::",port:t=0,reuseAddr:r=!1,ipv6Only:s=!1}={}){Kf(this[nu]);let i=Tf(e,t);this.logger.info(`Start ${this.constructor.name} on ${i}`);const[n,o]=await Of(e,this.resolveHostname),a=Uf(t);this.socket=Oh.createSocket({type:o,reuseAddr:r,ipv6Only:s}),this.socketBind=wf(this.socket.bind).bind(this.socket),this.socketClose=wf(this.socket.close).bind(this.socket),this.socketSend=wf(this.socket.send).bind(this.socket);const{p:c,rejectP:l}=Sf();c.catch(()=>{}),this.socket.once("error",l);const h=this.socketBind(a,n);try{await Promise.race([h,c])}catch(t){throw new Pd(e!==n?`Could not bind to resolved ${e} -> ${n}`:`Could not bind to ${e}`,{cause:t})}this.socket.removeListener("error",l);const u=this.socket.address();this._host=u.address,this._port=u.port,"::"!==n||s?"udp4"===o||kf(n)?this._type="ipv4":"udp6"===o&&(this._type="ipv6"):this._type="ipv4&ipv6",this.socket.on("message",this.handleSocketMessage),this.addEventListener($f.name,this.handleEventQUICSocketError),this.addEventListener(jf.name,this.handleEventQUICSocketClose,{once:!0}),this._closed=!1,i=Tf(this._host,this._port),this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({force:e=!1}={}){const t=Tf(this._host,this._port);if(this.logger.info(`Stop ${this.constructor.name} on ${t}`),!e&&this.connectionMap.size>0)throw new Md(`Cannot stop QUICSocket with ${this.connectionMap.size} active connection(s)`);this._closed||this.dispatchEvent(new jf),await this._closedP;const{p:r,resolveP:s}=Sf();this._closedP=r,this.resolveClosedP=s,this.removeEventListener($f.name,this.handleEventQUICSocketError),this.removeEventListener(jf.name,this.handleEventQUICSocketClose),this.socket.off("message",this.handleSocketMessage),this.logger.info(`Stopped ${this.constructor.name} on ${t}`)}async send(...e){let t;if(3===e.length&&"string"==typeof e[2])t=2;else{if(5!==e.length||"string"!=typeof e[4])throw new TypeError("QUICSocket.send requires `port` and `address` parameters");t=4}const r=e[t];let[s,i]=await Of(r,this.resolveHostname);return s=Bf(s),s=Nf(this._host,this._type,s,i,Ld),e[t]=s,this.socketSend(...e)}async send_(...e){return this.socketSend(...e)}setServer(e){this.server=e}unsetServer(){delete this.server}};dp([dd(new Dd)],fp.prototype,"host",null),dp([dd(new Dd)],fp.prototype,"port",null),dp([dd(new Dd)],fp.prototype,"type",null),dp([dd(new Dd)],fp.prototype,"send",null),dp([dd(new Dd)],fp.prototype,"send_",null),fp=dp([ud({eventStart:class extends Vf{},eventStarted:class extends Vf{},eventStop:class extends Vf{},eventStopped:Ff})],fp);const pp=fp,gp=new WeakMap;const yp=function(e,t,r){const s=e.name??e.constructor.name,i=e[t];if(gp.has(i))throw new TypeError(`\`${s}.${t.toString()}\` redeclares \`@context\` decorator`);gp.set(i,r)};class mp extends Eu{static description="Contexts error"}class bp extends mp{static description="Aborted due to timer expiration"}const Ap=function(e=!1,t=1/0,r=bp){return(s,i,n)=>{const o=s.name??s.constructor.name,a=n.value;if("function"!=typeof a)throw new TypeError(`\`${o}.${i.toString()}\` is not a function`);const c=function(e,t,r){const s=gp.get(e[t]);if(null==s)throw new TypeError(`\`${r}.${t.toString()}\` does not have a \`@context\` parameter decorator`);return s}(s,i,o);return n.value=function(...s){let n=s[c];return n=void 0===n?{}:{...n},s[c]=n,function(e,t,r){if("object"!=typeof e||null===e)throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter is not a context object`);if(void 0!==e.signal&&!(e.signal instanceof AbortSignal))throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter's \`signal\` property is not an instance of \`AbortSignal\``);if(void 0!==e.timer&&!("number"==typeof e.timer||e.timer instanceof Bu))throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter's \`timer\` property is not a number nor an instance of \`Timer\``)}(n,i,o),function(e,t,r,s,i,n){let o,a;if(void 0!==i.timer&&"number"!=typeof i.timer||void 0!==i.signal)if((void 0===i.timer||"number"==typeof i.timer)&&i.signal instanceof AbortSignal){o=new AbortController;const e=new s,t=new Bu(()=>{o.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),o.abort(n.reason)};n.aborted?(t.cancel(),o.abort(n.reason)):n.addEventListener("abort",c),i.signal=o.signal,i.timer=t,a=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof Bu&&void 0===i.signal){o=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||o.abort(e),r),()=>{}),i.signal=o.signal,a=()=>{t=!0}}else{o=new AbortController;const e=i.signal,t=()=>{o.abort(e.reason)};e.aborted?o.abort(e.reason):e.addEventListener("abort",t),i.signal=o.signal,a=()=>{e.removeEventListener("abort",t)}}else{o=new AbortController;const e=new s,t=new Bu(()=>{o.abort(e)},i.timer??r);o.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=o.signal,i.timer=t,a=()=>{t.cancel()}}const c=e(i,...n);return new Au((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},o).finally(()=>{a()},o)}((e,...t)=>a.apply(this,t),"boolean"==typeof e?e:e(this),"number"==typeof t?t:t(this),r,n,s)},Object.defineProperty(n.value,"name",{value:"symbol"==typeof i?`[${i.description}]`:i}),n}},Ip=["rsa_pkcs1_sha256","rsa_pkcs1_sha384","rsa_pkcs1_sha512","rsa_pss_rsae_sha256","rsa_pss_rsae_sha384","rsa_pss_rsae_sha512","ecdsa_secp256r1_sha256","ecdsa_secp384r1_sha384","ecdsa_secp521r1_sha512","ed25519"].join(":"),vp=1/0,wp={sigalgs:Ip,verifyPeer:!0,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:kd.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:kd.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:kd.MAX_CONNECTION_WINDOW,maxStreamWindow:kd.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},Sp={sigalgs:Ip,verifyPeer:!1,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:kd.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:kd.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:kd.MAX_CONNECTION_WINDOW,maxStreamWindow:kd.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},Ep=t(import.meta.url)("stream/web");var Cp=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};const kp=Symbol("abort readableP reason");let xp=class{static createQUICStream({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i=()=>0,codeToReason:n=(e,t)=>new Error(`${e.toString()} ${t.toString()}`),logger:o=new Jh(`${this.name} ${t}`)}){o.info(`Create ${this.name}`);const a=new this({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:o});return"uni"===a.type&&("local"===e?(a.readableController.close(),a._readClosed=!0):"peer"===e&&(a.writable.close().catch(()=>{}),a._writeClosed=!0)),a.addEventListener(cp.name,a.handleEventQUICStreamError),a.addEventListener(lp.name,a.handleEventQUICStreamCloseRead,{once:!0}),a.addEventListener(hp.name,a.handleEventQUICStreamCloseWrite,{once:!0}),o.info(`Created ${this.name}`),a}type;initiated;streamId;readable;writable;closedP;logger;connection;reasonToCode;codeToReason;readableController;writableController;_readClosed=!1;_writeClosed=!1;readableChunk;resolveReadableP;rejectReadableP;resolveWritableP;rejectWritableP;resolveClosedP;handleEventQUICStreamError=e=>{const t=e.detail;if(t instanceof mf)throw this.logger.debug(Pf(t)),t;t instanceof ff||t instanceof gf?this.dispatchEvent(new lp({detail:t})):(t instanceof pf||t instanceof yf)&&this.dispatchEvent(new hp({detail:t}))};handleEventQUICStreamCloseRead=async()=>{this._readClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[Ku]||"destroying"===this[Vu]||await this.destroy({force:!1}))};handleEventQUICStreamCloseWrite=async()=>{this._writeClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[Ku]||"destroying"===this[Vu]||await this.destroy({force:!1}))};constructor({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:o}){!function(e){return!(2&e)}(t)?function(e){return!!(2&e)}(t)&&(this.type="uni"):this.type="bidi",this.logger=o,this.initiated=e,this.streamId=t,this.connection=r,this.reasonToCode=i,this.codeToReason=n;const{p:a,resolveP:c}=Sf();if(this.closedP=a,this.resolveClosedP=c,"uni"===this.type&&"local"===e?this.readableChunk=void 0:this.readableChunk=Buffer.allocUnsafe(s.readableChunkSize),"uni"===this.type&&"local"===e?this.readable=new Ep.ReadableStream({start:this.readableStart.bind(this)}):this.readable=new Ep.ReadableStream({start:this.readableStart.bind(this),pull:this.readablePull.bind(this),cancel:this.readableCancel.bind(this)},new Ep.CountQueuingStrategy({highWaterMark:1})),"uni"===this.type&&"peer"===this.initiated)this.writable=new Ep.WritableStream({start:this.writableStart.bind(this)});else{this.writable=new Ep.WritableStream({start:this.writableStart.bind(this),write:this.writableWrite.bind(this),close:this.writableClose.bind(this),abort:this.writableAbort.bind(this)},{highWaterMark:1});try{r.conn.streamSend(t,new Uint8Array(0),!1)}catch(e){if(!1===Lf(e)){if("StreamLimit"===e.message){const t="bidi"===this.type?s.initialMaxStreamsBidi:s.initialMaxStreamsUni;throw new bf(`Stream limit of ${t} has been reached`,{cause:e})}throw new mf(`Failed to prime local stream state with a 0-length message: ${e.message}`,{cause:e})}}}}get writeClosed(){return this._writeClosed}get readClosed(){return this._readClosed}get meta(){return this.connection.meta()}get closed(){return this._readClosed&&this._writeClosed}async destroy({force:e=!0,reason:t}={}){this.logger.info(`Destroy ${this.constructor.name}`),!e||this._readClosed&&this._writeClosed||this.cancel(t),await this.closedP,this.removeEventListener(cp.name,this.handleEventQUICStreamError),this.removeEventListener(lp.name,this.handleEventQUICStreamCloseRead),this.removeEventListener(hp.name,this.handleEventQUICStreamCloseWrite),this.logger.info(`Destroyed ${this.constructor.name}`)}cancel(e){this.readableCancel(e),this.writableAbort(e)}read(){if(this.connection.conn.streamFinished(this.streamId)){let e;try{e=this.connection.conn.streamRecv(this.streamId,this.readableChunk)}catch(e){let t;if(!1!==(t=Hf(e))){const e=this.codeToReason("read",t),r=new gf("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),this.rejectReadableP?.(e),void this.dispatchEvent(new cp({detail:r}))}{const t=new mf("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.rejectReadableP?.(t),this.dispatchEvent(new cp({detail:t})),t}}if(null===e){const e=new mf("Failed `streamRecv` on the readable stream");throw this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new cp({detail:e})),e}const[t]=e;return t>0&&this.readableController.enqueue(Buffer.from(this.readableChunk.subarray(0,t))),this.readableController.close(),this.dispatchEvent(new lp),void this.rejectReadableP?.(kp)}this.resolveReadableP?.()}write(){try{this.connection.conn.streamCapacity(this.streamId)}catch(e){let t;if(!1!==(t=Lf(e))){this.connection.conn.streamShutdown(this.streamId,kd.Shutdown.Write,t);const e=this.codeToReason("write",t),r=new yf("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),this.rejectWritableP?.(e),void this.dispatchEvent(new cp({detail:r}))}{const t=new mf("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.rejectWritableP?.(t),this.dispatchEvent(new cp({detail:t})),t}}this.resolveWritableP?.()}readableStart(e){this.readableController=e}writableStart(e){this.writableController=e}async readablePull(){if(!this.connection.conn.streamReadable(this.streamId)){const{p:e,resolveP:t,rejectP:r}=Sf();e.catch(()=>{}),this.resolveReadableP=t,this.rejectReadableP=r;try{await e}catch(e){return}}let e;try{e=this.connection.conn.streamRecv(this.streamId,this.readableChunk)}catch(e){let t;if(!1!==(t=Hf(e))){const e=this.codeToReason("read",t),r=new gf("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),void this.dispatchEvent(new cp({detail:r}))}{const t=new mf("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.dispatchEvent(new cp({detail:t})),t}}if(null===e){const e=new mf("Failed `streamRecv` on the readable stream because it is not readable");throw this.readableController.error(e),this.dispatchEvent(new cp({detail:e})),e}const[t,r]=e;t>0&&this.readableController.enqueue(Buffer.from(this.readableChunk.subarray(0,t))),r&&(this.readableController.close(),this.dispatchEvent(new lp)),this.dispatchEvent(new up)}async writableWrite(e){if(0===e.byteLength)return;let t;for(;;){try{const r=this.connection.conn.streamSend(this.streamId,e,!1);t=null===r?0:r}catch(e){let t;if(!1!==(t=Lf(e))){const e=this.codeToReason("write",t),r=new yf("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new cp({detail:r}))}{const t=new mf("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new cp({detail:t})),t}}if(this.dispatchEvent(new up),t<e.byteLength){e=e.subarray(t,e.byteLength);const{p:r,resolveP:s,rejectP:i}=Sf();r.catch(()=>{}),this.resolveWritableP=s,this.rejectWritableP=i,await r;continue}return}}writableClose(){try{this.connection.conn.streamSend(this.streamId,new Uint8Array(0),!0)}catch(e){let t;if(!1!==(t=Lf(e))){const e=this.codeToReason("write",t),r=new yf("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new cp({detail:r}))}{const t=new mf("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new cp({detail:t})),t}}this.dispatchEvent(new hp),this.dispatchEvent(new up)}readableCancel(e){if(this._readClosed)return;const t=this.reasonToCode("read",e);try{this.connection.conn.streamShutdown(this.streamId,kd.Shutdown.Read,t)}catch(r){const e=new mf("Local stream readable could not be shutdown",{cause:r});throw this.readableController.error(e),this.dispatchEvent(new cp({detail:e})),e}const r=new ff("Closing readable stream locally",{data:{code:t},cause:e});this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new cp({detail:r})),this.dispatchEvent(new up)}writableAbort(e){if(this._writeClosed)return;const t=this.reasonToCode("write",e);try{this.connection.conn.streamShutdown(this.streamId,kd.Shutdown.Write,t)}catch(r){const e=new mf("Local stream writable could not be shutdown",{cause:r});throw this.writableController.error(e),this.dispatchEvent(new cp({detail:e})),e}const r=new pf("Closing writable stream locally",{data:{code:t},cause:e});this.writableController.error(e),this.rejectWritableP?.(e),this.dispatchEvent(new cp({detail:r})),this.dispatchEvent(new up)}};Cp([hd(new df)],xp.prototype,"meta",null),Cp([hd(new df,!1,["destroying"])],xp.prototype,"read",null),Cp([hd(new df,!1,["destroying"])],xp.prototype,"write",null),xp=Cp([ld({eventDestroy:class extends op{},eventDestroyed:ap})],xp);const _p=xp;var Bp,Rp,Op,Up,Tp,Np;!function(e){e[e.Reno=0]="Reno",e[e.CUBIC=1]="CUBIC",e[e.BBR=2]="BBR"}(Bp||(Bp={})),function(e){e[e.Read=0]="Read",e[e.Write=1]="Write"}(Rp||(Rp={})),function(e){e[e.Initial=0]="Initial",e[e.Retry=1]="Retry",e[e.Handshake=2]="Handshake",e[e.ZeroRTT=3]="ZeroRTT",e[e.VersionNegotiation=4]="VersionNegotiation",e[e.Short=5]="Short"}(Op||(Op={})),function(e){e[e.NoError=0]="NoError",e[e.InternalError=1]="InternalError",e[e.ConnectionRefused=2]="ConnectionRefused",e[e.FlowControlError=3]="FlowControlError",e[e.StreamLimitError=4]="StreamLimitError",e[e.StreamStateError=5]="StreamStateError",e[e.FinalSizeError=6]="FinalSizeError",e[e.FrameEncodingError=7]="FrameEncodingError",e[e.TransportParameterError=8]="TransportParameterError",e[e.ConnectionIdLimitError=9]="ConnectionIdLimitError",e[e.ProtocolViolation=10]="ProtocolViolation",e[e.InvalidToken=11]="InvalidToken",e[e.ApplicationError=12]="ApplicationError",e[e.CryptoBufferExceeded=13]="CryptoBufferExceeded",e[e.KeyUpdateError=14]="KeyUpdateError",e[e.AEADLimitReached=15]="AEADLimitReached",e[e.NoViablePath=16]="NoViablePath"}(Up||(Up={})),(Np=Tp||(Tp={}))[Np.CloseNotify=256]="CloseNotify",Np[Np.UnexpectedMessage=266]="UnexpectedMessage",Np[Np.BadRecordMac=276]="BadRecordMac",Np[Np.RecordOverflow=278]="RecordOverflow",Np[Np.HandshakeFailure=296]="HandshakeFailure",Np[Np.BadCertificate=298]="BadCertificate",Np[Np.UnsupportedCertificate=299]="UnsupportedCertificate",Np[Np.CertificateRevoked=300]="CertificateRevoked",Np[Np.CertificateExpired=301]="CertificateExpired",Np[Np.CertificateUnknown=302]="CertificateUnknown",Np[Np.IllegalParameter=303]="IllegalParameter",Np[Np.UnknownCA=304]="UnknownCA",Np[Np.AccessDenied=305]="AccessDenied",Np[Np.DecodeError=306]="DecodeError",Np[Np.DecryptError=307]="DecryptError",Np[Np.ProtocolVersion=326]="ProtocolVersion",Np[Np.InsufficientSecurity=327]="InsufficientSecurity",Np[Np.InternalError=336]="InternalError",Np[Np.InappropriateFallback=342]="InappropriateFallback",Np[Np.UserCanceled=346]="UserCanceled",Np[Np.MissingExtension=365]="MissingExtension",Np[Np.UnsupportedExtension=366]="UnsupportedExtension",Np[Np.UnrecognizedName=368]="UnrecognizedName",Np[Np.BadCertificateStatusResponse=369]="BadCertificateStatusResponse",Np[Np.UnknownPSKIdentity=371]="UnknownPSKIdentity",Np[Np.CertificateRequired=372]="CertificateRequired",Np[Np.NoApplicationProtocol=376]="NoApplicationProtocol";var Dp=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let Mp=class{type;closedP;conn;streamMap=new Map;sendId;logger;socket;config;reasonToCode;codeToReason;recvLock=new Du;streamIdClientBidi=0;streamIdServerBidi=1;streamIdClientUni=2;streamIdServerUni=3;streamIdUsedClientBidi=-4;streamIdUsedServerBidi=-3;streamIdUsedClientUni=-2;streamIdUsedServerUni=-1;streamIdUsedSet=new Set;connTimeoutTimer;keepAliveIntervalTimer;_remoteHost;_remotePort;certDERs=[];caDERs=[];secureEstablished=!1;secureEstablishedP;resolveSecureEstablishedP;rejectSecureEstablishedP;resolveClosedP;errorLast=null;handleEventQUICConnectionError=e=>{const t=e.detail;if(this.errorLast=t,this.logger.info(Pf(t)),t instanceof hf)throw t;this.dispatchEvent(new sp({detail:t}))};handleEventQUICConnectionClose=async e=>{const t=e.detail;this.secureEstablished||this.rejectSecureEstablishedP(t),t instanceof nf&&await this.send(),this[Lu]&&"stopping"!==this[Vu]&&await this.stop({force:!0})};handleEventQUICStream=e=>{e.detail instanceof Xh&&!(e.detail instanceof up)&&this.dispatchEvent(e.detail.clone())};handleEventQUICStreamSend=async()=>{this[Lu]&&await this.send()};handleEventQUICStreamDestroyed=e=>{const t=e.target;t.removeEventListener(up.name,this.handleEventQUICStreamSend),t.removeEventListener(ru.name,this.handleEventQUICStream),this.streamMap.delete(t.streamId)};constructor({type:e,scid:t,dcid:r,serverName:s=null,remoteInfo:i,config:n,socket:o,reasonToCode:a=()=>0,codeToReason:c=(e,t)=>new Error(`${e} ${t}`),logger:l}){if(this.logger=l??new Jh(`${this.constructor.name} ${t}`),this.sendId=t.toString(),null!=n.keepAliveIntervalTime&&0!==n.maxIdleTimeout&&n.keepAliveIntervalTime>=n.maxIdleTimeout)throw new sf("`keepAliveIntervalTime` must be less than `maxIdleTimeout`");const h=function(e){if(null!=e.key&&null==e.cert)throw new Td("The cert option must be set when key is set");if(null==e.key&&null!=e.cert)throw new Td("The key option must be set when cert is set");if(null!=e.key&&null!=e.cert&&Array.isArray(e.key)&&Array.isArray(e.cert)&&e.key.length!==e.cert.length)throw new Td("The number of keys must match the number of certs");let t,r,s,i;if(null!=e.ca){const r=Df(e.ca);t=Af.encode(r.join(""))}null!=e.key&&(r=Df(e.key).map(e=>Af.encode(e))),null!=e.cert&&(s=Df(e.cert).map(e=>Af.encode(e)));try{i=kd.Config.withBoringSslCtx(e.verifyPeer,null!=e.verifyCallback,t,r,s,e.sigalgs)}catch(e){throw new Td(`Failed to build Quiche config with custom SSL context: ${e.message}`,{cause:e})}return null!=e.logKeys&&i.logKeys(),e.enableEarlyData&&i.enableEarlyData(),i.grease(e.grease),i.setMaxIdleTimeout(e.maxIdleTimeout),i.setMaxRecvUdpPayloadSize(e.maxRecvUdpPayloadSize),i.setMaxSendUdpPayloadSize(e.maxSendUdpPayloadSize),i.setInitialMaxData(e.initialMaxData),i.setInitialMaxStreamDataBidiLocal(e.initialMaxStreamDataBidiLocal),i.setInitialMaxStreamDataBidiRemote(e.initialMaxStreamDataBidiRemote),i.setInitialMaxStreamDataUni(e.initialMaxStreamDataUni),i.setInitialMaxStreamsBidi(e.initialMaxStreamsBidi),i.setInitialMaxStreamsUni(e.initialMaxStreamsUni),i.enableDgram(...e.enableDgram),i.setDisableActiveMigration(e.disableActiveMigration),i.setApplicationProtos(e.applicationProtos),i}(n);let u;if("client"===e?(this.logger.info(`Connect ${this.constructor.name}`),u=kd.Connection.connect(s,t,{host:o.host,port:o.port},{host:i.host,port:i.port},h)):"server"===e&&(this.logger.info(`Accept ${this.constructor.name}`),u=kd.Connection.accept(t,r,{host:o.host,port:o.port},{host:i.host,port:i.port},h)),null!=n.logKeys&&u.setKeylog(n.logKeys),this.type=e,this.conn=u,this.socket=o,this.config=n,null!=this.config.cert){const e=Df(this.config.cert);this.certDERs=e.map(Mf)}if(null!=this.config.ca){const e=Df(this.config.ca);this.caDERs=e.map(Mf)}this.reasonToCode=a,this.codeToReason=c,this._remoteHost=i.host,this._remotePort=i.port;const{p:d,resolveP:f,rejectP:p}=Sf();d.catch(()=>{}),this.secureEstablishedP=d,this.resolveSecureEstablishedP=()=>{this.secureEstablished=!0,f()},this.rejectSecureEstablishedP=p;const{p:g,resolveP:y}=Sf();this.closedP=g,this.resolveClosedP=y}get connectionId(){const e=this.conn.sourceId();return new pd(e.buffer,e.byteOffset,e.byteLength)}get connectionIdPeer(){const e=this.conn.destinationId();return new pd(e.buffer,e.byteOffset,e.byteLength)}get connectionIdShared(){const e=this.conn.sourceId(),t=this.conn.destinationId();return Buffer.compare(e,t)<=0?new pd(Buffer.concat([e,t])):new pd(Buffer.concat([t,e]))}get remoteHost(){return this._remoteHost}get remotePort(){return this._remotePort}get localHost(){return this.socket.host}get localPort(){return this.socket.port}get closed(){return this.conn.isClosed()}async start({data:e,remoteInfo:t}={},r){if(this.logger.info(`Start ${this.constructor.name}`),this.conn.isClosed())throw new tf;r.signal.throwIfAborted();const{p:s,rejectP:i}=Sf();s.catch(()=>{});const n=()=>{i(r.signal.reason)};if(r.signal.addEventListener("abort",n),this.addEventListener(rp.name,this.handleEventQUICConnectionError),this.addEventListener(sp.name,this.handleEventQUICConnectionClose,{once:!0}),"client"===this.type)await this.send();else if("server"===this.type){if(null==e||null==t)throw new rf("Starting a server connection requires initial data and remote information");await this.recv(e,t)}try{await Promise.race([this.secureEstablishedP,s])}catch(e){if(r.signal.aborted){for(const t of this.conn.readable())this.conn.streamShutdown(t,kd.Shutdown.Read,this.reasonToCode("read",e));for(const t of this.conn.writable())this.conn.streamShutdown(t,kd.Shutdown.Write,this.reasonToCode("write",e));this.conn.close(!1,Up.ApplicationError,Buffer.from(""));const t=this.conn.localError(),r=new nf("Failed to start QUIC connection due to start timeout",{data:t,cause:e});this.dispatchEvent(new rp({detail:r}))}throw await this.closedP,e}finally{r.signal.removeEventListener("abort",n)}null!=this.config.keepAliveIntervalTime&&this.startKeepAliveIntervalTimer(this.config.keepAliveIntervalTime),this.logger.info(`Started ${this.constructor.name}`)}async stop({isApp:e=!0,errorCode:t=0,reason:r=new Uint8Array,force:s=!0}={}){this.logger.info(`Stop ${this.constructor.name}`),this.stopKeepAliveIntervalTimer(),await async function(){return await new Promise(e=>queueMicrotask(e))}();const i=[];for(const e of this.streamMap.values())i.push(e.destroy({reason:this.errorLast,force:s||this.conn.isDraining()||this.conn.isClosed()}));if(await Promise.all(i),!this.conn.isDraining()&&!this.conn.isClosed()){this.conn.close(e,t,r);const s=this.conn.localError(),i=`Locally closed with ${s.isApp?"application":"transport"} code ${s.errorCode}`,n=new nf(i,{data:s});this.dispatchEvent(new rp({detail:n}))}await this.closedP,this.removeEventListener(rp.name,this.handleEventQUICConnectionError),this.removeEventListener(sp.name,this.handleEventQUICConnectionClose),this.logger.info(`Stopped ${this.constructor.name}`)}getConnectionError(){return this.conn.localError()??this.conn.peerError()??void 0}getLocalCACertsChain(){return this.caDERs}getLocalCertsChain(){return this.certDERs}getRemoteCertsChain(){return this.conn.peerCertChain()??[]}meta(){return{localHost:this.localHost,localPort:this.localPort,remoteHost:this.remoteHost,remotePort:this.remotePort,localCertsChain:this.certDERs,localCACertsChain:this.caDERs,remoteCertsChain:this.getRemoteCertsChain()}}async recv(e,t){await this.recvLock.withF(async()=>{const r={to:{host:this.localHost,port:this.localPort},from:{host:t.host,port:t.port}};try{this.conn.recv(e,r)}catch(e){const t=this.conn.localError();if(null==t){const t=new hf("Failed connection recv due with unknown error",{cause:e});throw this.dispatchEvent(new rp({detail:t})),t}{let r;return r="TlsFail"===e.message?new of("Failed connection due to native TLS verification",{cause:e,data:t}):new nf("Failed connection due to local error",{cause:e,data:t}),void this.dispatchEvent(new rp({detail:r}))}}this._remoteHost=t.host,this._remotePort=t.port,!this.secureEstablished&&this.conn.isEstablished()&&null==this.config.verifyCallback&&this.resolveSecureEstablishedP(),this.secureEstablished&&this.processStreams(),await this.send()})}async send(){let e,t;for(;;){const r=Buffer.allocUnsafe(this.config.maxSendUdpPayloadSize);try{const s=this.conn.send(r);if(null===s)break;[e,t]=s}catch(e){const t=new hf("Failed connection send with unknown internal error",{cause:e});throw this.dispatchEvent(new rp({detail:t})),t}this.dispatchEvent(new np({detail:{id:this.sendId,msg:r.subarray(0,e),port:t.to.port,address:t.to.host}}))}if(this.setConnTimeoutTimer(),!this.secureEstablished&&!this.conn.isDraining()&&!this.conn.isClosed()&&this.conn.isEstablished()&&this.config.verifyPeer&&null!=this.config.verifyCallback){const e=this.conn.peerCertChain(),t=await this.config.verifyCallback(e,this.caDERs);if(null!=t){this.conn.close(!1,t,Buffer.from(""));const e=this.conn.localError(),r=new of("Failed connection due to custom TLS verification",{data:e});return void this.dispatchEvent(new rp({detail:r}))}this.resolveSecureEstablishedP(),this.processStreams()}if("stopping"!==this[Vu]){const e=this.conn.peerError();if(null!=e){const t=`Peer closed with ${e.isApp?"application":"transport"} code ${e.errorCode}`;return void(e.errorCode>=kd.CRYPTO_ERROR_START&&e.errorCode<=kd.CRYPTO_ERROR_STOP?this.dispatchEvent(new rp({detail:new cf(t,{data:e})})):this.dispatchEvent(new rp({detail:new af(t,{data:e})})))}}}isStreamUsed(e){let t;switch(3&e){case 0:if(t=this.streamIdUsedClientBidi+4,e<=this.streamIdUsedClientBidi||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedClientBidi=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;case 1:if(t=this.streamIdUsedServerBidi+4,e<=this.streamIdUsedServerBidi||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedServerBidi=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;case 2:if(t=this.streamIdUsedClientUni+4,e<=this.streamIdUsedClientUni||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedClientUni=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;case 3:if(t=this.streamIdUsedServerUni+4,e<=this.streamIdUsedServerUni||this.streamIdUsedSet.has(e))return!0;if(e===t){do{this.streamIdUsedServerUni=t,this.streamIdUsedSet.delete(t),t+=4}while(this.streamIdUsedSet.has(t));return!1}return this.streamIdUsedSet.add(e),!1;default:vf("got an unexpected ID type")}}processStreams(){for(const e of this.conn.readable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[Lu]||"stopping"===this[Vu]){this.conn.streamShutdown(e,Rp.Write,this.reasonToCode("write",Zd)),this.conn.streamShutdown(e,Rp.Read,this.reasonToCode("read",Zd));continue}this.isStreamUsed(e)&&vf("We should never repeat streamIds when creating streams"),t=_p.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${_p.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(up.name,this.handleEventQUICStreamSend),t.addEventListener(ap.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(ru.name,this.handleEventQUICStream),this.dispatchEvent(new ip({detail:t}))}t.read()}for(const e of this.conn.writable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[Lu]||"stopping"===this[Vu]){this.conn.streamShutdown(e,Rp.Write,this.reasonToCode("write",Zd)),this.conn.streamShutdown(e,Rp.Read,this.reasonToCode("read",Zd));continue}if(this.isStreamUsed(e)){try{this.conn.streamSend(e,new Uint8Array,!1)}catch(e){if(!1!==Lf(e))continue;if("FinalSize"===e.message)continue;throw e}vf("We never expect a duplicate stream to be readable")}t=_p.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${_p.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(up.name,this.handleEventQUICStreamSend),t.addEventListener(ap.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(ru.name,this.handleEventQUICStream),this.dispatchEvent(new ip({detail:t}))}t.write()}}setConnTimeoutTimer(){const e=async t=>{if(t.aborted)return;if(this.conn.onTimeout(),this.conn.isClosed())return this.resolveClosedP(),void(this.conn.isTimedOut()&&this.dispatchEvent(new rp({detail:new lf})));await this.send();const r=this.conn.timeout();null!=r&&(this.connTimeoutTimer=new Bu({delay:r+1,handler:e,lazy:!0}))},t=this.conn.timeout();if(null==t)return this.connTimeoutTimer?.cancel(),delete this.connTimeoutTimer,void(this.conn.isClosed()&&(this.resolveClosedP(),this.conn.isTimedOut()&&this.dispatchEvent(new rp({detail:new lf}))));null==this.connTimeoutTimer||"settled"===this.connTimeoutTimer.status?this.connTimeoutTimer=new Bu({delay:t+1,handler:e,lazy:!0}):null==this.connTimeoutTimer.status&&this.connTimeoutTimer.reset(t+1)}newStream(e="bidi"){let t;"client"===this.type&&"bidi"===e?t=this.streamIdClientBidi:"server"===this.type&&"bidi"===e?t=this.streamIdServerBidi:"client"===this.type&&"uni"===e?t=this.streamIdClientUni:"server"===this.type&&"uni"===e&&(t=this.streamIdServerUni),this.isStreamUsed(t)&&vf("We should never repeat streamIds when creating streams");const r=_p.createQUICStream({initiated:"local",streamId:t,connection:this,config:this.config,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${_p.name} ${t}`)});return this.streamMap.set(r.streamId,r),r.addEventListener(up.name,this.handleEventQUICStreamSend),r.addEventListener(ap.name,this.handleEventQUICStreamDestroyed,{once:!0}),r.addEventListener(ru.name,this.handleEventQUICStream),"client"===this.type&&"bidi"===e?this.streamIdClientBidi=this.streamIdClientBidi+4:"server"===this.type&&"bidi"===e?this.streamIdServerBidi=this.streamIdServerBidi+4:"client"===this.type&&"uni"===e?this.streamIdClientUni=this.streamIdClientUni+4:"server"===this.type&&"uni"===e&&(this.streamIdServerUni=this.streamIdServerUni+4),r}destroyStreams(e){for(const t of this.streamMap.values())t.cancel(e)}startKeepAliveIntervalTimer(e){const t=async r=>{r.aborted||(this.conn.sendAckEliciting(),await this.send(),r.aborted||(this.keepAliveIntervalTimer=new Bu({delay:e,handler:t,lazy:!0})))};this.keepAliveIntervalTimer=new Bu({delay:e,handler:t,lazy:!0})}stopKeepAliveIntervalTimer(){this.keepAliveIntervalTimer?.cancel()}};var Pp,Lp;Dp([dd(new ef)],Mp.prototype,"connectionIdPeer",null),Dp([dd(new ef)],Mp.prototype,"connectionIdShared",null),Dp([Ap(!0,vp,class extends Xd{static description="QUIC Connection start timeout"}),(Pp=1,Lp=yp,function(e,t){Lp(e,t,Pp)})],Mp.prototype,"start",null),Dp([dd(new ef,!1,["starting","stopping"])],Mp.prototype,"recv",null),Dp([dd(new ef,!1,["starting","stopping"])],Mp.prototype,"send",null),Dp([dd(new ef)],Mp.prototype,"newStream",null),Mp=Dp([ud({eventStart:class extends ep{},eventStarted:class extends ep{},eventStop:class extends ep{},eventStopped:tp})],Mp);const Hp=Mp;var Kp=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let Qp=class{isSocketShared;reasonToCode;codeToReason;minIdleTimeout;logger;socket;crypto;config;_closed=!1;_closedP;resolveClosedP;stopAbortController;handleEventQUICServerError=e=>{const t=e.detail;if(this.logger.info(Pf(t)),t instanceof Jd)throw t;this.dispatchEvent(new Zf({detail:t}))};handleEventQUICServerClose=async e=>{const t=e.detail;if(!(t instanceof zd||this.isSocketShared)){this.socket.removeEventListener(Ff.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new Jd("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new Xf({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[Lu]&&"stopping"!==this[Vu]&&(void 0!==t?await this.stop({isApp:!1,errorCode:Up.InternalError,reason:Buffer.from(t.description),force:!0}):await this.stop({force:!0}))};handleEventQUICSocket=e=>{e.detail instanceof Xh&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new zd;this.removeEventListener(ru.name,this.handleEventQUICSocket),this.dispatchEvent(new Xf({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof Xh&&!(e.detail instanceof np)&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionSend=async e=>{if(this.socket[Lu]&&"stopping"!==this.socket[Vu])try{await this.socket.send_(e.detail.msg,e.detail.port,e.detail.address)}catch(t){switch(t.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":case"EHOSTUNREACH":this.dispatchEvent(new zf(`${zf.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new Xf({detail:new Jd("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(np.name,this.handleEventQUICConnectionSend),t.removeEventListener(ru.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({crypto:e,config:t,socket:r,resolveHostname:s=Rf,reasonToCode:i,codeToReason:n,minIdleTimeout:o,logger:a}){this.logger=a??new Jh(this.constructor.name),this.crypto=e,null==r?(this.socket=new pp({resolveHostname:s,logger:this.logger.getChild(pp.name)}),this.isSocketShared=!1):(this.socket=r,this.isSocketShared=!0),this.config={...Sp,...t},this.reasonToCode=i,this.codeToReason=n,this.minIdleTimeout=o;const{p:c,resolveP:l}=Sf();this._closedP=c,this.resolveClosedP=l}get host(){return this.socket.host}get port(){return this.socket.port}get closed(){return this._closed}get closedP(){return this._closedP}async start({host:e="::",port:t=0,reuseAddr:r,ipv6Only:s}={}){let i;if(this.stopAbortController=new AbortController,Kf(this.stopAbortController.signal),this.isSocketShared){if(!this.socket[Lu])throw new zd;i=Tf(this.socket.host,this.socket.port),this.logger.info(`Start ${this.constructor.name} on ${i}`)}else i=Tf(e,t),this.logger.info(`Start ${this.constructor.name} on ${i}`),await this.socket.start({host:e,port:t,reuseAddr:r,ipv6Only:s}),i=Tf(this.socket.host,this.socket.port);this.socket.setServer(this),this.addEventListener(Xf.name,this.handleEventQUICServerError),this.addEventListener(Zf.name,this.handleEventQUICServerClose,{once:!0}),this.socket.addEventListener(Ff.name,this.handleEventQUICSocketStopped,{once:!0}),this.isSocketShared||this.socket.addEventListener(ru.name,this.handleEventQUICSocket),this._closed=!1,this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({isApp:e=!0,errorCode:t=0,reason:r=new Uint8Array,force:s=!0}={}){let i;this.socket[Lu]&&(i=Tf(this.socket.host,this.socket.port)),this.logger.info(`Stop ${this.constructor.name}${null!=i?` on ${i}`:""}`),this.socket.unsetServer();const n=[];s&&this.stopAbortController?.abort(new Yd),this.stopAbortController=void 0;for(const i of this.socket.connectionMap.serverConnections.values())n.push(i.stop({isApp:e,errorCode:t,reason:r,force:s}));await Promise.all(n),this._closed||this.dispatchEvent(new Zf),await this._closedP;const{p:o,resolveP:a}=Sf();this._closedP=o,this.resolveClosedP=a,this.removeEventListener(Xf.name,this.handleEventQUICServerError),this.removeEventListener(Zf.name,this.handleEventQUICServerClose),this.socket.removeEventListener(Ff.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(ru.name,this.handleEventQUICSocket),this.logger.info(`Stopped ${this.constructor.name}${null!=i?` on ${i}`:""}`)}async acceptConnection(e,t,r,s){if(t.ty!==kd.Type.Initial&&t.ty!==kd.Type.ZeroRTT)return;const i=new pd(await this.crypto.ops.sign(this.crypto.key,r),0,kd.MAX_CONN_ID_LEN),n=Tf(e.host,e.port);if(!kd.versionIsSupported(t.version)){const r=Buffer.allocUnsafe(kd.MAX_DATAGRAM_SIZE),s=kd.negotiateVersion(t.scid,t.dcid,r);try{await this.socket.send_(r,0,s,e.port,e.host)}catch(e){throw new Wd(`Failed to send version datagram ${n}`,{cause:e})}return}const o=t.token;if(0===o.byteLength){const s=await this.mintToken(r,e.host),o=Buffer.allocUnsafe(kd.MAX_DATAGRAM_SIZE),a=kd.retry(t.scid,t.dcid,i,s,t.version,o);try{await this.socket.send_(o,0,a,e.port,e.host)}catch(e){throw new Wd(`Failed to send stateless retry datagram to ${n}`,{cause:e})}return}const a=await this.validateToken(Buffer.from(o),e.host);if(null==a)return;if(i.byteLength!==t.dcid.byteLength)return;const c=new pd(t.dcid),l=new Hp({type:"server",scid:c,dcid:a,socket:this.socket,remoteInfo:e,config:{...this.config},reasonToCode:this.reasonToCode,codeToReason:this.codeToReason,logger:this.logger.getChild(`${Hp.name} ${i.toString()}`)});this.socket.connectionMap.set(l.connectionId,l),l.addEventListener(np.name,this.handleEventQUICConnectionSend),l.addEventListener(tp.name,this.handleEventQUICConnectionStopped,{once:!0}),l.addEventListener(ru.name,this.handleEventQUICConnection);try{await l.start({data:s,remoteInfo:e},{timer:this.minIdleTimeout,signal:this.stopAbortController?.signal})}catch(e){throw l.removeEventListener(np.name,this.handleEventQUICConnectionSend),l.removeEventListener(tp.name,this.handleEventQUICConnectionStopped),l.removeEventListener(ru.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(l.connectionId),new Wd("Failed to start accepted connection",{cause:e})}return this.dispatchEvent(new Yf({detail:l})),l}updateCrypto(e){this.crypto={...this.crypto,...e}}updateConfig(e){this.config={...this.config,...e}}async mintToken(e,t){return async function(e,t,r){const s={dcid:e.toString(),host:t},i=JSON.stringify(s),n=Buffer.from(i),o=Buffer.from(await r.ops.sign(r.key,n)),a={msg:n.toString("base64url"),sig:o.toString("base64url")},c=JSON.stringify(a);return Buffer.from(c)}(e,t,this.crypto)}async validateToken(e,t){return async function(e,t,r){let s;try{s=JSON.parse(e.toString())}catch{return}if("object"!=typeof s||null==s)return;if("string"!=typeof s.msg||"string"!=typeof s.sig)return;const i=Buffer.from(s.msg,"base64url"),n=Buffer.from(s.sig,"base64url");if(!await r.ops.verify(r.key,i,n))return;let o;try{o=JSON.parse(i.toString())}catch{return}return"object"==typeof o&&null!=o&&"string"==typeof o.dcid&&"string"==typeof o.host&&o.host===t?pd.fromString(o.dcid):void 0}(e,t,this.crypto)}};Kp([dd(new qd)],Qp.prototype,"host",null),Kp([dd(new qd)],Qp.prototype,"port",null),Kp([dd(new qd)],Qp.prototype,"acceptConnection",null),Qp=Kp([ud({eventStart:class extends Jf{},eventStarted:class extends Jf{},eventStop:class extends Jf{},eventStopped:class extends Jf{}})],Qp);var Vp=function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o};let Fp=class{static async createQUICClient({host:e,port:t,serverName:r,localHost:s="::",localPort:i=0,socket:n,crypto:o,config:a={},resolveHostname:c=Rf,reuseAddr:l,ipv6Only:h,reasonToCode:u,codeToReason:d,logger:f=new Jh(`${this.name}`)},p){let g=Tf(e,t);f.info(`Create ${this.name} to ${g}`);const y={...wp,...a},m=new ArrayBuffer(kd.MAX_CONN_ID_LEN);await o.ops.randomBytes(m);const b=new pd(m);let[A,I]=await Of(e,c);const v=Uf(t);let w,S;if(A=Bf(A),null==n){const[e]=await Of(s,c),t=Uf(i);n=new pp({resolveHostname:c,logger:f.getChild(pp.name)}),w=!1,await n.start({host:e,port:t,reuseAddr:l,ipv6Only:h})}else if(w=!0,!n[Lu])throw new zd;try{A=Nf(n.host,n.type,A,I,$d)}catch(e){throw w||await n.stop({force:!0}),e}try{S=new Hp({type:"client",scid:b,serverName:r??e,socket:n,remoteInfo:{host:A,port:v},config:y,reasonToCode:u,codeToReason:d,logger:f.getChild(`${Hp.name} ${b.toString()}`)})}catch(e){throw w||await n.stop({force:!0}),e}const E=new this({socket:n,connection:S,isSocketShared:w,logger:f});w||n.addEventListener(ru.name,E.handleEventQUICSocket),n.addEventListener(Ff.name,E.handleEventQUICSocketStopped,{once:!0}),S.addEventListener(ru.name,E.handleEventQUICConnection),S.addEventListener(rp.name,E.handleEventQUICConnectionError),S.addEventListener(np.name,E.handleEventQUICConnectionSend),S.addEventListener(tp.name,E.handleEventQUICConnectionStopped,{once:!0}),E.addEventListener(qf.name,E.handleEventQUICClientError),E.addEventListener(Wf.name,E.handleEventQUICClientClose,{once:!0}),n.connectionMap.set(S.connectionId,S);const C=new AbortController,k=()=>{C.abort(p.signal.reason)};p.signal.aborted?C.abort(p.signal.reason):p.signal.addEventListener("abort",k);const x=e=>{switch(e.detail.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":C.abort(new Fd(void 0,{cause:e.detail}))}};E.addEventListener(`${zf.name}-${S.sendId}`,x);try{await S.start(void 0,{timer:p.timer,signal:C.signal})}catch(e){throw n.connectionMap.delete(S.connectionId),n.removeEventListener(Ff.name,E.handleEventQUICSocketStopped),w||(n.removeEventListener(ru.name,E.handleEventQUICSocket),await n.stop({force:!0})),S.removeEventListener(ru.name,E.handleEventQUICConnection),S.removeEventListener(rp.name,E.handleEventQUICConnectionError),S.removeEventListener(np.name,E.handleEventQUICConnectionSend),S.removeEventListener(tp.name,E.handleEventQUICConnectionStopped),E.removeEventListener(qf.name,E.handleEventQUICClientError),E.removeEventListener(Wf.name,E.handleEventQUICClientClose),e}finally{p.signal.removeEventListener("abort",k),E.removeEventListener(`${zf.name}-${S.sendId}`,x)}return g=Tf(A,t),f.info(`Created ${this.name} to ${g}`),E}isSocketShared;connection;closedP;logger;socket;config;_closed=!1;resolveClosedP;handleEventQUICClientError=e=>{const t=e.detail;if(this.logger.info(Pf(t)),t instanceof jd||t instanceof hf)throw t;this.dispatchEvent(new Wf({detail:t}))};handleEventQUICClientClose=async e=>{const t=e.detail;if(this.connection.removeEventListener(rp.name,this.handleEventQUICConnectionError),await this.connection.stop({isApp:!1,errorCode:Up.InternalError,reason:Buffer.from(t.description),force:!0}),!(t instanceof Vd||this.isSocketShared)){this.socket.removeEventListener(Ff.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new jd("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new qf({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[Ku]||"destroying"===this[Vu]||await this.destroy({force:!0})};handleEventQUICSocket=e=>{e.detail instanceof Xh&&!(e.detail instanceof np)&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new Vd;this.removeEventListener(ru.name,this.handleEventQUICSocket),this.dispatchEvent(new qf({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof Xh&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionError=e=>{const t=e.detail;this.dispatchEvent(new qf({detail:t}))};handleEventQUICConnectionSend=async e=>{try{if(!this.socket[Lu]||"stopping"===this.socket[Vu])return;await this.socket.send_(e.detail.msg,e.detail.port,e.detail.address)}catch(t){switch(t.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":case"EHOSTUNREACH":this.dispatchEvent(new zf(`${zf.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new qf({detail:new jd("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(rp.name,this.handleEventQUICConnectionError),t.removeEventListener(np.name,this.handleEventQUICConnectionSend),t.removeEventListener(ru.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({socket:e,isSocketShared:t,connection:r,logger:s}){this.logger=s,this.socket=e,this.isSocketShared=t,this.connection=r;const{p:i,resolveP:n}=Sf();this.closedP=i,this.resolveClosedP=n}get host(){return this.connection.remoteHost}get port(){return this.connection.remotePort}get localHost(){return this.socket.host}get localPort(){return this.socket.port}get closed(){return this._closed}async destroy({isApp:e=!0,errorCode:t=0,reason:r=new Uint8Array,force:s=!0}={}){let i;this.connection[Lu]&&(i=Tf(this.connection.remoteHost,this.connection.remotePort)),this.logger.info(`Destroy ${this.constructor.name}${null!=i?` to ${i}`:""}`),this._closed||await this.connection.stop({isApp:e,errorCode:t,reason:r,force:s}),await this.closedP,this.removeEventListener(qf.name,this.handleEventQUICClientError),this.removeEventListener(Wf.name,this.handleEventQUICClientClose),this.socket.removeEventListener(Ff.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(ru.name,this.handleEventQUICSocket),this.logger.info(`Destroyed ${this.constructor.name}${null!=i?` to ${i}`:""}`)}};Vp([hd(new Qd)],Fp.prototype,"host",null),Vp([hd(new Qd)],Fp.prototype,"port",null),Vp([hd(new Qd)],Fp.prototype,"localHost",null),Vp([hd(new Qd)],Fp.prototype,"localPort",null),Vp([Ap(!0,vp,class extends Kd{static description="QUIC Client create timeout"}),function(e,t){return function(r,s){t(r,s,e)}}(1,yp)],Fp,"createQUICClient",null),Fp=Vp([ld({eventDestroy:class extends Gf{},eventDestroyed:class extends Gf{}})],Fp),t(import.meta.url)("node:crypto");class $p{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){const r=$p.toUint8Array(e),s=$p.toUint8Array(t);if(r.length!==s.byteLength)return!1;for(let e=0;e<r.length;e++)if(r[e]!==s[e])return!1;return!0}static concat(...e){let t;t=!Array.isArray(e[0])||e[1]instanceof Function?Array.isArray(e[0])&&e[1]instanceof Function?e[0]:e[e.length-1]instanceof Function?e.slice(0,e.length-1):e:e[0];let r=0;for(const e of t)r+=e.byteLength;const s=new Uint8Array(r);let i=0;for(const e of t){const t=this.toUint8Array(e);s.set(t,i),i+=t.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}}const jp="string",Gp=/^[0-9a-f\s]+$/i,qp=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,zp=/^[a-zA-Z0-9-_]+$/;class Wp{static fromString(e){const t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer}static toString(e){const t=$p.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return decodeURIComponent(escape(r))}}class Jp{static toString(e,t=!1){const r=$p.toArrayBuffer(e),s=new DataView(r);let i="";for(let e=0;e<r.byteLength;e+=2){const r=s.getUint16(e,t);i+=String.fromCharCode(r)}return i}static fromString(e,t=!1){const r=new ArrayBuffer(2*e.length),s=new DataView(r);for(let r=0;r<e.length;r++)s.setUint16(2*r,e.charCodeAt(r),t);return r}}class Yp{static isHex(e){return typeof e===jp&&Gp.test(e)}static isBase64(e){return typeof e===jp&&qp.test(e)}static isBase64Url(e){return typeof e===jp&&zp.test(e)}static ToString(e,t="utf8"){const r=$p.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(r);case"binary":return this.ToBinary(r);case"hex":return this.ToHex(r);case"base64":return this.ToBase64(r);case"base64url":return this.ToBase64Url(r);case"utf16le":return Jp.toString(r,!0);case"utf16":case"utf16be":return Jp.toString(r);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Jp.fromString(e,!0);case"utf16":case"utf16be":return Jp.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=$p.toUint8Array(e);if("undefined"!=typeof btoa){const e=this.ToString(t,"binary");return btoa(e)}return Buffer.from(t).toString("base64")}static FromBase64(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!Yp.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!=typeof atob?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){const t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!Yp.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=Yp.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Wp.fromString(e);case"utf16":case"utf16be":return Jp.fromString(e);case"utf16le":case"usc2":return Jp.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=Yp.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Wp.toString(e);case"utf16":case"utf16be":return Jp.toString(e);case"utf16le":case"usc2":return Jp.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){const t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return r.buffer}static ToBinary(e){const t=$p.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return r}static ToHex(e){const t=$p.toUint8Array(e);let r="";const s=t.length;for(let e=0;e<s;e++){const s=t[e];s<16&&(r+="0"),r+=s.toString(16)}return r}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!Yp.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);const r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2){const s=t.slice(e,e+2);r[e/2]=parseInt(s,16)}return r.buffer}static ToUtf16String(e,t=!1){return Jp.toString(e,t)}static FromUtf16String(e,t=!1){return Jp.fromString(e,t)}static Base64Padding(e){const t=4-e.length%4;if(t<4)for(let r=0;r<t;r++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}function Xp(...e){const t=e.map(e=>e.byteLength).reduce((e,t)=>e+t),r=new Uint8Array(t);let s=0;return e.map(e=>new Uint8Array(e)).forEach(e=>{for(const t of e)r[s++]=t}),r.buffer}function Zp(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(r[t]!==s[t])return!1;return!0}function eg(e,t){let r=0;if(1===e.length)return e[0];for(let s=e.length-1;s>=0;s--)r+=e[e.length-1-s]*Math.pow(2,t*s);return r}function tg(e,t,r=-1){const s=r;let i=e,n=0,o=Math.pow(2,t);for(let r=1;r<8;r++){if(e<o){let e;if(s<0)e=new ArrayBuffer(r),n=r;else{if(s<r)return new ArrayBuffer(0);e=new ArrayBuffer(s),n=s}const o=new Uint8Array(e);for(let e=r-1;e>=0;e--){const r=Math.pow(2,e*t);o[n-e-1]=Math.floor(i/r),i-=o[n-e-1]*r}return e}o*=Math.pow(2,t)}return new ArrayBuffer(0)}function rg(...e){let t=0,r=0;for(const r of e)t+=r.length;const s=new ArrayBuffer(t),i=new Uint8Array(s);for(const t of e)i.set(t,r),r+=t.length;return i}function sg(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const t=255===e[0]&&128&e[1],r=0===e[0]&&!(128&e[1]);(t||r)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(t);for(let e=0;e<this.valueHex.byteLength;e++)r[e]=0;r[0]=128&e[0];const s=eg(r,8),i=new ArrayBuffer(this.valueHex.byteLength),n=new Uint8Array(i);for(let t=0;t<this.valueHex.byteLength;t++)n[t]=e[t];return n[0]&=127,eg(n,8)-s}function ig(e,t){const r=e.toString(10);if(t<r.length)return"";const s=t-r.length,i=new Array(s);for(let e=0;e<s;e++)i[e]="0";return i.join("").concat(r)}function ng(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function og(e){let t=0,r=0;for(let r=0;r<e.length;r++)t+=e[r].byteLength;const s=new Uint8Array(t);for(let t=0;t<e.length;t++){const i=e[t];s.set(new Uint8Array(i),r),r+=i.byteLength}return s.buffer}function ag(e,t,r,s){return t instanceof Uint8Array?t.byteLength?r<0?(e.error="Wrong parameter: inputOffset less than zero",!1):s<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(t.byteLength-r-s<0&&(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",1)):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}Yp.DEFAULT_UTF8_ENCODING="utf8",Math.log(2);class cg{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return og(this.items)}}const lg=[new Uint8Array([1])],hg="0123456789",ug="name",dg="valueHexView",fg="isHexOnly",pg="idBlock",gg="tagClass",yg="tagNumber",mg="isConstructed",bg="fromBER",Ag="toBER",Ig="local",vg="",wg=new ArrayBuffer(0),Sg=new Uint8Array(0),Eg="EndOfContent",Cg="OCTET STRING",kg="BIT STRING";function xg(e){var t;return t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(...e){var t;super(...e);const r=e[0]||{};this.isHexOnly=null!==(t=r.isHexOnly)&&void 0!==t&&t,this.valueHexView=r.valueHex?$p.toUint8Array(r.valueHex):Sg}fromBER(e,t,r){const s=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!ag(this,s,t,r))return-1;const i=t+r;return this.valueHexView=s.subarray(t,i),this.valueHexView.length?(this.blockLength=r,i):(this.warnings.push("Zero buffer length"),t)}toBER(e=!1){return this.isHexOnly?e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",wg)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Yp.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class _g{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=vg,warnings:r=[],valueBeforeDecode:s=Sg}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=$p.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Yp.ToHex(this.valueBeforeDecodeView)}}}_g.NAME="baseBlock";class Bg extends _g{fromBER(e,t,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Bg.NAME="valueBlock";class Rg extends(xg(_g)){constructor({idBlock:e={}}={}){var t,r,s,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?$p.toUint8Array(e.valueHex):Sg,this.tagClass=null!==(r=e.tagClass)&&void 0!==r?r:-1,this.tagNumber=null!==(s=e.tagNumber)&&void 0!==s?s:-1,this.isConstructed=null!==(i=e.isConstructed)&&void 0!==i&&i):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",wg}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){const r=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,t|=e,r[0]=t}return r.buffer}if(!this.isHexOnly){const r=tg(this.tagNumber,7),s=new Uint8Array(r),i=r.byteLength,n=new Uint8Array(i+1);if(n[0]=31|t,!e){for(let e=0;e<i-1;e++)n[e+1]=128|s[e];n[i]=s[i-1]}return n.buffer}const r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=31|t,!e){const e=this.valueHexView;for(let t=0;t<e.length-1;t++)r[t+1]=128|e[t];r[this.valueHexView.byteLength]=e[e.length-1]}return r.buffer}fromBER(e,t,r){const s=$p.toUint8Array(e);if(!ag(this,s,t,r))return-1;const i=s.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;switch(192&i[0]){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=!(32&~i[0]),this.isHexOnly=!1;const n=31&i[0];if(31!==n)this.tagNumber=n,this.blockLength=1;else{let e=1,t=this.valueHexView=new Uint8Array(255),r=255;for(;128&i[e];){if(t[e-1]=127&i[e],e++,e>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(e===r){r+=255;const e=new Uint8Array(r);for(let r=0;r<t.length;r++)e[r]=t[r];t=this.valueHexView=new Uint8Array(r)}}this.blockLength=e+1,t[e-1]=127&i[e];const s=new Uint8Array(e);for(let r=0;r<e;r++)s[r]=t[r];t=this.valueHexView=new Uint8Array(e),t.set(s),this.blockLength<=9?this.tagNumber=eg(t,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}Rg.NAME="identificationBlock";class Og extends _g{constructor({lenBlock:e={}}={}){var t,r,s;super(),this.isIndefiniteForm=null!==(t=e.isIndefiniteForm)&&void 0!==t&&t,this.longFormUsed=null!==(r=e.longFormUsed)&&void 0!==r&&r,this.length=null!==(s=e.length)&&void 0!==s?s:0}fromBER(e,t,r){const s=$p.toUint8Array(e);if(!ag(this,s,t,r))return-1;const i=s.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;if(255===i[0])return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=128===i[0],this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(128&i[0]),!1===this.longFormUsed)return this.length=i[0],this.blockLength=1,t+this.blockLength;const n=127&i[0];if(n>8)return this.error="Too big integer",-1;if(n+1>i.length)return this.error="End of input reached before message was fully decoded",-1;const o=t+1,a=s.subarray(o,o+n);return 0===a[n-1]&&this.warnings.push("Needlessly long encoded length"),this.length=eg(a,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=n+1,t+this.blockLength}toBER(e=!1){let t,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=128),t;if(this.longFormUsed){const s=tg(this.length,8);if(s.byteLength>127)return this.error="Too big length",wg;if(t=new ArrayBuffer(s.byteLength+1),e)return t;const i=new Uint8Array(s);r=new Uint8Array(t),r[0]=128|s.byteLength;for(let e=0;e<s.byteLength;e++)r[e+1]=i[e];return t}return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}Og.NAME="lengthBlock";const Ug={};class Tg extends _g{constructor({name:e=vg,optional:t=!1,primitiveSchema:r,...s}={},i){super(s),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new Rg(s),this.lenBlock=new Og(s),this.valueBlock=i?new i(s):new Bg(s)}fromBER(e,t,r){const s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===s?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}toBER(e,t){const r=t||new cg;t||Ng(this);const s=this.idBlock.toBER(e);if(r.write(s),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,r),r.write(new ArrayBuffer(2));else{const t=this.valueBlock.toBER(e);this.lenBlock.length=t.byteLength;const s=this.lenBlock.toBER(e);r.write(s),r.write(t)}return t?wg:r.final()}toJSON(){const e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return"ascii"===e?this.onAsciiEncoding():Yp.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${Yp.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){return this===e||e instanceof this.constructor&&function(e,t){if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let e=0;e<r.length;e++)if(r[e]!==s[e])return!1;return!0}(this.toBER(),e.toBER())}}function Ng(e){var t;if(e instanceof Ug.Constructed)for(const t of e.valueBlock.value)Ng(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}Tg.NAME="BaseBlock";class Dg extends Tg{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=vg,...t}={},r){super(t,r),e&&this.fromString(e)}fromBER(e,t,r){const s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===s?(this.error=this.valueBlock.error,s):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}Dg.NAME="BaseStringBlock";class Mg extends(xg(Bg)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var Pg,Lg,Hg,Kg,Qg,Vg,Fg,$g,jg,Gg,qg,zg,Wg,Jg,Yg,Xg,Zg,ey,ty,ry,sy,iy,ny,oy,ay,cy,ly,hy,uy,dy,fy,py,gy,yy,my,by;Mg.NAME="PrimitiveValueBlock";class Ay extends Tg{constructor(e={}){super(e,Mg),this.idBlock.isConstructed=!1}}function Iy(e,t=0,r=e.length){const s=t;let i=new Tg({},Bg);const n=new _g;if(!ag(n,e,t,r))return i.error=n.error,{offset:-1,result:i};if(!e.subarray(t,t+r).length)return i.error="Zero buffer length",{offset:-1,result:i};let o=i.idBlock.fromBER(e,t,r);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),-1===o)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=o,r-=i.idBlock.blockLength,o=i.lenBlock.fromBER(e,t,r),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),-1===o)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=o,r-=i.lenBlock.blockLength,!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let a=Tg;if(1===i.idBlock.tagClass){if(i.idBlock.tagNumber>=37&&!1===i.idBlock.isHexOnly)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};a=Ug.EndOfContent;break;case 1:a=Ug.Boolean;break;case 2:a=Ug.Integer;break;case 3:a=Ug.BitString;break;case 4:a=Ug.OctetString;break;case 5:a=Ug.Null;break;case 6:a=Ug.ObjectIdentifier;break;case 10:a=Ug.Enumerated;break;case 12:a=Ug.Utf8String;break;case 13:a=Ug.RelativeObjectIdentifier;break;case 14:a=Ug.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:a=Ug.Sequence;break;case 17:a=Ug.Set;break;case 18:a=Ug.NumericString;break;case 19:a=Ug.PrintableString;break;case 20:a=Ug.TeletexString;break;case 21:a=Ug.VideotexString;break;case 22:a=Ug.IA5String;break;case 23:a=Ug.UTCTime;break;case 24:a=Ug.GeneralizedTime;break;case 25:a=Ug.GraphicString;break;case 26:a=Ug.VisibleString;break;case 27:a=Ug.GeneralString;break;case 28:a=Ug.UniversalString;break;case 29:a=Ug.CharacterString;break;case 30:a=Ug.BmpString;break;case 31:a=Ug.DATE;break;case 32:a=Ug.TimeOfDay;break;case 33:a=Ug.DateTime;break;case 34:a=Ug.Duration;break;default:{const e=i.idBlock.isConstructed?new Ug.Constructed:new Ug.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else a=i.idBlock.isConstructed?Ug.Constructed:Ug.Primitive;return i=function(e,t){if(e instanceof t)return e;const r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(i,a),o=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?r:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(s,s+i.blockLength),{offset:o,result:i}}function vy(e){if(!e.byteLength){const e=new Tg({},Bg);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Iy($p.toUint8Array(e).slice(),0,e.byteLength)}function wy(e,t){return e?1:t}Pg=Ay,Ug.Primitive=Pg,Ay.NAME="PRIMITIVE";class Sy extends Bg{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const s=$p.toUint8Array(e);if(!ag(this,s,t,r))return-1;if(this.valueBeforeDecodeView=s.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;let i=t;for(;wy(this.isIndefiniteForm,r)>0;){const e=Iy(s,i,r);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(i=e.offset,this.blockLength+=e.result.blockLength,r-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===Eg)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Eg?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){const r=t||new cg;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?wg:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}Sy.NAME="ConstructedValueBlock";class Ey extends Tg{constructor(e={}){super(e,Sy),this.idBlock.isConstructed=!0}fromBER(e,t,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===s?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){const e=[];for(const t of this.valueBlock.value)e.push(t.toString("ascii").split("\n").map(e=>` ${e}`).join("\n"));const t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join("\n")}`:`${t} :`}}Lg=Ey,Ug.Constructed=Lg,Ey.NAME="CONSTRUCTED";class Cy extends Bg{fromBER(e,t,r){return t}toBER(e){return wg}}Cy.override="EndOfContentValueBlock";class ky extends Tg{constructor(e={}){super(e,Cy),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Hg=ky,Ug.EndOfContent=Hg,ky.NAME=Eg;class xy extends Tg{constructor(e={}){super(e,Bg),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=r,t+r>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+r}toBER(e,t){const r=new ArrayBuffer(2);if(!e){const e=new Uint8Array(r);e[0]=5,e[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}Kg=xy,Ug.Null=Kg,xy.NAME="NULL";class _y extends(xg(Bg)){get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=$p.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,r){const s=$p.toUint8Array(e);return ag(this,s,t,r)?(this.valueHexView=s.subarray(t,t+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,sg.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}_y.NAME="BooleanValueBlock";class By extends Tg{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,_y),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}Qg=By,Ug.Boolean=Qg,By.NAME="BOOLEAN";class Ry extends(xg(Sy)){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=Sy.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(let e=0;e<this.value.length;e++){const t=this.value[e].constructor.NAME;if(t===Eg){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==Cg)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,r),this.blockLength=r;return s}toBER(e,t){return this.isConstructed?Sy.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Ry.NAME="OctetStringValueBlock";class Oy extends Tg{constructor({idBlock:e={},lenBlock:t={},...r}={}){var s,i;null!==(s=r.isConstructed)&&void 0!==s||(r.isConstructed=!!(null===(i=r.value)||void 0===i?void 0:i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Ry),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,0===r)return 0===this.idBlock.error.length&&(this.blockLength+=this.idBlock.blockLength),0===this.lenBlock.error.length&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){const s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+r);try{if(s.byteLength){const e=Iy(s,0,s.byteLength);-1!==e.offset&&e.offset===r&&(this.valueBlock.value=[e.result])}}catch{}}return super.fromBER(e,t,r)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Ey.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${Yp.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const t of this.valueBlock.value)t instanceof Vg&&e.push(t.valueBlock.valueHexView);return $p.concat(e)}}Vg=Oy,Ug.OctetString=Vg,Oy.NAME=Cg;class Uy extends(xg(Sy)){constructor({unusedBits:e=0,isConstructed:t=!1,...r}={}){super(r),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r){if(!r)return t;let s=-1;if(this.isConstructed){if(s=Sy.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(const e of this.value){const t=e.constructor.NAME;if(t===Eg){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==kg)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const r=e.valueBlock;if(this.unusedBits>0&&r.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=r.unusedBits}return s}const i=$p.toUint8Array(e);if(!ag(this,i,t,r))return-1;const n=i.subarray(t,t+r);if(this.unusedBits=n[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const e=n.subarray(1);try{if(e.byteLength){const t=Iy(e,0,e.byteLength);-1!==t.offset&&t.offset===r-1&&(this.value=[t.result])}}catch{}}return this.valueHexView=n.subarray(1),this.blockLength=n.length,t+r}toBER(e,t){if(this.isConstructed)return Sy.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return wg;const r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}Uy.NAME="BitStringValueBlock";class Ty extends Tg{constructor({idBlock:e={},lenBlock:t={},...r}={}){var s,i;null!==(s=r.isConstructed)&&void 0!==s||(r.isConstructed=!!(null===(i=r.value)||void 0===i?void 0:i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Uy),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ey.prototype.onAsciiEncoding.call(this);{const e=[],t=this.valueBlock.valueHexView;for(const r of t)e.push(r.toString(2).padStart(8,"0"));const r=e.join("");return`${this.constructor.NAME} : ${r.substring(0,r.length-this.valueBlock.unusedBits)}`}}}function Ny(e,t){const r=new Uint8Array([0]),s=new Uint8Array(e),i=new Uint8Array(t);let n=s.slice(0);const o=n.length-1,a=i.slice(0),c=a.length-1;let l=0,h=0;for(let e=c<o?o:c;e>=0;e--,h++)l=1==h<a.length?n[o-h]+a[c-h]+r[0]:n[o-h]+r[0],r[0]=l/10,1==h>=n.length?n=rg(new Uint8Array([l%10]),n):n[o-h]=l%10;return r[0]>0&&(n=rg(r,n)),n}function Dy(e){if(e>=lg.length)for(let t=lg.length;t<=e;t++){const e=new Uint8Array([0]);let r=lg[t-1].slice(0);for(let t=r.length-1;t>=0;t--){const s=new Uint8Array([(r[t]<<1)+e[0]]);e[0]=s[0]/10,r[t]=s[0]%10}e[0]>0&&(r=rg(e,r)),lg.push(r)}return lg[e]}function My(e,t){let r=0;const s=new Uint8Array(e),i=new Uint8Array(t),n=s.slice(0),o=n.length-1,a=i.slice(0),c=a.length-1;let l,h=0;for(let e=c;e>=0;e--,h++)l=n[o-h]-a[c-h]-r,1==l<0?(r=1,n[o-h]=l+10):(r=0,n[o-h]=l);if(r>0)for(let e=o-c+1;e>=0;e--,h++){if(l=n[o-h]-r,!(l<0)){r=0,n[o-h]=l;break}r=1,n[o-h]=l+10}return n.slice()}Fg=Ty,Ug.BitString=Fg,Ty.NAME=kg;class Py extends(xg(Bg)){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=sg.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),void 0!==e&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){const t=e<0?-1*e:e;let r=128;for(let s=1;s<8;s++){if(t<=r){if(e<0){const e=tg(r-t,8,s);return new Uint8Array(e)[0]|=128,e}let i=tg(t,8,s),n=new Uint8Array(i);if(128&n[0]){const e=i.slice(0),t=new Uint8Array(e);i=new ArrayBuffer(i.byteLength+1),n=new Uint8Array(i);for(let r=0;r<e.byteLength;r++)n[r+1]=t[r];n[0]=0}return i}r*=Math.pow(2,8)}return new ArrayBuffer(0)}(e))}get valueDec(){return this._valueDec}fromDER(e,t,r,s=0){const i=this.fromBER(e,t,r);if(-1===i)return i;const n=this.valueHexView;return 0===n[0]&&128&n[1]?this.valueHexView=n.subarray(1):0!==s&&n.length<s&&(s-n.length>1&&(s=n.length+1),this.valueHexView=n.subarray(s-n.length)),i}toDER(e=!1){const t=this.valueHexView;switch(!0){case!!(128&t[0]):{const e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case 0===t[0]&&!(128&t[1]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){const s=super.fromBER(e,t,r);return-1===s||this.setValueHex(),s}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=8*this.valueHexView.length-1;let t,r=new Uint8Array(8*this.valueHexView.length/3),s=0;const i=this.valueHexView;let n="",o=!1;for(let o=i.byteLength-1;o>=0;o--){t=i[o];for(let i=0;i<8;i++)1&~t||(s===e?(r=My(Dy(s),r),n="-"):r=Ny(r,Dy(s))),s++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(o=!0),o&&(n+=hg.charAt(r[e]));return!1===o&&(n+=hg.charAt(0)),n}}$g=Py,Py.NAME="IntegerValueBlock",Object.defineProperty($g.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class Ly extends Tg{constructor(e={}){super(e,Py),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return ng(),BigInt(this.valueBlock.toString())}static fromBigInt(e){ng();const t=BigInt(e),r=new cg,s=t.toString(16).replace(/^-/,""),i=new Uint8Array(Yp.FromHex(s));if(t<0){const e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;const s=BigInt(`0x${Yp.ToHex(e)}`)+t,n=$p.toUint8Array(Yp.FromHex(s.toString(16)));n[0]|=128,r.write(n)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);return new jg({valueHex:r.final()})}convertToDER(){const e=new jg({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new jg({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}jg=Ly,Ug.Integer=jg,Ly.NAME="INTEGER";class Hy extends Ly{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Gg=Hy,Ug.Enumerated=Gg,Hy.NAME="ENUMERATED";class Ky extends(xg(Bg)){constructor({valueDec:e=-1,isFirstSid:t=!1,...r}={}){super(r),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,r){if(!r)return t;const s=$p.toUint8Array(e);if(!ag(this,s,t,r))return-1;const i=s.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&i[e],this.blockLength++,128&i[e]);e++);const n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)n[e]=this.valueHexView[e];return this.valueHexView=n,128&i[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=eg(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){ng();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;const r=new Uint8Array(t.length/7);for(let e=0;e<r.length;e++)r[e]=parseInt(t.slice(7*e,7*e+7),2)+(e+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}const t=tg(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",wg;const r=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),s=t.byteLength-1;for(let t=0;t<s;t++)r[t]=128|e[t];r[s]=e[s]}return r}toString(){let e="";if(this.isHexOnly)e=Yp.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}Ky.NAME="sidBlock";class Qy extends Bg{constructor({value:e=vg,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new Ky;if(s=t.fromBER(e,s,r),-1===s)return this.blockLength=0,this.error=t.error,s;0===this.value.length&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return s}toBER(e){const t=[];for(let r=0;r<this.value.length;r++){const s=this.value[r].toBER(e);if(0===s.byteLength)return this.error=this.value[r].error,wg;t.push(s)}return og(t)}fromString(e){this.value=[];let t=0,r=0,s="",i=!1;do{if(r=e.indexOf(".",t),s=-1===r?e.substring(t):e.substring(t,r),t=r+1,i){const e=this.value[0];let t=0;switch(e.valueDec){case 0:break;case 1:t=40;break;case 2:t=80;break;default:return void(this.value=[])}const r=parseInt(s,10);if(isNaN(r))return;e.valueDec=r+t,i=!1}else{const e=new Ky;if(s>Number.MAX_SAFE_INTEGER){ng();const t=BigInt(s);e.valueBigInt=t}else if(e.valueDec=parseInt(s,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,i=!0),this.value.push(e)}}while(-1!==r)}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let s=this.value[r].toString();0!==r&&(e=`${e}.`),t?(s=`{${s}}`,this.value[r].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}Qy.NAME="ObjectIdentifierValueBlock";class Vy extends Tg{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Qy),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}qg=Vy,Ug.ObjectIdentifier=qg,Vy.NAME="OBJECT IDENTIFIER";class Fy extends(xg(_g)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const s=$p.toUint8Array(e);if(!ag(this,s,t,r))return-1;const i=s.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let e=0;e<r&&(this.valueHexView[e]=127&i[e],this.blockLength++,128&i[e]);e++);const n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)n[e]=this.valueHexView[e];return this.valueHexView=n,128&i[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=eg(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const t=this.valueHexView,r=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)r[e]=128|t[e];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}const t=tg(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",wg;const r=new Uint8Array(t.byteLength);if(!e){const e=new Uint8Array(t),s=t.byteLength-1;for(let t=0;t<s;t++)r[t]=128|e[t];r[s]=e[s]}return r.buffer}toString(){let e="";return e=this.isHexOnly?Yp.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Fy.NAME="relativeSidBlock";class $y extends Bg{constructor({value:e=vg,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new Fy;if(s=t.fromBER(e,s,r),-1===s)return this.blockLength=0,this.error=t.error,s;this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return s}toBER(e,t){const r=[];for(let t=0;t<this.value.length;t++){const s=this.value[t].toBER(e);if(0===s.byteLength)return this.error=this.value[t].error,wg;r.push(s)}return og(r)}fromString(e){this.value=[];let t=0,r=0,s="";do{r=e.indexOf(".",t),s=-1===r?e.substring(t):e.substring(t,r),t=r+1;const i=new Fy;if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(-1!==r);return!0}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let s=this.value[r].toString();0!==r&&(e=`${e}.`),t?(s=`{${s}}`,e+=s):e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}$y.NAME="RelativeObjectIdentifierValueBlock";class jy extends Tg{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,$y),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}zg=jy,Ug.RelativeObjectIdentifier=zg,jy.NAME="RelativeObjectIdentifier";class Gy extends Ey{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}Wg=Gy,Ug.Sequence=Wg,Gy.NAME="SEQUENCE";class qy extends Ey{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}Jg=qy,Ug.Set=Jg,qy.NAME="SET";class zy extends(xg(Bg)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=vg}toJSON(){return{...super.toJSON(),value:this.value}}}zy.NAME="StringValueBlock";class Wy extends zy{}Wy.NAME="SimpleStringValueBlock";class Jy extends Dg{constructor({...e}={}){super(e,Wy)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,$p.toUint8Array(e))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);this.valueBlock.value=e}}Jy.NAME="SIMPLE STRING";class Yy extends Jy{fromBuffer(e){this.valueBlock.valueHexView=$p.toUint8Array(e);try{this.valueBlock.value=Yp.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=Yp.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Yp.FromUtf8String(e)),this.valueBlock.value=e}}Yy.NAME="Utf8StringValueBlock";class Xy extends Yy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}Yg=Xy,Ug.Utf8String=Yg,Xy.NAME="UTF8String";class Zy extends Jy{fromBuffer(e){this.valueBlock.value=Yp.ToUtf16String(e),this.valueBlock.valueHexView=$p.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Yp.FromUtf16String(e))}}Zy.NAME="BmpStringValueBlock";class em extends Zy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}Xg=em,Ug.BmpString=Xg,em.NAME="BMPString";class tm extends Jy{fromBuffer(e){const t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(t);for(let e=0;e<r.length;e+=4)r[e]=r[e+3],r[e+1]=r[e+2],r[e+2]=0,r[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){const t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(4*t);for(let s=0;s<t;s++){const t=tg(e.charCodeAt(s),8),i=new Uint8Array(t);if(i.length>4)continue;const n=4-i.length;for(let e=i.length-1;e>=0;e--)r[4*s+e+n]=i[e]}this.valueBlock.value=e}}tm.NAME="UniversalStringValueBlock";class rm extends tm{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Zg=rm,Ug.UniversalString=Zg,rm.NAME="UniversalString";class sm extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}ey=sm,Ug.NumericString=ey,sm.NAME="NumericString";class im extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}ty=im,Ug.PrintableString=ty,im.NAME="PrintableString";class nm extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}ry=nm,Ug.TeletexString=ry,nm.NAME="TeletexString";class om extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}sy=om,Ug.VideotexString=sy,om.NAME="VideotexString";class am extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}iy=am,Ug.IA5String=iy,am.NAME="IA5String";class cm extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}ny=cm,Ug.GraphicString=ny,cm.NAME="GraphicString";class lm extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}oy=lm,Ug.VisibleString=oy,lm.NAME="VisibleString";class hm extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}ay=hm,Ug.GeneralString=ay,hm.NAME="GeneralString";class um extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}cy=um,Ug.CharacterString=cy,um.NAME="CharacterString";class dm extends lm{constructor({value:e,valueDate:t,...r}={}){if(super(r),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let t=0;t<e.length;t++)this.valueBlock.valueHexView[t]=e.charCodeAt(t)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,$p.toUint8Array(e)))}toBuffer(){const e=this.toString(),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(null===t)return void(this.error="Wrong input string for conversion");const r=parseInt(t[1],10);this.year=r>=50?1900+r:2e3+r,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e="iso"){if("iso"===e){const e=new Array(7);return e[0]=ig(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=ig(this.month,2),e[2]=ig(this.day,2),e[3]=ig(this.hour,2),e[4]=ig(this.minute,2),e[5]=ig(this.second,2),e[6]="Z",e.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}ly=dm,Ug.UTCTime=ly,dm.NAME="UTCTime";class fm extends dm{constructor(e={}){var t;super(e),null!==(t=this.millisecond)&&void 0!==t||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){const e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t,r=!1,s="",i="",n=0,o=0,a=0;if("Z"===e[e.length-1])s=e.substring(0,e.length-1),r=!0;else{const t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw new Error("Wrong input string for conversion");s=e}if(r){if(-1!==s.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==s.indexOf("-"))throw new Error("Wrong input string for conversion")}else{let e=1,t=s.indexOf("+"),r="";if(-1===t&&(t=s.indexOf("-"),e=-1),-1!==t){if(r=s.substring(t+1),s=s.substring(0,t),2!==r.length&&4!==r.length)throw new Error("Wrong input string for conversion");let i=parseInt(r.substring(0,2),10);if(isNaN(i.valueOf()))throw new Error("Wrong input string for conversion");if(o=e*i,4===r.length){if(i=parseInt(r.substring(2,4),10),isNaN(i.valueOf()))throw new Error("Wrong input string for conversion");a=e*i}}}let c=s.indexOf(".");if(-1===c&&(c=s.indexOf(",")),-1!==c){const e=new Number(`0${s.substring(c)}`);if(isNaN(e.valueOf()))throw new Error("Wrong input string for conversion");n=e.valueOf(),i=s.substring(0,c)}else i=s;switch(!0){case 8===i.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==c)throw new Error("Wrong input string for conversion");break;case 10===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*n;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 12===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*n;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){const e=1e3*n;this.millisecond=Math.floor(e)}break;default:throw new Error("Wrong input string for conversion")}const l=t.exec(i);if(null===l)throw new Error("Wrong input string for conversion");for(let e=1;e<l.length;e++)switch(e){case 1:this.year=parseInt(l[e],10);break;case 2:this.month=parseInt(l[e],10);break;case 3:this.day=parseInt(l[e],10);break;case 4:this.hour=parseInt(l[e],10)+o;break;case 5:this.minute=parseInt(l[e],10)+a;break;case 6:this.second=parseInt(l[e],10);break;default:throw new Error("Wrong input string for conversion")}if(!1===r){const e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e="iso"){if("iso"===e){const e=[];return e.push(ig(this.year,4)),e.push(ig(this.month,2)),e.push(ig(this.day,2)),e.push(ig(this.hour,2)),e.push(ig(this.minute,2)),e.push(ig(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(ig(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}hy=fm,Ug.GeneralizedTime=hy,fm.NAME="GeneralizedTime";class pm extends Xy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}uy=pm,Ug.DATE=uy,pm.NAME="DATE";class gm extends Xy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}dy=gm,Ug.TimeOfDay=dy,gm.NAME="TimeOfDay";class ym extends Xy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}fy=ym,Ug.DateTime=fy,ym.NAME="DateTime";class mm extends Xy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}py=mm,Ug.Duration=py,mm.NAME="Duration";class bm extends Xy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}gy=bm,Ug.TIME=gy,bm.NAME="TIME";class Am{constructor({name:e=vg,optional:t=!1}={}){this.name=e,this.optional=t}}class Im extends Am{constructor({value:e=[],...t}={}){super(t),this.value=e}}class vm extends Am{constructor({value:e=new Am,local:t=!1,...r}={}){super(r),this.value=e,this.local=t}}class wm{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=$p.toUint8Array(e)}constructor({data:e=Sg}={}){this.dataView=$p.toUint8Array(e)}fromBER(e,t,r){const s=t+r;return this.dataView=$p.toUint8Array(e).subarray(t,s),s}toBER(e){return this.dataView.slice().buffer}}function Sm(e,t,r){if(r instanceof Im){for(const s of r.value)if(Sm(e,t,s).verified)return{verified:!0,result:e};{const e={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(ug)&&(e.name=r.name),e}}if(r instanceof Am)return r.hasOwnProperty(ug)&&(e[r.name]=t),{verified:!0,result:e};if(e instanceof Object==0)return{verified:!1,result:{error:"Wrong root object"}};if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(r instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(pg in r==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(bg in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(Ag in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const s=r.idBlock.toBER(!1);if(0===s.byteLength)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(-1===r.idBlock.fromBER(s,0,s.byteLength))return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(!1===r.idBlock.hasOwnProperty(gg))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==t.idBlock.tagClass)return{verified:!1,result:e};if(!1===r.idBlock.hasOwnProperty(yg))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==t.idBlock.tagNumber)return{verified:!1,result:e};if(!1===r.idBlock.hasOwnProperty(mg))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(fg in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==t.idBlock.isHexOnly)return{verified:!1,result:e};if(r.idBlock.isHexOnly){if(dg in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const s=r.idBlock.valueHexView,i=t.idBlock.valueHexView;if(s.length!==i.length)return{verified:!1,result:e};for(let t=0;t<s.length;t++)if(s[t]!==i[1])return{verified:!1,result:e}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,vg),r.name&&(e[r.name]=t)),r instanceof Ug.Constructed){let s=0,i={verified:!1,result:{error:"Unknown error"}},n=r.valueBlock.value.length;if(n>0&&r.valueBlock.value[0]instanceof vm&&(n=t.valueBlock.value.length),0===n)return{verified:!0,result:e};if(0===t.valueBlock.value.length&&0!==r.valueBlock.value.length){let t=!0;for(let e=0;e<r.valueBlock.value.length;e++)t=t&&(r.valueBlock.value[e].optional||!1);return t?{verified:!0,result:e}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,vg),r.name&&delete e[r.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(let o=0;o<n;o++)if(o-s>=t.valueBlock.value.length){if(!1===r.valueBlock.value[o].optional){const t={verified:!1,result:e};return e.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,vg),r.name&&(delete e[r.name],t.name=r.name)),t}}else if(r.valueBlock.value[0]instanceof vm){if(i=Sm(e,t.valueBlock.value[o],r.valueBlock.value[0].value),!1===i.verified){if(!r.valueBlock.value[0].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,vg),r.name&&delete e[r.name]),i;s++}if(ug in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let s={};s=Ig in r.valueBlock.value[0]&&r.valueBlock.value[0].local?t:e,void 0===s[r.valueBlock.value[0].name]&&(s[r.valueBlock.value[0].name]=[]),s[r.valueBlock.value[0].name].push(t.valueBlock.value[o])}}else if(i=Sm(e,t.valueBlock.value[o-s],r.valueBlock.value[o]),!1===i.verified){if(!r.valueBlock.value[o].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,vg),r.name&&delete e[r.name]),i;s++}if(!1===i.verified){const t={verified:!1,result:e};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,vg),r.name&&(delete e[r.name],t.name=r.name)),t}return{verified:!0,result:e}}if(r.primitiveSchema&&dg in t.valueBlock){const s=Iy(t.valueBlock.valueHexView);if(-1===s.offset){const t={verified:!1,result:s.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,vg),r.name&&(delete e[r.name],t.name=r.name)),t}return Sm(e,s.result,r.primitiveSchema)}return{verified:!0,result:e}}function Em(e,t){if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=Iy($p.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:Sm(r.result,r.result,t)}(by=yy||(yy={}))[by.Sequence=0]="Sequence",by[by.Set=1]="Set",by[by.Choice=2]="Choice",function(e){e[e.Any=1]="Any",e[e.Boolean=2]="Boolean",e[e.OctetString=3]="OctetString",e[e.BitString=4]="BitString",e[e.Integer=5]="Integer",e[e.Enumerated=6]="Enumerated",e[e.ObjectIdentifier=7]="ObjectIdentifier",e[e.Utf8String=8]="Utf8String",e[e.BmpString=9]="BmpString",e[e.UniversalString=10]="UniversalString",e[e.NumericString=11]="NumericString",e[e.PrintableString=12]="PrintableString",e[e.TeletexString=13]="TeletexString",e[e.VideotexString=14]="VideotexString",e[e.IA5String=15]="IA5String",e[e.GraphicString=16]="GraphicString",e[e.VisibleString=17]="VisibleString",e[e.GeneralString=18]="GeneralString",e[e.CharacterString=19]="CharacterString",e[e.UTCTime=20]="UTCTime",e[e.GeneralizedTime=21]="GeneralizedTime",e[e.DATE=22]="DATE",e[e.TimeOfDay=23]="TimeOfDay",e[e.DateTime=24]="DateTime",e[e.Duration=25]="Duration",e[e.TIME=26]="TIME",e[e.Null=27]="Null"}(my||(my={}));class Cm{constructor(e,t=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if("number"==typeof e)this.fromNumber(e);else{if(!$p.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=$p.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof Ty))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=e.valueBlock.valueHex,this}toASN(){return new Ty({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new Ty({name:e})}toNumber(){let e="";const t=new Uint8Array(this.value);for(const r of t)e+=r.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let t=e.toString(2);const r=t.length+7>>3;this.unusedBits=(r<<3)-t.length;const s=new Uint8Array(r);t=t.padStart(r<<3,"0").split("").reverse().join("");let i=0;for(;i<r;)s[i]=parseInt(t.slice(i<<3,8+(i<<3)),2),i++;this.value=s.buffer}}class km{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):$p.isBufferSource(e)?this.buffer=$p.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Oy))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new Oy({valueHex:this.buffer})}toSchema(e){return new Oy({name:e})}}const xm={fromASN:e=>e instanceof xy?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new xy;const t=vy(e);if(t.result.error)throw new Error(t.result.error);return t.result}},_m={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new Ly({value:+e})},Bm={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new Hy({value:e})},Rm={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Ly({valueHex:e})},Om={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Ty({valueHex:e})},Um={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Vy({value:e})},Tm={fromASN:e=>e.valueBlock.value,toASN:e=>new By({value:e})},Nm={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Oy({valueHex:e})},Dm={fromASN:e=>new km(e.getValue()),toASN:e=>e.toASN()};function Mm(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}const Pm=Mm(Xy),Lm=Mm(em),Hm=Mm(rm),Km=Mm(sm),Qm=Mm(im),Vm=Mm(nm),Fm=Mm(om),$m=Mm(am),jm=Mm(cm),Gm=Mm(lm),qm=Mm(hm),zm=Mm(um),Wm={fromASN:e=>e.toDate(),toASN:e=>new dm({valueDate:e})},Jm={fromASN:e=>e.toDate(),toASN:e=>new fm({valueDate:e})},Ym={fromASN:()=>null,toASN:()=>new xy};function Xm(e){switch(e){case my.Any:return xm;case my.BitString:return Om;case my.BmpString:return Lm;case my.Boolean:return Tm;case my.CharacterString:return zm;case my.Enumerated:return Bm;case my.GeneralString:return qm;case my.GeneralizedTime:return Jm;case my.GraphicString:return jm;case my.IA5String:return $m;case my.Integer:return _m;case my.Null:return Ym;case my.NumericString:return Km;case my.ObjectIdentifier:return Um;case my.OctetString:return Nm;case my.PrintableString:return Qm;case my.TeletexString:return Vm;case my.UTCTime:return Wm;case my.UniversalString:return Hm;case my.Utf8String:return Pm;case my.VideotexString:return Fm;case my.VisibleString:return Gm;default:return null}}function Zm(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||Zm(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function eb(e){var t;if(e){const r=Object.getPrototypeOf(e);return(null===(t=null==r?void 0:r.prototype)||void 0===t?void 0:t.constructor)===Array||eb(r)}return!1}function tb(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(r[t]!==s[t])return!1;return!0}const rb=new class{constructor(){this.items=new WeakMap}has(e){return this.items.has(e)}get(e,t=!1){const r=this.items.get(e);if(!r)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!r.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return r}cache(e){const t=this.get(e);t.schema||(t.schema=this.create(e,!0))}createDefault(e){const t={type:yy.Sequence,items:{}},r=this.findParentSchema(e);return r&&(Object.assign(t,r),t.items=Object.assign({},t.items,r.items)),t}create(e,t){const r=this.items.get(e)||this.createDefault(e),s=[];for(const e in r.items){const i=r.items[e],n=t?e:"";let o;if("number"==typeof i.type){const e=my[i.type],t=a[e];if(!t)throw new Error(`Cannot get ASN1 class by name '${e}'`);o=new t({name:n})}else Zm(i.type)?o=(new i.type).toSchema(n):i.optional?this.get(i.type).type===yy.Choice?o=new Am({name:n}):(o=this.create(i.type,!1),o.name=n):o=new Am({name:n});const c=!!i.optional||void 0!==i.defaultValue;if(i.repeated&&(o.name="",o=new("set"===i.repeated?qy:Gy)({name:"",value:[new vm({name:n,value:o})]})),null!==i.context&&void 0!==i.context)if(i.implicit)if("number"==typeof i.type||Zm(i.type)){const e=i.repeated?Ey:Ay;s.push(new e({name:n,optional:c,idBlock:{tagClass:3,tagNumber:i.context}}))}else{this.cache(i.type);const e=!!i.repeated;let t=e?o:this.get(i.type,!0).schema;t="valueBlock"in t?t.valueBlock.value:t.value,s.push(new Ey({name:e?"":n,optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}else s.push(new Ey({optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:[o]}));else o.optional=c,s.push(o)}switch(r.type){case yy.Sequence:return new Gy({value:s,name:""});case yy.Set:return new qy({value:s,name:""});case yy.Choice:return new Im({value:s,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){const t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}},sb=e=>t=>{let r;rb.has(t)?r=rb.get(t):(r=rb.createDefault(t),rb.set(t,r)),Object.assign(r,e)},ib=e=>(t,r)=>{let s;rb.has(t.constructor)?s=rb.get(t.constructor):(s=rb.createDefault(t.constructor),rb.set(t.constructor,s));const i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){const s=Xm(e.type);if(!s)throw new Error(`Cannot get default converter for property '${r}' of ${t.constructor.name}`);i.converter=s}s.items[r]=i};class nb extends Error{constructor(){super(...arguments),this.schemas=[]}}class ob{static parse(e,t){const r=vy(e);if(r.result.error)throw new Error(r.result.error);return this.fromASN(r.result,t)}static fromASN(e,t){var r;try{if(Zm(t))return(new t).fromASN(e);const s=rb.get(t);rb.cache(t);let i=s.schema;if(e.constructor===Ey&&s.type!==yy.Choice){i=new Ey({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:s.schema.valueBlock.value});for(const t in s.items)delete e[t]}const n=Sm({},e,i);if(!n.verified)throw new nb(`Data does not match to ${t.name} ASN1 schema. ${n.result.error}`);const o=new t;if(eb(t)){if(!("value"in e.valueBlock)||!Array.isArray(e.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const r=s.itemType;if("number"==typeof r){const s=Xm(r);if(!s)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);return t.from(e.valueBlock.value,e=>s.fromASN(e))}return t.from(e.valueBlock.value,e=>this.fromASN(e,r))}for(const e in s.items){const t=n.result[e];if(!t)continue;const i=s.items[e],c=i.type;if("number"==typeof c||Zm(c)){const s=null!==(r=i.converter)&&void 0!==r?r:Zm(c)?new c:null;if(!s)throw new Error("Converter is empty");if(i.repeated)if(i.implicit){const r=new("sequence"===i.repeated?Gy:qy);r.valueBlock=t.valueBlock;const n=vy(r.toBER(!1));if(-1===n.offset)throw new Error(`Cannot parse the child item. ${n.result.error}`);if(!("value"in n.result.valueBlock)||!Array.isArray(n.result.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const a=n.result.valueBlock.value;o[e]=Array.from(a,e=>s.fromASN(e))}else o[e]=Array.from(t,e=>s.fromASN(e));else{let r=t;if(i.implicit){let e;if(Zm(c))e=(new c).toSchema("");else{const t=my[c],r=a[t];if(!r)throw new Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=r.valueBlock,r=vy(e.toBER(!1)).result}o[e]=s.fromASN(r)}}else if(i.repeated){if(!Array.isArray(t))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");o[e]=Array.from(t,e=>this.fromASN(e,c))}else o[e]=this.fromASN(t,c)}return o}catch(e){throw e instanceof nb&&e.schemas.push(t.name),e}}}class ab{static serialize(e){return e instanceof Tg?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&"object"==typeof e&&Zm(e))return e.toASN();if(!e||"object"!=typeof e)throw new TypeError("Parameter 1 should be type of Object.");const t=e.constructor,r=rb.get(t);rb.cache(t);let s,i=[];if(r.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if("number"==typeof r.itemType){const s=Xm(r.itemType);if(!s)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);i=e.map(e=>s.toASN(e))}else i=e.map(e=>this.toAsnItem({type:r.itemType},"[]",t,e))}else for(const s in r.items){const n=r.items[s],o=e[s];if(void 0===o||n.defaultValue===o||"object"==typeof n.defaultValue&&"object"==typeof o&&tb(this.serialize(n.defaultValue),this.serialize(o)))continue;const a=ab.toAsnItem(n,s,t,o);if("number"==typeof n.context)if(n.implicit)if(n.repeated||"number"!=typeof n.type&&!Zm(n.type))i.push(new Ey({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:a.valueBlock.value}));else{const e={};e.valueHex=a instanceof xy?a.valueBeforeDecodeView:a.valueBlock.toBER(),i.push(new Ay({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},...e}))}else i.push(new Ey({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:[a]}));else n.repeated?i=i.concat(a):i.push(a)}switch(r.type){case yy.Sequence:s=new Gy({value:i});break;case yy.Set:s=new qy({value:i});break;case yy.Choice:if(!i[0])throw new Error(`Schema '${t.name}' has wrong data. Choice cannot be empty.`);s=i[0]}return s}static toAsnItem(e,t,r,s){let i;if("number"==typeof e.type){const n=e.converter;if(!n)throw new Error(`Property '${t}' doesn't have converter for type ${my[e.type]} in schema '${r.name}'`);if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");const t=Array.from(s,e=>n.toASN(e));i=new("sequence"===e.repeated?Gy:qy)({value:t})}else i=n.toASN(s)}else if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");const t=Array.from(s,e=>this.toASN(e));i=new("sequence"===e.repeated?Gy:qy)({value:t})}else i=this.toASN(s);return i}}class cb extends Array{constructor(e=[]){if("number"==typeof e)super(e);else{super();for(const t of e)this.push(t)}}}class lb{static serialize(e){return ab.serialize(e)}static parse(e,t){return ob.parse(e,t)}static toString(e){const t=vy($p.isBufferSource(e)?$p.toArrayBuffer(e):lb.serialize(e));if(-1===t.offset)throw new Error(`Cannot decode ASN.1 data. ${t.result.error}`);return t.result.toString()}}function hb(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;class ub extends Error{constructor(e,t){super(t?`${e}. See the inner exception for more details.`:e),this.message=e,this.innerError=t}}class db extends ub{constructor(e,t,r){super(t,r),this.schema=e}}class fb extends db{constructor(e,t,r){super(e,`JSON doesn't match to '${e.target.name}' schema. ${t}`,r)}}class pb extends ub{}class gb extends ub{constructor(e,t,r){super(`Cannot serialize by '${e}' schema. ${t}`,r),this.schemaName=e}}class yb extends fb{constructor(e,t,r={}){super(e,"Some keys doesn't match to schema"),this.keys=t,this.errors=r}}var mb;function bb(e,t){if(!function(e,t){switch(t){case mb.Boolean:return"boolean"==typeof e;case mb.Number:return"number"==typeof e;case mb.String:return"string"==typeof e}return!0}(e,t))throw new TypeError(`Value must be ${mb[t]}`)}function Ab(e){return e&&e.prototype?!(!e.prototype.toJSON||!e.prototype.fromJSON)||Ab(e.prototype):!!(e&&e.toJSON&&e.fromJSON)}!function(e){e[e.Any=0]="Any",e[e.Boolean=1]="Boolean",e[e.Number=2]="Number",e[e.String=3]="String"}(mb||(mb={}));const Ib="default",vb=new class{constructor(){this.items=new Map}has(e){return this.items.has(e)||!!this.findParentSchema(e)}get(e){const t=this.items.get(e)||this.findParentSchema(e);if(!t)throw new Error("Cannot get schema for current target");return t}create(e){const t={names:{}},r=this.findParentSchema(e);if(r){Object.assign(t,r),t.names={};for(const e in r.names)t.names[e]=Object.assign({},r.names[e])}return t.target=e,t}set(e,t){return this.items.set(e,t),this}findParentSchema(e){const t=e.__proto__;return t?this.items.get(t)||this.findParentSchema(t):null}};class wb{constructor(e){this.pattern=new RegExp(e)}validate(e){const t=new RegExp(this.pattern.source,this.pattern.flags);if("string"!=typeof e)throw new pb("Incoming value must be string");if(!t.exec(e))throw new pb(`Value doesn't match to pattern '${t.toString()}'`)}}class Sb{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(bb(e,mb.Number),!(this.min<=e&&e<=this.max)){const e=this.min===Number.MIN_VALUE?"MIN":this.min,t=this.max===Number.MAX_VALUE?"MAX":this.max;throw new pb(`Value doesn't match to diapason [${e},${t}]`)}}}class Eb{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(bb(e,mb.Number),!(this.min<e&&e<this.max)){const e=this.min===Number.MIN_VALUE?"MIN":this.min,t=this.max===Number.MAX_VALUE?"MAX":this.max;throw new pb(`Value doesn't match to diapason (${e},${t})`)}}}class Cb{constructor(e,t,r){this.length=e,this.minLength=t,this.maxLength=r}validate(e){if(void 0===this.length){if(void 0!==this.minLength&&e.length<this.minLength)throw new pb(`Value length must be more than ${this.minLength}.`);if(void 0!==this.maxLength&&e.length>this.maxLength)throw new pb(`Value length must be less than ${this.maxLength}.`)}else if(e.length!==this.length)throw new pb(`Value length must be exactly ${this.length}.`)}}class kb{constructor(e){this.enumeration=e}validate(e){if(bb(e,mb.String),!this.enumeration.includes(e))throw new pb(`Value must be one of ${this.enumeration.map(e=>`'${e}'`).join(", ")}`)}}class xb{static checkValues(e,t){const r=Array.isArray(e)?e:[e];for(const s of r)for(const r of t.validations)r instanceof Cb&&t.repeated?r.validate(e):r.validate(s)}static checkTypes(e,t){if(t.repeated&&!Array.isArray(e))throw new TypeError("Value must be Array");if("number"==typeof t.type){const r=Array.isArray(e)?e:[e];for(const e of r)bb(e,t.type)}}static getSchemaByName(e,t=Ib){return{...e.names[Ib],...e.names[t]}}}class _b extends xb{static serialize(e,t,r,s){const i=this.toJSON(e,t);return JSON.stringify(i,r,s)}static toJSON(e,t={}){let r,s=t.targetSchema;const i=t.schemaName||Ib;if(Ab(e))return e.toJSON();if(Array.isArray(e)){r=[];for(const s of e)r.push(this.toJSON(s,t))}else if("object"==typeof e){if(s&&!vb.has(s))throw new ub("Cannot get schema for `targetSchema` param");if(s=s||e.constructor,vb.has(s)){const t=vb.get(s);r={};const n=this.getSchemaByName(t,i);for(const o in n)try{const t=n[o],a=e[o];let c;if(t.optional&&void 0===a||void 0!==t.defaultValue&&a===t.defaultValue)continue;if(!t.optional&&void 0===a)throw new gb(s.name,`Property '${o}' is required.`);c="number"==typeof t.type?t.converter?t.repeated?a.map(r=>t.converter.toJSON(r,e)):t.converter.toJSON(a,e):a:t.repeated?a.map(e=>this.toJSON(e,{schemaName:i})):this.toJSON(a,{schemaName:i}),this.checkTypes(c,t),this.checkValues(c,t),r[t.name||o]=c}catch(e){throw e instanceof gb?e:new gb(t.target.name,`Property '${o}' is wrong. ${e.message}`,e)}}else{r={};for(const t in e)r[t]=this.toJSON(e[t],{schemaName:i})}}else r=e;return r}}class Bb extends xb{static parse(e,t){const r=JSON.parse(e);return this.fromJSON(r,t)}static fromJSON(e,t){const r=t.targetSchema,s=t.schemaName||Ib,i=new r;if(Ab(i))return i.fromJSON(e);const n=vb.get(r),o=this.getSchemaByName(n,s),a={};t.strictProperty&&!Array.isArray(e)&&Bb.checkStrictProperty(e,o,n);for(const r in o)try{const a=o[r],c=a.name||r,l=e[c];if(void 0===l&&(a.optional||void 0!==a.defaultValue))continue;if(!a.optional&&void 0===l)throw new fb(n,`Property '${c}' is required.`);if(this.checkTypes(l,a),this.checkValues(l,a),"number"==typeof a.type)a.converter?a.repeated?i[r]=l.map(e=>a.converter.fromJSON(e,i)):i[r]=a.converter.fromJSON(l,i):i[r]=l;else{const e={...t,targetSchema:a.type,schemaName:s};a.repeated?i[r]=l.map(t=>this.fromJSON(t,e)):i[r]=this.fromJSON(l,e)}}catch(e){if(e instanceof fb||(e=new fb(n,`Property '${r}' is wrong. ${e.message}`,e)),!t.strictAllKeys)throw e;a[r]=e}const c=Object.keys(a);if(c.length)throw new yb(n,c,a);return i}static checkStrictProperty(e,t,r){const s=Object.keys(e),i=Object.keys(t),n=[];for(const e of s)-1===i.indexOf(e)&&n.push(e);if(n.length)throw new yb(r,n)}}const Rb=(e={})=>(t,r)=>{const s=`Cannot set type for ${r} property of ${t.constructor.name} schema`;let i;vb.has(t.constructor)?(i=vb.get(t.constructor),i.target!==t.constructor&&(i=vb.create(t.constructor),vb.set(t.constructor,i))):(i=vb.create(t.constructor),vb.set(t.constructor,i));const n={type:mb.Any,validations:[]},o=Object.assign(n,e);if(o.validations=function(e){const t=[];return e.pattern&&t.push(new wb(e.pattern)),e.type!==mb.Number&&e.type!==mb.Any||(void 0===e.minInclusive&&void 0===e.maxInclusive||t.push(new Sb(e.minInclusive,e.maxInclusive)),void 0===e.minExclusive&&void 0===e.maxExclusive||t.push(new Eb(e.minExclusive,e.maxExclusive)),void 0!==e.enumeration&&t.push(new kb(e.enumeration))),(e.type===mb.String||e.repeated||e.type===mb.Any)&&(void 0===e.length&&void 0===e.minLength&&void 0===e.maxLength||t.push(new Cb(e.length,e.minLength,e.maxLength))),t}(o),"number"!=typeof o.type&&!vb.has(o.type)&&!Ab(o.type))throw new Error(`${s}. Assigning type doesn't have schema.`);let a;a=Array.isArray(e.schema)?e.schema:[e.schema||Ib];for(const e of a)i.names[e]||(i.names[e]={}),i.names[e][r]=o};class Ob extends Error{}class Ub extends Ob{}class Tb extends Ob{constructor(e){super("Unsupported operation: "+(e?`${e}`:""))}}class Nb extends Ob{}class Db extends Ob{constructor(e){super(`${e}: Missing required property`)}}class Mb{static toArrayBuffer(e){const t=e.replace(/-{5}(BEGIN|END) .*-{5}/g,"").replace("\r","").replace("\n","");return Yp.FromBase64(t)}static toUint8Array(e){const t=this.toArrayBuffer(e);return new Uint8Array(t)}static fromBufferSource(e,t){const r=Yp.ToBase64(e);let s,i=0;const n=[];for(;i<r.length&&(s=r.slice(i,i+64),s.length);)n.push(s),i+=64;const o=t.toUpperCase();return`-----BEGIN ${o}-----\n${n.join("\n")}\n-----END ${o}-----`}static isPEM(e){return/-----BEGIN .+-----[A-Za-z0-9+/+=\s\n]+-----END .+-----/i.test(e)}static getTagName(e){if(!this.isPEM(e))throw new Error("Bad parameter. Incoming data is not right PEM");const t=/-----BEGIN (.+)-----/.exec(e);if(!t)throw new Error("Cannot get tag from PEM");return t[1]}static hasTagName(e,t){const r=this.getTagName(e);return t.toLowerCase()===r.toLowerCase()}static isCertificate(e){return this.hasTagName(e,"certificate")}static isCertificateRequest(e){return this.hasTagName(e,"certificate request")}static isCRL(e){return this.hasTagName(e,"x509 crl")}static isPublicKey(e){return this.hasTagName(e,"public key")}}class Pb{async digest(...e){return this.checkDigest.apply(this,e),this.onDigest.apply(this,e)}checkDigest(e,t){this.checkAlgorithmName(e)}async onDigest(e,t){throw new Tb("digest")}async generateKey(...e){return this.checkGenerateKey.apply(this,e),this.onGenerateKey.apply(this,e)}checkGenerateKey(e,t,r,...s){if(this.checkAlgorithmName(e),this.checkGenerateKeyParams(e),!r||!r.length)throw new TypeError("Usages cannot be empty when creating a key.");let i;i=Array.isArray(this.usages)?this.usages:this.usages.privateKey.concat(this.usages.publicKey),this.checkKeyUsages(r,i)}checkGenerateKeyParams(e){}async onGenerateKey(e,t,r,...s){throw new Tb("generateKey")}async sign(...e){return this.checkSign.apply(this,e),this.onSign.apply(this,e)}checkSign(e,t,r,...s){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,"sign")}async onSign(e,t,r,...s){throw new Tb("sign")}async verify(...e){return this.checkVerify.apply(this,e),this.onVerify.apply(this,e)}checkVerify(e,t,r,s,...i){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,"verify")}async onVerify(e,t,r,s,...i){throw new Tb("verify")}async encrypt(...e){return this.checkEncrypt.apply(this,e),this.onEncrypt.apply(this,e)}checkEncrypt(e,t,r,s={},...i){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,s.keyUsage?"encrypt":void 0)}async onEncrypt(e,t,r,...s){throw new Tb("encrypt")}async decrypt(...e){return this.checkDecrypt.apply(this,e),this.onDecrypt.apply(this,e)}checkDecrypt(e,t,r,s={},...i){this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,s.keyUsage?"decrypt":void 0)}async onDecrypt(e,t,r,...s){throw new Tb("decrypt")}async deriveBits(...e){return this.checkDeriveBits.apply(this,e),this.onDeriveBits.apply(this,e)}checkDeriveBits(e,t,r,s={},...i){if(this.checkAlgorithmName(e),this.checkAlgorithmParams(e),this.checkCryptoKey(t,s.keyUsage?"deriveBits":void 0),r%8!=0)throw new Nb("length: Is not multiple of 8")}async onDeriveBits(e,t,r,...s){throw new Tb("deriveBits")}async exportKey(...e){return this.checkExportKey.apply(this,e),this.onExportKey.apply(this,e)}checkExportKey(e,t,...r){if(this.checkKeyFormat(e),this.checkCryptoKey(t),!t.extractable)throw new Ob("key: Is not extractable")}async onExportKey(e,t,...r){throw new Tb("exportKey")}async importKey(...e){return this.checkImportKey.apply(this,e),this.onImportKey.apply(this,e)}checkImportKey(e,t,r,s,i,...n){this.checkKeyFormat(e),this.checkKeyData(e,t),this.checkAlgorithmName(r),this.checkImportParams(r),Array.isArray(this.usages)&&this.checkKeyUsages(i,this.usages)}async onImportKey(e,t,r,s,i,...n){throw new Tb("importKey")}checkAlgorithmName(e){if(e.name.toLowerCase()!==this.name.toLowerCase())throw new Ub("Unrecognized name")}checkAlgorithmParams(e){}checkDerivedKeyParams(e){}checkKeyUsages(e,t){for(const r of e)if(-1===t.indexOf(r))throw new TypeError("Cannot create a key using the specified key usages")}checkCryptoKey(e,t){if(this.checkAlgorithmName(e.algorithm),t&&-1===e.usages.indexOf(t))throw new Ob("key does not match that of operation")}checkRequiredProperty(e,t){if(!(t in e))throw new Db(t)}checkHashAlgorithm(e,t){for(const r of t)if(r.toLowerCase()===e.name.toLowerCase())return;throw new Nb(`hash: Must be one of ${t.join(", ")}`)}checkImportParams(e){}checkKeyFormat(e){switch(e){case"raw":case"pkcs8":case"spki":case"jwk":break;default:throw new TypeError("format: Is invalid value. Must be 'jwk', 'raw', 'spki', or 'pkcs8'")}}checkKeyData(e,t){if(!t)throw new TypeError("keyData: Cannot be empty on empty on key importing");if("jwk"===e){if("object"!=typeof(r=t)||!("kty"in r))throw new TypeError("keyData: Is not JsonWebToken")}else if(!$p.isBufferSource(t))throw new TypeError("keyData: Is not ArrayBufferView or ArrayBuffer");var r}prepareData(e){return $p.toArrayBuffer(e)}}class Lb extends Pb{checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not of type Number");switch(e.length){case 128:case 192:case 256:break;default:throw new TypeError("length: Must be 128, 192, or 256")}}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class Hb extends Lb{constructor(){super(...arguments),this.name="AES-CBC",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"iv"),!(e.iv instanceof ArrayBuffer||ArrayBuffer.isView(e.iv)))throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(16!==e.iv.byteLength)throw new TypeError("iv: Must have length 16 bytes")}}class Kb extends Lb{constructor(){super(...arguments),this.name="AES-CMAC",this.usages=["sign","verify"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not a Number");if(e.length<1)throw new Nb("length: Must be more than 0")}}class Qb extends Lb{constructor(){super(...arguments),this.name="AES-CTR",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"counter"),!(e.counter instanceof ArrayBuffer||ArrayBuffer.isView(e.counter)))throw new TypeError("counter: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(16!==e.counter.byteLength)throw new TypeError("iv: Must have length 16 bytes");if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not a Number");if(e.length<1)throw new Nb("length: Must be more than 0")}}class Vb extends Lb{constructor(){super(...arguments),this.name="AES-ECB",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}}class Fb extends Lb{constructor(){super(...arguments),this.name="AES-GCM",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){var t;if(this.checkRequiredProperty(e,"iv"),!(e.iv instanceof ArrayBuffer||ArrayBuffer.isView(e.iv)))throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(e.iv.byteLength<1)throw new Nb("iv: Must have length more than 0 and less than 2^64 - 1");switch(null!==(t=e.tagLength)&&void 0!==t||(e.tagLength=128),e.tagLength){case 32:case 64:case 96:case 104:case 112:case 120:case 128:break;default:throw new Nb("tagLength: Must be one of 32, 64, 96, 104, 112, 120 or 128")}}}class $b extends Lb{constructor(){super(...arguments),this.name="AES-KW",this.usages=["wrapKey","unwrapKey"]}}class jb extends Pb{constructor(){super(...arguments),this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}checkAlgorithmParams(e){if(this.ivSize){if(this.checkRequiredProperty(e,"iv"),!(e.iv instanceof ArrayBuffer||ArrayBuffer.isView(e.iv)))throw new TypeError("iv: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(e.iv.byteLength!==this.ivSize)throw new TypeError(`iv: Must have length ${this.ivSize} bytes`)}}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"length"),"number"!=typeof e.length)throw new TypeError("length: Is not of type Number");if(e.length!==this.keySizeBits)throw new Nb(`algorithm.length: Must be ${this.keySizeBits}`)}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class Gb extends Pb{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"]}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),this.checkRequiredProperty(e,"publicExponent"),!(e.publicExponent&&e.publicExponent instanceof Uint8Array))throw new TypeError("publicExponent: Missing or not a Uint8Array");const t=Yp.ToBase64(e.publicExponent);if("Aw=="!==t&&"AQAB"!==t)throw new TypeError("publicExponent: Must be [3] or [1,0,1]");if(this.checkRequiredProperty(e,"modulusLength"),e.modulusLength%8||e.modulusLength<256||e.modulusLength>16384)throw new TypeError("The modulus length must be a multiple of 8 bits and >= 256 and <= 16384")}checkImportParams(e){this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms)}}class qb extends Gb{constructor(){super(...arguments),this.name="RSASSA-PKCS1-v1_5",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class zb extends Gb{constructor(){super(...arguments),this.name="RSA-PSS",this.usages={privateKey:["sign"],publicKey:["verify"]}}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"saltLength"),"number"!=typeof e.saltLength)throw new TypeError("saltLength: Is not a Number");if(e.saltLength<0)throw new RangeError("saltLength: Must be positive number")}}class Wb extends Gb{constructor(){super(...arguments),this.name="RSA-OAEP",this.usages={privateKey:["decrypt","unwrapKey"],publicKey:["encrypt","wrapKey"]}}checkAlgorithmParams(e){if(e.label&&!(e.label instanceof ArrayBuffer||ArrayBuffer.isView(e.label)))throw new TypeError("label: Is not of type '(ArrayBuffer or ArrayBufferView)'")}}class Jb extends Pb{checkGenerateKeyParams(e){this.checkRequiredProperty(e,"namedCurve"),this.checkNamedCurve(e.namedCurve)}checkNamedCurve(e){for(const t of this.namedCurves)if(t.toLowerCase()===e.toLowerCase())return;throw new Nb(`namedCurve: Must be one of ${this.namedCurves.join(", ")}`)}}class Yb extends Jb{constructor(){super(...arguments),this.name="ECDSA",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["P-256","P-384","P-521","K-256"]}checkAlgorithmParams(e){this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms)}}const Xb=["secret","private","public"];class Zb{static create(e,t,r,s){const i=new this;return i.algorithm=e,i.type=t,i.extractable=r,i.usages=s,i}static isKeyType(e){return-1!==Xb.indexOf(e)}get[Symbol.toStringTag](){return"CryptoKey"}}class eA extends Jb{constructor(){super(...arguments),this.name="ECDH",this.usages={privateKey:["deriveBits","deriveKey"],publicKey:[]},this.namedCurves=["P-256","P-384","P-521","K-256"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"public"),!(e.public instanceof Zb))throw new TypeError("public: Is not a CryptoKey");if("public"!==e.public.type)throw new Nb("public: Is not a public key");if(e.public.algorithm.name!==this.name)throw new Nb(`public: Is not ${this.name} key`)}}class tA extends eA{constructor(){super(...arguments),this.name="ECDH-ES",this.namedCurves=["X25519","X448"]}}class rA extends Jb{constructor(){super(...arguments),this.name="EdDSA",this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["Ed25519","Ed448"]}}let sA=class{constructor(e){e&&(this.value=e)}};hb([ib({type:my.ObjectIdentifier})],sA.prototype,"value",void 0),sA=hb([sb({type:yy.Choice})],sA);class iA{constructor(e){Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],iA.prototype,"algorithm",void 0),hb([ib({type:my.Any,optional:!0})],iA.prototype,"parameters",void 0);class nA{constructor(){this.version=0,this.privateKeyAlgorithm=new iA,this.privateKey=new ArrayBuffer(0)}}hb([ib({type:my.Integer})],nA.prototype,"version",void 0),hb([ib({type:iA})],nA.prototype,"privateKeyAlgorithm",void 0),hb([ib({type:my.OctetString})],nA.prototype,"privateKey",void 0),hb([ib({type:my.Any,optional:!0})],nA.prototype,"attributes",void 0);class oA{constructor(){this.publicKeyAlgorithm=new iA,this.publicKey=new ArrayBuffer(0)}}hb([ib({type:iA})],oA.prototype,"publicKeyAlgorithm",void 0),hb([ib({type:my.BitString})],oA.prototype,"publicKey",void 0);const aA={fromJSON:e=>Yp.FromBase64Url(e),toJSON:e=>Yp.ToBase64Url(new Uint8Array(e))},cA={fromASN:e=>{const t=e.valueBlock.valueHex;return new Uint8Array(t)[0]?e.valueBlock.valueHex:e.valueBlock.valueHex.slice(1)},toASN:e=>{const t=new Uint8Array(e)[0]>127?Xp(new Uint8Array([0]).buffer,e):e;return new Ly({valueHex:t})}};class lA{constructor(){this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0)}}hb([ib({type:my.Integer,converter:_m})],lA.prototype,"version",void 0),hb([ib({type:my.Integer,converter:cA}),Rb({name:"n",converter:aA})],lA.prototype,"modulus",void 0),hb([ib({type:my.Integer,converter:cA}),Rb({name:"e",converter:aA})],lA.prototype,"publicExponent",void 0),hb([ib({type:my.Integer,converter:cA}),Rb({name:"d",converter:aA})],lA.prototype,"privateExponent",void 0),hb([ib({type:my.Integer,converter:cA}),Rb({name:"p",converter:aA})],lA.prototype,"prime1",void 0),hb([ib({type:my.Integer,converter:cA}),Rb({name:"q",converter:aA})],lA.prototype,"prime2",void 0),hb([ib({type:my.Integer,converter:cA}),Rb({name:"dp",converter:aA})],lA.prototype,"exponent1",void 0),hb([ib({type:my.Integer,converter:cA}),Rb({name:"dq",converter:aA})],lA.prototype,"exponent2",void 0),hb([ib({type:my.Integer,converter:cA}),Rb({name:"qi",converter:aA})],lA.prototype,"coefficient",void 0),hb([ib({type:my.Any,optional:!0})],lA.prototype,"otherPrimeInfos",void 0);class hA{constructor(){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0)}}hb([ib({type:my.Integer,converter:cA}),Rb({name:"n",converter:aA})],hA.prototype,"modulus",void 0),hb([ib({type:my.Integer,converter:cA}),Rb({name:"e",converter:aA})],hA.prototype,"publicExponent",void 0);let uA=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){let e=new Uint8Array(this.value);if(4!==e[0])throw new Ob("Wrong ECPoint. Current version supports only Uncompressed (0x04) point");e=new Uint8Array(this.value.slice(1));const t=e.length/2;return{x:Yp.ToBase64Url(e.buffer.slice(0,0+t)),y:Yp.ToBase64Url(e.buffer.slice(0+t,0+t+t))}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");if(!("y"in e))throw new Error("y: Missing required property");const t=Yp.FromBase64Url(e.x),r=Yp.FromBase64Url(e.y),s=Xp(new Uint8Array([4]).buffer,t,r);return this.value=new Uint8Array(s).buffer,this}};hb([ib({type:my.OctetString})],uA.prototype,"value",void 0),uA=hb([sb({type:yy.Choice})],uA);class dA{constructor(){this.version=1,this.privateKey=new ArrayBuffer(0)}fromJSON(e){if(!("d"in e))throw new Error("d: Missing required property");if(this.privateKey=Yp.FromBase64Url(e.d),"x"in e){const t=new uA;t.fromJSON(e);const r=ab.toASN(t);"valueHex"in r.valueBlock&&(this.publicKey=r.valueBlock.valueHex)}return this}toJSON(){const e={};return e.d=Yp.ToBase64Url(this.privateKey),this.publicKey&&Object.assign(e,new uA(this.publicKey).toJSON()),e}}hb([ib({type:my.Integer,converter:_m})],dA.prototype,"version",void 0),hb([ib({type:my.OctetString})],dA.prototype,"privateKey",void 0),hb([ib({context:0,type:my.Any,optional:!0})],dA.prototype,"parameters",void 0),hb([ib({context:1,type:my.BitString,optional:!0})],dA.prototype,"publicKey",void 0);const fA={fromASN:e=>{const t=new Uint8Array(e.valueBlock.valueHex);return 0===t[0]?t.buffer.slice(1):t.buffer},toASN:e=>{const t=new Uint8Array(e);if(t[0]>127){const e=new Uint8Array(t.length+1);return e.set(t,1),new Ly({valueHex:e.buffer})}return new Ly({valueHex:e})}};var pA=Object.freeze({__proto__:null,AsnIntegerWithoutPaddingConverter:fA});class gA{static decodePoint(e,t){const r=$p.toUint8Array(e);if(0===r.length||4!==r[0])throw new Error("Only uncompressed point format supported");const s=(r.length-1)/2;if(s!==Math.ceil(t/8))throw new Error("Point does not match field size");return{x:r.slice(1,s+1),y:r.slice(s+1,s+1+s)}}static encodePoint(e,t){const r=Math.ceil(t/8);if(e.x.byteLength!==r||e.y.byteLength!==r)throw new Error("X,Y coordinates don't match point size criteria");const s=$p.toUint8Array(e.x),i=$p.toUint8Array(e.y),n=new Uint8Array(2*r+1);return n[0]=4,n.set(s,1),n.set(i,r+1),n}static getSize(e){return Math.ceil(e/8)}static encodeSignature(e,t){const r=this.getSize(t),s=$p.toUint8Array(e.r),i=$p.toUint8Array(e.s),n=new Uint8Array(2*r);return n.set(this.padStart(s,r)),n.set(this.padStart(i,r),r),n}static decodeSignature(e,t){const r=this.getSize(t),s=$p.toUint8Array(e);if(s.length!==2*r)throw new Error("Incorrect size of the signature");const i=s.slice(0,r),n=s.slice(r);return{r:this.trimStart(i),s:this.trimStart(n)}}static trimStart(e){let t=0;for(;t<e.length-1&&0===e[t];)t++;return 0===t?e:e.slice(t,e.length)}static padStart(e,t){if(t===e.length)return e;const r=new Uint8Array(t);return r.set(e,t-e.length),r}}class yA{constructor(){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0)}static fromWebCryptoSignature(e){const t=e.byteLength/2,r=gA.decodeSignature(e,8*t),s=new yA;return s.r=$p.toArrayBuffer(r.r),s.s=$p.toArrayBuffer(r.s),s}toWebCryptoSignature(e){if(!e){const t=Math.max(this.r.byteLength,this.s.byteLength);e=t<=32?256:t<=48?384:521}return gA.encodeSignature(this,e).buffer}}hb([ib({type:my.Integer,converter:fA})],yA.prototype,"r",void 0),hb([ib({type:my.Integer,converter:fA})],yA.prototype,"s",void 0);class mA extends nA{}hb([ib({context:1,implicit:!0,type:my.BitString,optional:!0})],mA.prototype,"publicKey",void 0);let bA=class{constructor(){this.value=new ArrayBuffer(0)}fromJSON(e){if(!e.d)throw new Error("d: Missing required property");return this.value=Yp.FromBase64Url(e.d),this}toJSON(){return{d:Yp.ToBase64Url(this.value)}}};hb([ib({type:my.OctetString})],bA.prototype,"value",void 0),bA=hb([sb({type:yy.Choice})],bA);let AA=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){return{x:Yp.ToBase64Url(this.value)}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");return this.value=Yp.FromBase64Url(e.x),this}};hb([ib({type:my.BitString})],AA.prototype,"value",void 0),AA=hb([sb({type:yy.Choice})],AA);let IA=class{};hb([ib({type:my.OctetString}),Rb({type:mb.String,converter:aA})],IA.prototype,"d",void 0),IA=hb([sb({type:yy.Choice})],IA);const vA="1.2.840.10045.3.1.7",wA="1.3.132.0",SA=`${wA}.34`,EA=`${wA}.35`,CA=`${wA}.10`,kA="1.3.36.3.3.2.8.1.1",xA=`${kA}.1`,_A=`${kA}.2`,BA=`${kA}.3`,RA=`${kA}.4`,OA=`${kA}.5`,UA=`${kA}.6`,TA=`${kA}.7`,NA=`${kA}.8`,DA=`${kA}.9`,MA=`${kA}.10`,PA=`${kA}.11`,LA=`${kA}.12`,HA=`${kA}.13`,KA=`${kA}.14`;var QA=Object.freeze({__proto__:null,AlgorithmIdentifier:iA,get CurvePrivateKey(){return IA},EcDsaSignature:yA,EcPrivateKey:dA,get EcPublicKey(){return uA},get EdPrivateKey(){return bA},get EdPublicKey(){return AA},get ObjectIdentifier(){return sA},OneAsymmetricKey:mA,PrivateKeyInfo:nA,PublicKeyInfo:oA,RsaPrivateKey:lA,RsaPublicKey:hA,converters:pA,idBrainpoolP160r1:xA,idBrainpoolP160t1:_A,idBrainpoolP192r1:BA,idBrainpoolP192t1:RA,idBrainpoolP224r1:OA,idBrainpoolP224t1:UA,idBrainpoolP256r1:TA,idBrainpoolP256t1:NA,idBrainpoolP320r1:DA,idBrainpoolP320t1:MA,idBrainpoolP384r1:PA,idBrainpoolP384t1:LA,idBrainpoolP512r1:HA,idBrainpoolP512t1:KA,idEd25519:"1.3.101.112",idEd448:"1.3.101.113",idEllipticCurve:wA,idSecp256k1:CA,idSecp256r1:vA,idSecp384r1:SA,idSecp521r1:EA,idVersionOne:kA,idX25519:"1.3.101.110",idX448:"1.3.101.111"});class VA{constructor(){}static register(e){const t=new sA;t.value=e.id;const r=lb.serialize(t);this.items.push({...e,raw:r}),this.names.push(e.name)}static find(e){e=e.toUpperCase();for(const t of this.items)if(t.name.toUpperCase()===e||t.id.toUpperCase()===e)return t;return null}static get(e){const t=this.find(e);if(!t)throw new Error(`Unsupported EC named curve '${e}'`);return t}}VA.items=[],VA.names=[],VA.register({name:"P-256",id:vA,size:256}),VA.register({name:"P-384",id:SA,size:384}),VA.register({name:"P-521",id:EA,size:521}),VA.register({name:"K-256",id:CA,size:256}),VA.register({name:"brainpoolP160r1",id:xA,size:160}),VA.register({name:"brainpoolP160t1",id:_A,size:160}),VA.register({name:"brainpoolP192r1",id:BA,size:192}),VA.register({name:"brainpoolP192t1",id:RA,size:192}),VA.register({name:"brainpoolP224r1",id:OA,size:224}),VA.register({name:"brainpoolP224t1",id:UA,size:224}),VA.register({name:"brainpoolP256r1",id:TA,size:256}),VA.register({name:"brainpoolP256t1",id:NA,size:256}),VA.register({name:"brainpoolP320r1",id:DA,size:320}),VA.register({name:"brainpoolP320t1",id:MA,size:320}),VA.register({name:"brainpoolP384r1",id:PA,size:384}),VA.register({name:"brainpoolP384t1",id:LA,size:384}),VA.register({name:"brainpoolP512r1",id:HA,size:512}),VA.register({name:"brainpoolP512t1",id:KA,size:512});class FA extends Pb{constructor(){super(...arguments),this.name="X25519",this.usages={privateKey:["deriveKey","deriveBits"],publicKey:[]}}checkAlgorithmParams(e){this.checkRequiredProperty(e,"public")}}class $A extends Pb{constructor(){super(...arguments),this.name="Ed25519",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class jA extends Pb{constructor(){super(...arguments),this.name="HMAC",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages=["sign","verify"]}getDefaultLength(e){switch(e.toUpperCase()){case"SHA-1":case"SHA-256":case"SHA-384":case"SHA-512":return 512;default:throw new Error(`Unknown algorithm name '${e}'`)}}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),"length"in e){if("number"!=typeof e.length)throw new TypeError("length: Is not a Number");if(e.length<1)throw new RangeError("length: Number is out of range")}}checkImportParams(e){this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms)}}class GA extends Pb{constructor(){super(...arguments),this.name="PBKDF2",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages=["deriveBits","deriveKey"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),this.checkRequiredProperty(e,"salt"),!(e.salt instanceof ArrayBuffer||ArrayBuffer.isView(e.salt)))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"iterations"),"number"!=typeof e.iterations)throw new TypeError("iterations: Is not a Number");if(e.iterations<1)throw new TypeError("iterations: Is less than 1")}checkImportKey(e,t,r,s,i,...n){if(super.checkImportKey(e,t,r,s,i,...n),s)throw new SyntaxError("extractable: Must be 'false'")}}class qA extends Pb{constructor(){super(...arguments),this.name="HKDF",this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512"],this.usages=["deriveKey","deriveBits"]}checkAlgorithmParams(e){if(this.checkRequiredProperty(e,"hash"),this.checkHashAlgorithm(e.hash,this.hashAlgorithms),this.checkRequiredProperty(e,"salt"),!$p.isBufferSource(e.salt))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"info"),!$p.isBufferSource(e.info))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'")}checkImportKey(e,t,r,s,i,...n){if(super.checkImportKey(e,t,r,s,i,...n),s)throw new SyntaxError("extractable: Must be 'false'")}}class zA extends Pb{constructor(){super(...arguments),this.usages=[],this.defaultLength=0}digest(...e){return e[0]={length:this.defaultLength,...e[0]},super.digest.apply(this,e)}checkDigest(e,t){super.checkDigest(e,t);const r=e.length||0;if("number"!=typeof r)throw new TypeError("length: Is not a Number");if(r<0)throw new TypeError("length: Is negative")}}class WA extends zA{constructor(){super(...arguments),this.name="shake128",this.defaultLength=16}}class JA extends zA{constructor(){super(...arguments),this.name="shake256",this.defaultLength=32}}class YA{get[Symbol.toStringTag](){return"Crypto"}randomUUID(){const e=this.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Yp.ToHex(e).toLowerCase();return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}}class XA{constructor(){this.items={}}get(e){return this.items[e.toLowerCase()]||null}set(e){this.items[e.name.toLowerCase()]=e}removeAt(e){const t=this.get(e.toLowerCase());return t&&delete this.items[e],t}has(e){return!!this.get(e)}get length(){return Object.keys(this.items).length}get algorithms(){const e=[];for(const t in this.items){const r=this.items[t];e.push(r.name)}return e.sort()}}const ZA={jwk:["private","public","secret"],pkcs8:["private"],spki:["public"],raw:["secret","public"]},eI=["pkcs8","spki","raw"];class tI{constructor(){this.providers=new XA}static isHashedAlgorithm(e){return!!(e&&"object"==typeof e&&"name"in e&&"hash"in e)}get[Symbol.toStringTag](){return"SubtleCrypto"}async digest(...e){this.checkRequiredArguments(e,2,"digest");const[t,r,...s]=e,i=this.prepareAlgorithm(t),n=$p.toArrayBuffer(r),o=this.getProvider(i.name);return await o.digest(i,n,...s)}async generateKey(...e){this.checkRequiredArguments(e,3,"generateKey");const[t,r,s,...i]=e,n=this.prepareAlgorithm(t),o=this.getProvider(n.name);return await o.generateKey({...n,name:o.name},r,s,...i)}async sign(...e){this.checkRequiredArguments(e,3,"sign");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=$p.toArrayBuffer(s),a=this.getProvider(n.name);return await a.sign({...n,name:a.name},r,o,...i)}async verify(...e){this.checkRequiredArguments(e,4,"verify");const[t,r,s,i,...n]=e;this.checkCryptoKey(r);const o=this.prepareAlgorithm(t),a=$p.toArrayBuffer(i),c=$p.toArrayBuffer(s),l=this.getProvider(o.name);return await l.verify({...o,name:l.name},r,c,a,...n)}async encrypt(...e){this.checkRequiredArguments(e,3,"encrypt");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=$p.toArrayBuffer(s),a=this.getProvider(n.name);return await a.encrypt({...n,name:a.name},r,o,{keyUsage:!0},...i)}async decrypt(...e){this.checkRequiredArguments(e,3,"decrypt");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=$p.toArrayBuffer(s),a=this.getProvider(n.name);return await a.decrypt({...n,name:a.name},r,o,{keyUsage:!0},...i)}async deriveBits(...e){this.checkRequiredArguments(e,3,"deriveBits");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),o=this.getProvider(n.name);return await o.deriveBits({...n,name:o.name},r,s,{keyUsage:!0},...i)}async deriveKey(...e){this.checkRequiredArguments(e,5,"deriveKey");const[t,r,s,i,n,...o]=e,a=this.prepareAlgorithm(s);this.getProvider(a.name).checkDerivedKeyParams(a);const c=this.prepareAlgorithm(t),l=this.getProvider(c.name);l.checkCryptoKey(r,"deriveKey");const h=await l.deriveBits({...c,name:l.name},r,s.length||512,{keyUsage:!1},...o);return this.importKey("raw",h,s,i,n,...o)}async exportKey(...e){this.checkRequiredArguments(e,2,"exportKey");const[t,r,...s]=e;if(this.checkCryptoKey(r),!ZA[t])throw new TypeError("Invalid keyFormat argument");if(!ZA[t].includes(r.type))throw new DOMException("The key is not of the expected type");const i=this.getProvider(r.algorithm.name);return await i.exportKey(t,r,...s)}async importKey(...e){this.checkRequiredArguments(e,5,"importKey");const[t,r,s,i,n,...o]=e,a=this.prepareAlgorithm(s),c=this.getProvider(a.name);if("jwk"===t){if("object"!=typeof r||!r.kty)throw new TypeError("Key data must be an object for JWK import")}else{if(!eI.includes(t))throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView or JsonWebKey)'");if(!$p.isBufferSource(r))throw new TypeError("Key data must be a BufferSource for non-JWK formats")}return c.importKey(t,r,{...a,name:c.name},i,n,...o)}async wrapKey(e,t,r,s,...i){let n=await this.exportKey(e,t,...i);if("jwk"===e){const e=JSON.stringify(n);n=Yp.FromUtf8String(e)}const o=this.prepareAlgorithm(s),a=$p.toArrayBuffer(n),c=this.getProvider(o.name);return c.encrypt({...o,name:c.name},r,a,{keyUsage:!1},...i)}async unwrapKey(e,t,r,s,i,n,o,...a){const c=this.prepareAlgorithm(s),l=$p.toArrayBuffer(t),h=this.getProvider(c.name);let u=await h.decrypt({...c,name:h.name},r,l,{keyUsage:!1},...a);if("jwk"===e)try{u=JSON.parse(Yp.ToUtf8String(u))}catch(e){const t=new TypeError("wrappedKey: Is not a JSON");throw t.internal=e,t}return this.importKey(e,u,i,n,o,...a)}checkRequiredArguments(e,t,r){if(e.length<t)throw new TypeError(`Failed to execute '${r}' on 'SubtleCrypto': ${t} arguments required, but only ${e.length} present`)}prepareAlgorithm(e){if("string"==typeof e)return{name:e};if(tI.isHashedAlgorithm(e)){const t={...e};return t.hash=this.prepareAlgorithm(e.hash),t}return{...e}}getProvider(e){const t=this.providers.get(e);if(!t)throw new Ub("Unrecognized name");return t}checkCryptoKey(e){if(!(e instanceof Zb))throw new TypeError("Key is not of type 'CryptoKey'")}}const rI=t(import.meta.url)("buffer"),sI=t(import.meta.url)("crypto");var iI=o.n(sI);const nI={fromJSON:e=>rI.Buffer.from(Yp.FromBase64Url(e)),toJSON:e=>Yp.ToBase64Url(e)};class oI extends Zb{constructor(){super(...arguments),this.data=rI.Buffer.alloc(0),this.algorithm={name:""},this.extractable=!1,this.type="secret",this.usages=[],this.kty="oct",this.alg=""}}hb([Rb({name:"ext",type:mb.Boolean,optional:!0})],oI.prototype,"extractable",void 0),hb([Rb({name:"key_ops",type:mb.String,repeated:!0,optional:!0})],oI.prototype,"usages",void 0),hb([Rb({type:mb.String})],oI.prototype,"kty",void 0),hb([Rb({type:mb.String,optional:!0})],oI.prototype,"alg",void 0);class aI extends oI{constructor(){super(...arguments),this.kty="oct",this.type="secret"}}class cI extends oI{}class lI extends aI{get alg(){switch(this.algorithm.name.toUpperCase()){case"AES-CBC":return`A${this.algorithm.length}CBC`;case"AES-CTR":return`A${this.algorithm.length}CTR`;case"AES-GCM":return`A${this.algorithm.length}GCM`;case"AES-KW":return`A${this.algorithm.length}KW`;case"AES-CMAC":return`A${this.algorithm.length}CMAC`;case"AES-ECB":return`A${this.algorithm.length}ECB`;default:throw new Ub("Unsupported algorithm name")}}set alg(e){}}hb([Rb({name:"k",converter:nI})],lI.prototype,"data",void 0);class hI{static async generateKey(e,t,r){const s=new lI;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=iI().randomBytes(e.length>>3),s}static async exportKey(e,t){if(!(t instanceof lI))throw new Error("key: Is not AesCryptoKey");switch(e.toLowerCase()){case"jwk":return _b.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new Nb("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Bb.fromJSON(t,{targetSchema:lI});break;case"raw":n=new lI,n.data=rI.Buffer.from(t);break;default:throw new Nb("format: Must be 'jwk' or 'raw'")}switch(n.algorithm=r,n.algorithm.length=n.data.length<<3,n.extractable=s,n.usages=i,n.algorithm.length){case 128:case 192:case 256:break;default:throw new Nb("keyData: Is wrong key length")}return n}static async encrypt(e,t,r){switch(e.name.toUpperCase()){case"AES-CBC":return this.encryptAesCBC(e,t,rI.Buffer.from(r));case"AES-CTR":return this.encryptAesCTR(e,t,rI.Buffer.from(r));case"AES-GCM":return this.encryptAesGCM(e,t,rI.Buffer.from(r));case"AES-KW":return this.encryptAesKW(e,t,rI.Buffer.from(r));case"AES-ECB":return this.encryptAesECB(e,t,rI.Buffer.from(r));default:throw new Nb("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof lI))throw new Error("key: Is not AesCryptoKey");switch(e.name.toUpperCase()){case"AES-CBC":return this.decryptAesCBC(e,t,rI.Buffer.from(r));case"AES-CTR":return this.decryptAesCTR(e,t,rI.Buffer.from(r));case"AES-GCM":return this.decryptAesGCM(e,t,rI.Buffer.from(r));case"AES-KW":return this.decryptAesKW(e,t,rI.Buffer.from(r));case"AES-ECB":return this.decryptAesECB(e,t,rI.Buffer.from(r));default:throw new Nb("algorithm: Is not recognized")}}static async encryptAesCBC(e,t,r){const s=iI().createCipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=rI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCBC(e,t,r){const s=iI().createDecipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=rI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesCTR(e,t,r){const s=iI().createCipheriv(`aes-${t.algorithm.length}-ctr`,t.data,rI.Buffer.from(e.counter));let i=s.update(r);return i=rI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCTR(e,t,r){const s=iI().createDecipheriv(`aes-${t.algorithm.length}-ctr`,t.data,new Uint8Array(e.counter));let i=s.update(r);return i=rI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesGCM(e,t,r){const s=iI().createCipheriv(`aes-${t.algorithm.length}-gcm`,t.data,rI.Buffer.from(e.iv),{authTagLength:(e.tagLength||128)>>3});e.additionalData&&s.setAAD(rI.Buffer.from(e.additionalData));let i=s.update(r);return i=rI.Buffer.concat([i,s.final(),s.getAuthTag()]),new Uint8Array(i).buffer}static async decryptAesGCM(e,t,r){const s=(e.tagLength||128)>>3,i=iI().createDecipheriv(`aes-${t.algorithm.length}-gcm`,t.data,new Uint8Array(e.iv),{authTagLength:s}),n=r.slice(0,r.length-s),o=r.slice(r.length-s);e.additionalData&&i.setAAD(rI.Buffer.from(e.additionalData)),i.setAuthTag(o);let a=i.update(n);return a=rI.Buffer.concat([a,i.final()]),new Uint8Array(a).buffer}static async encryptAesKW(e,t,r){const s=iI().createCipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=rI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesKW(e,t,r){const s=iI().createDecipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=rI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesECB(e,t,r){const s=iI().createCipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=rI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesECB(e,t,r){const s=iI().createDecipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=rI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}hI.AES_KW_IV=rI.Buffer.from("A6A6A6A6A6A6A6A6","hex");const uI=new WeakMap;function dI(e){const t=uI.get(e);if(!t)throw new Nb("Cannot get CryptoKey from secure storage");return t}function fI(e){const t=Zb.create(e.algorithm,e.type,e.extractable,e.usages);return Object.freeze(t),uI.set(t,e),t}class pI extends Hb{async onGenerateKey(e,t,r){return fI(await hI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return hI.encrypt(e,dI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return hI.decrypt(e,dI(t),new Uint8Array(r))}async onExportKey(e,t){return hI.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await hI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(dI(e)instanceof lI))throw new TypeError("key: Is not a AesCryptoKey")}}const gI=rI.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),yI=rI.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,135]),mI=16;function bI(e){const t=rI.Buffer.alloc(e.length),r=e.length-1;for(let s=0;s<r;s++)t[s]=e[s]<<1,128&e[s+1]&&(t[s]+=1);return t[r]=e[r]<<1,t}function AI(e,t){const r=Math.min(e.length,t.length),s=rI.Buffer.alloc(r);for(let i=0;i<r;i++)s[i]=e[i]^t[i];return s}function II(e,t){const r=iI().createCipheriv("aes"+(e.length<<3),e,gI),s=r.update(t);return r.final(),s}function vI(e,t){const r=rI.Buffer.alloc(mI),s=t*mI,i=s+mI;return e.copy(r,0,s,i),r}class wI extends Kb{async onGenerateKey(e,t,r){return fI(await hI.generateKey({name:this.name,length:e.length},t,r))}async onSign(e,t,r){const s=function(e,t){const r=function(e){const t=II(e,gI);let r=bI(t);128&t[0]&&(r=AI(r,yI));let s=bI(r);return 128&r[0]&&(s=AI(s,yI)),{subkey1:r,subkey2:s}}(e);let s,i,n=Math.ceil(t.length/mI);0===n?(n=1,s=!1):s=t.length%mI===0;const o=n-1;i=s?AI(vI(t,o),r.subkey1):AI(function(e,t){const r=rI.Buffer.alloc(mI),s=t*mI,i=e.length;return r.fill(0),e.copy(r,0,s,i),r[i-s]=128,r}(t,o),r.subkey2);let a,c=gI;for(let r=0;r<o;r++)a=AI(c,vI(t,r)),c=II(e,a);return a=AI(i,c),II(e,a)}(dI(t).data,rI.Buffer.from(r));return new Uint8Array(s).buffer}async onVerify(e,t,r,s){const i=await this.sign(e,t,s);return 0===rI.Buffer.from(r).compare(rI.Buffer.from(i))}async onExportKey(e,t){return hI.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await hI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(dI(e)instanceof lI))throw new TypeError("key: Is not a AesCryptoKey")}}class SI extends Qb{async onGenerateKey(e,t,r){return fI(await hI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return hI.encrypt(e,dI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return hI.decrypt(e,dI(t),new Uint8Array(r))}async onExportKey(e,t){return hI.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await hI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(dI(e)instanceof lI))throw new TypeError("key: Is not a AesCryptoKey")}}class EI extends Fb{async onGenerateKey(e,t,r){return fI(await hI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return hI.encrypt(e,dI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return hI.decrypt(e,dI(t),new Uint8Array(r))}async onExportKey(e,t){return hI.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await hI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(dI(e)instanceof lI))throw new TypeError("key: Is not a AesCryptoKey")}}class CI extends $b{async onGenerateKey(e,t,r){return fI(await hI.generateKey({name:this.name,length:e.length},t,r))}async onExportKey(e,t){return hI.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await hI.importKey(e,t,{name:r.name},s,i))}async onEncrypt(e,t,r){return hI.encrypt(e,dI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return hI.decrypt(e,dI(t),new Uint8Array(r))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(dI(e)instanceof lI))throw new TypeError("key: Is not a AesCryptoKey")}}class kI extends Vb{async onGenerateKey(e,t,r){return fI(await hI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return hI.encrypt(e,dI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return hI.decrypt(e,dI(t),new Uint8Array(r))}async onExportKey(e,t){return hI.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await hI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(dI(e)instanceof lI))throw new TypeError("key: Is not a AesCryptoKey")}}class xI extends aI{get alg(){switch(this.algorithm.name.toUpperCase()){case"DES-CBC":return"DES-CBC";case"DES-EDE3-CBC":return"3DES-CBC";default:throw new Ub("Unsupported algorithm name")}}set alg(e){}}hb([Rb({name:"k",converter:nI})],xI.prototype,"data",void 0);class _I{static async generateKey(e,t,r){const s=new xI;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=iI().randomBytes(e.length>>3),s}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return _b.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new Nb("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Bb.fromJSON(t,{targetSchema:xI});break;case"raw":n=new xI,n.data=rI.Buffer.from(t);break;default:throw new Nb("format: Must be 'jwk' or 'raw'")}return n.algorithm=r,n.extractable=s,n.usages=i,n}static async encrypt(e,t,r){switch(e.name.toUpperCase()){case"DES-CBC":return this.encryptDesCBC(e,t,rI.Buffer.from(r));case"DES-EDE3-CBC":return this.encryptDesEDE3CBC(e,t,rI.Buffer.from(r));default:throw new Nb("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof xI))throw new Error("key: Is not DesCryptoKey");switch(e.name.toUpperCase()){case"DES-CBC":return this.decryptDesCBC(e,t,rI.Buffer.from(r));case"DES-EDE3-CBC":return this.decryptDesEDE3CBC(e,t,rI.Buffer.from(r));default:throw new Nb("algorithm: Is not recognized")}}static async encryptDesCBC(e,t,r){const s=iI().createCipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=rI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesCBC(e,t,r){const s=iI().createDecipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=rI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptDesEDE3CBC(e,t,r){const s=iI().createCipheriv("des-ede3-cbc",t.data,rI.Buffer.from(e.iv));let i=s.update(r);return i=rI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesEDE3CBC(e,t,r){const s=iI().createDecipheriv("des-ede3-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=rI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}class BI extends jb{constructor(){super(...arguments),this.keySizeBits=64,this.ivSize=8,this.name="DES-CBC"}async onGenerateKey(e,t,r){return fI(await _I.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return _I.encrypt(e,dI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return _I.decrypt(e,dI(t),new Uint8Array(r))}async onExportKey(e,t){return _I.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){const n=await _I.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new Nb("keyData: Wrong key size");return fI(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(dI(e)instanceof xI))throw new TypeError("key: Is not a DesCryptoKey")}}class RI extends jb{constructor(){super(...arguments),this.keySizeBits=192,this.ivSize=8,this.name="DES-EDE3-CBC"}async onGenerateKey(e,t,r){return fI(await _I.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return _I.encrypt(e,dI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return _I.decrypt(e,dI(t),new Uint8Array(r))}async onExportKey(e,t){return _I.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){const n=await _I.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new Nb("keyData: Wrong key size");return fI(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(dI(e)instanceof xI))throw new TypeError("key: Is not a DesCryptoKey")}}function OI(e){switch(e.name.toUpperCase()){case"RSA-OAEP":{const t=/(\d+)$/.exec(e.hash.name)[1];return"RSA-OAEP"+("1"!==t?`-${t}`:"")}case"RSASSA-PKCS1-V1_5":return`RS${/(\d+)$/.exec(e.hash.name)[1]}`;case"RSA-PSS":return`PS${/(\d+)$/.exec(e.hash.name)[1]}`;case"RSA-PKCS1":return"RS1";default:throw new Nb("algorithm: Is not recognized")}}class UI extends cI{constructor(){super(...arguments),this.type="private"}getKey(){const e=ob.parse(this.data,QA.PrivateKeyInfo);return ob.parse(e.privateKey,QA.RsaPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:OI(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,_b.toJSON(e))}fromJSON(e){const t=Bb.fromJSON(e,{targetSchema:QA.RsaPrivateKey}),r=new QA.PrivateKeyInfo;r.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.privateKeyAlgorithm.parameters=null,r.privateKey=ab.serialize(t),this.data=rI.Buffer.from(ab.serialize(r))}}class TI extends cI{constructor(){super(...arguments),this.type="public"}getKey(){const e=ob.parse(this.data,QA.PublicKeyInfo);return ob.parse(e.publicKey,QA.RsaPublicKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:OI(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,_b.toJSON(e))}fromJSON(e){const t=Bb.fromJSON(e,{targetSchema:QA.RsaPublicKey}),r=new QA.PublicKeyInfo;r.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.publicKeyAlgorithm.parameters=null,r.publicKey=ab.serialize(t),this.data=rI.Buffer.from(ab.serialize(r))}}class NI{static async generateKey(e,t,r){const s=new UI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new TI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=rI.Buffer.concat([rI.Buffer.alloc(4-e.publicExponent.byteLength,0),rI.Buffer.from(e.publicExponent)]).readInt32BE(0),o=iI().generateKeyPairSync("rsa",{modulusLength:e.modulusLength,publicExponent:n,publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=o.privateKey,i.data=o.publicKey,{privateKey:s,publicKey:i}}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return _b.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;default:throw new Nb("format: Must be 'jwk', 'pkcs8' or 'spki'")}}static async importKey(e,t,r,s,i){switch(e.toLowerCase()){case"jwk":if(t.d){const e=Bb.fromJSON(t,{targetSchema:QA.RsaPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=Bb.fromJSON(t,{targetSchema:QA.RsaPublicKey});return this.importPublicKey(e,r,s,i)}case"spki":{const e=ob.parse(new Uint8Array(t),QA.PublicKeyInfo),n=ob.parse(e.publicKey,QA.RsaPublicKey);return this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=ob.parse(new Uint8Array(t),QA.PrivateKeyInfo),n=ob.parse(e.privateKey,QA.RsaPrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new Nb("format: Must be 'jwk', 'pkcs8' or 'spki'")}}static async sign(e,t,r){switch(e.name.toUpperCase()){case"RSA-PSS":case"RSASSA-PKCS1-V1_5":return this.signRsa(e,t,r);default:throw new Nb("algorithm: Is not recognized")}}static async verify(e,t,r,s){switch(e.name.toUpperCase()){case"RSA-PSS":case"RSASSA-PKCS1-V1_5":return this.verifySSA(e,t,s,r);default:throw new Nb("algorithm: Is not recognized")}}static async encrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.encryptOAEP(e,t,r);throw new Nb("algorithm: Is not recognized")}static async decrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.decryptOAEP(e,t,r);throw new Nb("algorithm: Is not recognized")}static importPrivateKey(e,t,r,s){const i=new QA.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.privateKeyAlgorithm.parameters=null,i.privateKey=ab.serialize(e);const n=new UI;return n.data=rI.Buffer.from(ab.serialize(i)),n.algorithm=Object.assign({},t),n.algorithm.publicExponent=new Uint8Array(e.publicExponent),n.algorithm.modulusLength=e.modulus.byteLength<<3,n.extractable=r,n.usages=s,n}static importPublicKey(e,t,r,s){const i=new QA.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.publicKeyAlgorithm.parameters=null,i.publicKey=ab.serialize(e);const n=new TI;return n.data=rI.Buffer.from(ab.serialize(i)),n.algorithm=Object.assign({},t),n.algorithm.publicExponent=new Uint8Array(e.publicExponent),n.algorithm.modulusLength=e.modulus.byteLength<<3,n.extractable=r,n.usages=s,n}static getCryptoAlgorithm(e){switch(e.hash.name.toUpperCase()){case"SHA-1":return"RSA-SHA1";case"SHA-256":return"RSA-SHA256";case"SHA-384":return"RSA-SHA384";case"SHA-512":return"RSA-SHA512";case"SHA3-256":return"RSA-SHA3-256";case"SHA3-384":return"RSA-SHA3-384";case"SHA3-512":return"RSA-SHA3-512";default:throw new Nb("algorithm.hash: Is not recognized")}}static signRsa(e,t,r){const s=this.getCryptoAlgorithm(t.algorithm),i=iI().createSign(s);i.update(rI.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem};"RSA-PSS"===e.name.toUpperCase()&&(n.padding=iI().constants.RSA_PKCS1_PSS_PADDING,n.saltLength=e.saltLength);const o=i.sign(n);return new Uint8Array(o).buffer}static verifySSA(e,t,r,s){const i=this.getCryptoAlgorithm(t.algorithm),n=iI().createVerify(i);n.update(rI.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const o={key:t.pem};return"RSA-PSS"===e.name.toUpperCase()&&(o.padding=iI().constants.RSA_PKCS1_PSS_PADDING,o.saltLength=e.saltLength),n.verify(o,s)}static encryptOAEP(e,t,r){const s={key:`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`,padding:iI().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(iI().publicEncrypt(s,r)).buffer}static decryptOAEP(e,t,r){const s={key:`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`,padding:iI().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(iI().privateDecrypt(s,r)).buffer}}NI.publicKeyUsages=["verify","encrypt","wrapKey"],NI.privateKeyUsages=["sign","decrypt","unwrapKey"];class DI extends qb{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await NI.generateKey({...e,name:this.name},t,r);return{privateKey:fI(s.privateKey),publicKey:fI(s.publicKey)}}async onSign(e,t,r){return NI.sign(e,dI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return NI.verify(e,dI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return NI.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await NI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=dI(e);if(!(r instanceof UI||r instanceof TI))throw new TypeError("key: Is not RSA CryptoKey")}}class MI extends zb{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await NI.generateKey({...e,name:this.name},t,r);return{privateKey:fI(s.privateKey),publicKey:fI(s.publicKey)}}async onSign(e,t,r){return NI.sign(e,dI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return NI.verify(e,dI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return NI.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await NI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=dI(e);if(!(r instanceof UI||r instanceof TI))throw new TypeError("key: Is not RSA CryptoKey")}}class PI{static size(e){switch(e.name.toUpperCase()){case"SHA-1":return 160;case"SHA-256":case"SHA3-256":return 256;case"SHA-384":case"SHA3-384":return 384;case"SHA-512":case"SHA3-512":return 512;default:throw new Error("Unrecognized name")}}static getAlgorithmName(e){switch(e.name.toUpperCase()){case"SHA-1":return"sha1";case"SHA-256":return"sha256";case"SHA-384":return"sha384";case"SHA-512":return"sha512";case"SHA3-256":return"sha3-256";case"SHA3-384":return"sha3-384";case"SHA3-512":return"sha3-512";default:throw new Error("Unrecognized name")}}static digest(e,t){const r=this.getAlgorithmName(e),s=iI().createHash(r).update(rI.Buffer.from(t)).digest();return new Uint8Array(s).buffer}}class LI extends Wb{async onGenerateKey(e,t,r){const s=await NI.generateKey({...e,name:this.name},t,r);return{privateKey:fI(s.privateKey),publicKey:fI(s.publicKey)}}async onEncrypt(e,t,r){const s=dI(t),i=new Uint8Array(r),n=Math.ceil(s.algorithm.modulusLength>>3),o=PI.size(s.algorithm.hash)>>3,a=i.byteLength,c=n-a-2*o-2;if(a>n-2*o-2)throw new Error("Data too large");const l=new Uint8Array(n),h=l.subarray(1,o+1),u=l.subarray(o+1);u.set(i,o+c+1);const d=iI().createHash(s.algorithm.hash.name.replace("-","")).update($p.toUint8Array(e.label||new Uint8Array(0))).digest();u.set(d,0),u[o+c]=1,iI().randomFillSync(h);const f=this.mgf1(s.algorithm.hash,h,u.length);for(let e=0;e<u.length;e++)u[e]^=f[e];const p=this.mgf1(s.algorithm.hash,u,h.length);for(let e=0;e<h.length;e++)h[e]^=p[e];s.pem||(s.pem=`-----BEGIN PUBLIC KEY-----\n${s.data.toString("base64")}\n-----END PUBLIC KEY-----`);const g=iI().publicEncrypt({key:s.pem,padding:iI().constants.RSA_NO_PADDING},rI.Buffer.from(l));return new Uint8Array(g).buffer}async onDecrypt(e,t,r){const s=dI(t),i=Math.ceil(s.algorithm.modulusLength>>3),n=PI.size(s.algorithm.hash)>>3;if(r.byteLength!==i)throw new Error("Bad data");s.pem||(s.pem=`-----BEGIN PRIVATE KEY-----\n${s.data.toString("base64")}\n-----END PRIVATE KEY-----`);let o=iI().privateDecrypt({key:s.pem,padding:iI().constants.RSA_NO_PADDING},rI.Buffer.from(r));const a=o[0],c=o.subarray(1,n+1),l=o.subarray(n+1);if(0!==a)throw new Error("Decryption failed");const h=this.mgf1(s.algorithm.hash,l,c.length);for(let e=0;e<c.length;e++)c[e]^=h[e];const u=this.mgf1(s.algorithm.hash,c,l.length);for(let e=0;e<l.length;e++)l[e]^=u[e];const d=iI().createHash(s.algorithm.hash.name.replace("-","")).update($p.toUint8Array(e.label||new Uint8Array(0))).digest();for(let e=0;e<n;e++)if(d[e]!==l[e])throw new Error("Decryption failed");let f=n;for(;f<l.length;f++){const e=l[f];if(1===e)break;if(0!==e)throw new Error("Decryption failed")}if(f===l.length)throw new Error("Decryption failed");return o=l.subarray(f+1),new Uint8Array(o).buffer}async onExportKey(e,t){return NI.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await NI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=dI(e);if(!(r instanceof UI||r instanceof TI))throw new TypeError("key: Is not RSA CryptoKey")}mgf1(e,t,r=0){const s=PI.size(e)>>3,i=new Uint8Array(r),n=new Uint8Array(4),o=Math.ceil(r/s);for(let r=0;r<o;r++){n[0]=r>>>24,n[1]=r>>>16&255,n[2]=r>>>8&255,n[3]=255&r;const o=i.subarray(r*s);let a=iI().createHash(e.name.replace("-","")).update(t).update(n).digest();a.length>o.length&&(a=a.subarray(0,o.length)),o.set(a)}return i}}class HI extends Pb{constructor(){super(...arguments),this.name="RSAES-PKCS1-v1_5",this.usages={publicKey:["encrypt","wrapKey"],privateKey:["decrypt","unwrapKey"]}}async onGenerateKey(e,t,r){const s=await NI.generateKey({...e,name:this.name},t,r);return{privateKey:fI(s.privateKey),publicKey:fI(s.publicKey)}}checkGenerateKeyParams(e){if(this.checkRequiredProperty(e,"publicExponent"),!(e.publicExponent&&e.publicExponent instanceof Uint8Array))throw new TypeError("publicExponent: Missing or not a Uint8Array");const t=Yp.ToBase64(e.publicExponent);if("Aw=="!==t&&"AQAB"!==t)throw new TypeError("publicExponent: Must be [3] or [1,0,1]");switch(this.checkRequiredProperty(e,"modulusLength"),e.modulusLength){case 1024:case 2048:case 4096:break;default:throw new TypeError("modulusLength: Must be 1024, 2048, or 4096")}}async onEncrypt(e,t,r){const s=this.toCryptoOptions(t),i=iI().publicEncrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onDecrypt(e,t,r){const s=this.toCryptoOptions(t),i=iI().privateDecrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onExportKey(e,t){return NI.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await NI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=dI(e);if(!(r instanceof UI||r instanceof TI))throw new TypeError("key: Is not RSA CryptoKey")}toCryptoOptions(e){const t=e.type.toUpperCase();return{key:`-----BEGIN ${t} KEY-----\n${dI(e).data.toString("base64")}\n-----END ${t} KEY-----`,padding:iI().constants.RSA_PKCS1_PADDING}}}const KI={"1.2.840.10045.3.1.7":"P-256","P-256":"1.2.840.10045.3.1.7","1.3.132.0.34":"P-384","P-384":"1.3.132.0.34","1.3.132.0.35":"P-521","P-521":"1.3.132.0.35","1.3.132.0.10":"K-256","K-256":"1.3.132.0.10",brainpoolP160r1:"1.3.36.3.3.2.8.1.1.1","1.3.36.3.3.2.8.1.1.1":"brainpoolP160r1",brainpoolP160t1:"1.3.36.3.3.2.8.1.1.2","1.3.36.3.3.2.8.1.1.2":"brainpoolP160t1",brainpoolP192r1:"1.3.36.3.3.2.8.1.1.3","1.3.36.3.3.2.8.1.1.3":"brainpoolP192r1",brainpoolP192t1:"1.3.36.3.3.2.8.1.1.4","1.3.36.3.3.2.8.1.1.4":"brainpoolP192t1",brainpoolP224r1:"1.3.36.3.3.2.8.1.1.5","1.3.36.3.3.2.8.1.1.5":"brainpoolP224r1",brainpoolP224t1:"1.3.36.3.3.2.8.1.1.6","1.3.36.3.3.2.8.1.1.6":"brainpoolP224t1",brainpoolP256r1:"1.3.36.3.3.2.8.1.1.7","1.3.36.3.3.2.8.1.1.7":"brainpoolP256r1",brainpoolP256t1:"1.3.36.3.3.2.8.1.1.8","1.3.36.3.3.2.8.1.1.8":"brainpoolP256t1",brainpoolP320r1:"1.3.36.3.3.2.8.1.1.9","1.3.36.3.3.2.8.1.1.9":"brainpoolP320r1",brainpoolP320t1:"1.3.36.3.3.2.8.1.1.10","1.3.36.3.3.2.8.1.1.10":"brainpoolP320t1",brainpoolP384r1:"1.3.36.3.3.2.8.1.1.11","1.3.36.3.3.2.8.1.1.11":"brainpoolP384r1",brainpoolP384t1:"1.3.36.3.3.2.8.1.1.12","1.3.36.3.3.2.8.1.1.12":"brainpoolP384t1",brainpoolP512r1:"1.3.36.3.3.2.8.1.1.13","1.3.36.3.3.2.8.1.1.13":"brainpoolP512r1",brainpoolP512t1:"1.3.36.3.3.2.8.1.1.14","1.3.36.3.3.2.8.1.1.14":"brainpoolP512t1"};function QI(e){const t=KI[e];if(!t)throw new Nb(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class VI extends cI{constructor(){super(...arguments),this.type="private"}getKey(){const e=ob.parse(this.data,QA.PrivateKeyInfo);return ob.parse(e.privateKey,QA.EcPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,_b.toJSON(e))}fromJSON(e){if(!e.crv)throw new Nb("Cannot get named curve from JWK. Property 'crv' is required");const t=new QA.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",t.privateKeyAlgorithm.parameters=ab.serialize(new QA.ObjectIdentifier(QI(e.crv)));const r=Bb.fromJSON(e,{targetSchema:QA.EcPrivateKey});return t.privateKey=ab.serialize(r),this.data=rI.Buffer.from(ab.serialize(t)),this}}class FI extends cI{constructor(){super(...arguments),this.type="public"}getKey(){const e=ob.parse(this.data,QA.PublicKeyInfo);return new QA.EcPublicKey(e.publicKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,_b.toJSON(e))}fromJSON(e){if(!e.crv)throw new Nb("Cannot get named curve from JWK. Property 'crv' is required");const t=Bb.fromJSON(e,{targetSchema:QA.EcPublicKey}),r=new QA.PublicKeyInfo;return r.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1",r.publicKeyAlgorithm.parameters=ab.serialize(new QA.ObjectIdentifier(QI(e.crv))),r.publicKey=ab.toASN(t).valueHex,this.data=rI.Buffer.from(ab.serialize(r)),this}}class $I extends Pb{constructor(){super(...arguments),this.name="SHA-1",this.usages=[]}async onDigest(e,t){return PI.digest(e,t)}}class jI extends Pb{constructor(){super(...arguments),this.name="SHA-256",this.usages=[]}async onDigest(e,t){return PI.digest(e,t)}}class GI extends Pb{constructor(){super(...arguments),this.name="SHA-384",this.usages=[]}async onDigest(e,t){return PI.digest(e,t)}}class qI extends Pb{constructor(){super(...arguments),this.name="SHA-512",this.usages=[]}async onDigest(e,t){return PI.digest(e,t)}}class zI extends Pb{constructor(){super(...arguments),this.name="SHA3-256",this.usages=[]}async onDigest(e,t){return PI.digest(e,t)}}class WI extends Pb{constructor(){super(...arguments),this.name="SHA3-384",this.usages=[]}async onDigest(e,t){return PI.digest(e,t)}}class JI extends Pb{constructor(){super(...arguments),this.name="SHA3-512",this.usages=[]}async onDigest(e,t){return PI.digest(e,t)}}class YI{static async generateKey(e,t,r){const s=new VI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new FI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=iI().generateKeyPairSync("ec",{namedCurve:this.getOpenSSLNamedCurve(e.namedCurve),publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=n.privateKey,i.data=n.publicKey,{privateKey:s,publicKey:i}}static async sign(e,t,r){const s=PI.getAlgorithmName(e.hash),i=iI().createSign(s);i.update(rI.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem},o=i.sign(n),a=ob.parse(o,QA.EcDsaSignature);return gA.encodeSignature(a,VA.get(t.algorithm.namedCurve).size).buffer}static async verify(e,t,r,s){const i=PI.getAlgorithmName(e.hash),n=iI().createVerify(i);n.update(rI.Buffer.from(s)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const o={key:t.pem},a=new QA.EcDsaSignature,c=VA.get(t.algorithm.namedCurve),l=gA.decodeSignature(r,c.size);a.r=$p.toArrayBuffer(l.r),a.s=$p.toArrayBuffer(l.s);const h=rI.Buffer.from(ab.serialize(a));return n.verify(o,h)}static async deriveBits(e,t,r){const s=this.getOpenSSLNamedCurve(t.algorithm.namedCurve),i=iI().createECDH(s),n=ob.parse(t.data,QA.PrivateKeyInfo),o=ob.parse(n.privateKey,QA.EcPrivateKey);i.setPrivateKey(rI.Buffer.from(o.privateKey));const a=ob.parse(e.public.data,QA.PublicKeyInfo),c=i.computeSecret(rI.Buffer.from(a.publicKey));return null===r?c:new Uint8Array(c).buffer.slice(0,r>>3)}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return _b.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return ob.parse(t.data,QA.PublicKeyInfo).publicKey;default:throw new Nb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'")}}static async importKey(e,t,r,s,i){switch(e.toLowerCase()){case"jwk":if(t.d){const e=Bb.fromJSON(t,{targetSchema:QA.EcPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=Bb.fromJSON(t,{targetSchema:QA.EcPublicKey});return this.importPublicKey(e,r,s,i)}case"raw":{const e=new QA.EcPublicKey(t);return this.importPublicKey(e,r,s,i)}case"spki":{const e=ob.parse(new Uint8Array(t),QA.PublicKeyInfo),n=new QA.EcPublicKey(e.publicKey);return this.assertKeyParameters(e.publicKeyAlgorithm.parameters,r.namedCurve),this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=ob.parse(new Uint8Array(t),QA.PrivateKeyInfo),n=ob.parse(e.privateKey,QA.EcPrivateKey);return this.assertKeyParameters(e.privateKeyAlgorithm.parameters,r.namedCurve),this.importPrivateKey(n,r,s,i)}default:throw new Nb("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static assertKeyParameters(e,t){if(!e)throw new Ob("Key info doesn't have required parameters");let r="";try{r=ob.parse(e,QA.ObjectIdentifier).value}catch(e){throw new Ob("Cannot read key info parameters")}if(QI(t)!==r)throw new Ob("Key info parameter doesn't match to named curve")}static async importPrivateKey(e,t,r,s){const i=new QA.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",i.privateKeyAlgorithm.parameters=ab.serialize(new QA.ObjectIdentifier(QI(t.namedCurve))),i.privateKey=ab.serialize(e);const n=new VI;return n.data=rI.Buffer.from(ab.serialize(i)),n.algorithm=Object.assign({},t),n.extractable=r,n.usages=s,n}static async importPublicKey(e,t,r,s){const i=new QA.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1";const n=QI(t.namedCurve);i.publicKeyAlgorithm.parameters=ab.serialize(new QA.ObjectIdentifier(n)),i.publicKey=e.value;const o=new FI;return o.data=rI.Buffer.from(ab.serialize(i)),o.algorithm=Object.assign({},t),o.extractable=r,o.usages=s,o}static getOpenSSLNamedCurve(e){switch(e.toUpperCase()){case"P-256":return"prime256v1";case"K-256":return"secp256k1";case"P-384":return"secp384r1";case"P-521":return"secp521r1";default:return e}}}YI.publicKeyUsages=["verify"],YI.privateKeyUsages=["sign","deriveKey","deriveBits"];class XI extends Yb{constructor(){super(...arguments),this.namedCurves=VA.names,this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await YI.generateKey({...e,name:this.name},t,r);return{privateKey:fI(s.privateKey),publicKey:fI(s.publicKey)}}async onSign(e,t,r){return YI.sign(e,dI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return YI.verify(e,dI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return YI.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await YI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=dI(e);if(!(r instanceof VI||r instanceof FI))throw new TypeError("key: Is not EC CryptoKey")}}class ZI extends eA{constructor(){super(...arguments),this.namedCurves=VA.names}async onGenerateKey(e,t,r){const s=await YI.generateKey({...e,name:this.name},t,r);return{privateKey:fI(s.privateKey),publicKey:fI(s.publicKey)}}async onExportKey(e,t){return YI.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await YI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=dI(e);if(!(r instanceof VI||r instanceof FI))throw new TypeError("key: Is not EC CryptoKey")}async onDeriveBits(e,t,r){return await YI.deriveBits({...e,public:dI(e.public)},dI(t),r)}}const ev={[QA.idEd448]:"Ed448",ed448:QA.idEd448,[QA.idX448]:"X448",x448:QA.idX448,[QA.idEd25519]:"Ed25519",ed25519:QA.idEd25519,[QA.idX25519]:"X25519",x25519:QA.idX25519};function tv(e){const t=ev[e.toLowerCase()];if(!t)throw new Nb(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class rv extends cI{constructor(){super(...arguments),this.type="private"}getKey(){const e=ob.parse(this.data,QA.PrivateKeyInfo);return ob.parse(e.privateKey,QA.CurvePrivateKey)}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,_b.toJSON(e))}fromJSON(e){if(!e.crv)throw new Nb("Cannot get named curve from JWK. Property 'crv' is required");const t=new QA.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm=tv(e.crv);const r=Bb.fromJSON(e,{targetSchema:QA.CurvePrivateKey});return t.privateKey=ab.serialize(r),this.data=rI.Buffer.from(ab.serialize(t)),this}}class sv extends cI{constructor(){super(...arguments),this.type="public"}getKey(){return ob.parse(this.data,QA.PublicKeyInfo).publicKey}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,{x:Yp.ToBase64Url(e)})}fromJSON(e){if(!e.crv)throw new Nb("Cannot get named curve from JWK. Property 'crv' is required");if(!e.x)throw new Nb("Cannot get property from JWK. Property 'x' is required");const t=new QA.PublicKeyInfo;return t.publicKeyAlgorithm.algorithm=tv(e.crv),t.publicKey=Yp.FromBase64Url(e.x),this.data=rI.Buffer.from(ab.serialize(t)),this}}class iv{static async generateKey(e,t,r){const s=new rv;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new sv;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=e.namedCurve.toLowerCase(),o=iI().generateKeyPairSync(n,{publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=o.privateKey,i.data=o.publicKey,{privateKey:s,publicKey:i}}static async sign(e,t,r){t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const s={key:t.pem},i=iI().sign(null,rI.Buffer.from(r),s);return $p.toArrayBuffer(i)}static async verify(e,t,r,s){t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const i={key:t.pem};return iI().verify(null,rI.Buffer.from(s),i,rI.Buffer.from(r))}static async deriveBits(e,t,r){const s=iI().createPublicKey({key:e.public.data,format:"der",type:"spki"}),i=iI().createPrivateKey({key:t.data,format:"der",type:"pkcs8"}),n=iI().diffieHellman({publicKey:s,privateKey:i});return new Uint8Array(n).buffer.slice(0,r>>3)}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return _b.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return ob.parse(t.data,QA.PublicKeyInfo).publicKey;default:throw new Nb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'")}}static async importKey(e,t,r,s,i){switch(e.toLowerCase()){case"jwk":{const e=t;if(e.d){const e=Bb.fromJSON(t,{targetSchema:QA.CurvePrivateKey});return this.importPrivateKey(e,r,s,i)}if(!e.x)throw new TypeError("keyData: Cannot get required 'x' filed");return this.importPublicKey(Yp.FromBase64Url(e.x),r,s,i)}case"raw":return this.importPublicKey(t,r,s,i);case"spki":{const e=ob.parse(new Uint8Array(t),QA.PublicKeyInfo);return this.importPublicKey(e.publicKey,r,s,i)}case"pkcs8":{const e=ob.parse(new Uint8Array(t),QA.PrivateKeyInfo),n=ob.parse(e.privateKey,QA.CurvePrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new Nb("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static importPrivateKey(e,t,r,s){const i=new rv;return i.fromJSON({crv:t.namedCurve,d:Yp.ToBase64Url(e.d)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}static async importPublicKey(e,t,r,s){const i=new sv;return i.fromJSON({crv:t.namedCurve,x:Yp.ToBase64Url(e)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}}iv.publicKeyUsages=["verify"],iv.privateKeyUsages=["sign","deriveKey","deriveBits"];class nv extends rA{async onGenerateKey(e,t,r){const s=await iv.generateKey({name:this.name,namedCurve:e.namedCurve.replace(/^ed/i,"Ed")},t,r);return{privateKey:fI(s.privateKey),publicKey:fI(s.publicKey)}}async onSign(e,t,r){return iv.sign(e,dI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return iv.verify(e,dI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return iv.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await iv.importKey(e,t,{...r,name:this.name},s,i))}}class ov extends tA{async onGenerateKey(e,t,r){const s=await iv.generateKey({name:this.name,namedCurve:e.namedCurve.toUpperCase()},t,r);return{privateKey:fI(s.privateKey),publicKey:fI(s.publicKey)}}async onDeriveBits(e,t,r){return await iv.deriveBits({...e,public:dI(e.public)},dI(t),r)}async onExportKey(e,t){return iv.exportKey(e,dI(t))}async onImportKey(e,t,r,s,i){return fI(await iv.importKey(e,t,{...r,name:this.name},s,i))}}class av extends oI{constructor(e,t,r,s){super(),this.algorithm=e,this.extractable=t,this.usages=r,this.data=Buffer.from(s)}toJWK(){return{kty:"OKP",crv:this.algorithm.name,key_ops:this.usages,ext:this.extractable}}}class cv extends av{constructor(){super(...arguments),this.type="private"}toJWK(){const e=iI().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"}),t=Mb.toUint8Array(this.data.toString()),r=lb.parse(t,QA.PrivateKeyInfo),s=lb.parse(r.privateKey,QA.EdPrivateKey).value;return{...super.toJWK(),...e,d:Buffer.from(new Uint8Array(s)).toString("base64url")}}}class lv extends av{constructor(){super(...arguments),this.type="public"}toJWK(){const e=iI().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"});return{...super.toJWK(),...e}}}class hv{static async generateKey(e,t,r){const s=e.name.toLowerCase(),i=iI().generateKeyPairSync(s,{publicKeyEncoding:{format:"pem",type:"spki"},privateKeyEncoding:{format:"pem",type:"pkcs8"}}),n={name:"ed25519"===s?"Ed25519":"X25519"},o=r.filter(e=>this.privateKeyUsages.includes(e)),a=r.filter(e=>this.publicKeyUsages.includes(e));return{privateKey:new cv(n,t,o,i.privateKey),publicKey:new lv(n,!0,a,i.publicKey)}}static async sign(e,t,r){const s=iI().sign(null,Buffer.from(r),t.data);return $p.toArrayBuffer(s)}static async verify(e,t,r,s){return iI().verify(null,Buffer.from(s),t.data,r)}static async exportKey(e,t){switch(e){case"jwk":return t.toJWK();case"pkcs8":case"spki":return Mb.toArrayBuffer(t.data.toString());case"raw":{const e=t.toJWK();return Yp.FromBase64Url(e.x)}default:return Promise.reject(new Nb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}static async importKey(e,t,r,s,i){switch(e){case"jwk":{const e=t;if(e.d){const t=new QA.EdPrivateKey;t.value=$p.toArrayBuffer(Buffer.from(e.d,"base64url"));const n=new QA.PrivateKeyInfo;n.privateKeyAlgorithm.algorithm="ed25519"===r.name.toLowerCase()?QA.idEd25519:QA.idX25519,n.privateKey=lb.serialize(t);const o=lb.serialize(n),a=Mb.fromBufferSource(o,"PRIVATE KEY");return new cv(r,s,i,a)}if(e.x){const t=iI().createPublicKey({format:"jwk",key:e}).export({format:"pem",type:"spki"});return new lv(r,s,i,t)}throw new Nb("keyData: Cannot import JWK. 'd' or 'x' must be presented")}case"pkcs8":{const e=Mb.fromBufferSource(t,"PRIVATE KEY");return new cv(r,s,i,e)}case"spki":{const e=Mb.fromBufferSource(t,"PUBLIC KEY");return new lv(r,s,i,e)}case"raw":{const e=t,n=iI().createPublicKey({format:"jwk",key:{kty:"OKP",crv:"ed25519"===r.name.toLowerCase()?"Ed25519":"X25519",x:Yp.ToBase64Url(e)}}).export({format:"pem",type:"spki"});return new lv(r,s,i,n)}default:return Promise.reject(new Nb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}}hv.privateKeyUsages=["sign","deriveBits","deriveKey"],hv.publicKeyUsages=["verify"];class uv extends $A{async onGenerateKey(e,t,r){const s=await hv.generateKey(e,t,r);return{privateKey:fI(s.privateKey),publicKey:fI(s.publicKey)}}async onSign(e,t,r){const s=dI(t);return hv.sign(e,s,new Uint8Array(r))}onVerify(e,t,r,s){const i=dI(t);return hv.verify(e,i,new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){const r=dI(t);return hv.exportKey(e,r)}async onImportKey(e,t,r,s,i){return fI(await hv.importKey(e,t,r,s,i))}}class dv extends FA{async onGenerateKey(e,t,r){const s=await hv.generateKey(e,t,r);return{privateKey:fI(s.privateKey),publicKey:fI(s.publicKey)}}async onDeriveBits(e,t,r){const s=dI(t),i=dI(e.public),n=iI().createPublicKey({key:i.data.toString(),format:"pem",type:"spki"}),o=iI().createPrivateKey({key:s.data.toString(),format:"pem",type:"pkcs8"}),a=iI().diffieHellman({publicKey:n,privateKey:o});return new Uint8Array(a).buffer.slice(0,r>>3)}async onExportKey(e,t){const r=dI(t);return hv.exportKey(e,r)}async onImportKey(e,t,r,s,i){return fI(await hv.importKey(e,t,r,s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(dI(e)instanceof av))throw new TypeError("key: Is not a Ed25519CryptoKey")}}class fv extends oI{}class pv extends GA{async onDeriveBits(e,t,r){return new Promise((s,i)=>{const n=$p.toArrayBuffer(e.salt),o=e.hash.name.replace("-","");iI().pbkdf2(dI(t).data,rI.Buffer.from(n),e.iterations,r>>3,o,(e,t)=>{e?i(e):s(new Uint8Array(t).buffer)})})}async onImportKey(e,t,r,s,i){if("raw"===e){const e=new fv;return e.data=rI.Buffer.from(t),e.algorithm={name:this.name},e.extractable=!1,e.usages=i,fI(e)}throw new Nb("format: Must be 'raw'")}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(dI(e)instanceof fv))throw new TypeError("key: Is not PBKDF CryptoKey")}}class gv extends oI{get alg(){return`HS${this.algorithm.hash.name.toUpperCase().replace("SHA-","")}`}set alg(e){}}hb([Rb({name:"k",converter:nI})],gv.prototype,"data",void 0);class yv extends jA{async onGenerateKey(e,t,r){const s=(e.length||this.getDefaultLength(e.hash.name))>>3<<3,i=new gv;return i.algorithm={...e,length:s,name:this.name},i.extractable=t,i.usages=r,i.data=iI().randomBytes(s>>3),fI(i)}async onSign(e,t,r){const s=PI.getAlgorithmName(t.algorithm.hash),i=iI().createHmac(s,dI(t).data).update(rI.Buffer.from(r)).digest();return new Uint8Array(i).buffer}async onVerify(e,t,r,s){const i=PI.getAlgorithmName(t.algorithm.hash);return 0===iI().createHmac(i,dI(t).data).update(rI.Buffer.from(s)).digest().compare(rI.Buffer.from(r))}async onImportKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Bb.fromJSON(t,{targetSchema:gv});break;case"raw":n=new gv,n.data=rI.Buffer.from(t);break;default:throw new Nb("format: Must be 'jwk' or 'raw'")}return n.algorithm={hash:{name:r.hash.name},name:this.name,length:n.data.length<<3},n.extractable=s,n.usages=i,fI(n)}async onExportKey(e,t){switch(e.toLowerCase()){case"jwk":return _b.toJSON(dI(t));case"raw":return new Uint8Array(dI(t).data).buffer;default:throw new Nb("format: Must be 'jwk' or 'raw'")}}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(dI(e)instanceof gv))throw new TypeError("key: Is not HMAC CryptoKey")}}class mv extends oI{}class bv extends qA{async onImportKey(e,t,r,s,i){if("raw"!==e.toLowerCase())throw new Nb("Operation not supported");const n=new mv;return n.data=rI.Buffer.from(t),n.algorithm={name:this.name},n.extractable=s,n.usages=i,fI(n)}async onDeriveBits(e,t,r){const s=e.hash.name.replace("-",""),i=iI().createHash(s).digest().length,n=r/8,o=$p.toUint8Array(e.info),a=iI().createHmac(s,$p.toUint8Array(e.salt)).update($p.toUint8Array(dI(t).data)).digest(),c=[rI.Buffer.alloc(0)],l=Math.ceil(n/i)+1;for(let e=1;e<l;++e)c.push(iI().createHmac(s,a).update(rI.Buffer.concat([c[e-1],o,rI.Buffer.from([e])])).digest());return rI.Buffer.concat(c).slice(0,n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(dI(e)instanceof mv))throw new TypeError("key: Is not HKDF CryptoKey")}}class Av{static digest(e,t){const r=iI().createHash(e.name.toLowerCase(),{outputLength:e.length}).update(rI.Buffer.from(t)).digest();return new Uint8Array(r).buffer}}class Iv extends WA{async onDigest(e,t){return Av.digest(e,t)}}class vv extends JA{async onDigest(e,t){return Av.digest(e,t)}}class wv extends tI{constructor(){var e;super(),this.providers.set(new pI),this.providers.set(new SI),this.providers.set(new EI),this.providers.set(new wI),this.providers.set(new CI),this.providers.set(new kI),iI().getCiphers().includes("des-cbc")&&this.providers.set(new BI),this.providers.set(new RI),this.providers.set(new DI),this.providers.set(new MI),this.providers.set(new LI),this.providers.set(new HI),this.providers.set(new XI),this.providers.set(new ZI),this.providers.set(new $I),this.providers.set(new jI),this.providers.set(new GI),this.providers.set(new qI),this.providers.set(new pv),this.providers.set(new yv),this.providers.set(new bv);const t=null===(e=/^v(\d+)/.exec(md.version))||void 0===e?void 0:e[1];t&&parseInt(t,10)>=12&&(this.providers.set(new Iv),this.providers.set(new vv));const r=iI().getHashes();r.includes("sha3-256")&&this.providers.set(new zI),r.includes("sha3-384")&&this.providers.set(new WI),r.includes("sha3-512")&&this.providers.set(new JI),t&&parseInt(t,10)>=14&&(this.providers.set(new nv),this.providers.set(new ov),this.providers.set(new uv),this.providers.set(new dv))}}var Sv,Ev,Cv;o(909);class kv{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){const t=e.split(".");if(4!==t.length)throw new Error("Invalid IPv4 address");return t.map(e=>{const t=parseInt(e,10);if(isNaN(t)||t<0||t>255)throw new Error("Invalid IPv4 address part");return t})}static parseIPv6(e){const t=this.expandIPv6(e).split(":");if(8!==t.length)throw new Error("Invalid IPv6 address");return t.reduce((e,t)=>{const r=parseInt(t,16);if(isNaN(r)||r<0||r>65535)throw new Error("Invalid IPv6 address part");return e.push(r>>8&255),e.push(255&r),e},[])}static expandIPv6(e){if(!e.includes("::"))return e;const t=e.split("::");if(t.length>2)throw new Error("Invalid IPv6 address");const r=t[0]?t[0].split(":"):[],s=t[1]?t[1].split(":"):[],i=8-(r.length+s.length);if(i<0)throw new Error("Invalid IPv6 address");return[...r,...Array(i).fill("0"),...s].join(":")}static formatIPv6(e){const t=[];for(let r=0;r<16;r+=2)t.push((e[r]<<8|e[r+1]).toString(16));return this.compressIPv6(t.join(":"))}static compressIPv6(e){const t=e.split(":");let r=-1,s=0,i=-1,n=0;for(let e=0;e<t.length;e++)"0"===t[e]?(-1===i&&(i=e),n++):(n>s&&(r=i,s=n),i=-1,n=0);return n>s&&(r=i,s=n),s>1?`${t.slice(0,r).join(":")}::${t.slice(r+s).join(":")}`:e}static parseCIDR(e){const[t,r]=e.split("/"),s=parseInt(r,10);if(this.isIPv4(t)){if(s<0||s>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(t),s]}if(s<0||s>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(t),s]}static decodeIP(e){if(64===e.length&&0===parseInt(e,16))return"::/0";if(16!==e.length)return e;const t=parseInt(e.slice(8),16).toString(2).split("").reduce((e,t)=>e+ +t,0);let r=e.slice(0,8).replace(/(.{2})/g,e=>`${parseInt(e,16)}.`);return r=r.slice(0,-1),`${r}/${t}`}static toString(e){const t=new Uint8Array(e);if(4===t.length)return Array.from(t).join(".");if(16===t.length)return this.formatIPv6(t);if(8===t.length||32===t.length){const e=t.length/2,r=t.slice(0,e),s=t.slice(e);if(t.every(e=>0===e))return 8===t.length?"0.0.0.0/0":"::/0";const i=s.reduce((e,t)=>e+(t.toString(2).match(/1/g)||[]).length,0);return 8===t.length?`${Array.from(r).join(".")}/${i}`:`${this.formatIPv6(r)}/${i}`}return this.decodeIP(Yp.ToHex(e))}static fromString(e){if(e.includes("/")){const[t,r]=this.parseCIDR(e),s=new Uint8Array(t.length);let i=r;for(let e=0;e<s.length;e++)i>=8?(s[e]=255,i-=8):i>0&&(s[e]=255<<8-i,i=0);const n=new Uint8Array(2*t.length);return n.set(t,0),n.set(s,t.length),n.buffer}const t=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(t).buffer}}let xv=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};hb([ib({type:my.TeletexString})],xv.prototype,"teletexString",void 0),hb([ib({type:my.PrintableString})],xv.prototype,"printableString",void 0),hb([ib({type:my.UniversalString})],xv.prototype,"universalString",void 0),hb([ib({type:my.Utf8String})],xv.prototype,"utf8String",void 0),hb([ib({type:my.BmpString})],xv.prototype,"bmpString",void 0),xv=hb([sb({type:yy.Choice})],xv);let _v=class extends xv{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Yp.ToHex(this.anyValue):super.toString())}};hb([ib({type:my.IA5String})],_v.prototype,"ia5String",void 0),hb([ib({type:my.Any})],_v.prototype,"anyValue",void 0),_v=hb([sb({type:yy.Choice})],_v);class Bv{constructor(e={}){this.type="",this.value=new _v,Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],Bv.prototype,"type",void 0),hb([ib({type:_v})],Bv.prototype,"value",void 0);let Rv=Sv=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,Sv.prototype)}};Rv=Sv=hb([sb({type:yy.Set,itemType:Bv})],Rv);let Ov=Ev=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,Ev.prototype)}};Ov=Ev=hb([sb({type:yy.Sequence,itemType:Rv})],Ov);let Uv=Cv=class extends Ov{constructor(e){super(e),Object.setPrototypeOf(this,Cv.prototype)}};Uv=Cv=hb([sb({type:yy.Sequence})],Uv);const Tv={fromASN:e=>kv.toString(Nm.fromASN(e)),toASN:e=>Nm.toASN(kv.fromString(e))};class Nv{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],Nv.prototype,"typeId",void 0),hb([ib({type:my.Any,context:0})],Nv.prototype,"value",void 0);class Dv{constructor(e={}){this.partyName=new xv,Object.assign(this,e)}}hb([ib({type:xv,optional:!0,context:0,implicit:!0})],Dv.prototype,"nameAssigner",void 0),hb([ib({type:xv,context:1,implicit:!0})],Dv.prototype,"partyName",void 0);let Mv=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:Nv,context:0,implicit:!0})],Mv.prototype,"otherName",void 0),hb([ib({type:my.IA5String,context:1,implicit:!0})],Mv.prototype,"rfc822Name",void 0),hb([ib({type:my.IA5String,context:2,implicit:!0})],Mv.prototype,"dNSName",void 0),hb([ib({type:my.Any,context:3,implicit:!0})],Mv.prototype,"x400Address",void 0),hb([ib({type:Uv,context:4,implicit:!1})],Mv.prototype,"directoryName",void 0),hb([ib({type:Dv,context:5})],Mv.prototype,"ediPartyName",void 0),hb([ib({type:my.IA5String,context:6,implicit:!0})],Mv.prototype,"uniformResourceIdentifier",void 0),hb([ib({type:my.OctetString,context:7,implicit:!0,converter:Tv})],Mv.prototype,"iPAddress",void 0),hb([ib({type:my.ObjectIdentifier,context:8,implicit:!0})],Mv.prototype,"registeredID",void 0),Mv=hb([sb({type:yy.Choice})],Mv);const Pv="1.3.6.1.5.5.7",Lv=`${Pv}.3`,Hv=`${Pv}.48`,Kv=`${Hv}.1`,Qv=`${Hv}.2`,Vv=`${Hv}.3`,Fv=`${Hv}.5`,$v="2.5.29";var jv;const Gv=`${Pv}.1.1`;class qv{constructor(e={}){this.accessMethod="",this.accessLocation=new Mv,Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],qv.prototype,"accessMethod",void 0),hb([ib({type:Mv})],qv.prototype,"accessLocation",void 0);let zv=jv=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,jv.prototype)}};zv=jv=hb([sb({type:yy.Sequence,itemType:qv})],zv);const Wv=`${$v}.35`;class Jv extends km{}class Yv{constructor(e={}){e&&Object.assign(this,e)}}hb([ib({type:Jv,context:0,optional:!0,implicit:!0})],Yv.prototype,"keyIdentifier",void 0),hb([ib({type:Mv,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Yv.prototype,"authorityCertIssuer",void 0),hb([ib({type:my.Integer,context:2,optional:!0,implicit:!0,converter:Rm})],Yv.prototype,"authorityCertSerialNumber",void 0);const Xv=`${$v}.19`;class Zv{constructor(e={}){this.cA=!1,Object.assign(this,e)}}var ew;hb([ib({type:my.Boolean,defaultValue:!1})],Zv.prototype,"cA",void 0),hb([ib({type:my.Integer,optional:!0})],Zv.prototype,"pathLenConstraint",void 0);let tw=ew=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,ew.prototype)}};var rw;tw=ew=hb([sb({type:yy.Sequence,itemType:Mv})],tw);let sw=rw=class extends tw{constructor(e){super(e),Object.setPrototypeOf(this,rw.prototype)}};var iw;sw=rw=hb([sb({type:yy.Sequence})],sw);const nw=`${$v}.32`;let ow=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};hb([ib({type:my.IA5String})],ow.prototype,"ia5String",void 0),hb([ib({type:my.VisibleString})],ow.prototype,"visibleString",void 0),hb([ib({type:my.BmpString})],ow.prototype,"bmpString",void 0),hb([ib({type:my.Utf8String})],ow.prototype,"utf8String",void 0),ow=hb([sb({type:yy.Choice})],ow);class aw{constructor(e={}){this.organization=new ow,this.noticeNumbers=[],Object.assign(this,e)}}hb([ib({type:ow})],aw.prototype,"organization",void 0),hb([ib({type:my.Integer,repeated:"sequence"})],aw.prototype,"noticeNumbers",void 0);class cw{constructor(e={}){Object.assign(this,e)}}hb([ib({type:aw,optional:!0})],cw.prototype,"noticeRef",void 0),hb([ib({type:ow,optional:!0})],cw.prototype,"explicitText",void 0);let lw=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:my.IA5String})],lw.prototype,"cPSuri",void 0),hb([ib({type:cw})],lw.prototype,"userNotice",void 0),lw=hb([sb({type:yy.Choice})],lw);class hw{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],hw.prototype,"policyQualifierId",void 0),hb([ib({type:my.Any})],hw.prototype,"qualifier",void 0);class uw{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],uw.prototype,"policyIdentifier",void 0),hb([ib({type:hw,repeated:"sequence",optional:!0})],uw.prototype,"policyQualifiers",void 0);let dw=iw=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,iw.prototype)}};dw=iw=hb([sb({type:yy.Sequence,itemType:uw})],dw);let fw=class{constructor(e=0){this.value=e}};hb([ib({type:my.Integer})],fw.prototype,"value",void 0),fw=hb([sb({type:yy.Choice})],fw);let pw=class extends fw{};var gw;pw=hb([sb({type:yy.Choice})],pw);const yw=`${$v}.31`;var mw;!function(e){e[e.unused=1]="unused",e[e.keyCompromise=2]="keyCompromise",e[e.cACompromise=4]="cACompromise",e[e.affiliationChanged=8]="affiliationChanged",e[e.superseded=16]="superseded",e[e.cessationOfOperation=32]="cessationOfOperation",e[e.certificateHold=64]="certificateHold",e[e.privilegeWithdrawn=128]="privilegeWithdrawn",e[e.aACompromise=256]="aACompromise"}(mw||(mw={}));class bw extends Cm{toJSON(){const e=[],t=this.toNumber();return t&mw.aACompromise&&e.push("aACompromise"),t&mw.affiliationChanged&&e.push("affiliationChanged"),t&mw.cACompromise&&e.push("cACompromise"),t&mw.certificateHold&&e.push("certificateHold"),t&mw.cessationOfOperation&&e.push("cessationOfOperation"),t&mw.keyCompromise&&e.push("keyCompromise"),t&mw.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&mw.superseded&&e.push("superseded"),t&mw.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let Aw=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:Mv,context:0,repeated:"sequence",implicit:!0})],Aw.prototype,"fullName",void 0),hb([ib({type:Rv,context:1,implicit:!0})],Aw.prototype,"nameRelativeToCRLIssuer",void 0),Aw=hb([sb({type:yy.Choice})],Aw);class Iw{constructor(e={}){Object.assign(this,e)}}hb([ib({type:Aw,context:0,optional:!0})],Iw.prototype,"distributionPoint",void 0),hb([ib({type:bw,context:1,optional:!0,implicit:!0})],Iw.prototype,"reasons",void 0),hb([ib({type:Mv,context:2,optional:!0,repeated:"sequence",implicit:!0})],Iw.prototype,"cRLIssuer",void 0);let vw=gw=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,gw.prototype)}};var ww;vw=gw=hb([sb({type:yy.Sequence,itemType:Iw})],vw);let Sw=ww=class extends vw{constructor(e){super(e),Object.setPrototypeOf(this,ww.prototype)}};Sw=ww=hb([sb({type:yy.Sequence,itemType:Iw})],Sw);class Ew{constructor(e={}){this.onlyContainsUserCerts=Ew.ONLY,this.onlyContainsCACerts=Ew.ONLY,this.indirectCRL=Ew.ONLY,this.onlyContainsAttributeCerts=Ew.ONLY,Object.assign(this,e)}}var Cw;Ew.ONLY=!1,hb([ib({type:Aw,context:0,optional:!0})],Ew.prototype,"distributionPoint",void 0),hb([ib({type:my.Boolean,context:1,defaultValue:Ew.ONLY,implicit:!0})],Ew.prototype,"onlyContainsUserCerts",void 0),hb([ib({type:my.Boolean,context:2,defaultValue:Ew.ONLY,implicit:!0})],Ew.prototype,"onlyContainsCACerts",void 0),hb([ib({type:bw,context:3,optional:!0,implicit:!0})],Ew.prototype,"onlySomeReasons",void 0),hb([ib({type:my.Boolean,context:4,defaultValue:Ew.ONLY,implicit:!0})],Ew.prototype,"indirectCRL",void 0),hb([ib({type:my.Boolean,context:5,defaultValue:Ew.ONLY,implicit:!0})],Ew.prototype,"onlyContainsAttributeCerts",void 0),function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(Cw||(Cw={}));let kw=class{constructor(e=Cw.unspecified){this.reason=Cw.unspecified,this.reason=e}toJSON(){return Cw[this.reason]}toString(){return this.toJSON()}};var xw;hb([ib({type:my.Enumerated})],kw.prototype,"reason",void 0),kw=hb([sb({type:yy.Choice})],kw);const _w=`${$v}.37`;let Bw=xw=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,xw.prototype)}};Bw=xw=hb([sb({type:yy.Sequence,itemType:my.ObjectIdentifier})],Bw);const Rw=`${Lv}.1`,Ow=`${Lv}.2`,Uw=`${Lv}.3`,Tw=`${Lv}.4`,Nw=`${Lv}.8`,Dw=`${Lv}.9`;let Mw=class{constructor(e=new ArrayBuffer(0)){this.value=e}};hb([ib({type:my.Integer,converter:Rm})],Mw.prototype,"value",void 0),Mw=hb([sb({type:yy.Choice})],Mw);let Pw=class{constructor(e){this.value=new Date,e&&(this.value=e)}};var Lw;hb([ib({type:my.GeneralizedTime})],Pw.prototype,"value",void 0),Pw=hb([sb({type:yy.Choice})],Pw);let Hw=Lw=class extends tw{constructor(e){super(e),Object.setPrototypeOf(this,Lw.prototype)}};Hw=Lw=hb([sb({type:yy.Sequence})],Hw);const Kw=`${$v}.15`;var Qw,Vw;!function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(Qw||(Qw={}));class Fw extends Cm{toJSON(){const e=this.toNumber(),t=[];return e&Qw.cRLSign&&t.push("crlSign"),e&Qw.dataEncipherment&&t.push("dataEncipherment"),e&Qw.decipherOnly&&t.push("decipherOnly"),e&Qw.digitalSignature&&t.push("digitalSignature"),e&Qw.encipherOnly&&t.push("encipherOnly"),e&Qw.keyAgreement&&t.push("keyAgreement"),e&Qw.keyCertSign&&t.push("keyCertSign"),e&Qw.keyEncipherment&&t.push("keyEncipherment"),e&Qw.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}}class $w{constructor(e={}){this.base=new Mv,this.minimum=0,Object.assign(this,e)}}hb([ib({type:Mv})],$w.prototype,"base",void 0),hb([ib({type:my.Integer,context:0,defaultValue:0,implicit:!0})],$w.prototype,"minimum",void 0),hb([ib({type:my.Integer,context:1,optional:!0,implicit:!0})],$w.prototype,"maximum",void 0);let jw=Vw=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,Vw.prototype)}};jw=Vw=hb([sb({type:yy.Sequence,itemType:$w})],jw);class Gw{constructor(e={}){Object.assign(this,e)}}hb([ib({type:jw,context:0,optional:!0,implicit:!0})],Gw.prototype,"permittedSubtrees",void 0),hb([ib({type:jw,context:1,optional:!0,implicit:!0})],Gw.prototype,"excludedSubtrees",void 0);class qw{constructor(e={}){Object.assign(this,e)}}var zw;hb([ib({type:my.Integer,context:0,implicit:!0,optional:!0,converter:Rm})],qw.prototype,"requireExplicitPolicy",void 0),hb([ib({type:my.Integer,context:1,implicit:!0,optional:!0,converter:Rm})],qw.prototype,"inhibitPolicyMapping",void 0);class Ww{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],Ww.prototype,"issuerDomainPolicy",void 0),hb([ib({type:my.ObjectIdentifier})],Ww.prototype,"subjectDomainPolicy",void 0);let Jw=zw=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,zw.prototype)}};var Yw;Jw=zw=hb([sb({type:yy.Sequence,itemType:Ww})],Jw);const Xw=`${$v}.17`;let Zw=Yw=class extends tw{constructor(e){super(e),Object.setPrototypeOf(this,Yw.prototype)}};Zw=Yw=hb([sb({type:yy.Sequence})],Zw);class eS{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}}var tS;hb([ib({type:my.ObjectIdentifier})],eS.prototype,"type",void 0),hb([ib({type:my.Any,repeated:"set"})],eS.prototype,"values",void 0);let rS=tS=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,tS.prototype)}};rS=tS=hb([sb({type:yy.Sequence,itemType:eS})],rS);const sS=`${$v}.14`;class iS extends Jv{}class nS{constructor(e={}){Object.assign(this,e)}}var oS,aS;hb([ib({type:my.GeneralizedTime,context:0,implicit:!0,optional:!0})],nS.prototype,"notBefore",void 0),hb([ib({type:my.GeneralizedTime,context:1,implicit:!0,optional:!0})],nS.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(oS||(oS={}));class cS extends Cm{toJSON(){const e=[],t=this.toNumber();return t&oS.pKIXCertificate&&e.push("pKIXCertificate"),t&oS.newExtensions&&e.push("newExtensions"),t&oS.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class lS{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new cS,Object.assign(this,e)}}hb([ib({type:my.GeneralString})],lS.prototype,"entrustVers",void 0),hb([ib({type:cS})],lS.prototype,"entrustInfoFlags",void 0);let hS=aS=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,aS.prototype)}};hS=aS=hb([sb({type:yy.Sequence,itemType:qv})],hS);class uS{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof uS&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Zp(e.parameters,this.parameters)||e.parameters===this.parameters)}}hb([ib({type:my.ObjectIdentifier})],uS.prototype,"algorithm",void 0),hb([ib({type:my.Any,optional:!0})],uS.prototype,"parameters",void 0);class dS{constructor(e={}){this.algorithm=new uS,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:uS})],dS.prototype,"algorithm",void 0),hb([ib({type:my.BitString})],dS.prototype,"subjectPublicKey",void 0);let fS=class{constructor(e){if(e)if("string"==typeof e||"number"==typeof e||e instanceof Date){const t=new Date(e);t.getUTCFullYear()>2049?this.generalTime=t:this.utcTime=t}else Object.assign(this,e)}getTime(){const e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};hb([ib({type:my.UTCTime})],fS.prototype,"utcTime",void 0),hb([ib({type:my.GeneralizedTime})],fS.prototype,"generalTime",void 0),fS=hb([sb({type:yy.Choice})],fS);class pS{constructor(e){this.notBefore=new fS(new Date),this.notAfter=new fS(new Date),e&&(this.notBefore=new fS(e.notBefore),this.notAfter=new fS(e.notAfter))}}var gS;hb([ib({type:fS})],pS.prototype,"notBefore",void 0),hb([ib({type:fS})],pS.prototype,"notAfter",void 0);class yS{constructor(e={}){this.extnID="",this.critical=yS.CRITICAL,this.extnValue=new km,Object.assign(this,e)}}yS.CRITICAL=!1,hb([ib({type:my.ObjectIdentifier})],yS.prototype,"extnID",void 0),hb([ib({type:my.Boolean,defaultValue:yS.CRITICAL})],yS.prototype,"critical",void 0),hb([ib({type:km})],yS.prototype,"extnValue",void 0);let mS=gS=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,gS.prototype)}};var bS;mS=gS=hb([sb({type:yy.Sequence,itemType:yS})],mS),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(bS||(bS={}));class AS{constructor(e={}){this.version=bS.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new uS,this.issuer=new Uv,this.validity=new pS,this.subject=new Uv,this.subjectPublicKeyInfo=new dS,Object.assign(this,e)}}hb([ib({type:my.Integer,context:0,defaultValue:bS.v1})],AS.prototype,"version",void 0),hb([ib({type:my.Integer,converter:Rm})],AS.prototype,"serialNumber",void 0),hb([ib({type:uS})],AS.prototype,"signature",void 0),hb([ib({type:Uv})],AS.prototype,"issuer",void 0),hb([ib({type:pS})],AS.prototype,"validity",void 0),hb([ib({type:Uv})],AS.prototype,"subject",void 0),hb([ib({type:dS})],AS.prototype,"subjectPublicKeyInfo",void 0),hb([ib({type:my.BitString,context:1,implicit:!0,optional:!0})],AS.prototype,"issuerUniqueID",void 0),hb([ib({type:my.BitString,context:2,implicit:!0,optional:!0})],AS.prototype,"subjectUniqueID",void 0),hb([ib({type:mS,context:3,optional:!0})],AS.prototype,"extensions",void 0);class IS{constructor(e={}){this.tbsCertificate=new AS,this.signatureAlgorithm=new uS,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:AS})],IS.prototype,"tbsCertificate",void 0),hb([ib({type:uS})],IS.prototype,"signatureAlgorithm",void 0),hb([ib({type:my.BitString})],IS.prototype,"signatureValue",void 0);class vS{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new fS,Object.assign(this,e)}}hb([ib({type:my.Integer,converter:Rm})],vS.prototype,"userCertificate",void 0),hb([ib({type:fS})],vS.prototype,"revocationDate",void 0),hb([ib({type:yS,optional:!0,repeated:"sequence"})],vS.prototype,"crlEntryExtensions",void 0);class wS{constructor(e={}){this.signature=new uS,this.issuer=new Uv,this.thisUpdate=new fS,Object.assign(this,e)}}hb([ib({type:my.Integer,optional:!0})],wS.prototype,"version",void 0),hb([ib({type:uS})],wS.prototype,"signature",void 0),hb([ib({type:Uv})],wS.prototype,"issuer",void 0),hb([ib({type:fS})],wS.prototype,"thisUpdate",void 0),hb([ib({type:fS,optional:!0})],wS.prototype,"nextUpdate",void 0),hb([ib({type:vS,repeated:"sequence",optional:!0})],wS.prototype,"revokedCertificates",void 0),hb([ib({type:yS,optional:!0,context:0,repeated:"sequence"})],wS.prototype,"crlExtensions",void 0);class SS{constructor(e={}){this.tbsCertList=new wS,this.signatureAlgorithm=new uS,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:wS})],SS.prototype,"tbsCertList",void 0),hb([ib({type:uS})],SS.prototype,"signatureAlgorithm",void 0),hb([ib({type:my.BitString})],SS.prototype,"signature",void 0);class ES{constructor(e={}){this.issuer=new Uv,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:Uv})],ES.prototype,"issuer",void 0),hb([ib({type:my.Integer,converter:Rm})],ES.prototype,"serialNumber",void 0);let CS=class{constructor(e={}){Object.assign(this,e)}};var kS;hb([ib({type:iS,context:0,implicit:!0})],CS.prototype,"subjectKeyIdentifier",void 0),hb([ib({type:ES})],CS.prototype,"issuerAndSerialNumber",void 0),CS=hb([sb({type:yy.Choice})],CS),function(e){e[e.v0=0]="v0",e[e.v1=1]="v1",e[e.v2=2]="v2",e[e.v3=3]="v3",e[e.v4=4]="v4",e[e.v5=5]="v5"}(kS||(kS={}));let xS=class extends uS{};xS=hb([sb({type:yy.Sequence})],xS);let _S=class extends uS{};_S=hb([sb({type:yy.Sequence})],_S);let BS=class extends uS{};BS=hb([sb({type:yy.Sequence})],BS);let RS=class extends uS{};RS=hb([sb({type:yy.Sequence})],RS);let OS=class extends uS{};OS=hb([sb({type:yy.Sequence})],OS);let US=class extends uS{};US=hb([sb({type:yy.Sequence})],US);class TS{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}}var NS;hb([ib({type:my.ObjectIdentifier})],TS.prototype,"attrType",void 0),hb([ib({type:my.Any,repeated:"set"})],TS.prototype,"attrValues",void 0);class DS{constructor(e={}){this.version=kS.v0,this.sid=new CS,this.digestAlgorithm=new xS,this.signatureAlgorithm=new _S,this.signature=new km,Object.assign(this,e)}}hb([ib({type:my.Integer})],DS.prototype,"version",void 0),hb([ib({type:CS})],DS.prototype,"sid",void 0),hb([ib({type:xS})],DS.prototype,"digestAlgorithm",void 0),hb([ib({type:TS,repeated:"set",context:0,implicit:!0,optional:!0})],DS.prototype,"signedAttrs",void 0),hb([ib({type:_S})],DS.prototype,"signatureAlgorithm",void 0),hb([ib({type:km})],DS.prototype,"signature",void 0),hb([ib({type:TS,repeated:"set",context:1,implicit:!0,optional:!0})],DS.prototype,"unsignedAttrs",void 0);let MS=NS=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,NS.prototype)}};MS=NS=hb([sb({type:yy.Set,itemType:DS})],MS);let PS=class extends fS{};PS=hb([sb({type:yy.Choice})],PS);let LS=class extends DS{};LS=hb([sb({type:yy.Sequence})],LS);class HS{constructor(e={}){this.acIssuer=new Mv,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}var KS;hb([ib({type:Mv})],HS.prototype,"acIssuer",void 0),hb([ib({type:my.Integer})],HS.prototype,"acSerial",void 0),hb([ib({type:eS,repeated:"sequence"})],HS.prototype,"attrs",void 0);let QS=KS=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,KS.prototype)}};QS=KS=hb([sb({type:yy.Sequence,itemType:my.ObjectIdentifier})],QS);class VS{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}}hb([ib({type:my.Integer,optional:!0})],VS.prototype,"pathLenConstraint",void 0),hb([ib({type:QS,implicit:!0,context:0,optional:!0})],VS.prototype,"permittedAttrs",void 0),hb([ib({type:QS,implicit:!0,context:1,optional:!0})],VS.prototype,"excludedAttrs",void 0),hb([ib({type:my.Boolean,defaultValue:!0})],VS.prototype,"permitUnSpecified",void 0);class FS{constructor(e={}){this.issuer=new tw,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}var $S;hb([ib({type:tw})],FS.prototype,"issuer",void 0),hb([ib({type:my.Integer,converter:Rm})],FS.prototype,"serial",void 0),hb([ib({type:my.BitString,optional:!0})],FS.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}($S||($S={}));class jS{constructor(e={}){this.digestedObjectType=$S.publicKey,this.digestAlgorithm=new uS,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.Enumerated})],jS.prototype,"digestedObjectType",void 0),hb([ib({type:my.ObjectIdentifier,optional:!0})],jS.prototype,"otherObjectTypeID",void 0),hb([ib({type:uS})],jS.prototype,"digestAlgorithm",void 0),hb([ib({type:my.BitString})],jS.prototype,"objectDigest",void 0);class GS{constructor(e={}){Object.assign(this,e)}}hb([ib({type:tw,optional:!0})],GS.prototype,"issuerName",void 0),hb([ib({type:FS,context:0,implicit:!0,optional:!0})],GS.prototype,"baseCertificateID",void 0),hb([ib({type:jS,context:1,implicit:!0,optional:!0})],GS.prototype,"objectDigestInfo",void 0);let qS=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:Mv,repeated:"sequence"})],qS.prototype,"v1Form",void 0),hb([ib({type:GS,context:0,implicit:!0})],qS.prototype,"v2Form",void 0),qS=hb([sb({type:yy.Choice})],qS);class zS{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}hb([ib({type:my.GeneralizedTime})],zS.prototype,"notBeforeTime",void 0),hb([ib({type:my.GeneralizedTime})],zS.prototype,"notAfterTime",void 0);class WS{constructor(e={}){Object.assign(this,e)}}var JS,YS,XS;hb([ib({type:FS,implicit:!0,context:0,optional:!0})],WS.prototype,"baseCertificateID",void 0),hb([ib({type:tw,implicit:!0,context:1,optional:!0})],WS.prototype,"entityName",void 0),hb([ib({type:jS,implicit:!0,context:2,optional:!0})],WS.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(JS||(JS={}));class ZS{constructor(e={}){this.version=JS.v2,this.holder=new WS,this.issuer=new qS,this.signature=new uS,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new zS,this.attributes=[],Object.assign(this,e)}}hb([ib({type:my.Integer})],ZS.prototype,"version",void 0),hb([ib({type:WS})],ZS.prototype,"holder",void 0),hb([ib({type:qS})],ZS.prototype,"issuer",void 0),hb([ib({type:uS})],ZS.prototype,"signature",void 0),hb([ib({type:my.Integer,converter:Rm})],ZS.prototype,"serialNumber",void 0),hb([ib({type:zS})],ZS.prototype,"attrCertValidityPeriod",void 0),hb([ib({type:eS,repeated:"sequence"})],ZS.prototype,"attributes",void 0),hb([ib({type:my.BitString,optional:!0})],ZS.prototype,"issuerUniqueID",void 0),hb([ib({type:mS,optional:!0})],ZS.prototype,"extensions",void 0);class eE{constructor(e={}){this.acinfo=new ZS,this.signatureAlgorithm=new uS,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:ZS})],eE.prototype,"acinfo",void 0),hb([ib({type:uS})],eE.prototype,"signatureAlgorithm",void 0),hb([ib({type:my.BitString})],eE.prototype,"signatureValue",void 0),function(e){e[e.unmarked=1]="unmarked",e[e.unclassified=2]="unclassified",e[e.restricted=4]="restricted",e[e.confidential=8]="confidential",e[e.secret=16]="secret",e[e.topSecret=32]="topSecret"}(YS||(YS={}));class tE extends Cm{}class rE{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier,implicit:!0,context:0})],rE.prototype,"type",void 0),hb([ib({type:my.Any,implicit:!0,context:1})],rE.prototype,"value",void 0);class sE{constructor(e={}){this.policyId="",this.classList=new tE(YS.unclassified),Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],sE.prototype,"policyId",void 0),hb([ib({type:tE,defaultValue:new tE(YS.unclassified)})],sE.prototype,"classList",void 0),hb([ib({type:rE,repeated:"set"})],sE.prototype,"securityCategories",void 0);class iE{constructor(e={}){Object.assign(this,e)}}hb([ib({type:km})],iE.prototype,"cotets",void 0),hb([ib({type:my.ObjectIdentifier})],iE.prototype,"oid",void 0),hb([ib({type:my.Utf8String})],iE.prototype,"string",void 0);class nE{constructor(e={}){this.values=[],Object.assign(this,e)}}hb([ib({type:tw,implicit:!0,context:0,optional:!0})],nE.prototype,"policyAuthority",void 0),hb([ib({type:iE,repeated:"sequence"})],nE.prototype,"values",void 0);class oE{constructor(e={}){this.targetCertificate=new FS,Object.assign(this,e)}}hb([ib({type:FS})],oE.prototype,"targetCertificate",void 0),hb([ib({type:Mv,optional:!0})],oE.prototype,"targetName",void 0),hb([ib({type:jS,optional:!0})],oE.prototype,"certDigestInfo",void 0);let aE=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:Mv,context:0,implicit:!0})],aE.prototype,"targetName",void 0),hb([ib({type:Mv,context:1,implicit:!0})],aE.prototype,"targetGroup",void 0),hb([ib({type:oE,context:2,implicit:!0})],aE.prototype,"targetCert",void 0),aE=hb([sb({type:yy.Choice})],aE);let cE=XS=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,XS.prototype)}};var lE;cE=XS=hb([sb({type:yy.Sequence,itemType:aE})],cE);let hE=lE=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,lE.prototype)}};hE=lE=hb([sb({type:yy.Sequence,itemType:cE})],hE);class uE{constructor(e={}){Object.assign(this,e)}}hb([ib({type:tw,implicit:!0,context:0,optional:!0})],uE.prototype,"roleAuthority",void 0),hb([ib({type:Mv,implicit:!0,context:1})],uE.prototype,"roleName",void 0);class dE{constructor(e={}){this.service=new Mv,this.ident=new Mv,Object.assign(this,e)}}var fE;hb([ib({type:Mv})],dE.prototype,"service",void 0),hb([ib({type:Mv})],dE.prototype,"ident",void 0),hb([ib({type:km,optional:!0})],dE.prototype,"authInfo",void 0);class pE{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],pE.prototype,"otherCertFormat",void 0),hb([ib({type:my.Any})],pE.prototype,"otherCert",void 0);let gE=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:IS})],gE.prototype,"certificate",void 0),hb([ib({type:eE,context:2,implicit:!0})],gE.prototype,"v2AttrCert",void 0),hb([ib({type:pE,context:3,implicit:!0})],gE.prototype,"other",void 0),gE=hb([sb({type:yy.Choice})],gE);let yE=fE=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,fE.prototype)}};yE=fE=hb([sb({type:yy.Set,itemType:gE})],yE);class mE{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],mE.prototype,"contentType",void 0),hb([ib({type:my.Any,context:0})],mE.prototype,"content",void 0);let bE=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:km})],bE.prototype,"single",void 0),hb([ib({type:my.Any})],bE.prototype,"any",void 0),bE=hb([sb({type:yy.Choice})],bE);class AE{constructor(e={}){this.eContentType="",Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],AE.prototype,"eContentType",void 0),hb([ib({type:bE,context:0,optional:!0})],AE.prototype,"eContent",void 0);let IE=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:km,context:0,implicit:!0,optional:!0})],IE.prototype,"value",void 0),hb([ib({type:km,converter:Dm,context:0,implicit:!0,optional:!0,repeated:"sequence"})],IE.prototype,"constructedValue",void 0),IE=hb([sb({type:yy.Choice})],IE);class vE{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new RS,Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],vE.prototype,"contentType",void 0),hb([ib({type:RS})],vE.prototype,"contentEncryptionAlgorithm",void 0),hb([ib({type:IE,optional:!0})],vE.prototype,"encryptedContent",void 0);class wE{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}}var SE;hb([ib({type:my.ObjectIdentifier})],wE.prototype,"keyAttrId",void 0),hb([ib({type:my.Any,optional:!0})],wE.prototype,"keyAttr",void 0);class EE{constructor(e={}){this.subjectKeyIdentifier=new iS,Object.assign(this,e)}}hb([ib({type:iS})],EE.prototype,"subjectKeyIdentifier",void 0),hb([ib({type:my.GeneralizedTime,optional:!0})],EE.prototype,"date",void 0),hb([ib({type:wE,optional:!0})],EE.prototype,"other",void 0);let CE=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:EE,context:0,implicit:!0,optional:!0})],CE.prototype,"rKeyId",void 0),hb([ib({type:ES,optional:!0})],CE.prototype,"issuerAndSerialNumber",void 0),CE=hb([sb({type:yy.Choice})],CE);class kE{constructor(e={}){this.rid=new CE,this.encryptedKey=new km,Object.assign(this,e)}}hb([ib({type:CE})],kE.prototype,"rid",void 0),hb([ib({type:km})],kE.prototype,"encryptedKey",void 0);let xE=SE=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,SE.prototype)}};xE=SE=hb([sb({type:yy.Sequence,itemType:kE})],xE);class _E{constructor(e={}){this.algorithm=new uS,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:uS})],_E.prototype,"algorithm",void 0),hb([ib({type:my.BitString})],_E.prototype,"publicKey",void 0);let BE=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:iS,context:0,implicit:!0,optional:!0})],BE.prototype,"subjectKeyIdentifier",void 0),hb([ib({type:_E,context:1,implicit:!0,optional:!0})],BE.prototype,"originatorKey",void 0),hb([ib({type:ES,optional:!0})],BE.prototype,"issuerAndSerialNumber",void 0),BE=hb([sb({type:yy.Choice})],BE);class RE{constructor(e={}){this.version=kS.v3,this.originator=new BE,this.keyEncryptionAlgorithm=new BS,this.recipientEncryptedKeys=new xE,Object.assign(this,e)}}hb([ib({type:my.Integer})],RE.prototype,"version",void 0),hb([ib({type:BE,context:0})],RE.prototype,"originator",void 0),hb([ib({type:km,context:1,optional:!0})],RE.prototype,"ukm",void 0),hb([ib({type:BS})],RE.prototype,"keyEncryptionAlgorithm",void 0),hb([ib({type:xE})],RE.prototype,"recipientEncryptedKeys",void 0);let OE=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:iS,context:0,implicit:!0})],OE.prototype,"subjectKeyIdentifier",void 0),hb([ib({type:ES})],OE.prototype,"issuerAndSerialNumber",void 0),OE=hb([sb({type:yy.Choice})],OE);class UE{constructor(e={}){this.version=kS.v0,this.rid=new OE,this.keyEncryptionAlgorithm=new BS,this.encryptedKey=new km,Object.assign(this,e)}}hb([ib({type:my.Integer})],UE.prototype,"version",void 0),hb([ib({type:OE})],UE.prototype,"rid",void 0),hb([ib({type:BS})],UE.prototype,"keyEncryptionAlgorithm",void 0),hb([ib({type:km})],UE.prototype,"encryptedKey",void 0);class TE{constructor(e={}){this.keyIdentifier=new km,Object.assign(this,e)}}hb([ib({type:km})],TE.prototype,"keyIdentifier",void 0),hb([ib({type:my.GeneralizedTime,optional:!0})],TE.prototype,"date",void 0),hb([ib({type:wE,optional:!0})],TE.prototype,"other",void 0);class NE{constructor(e={}){this.version=kS.v4,this.kekid=new TE,this.keyEncryptionAlgorithm=new BS,this.encryptedKey=new km,Object.assign(this,e)}}hb([ib({type:my.Integer})],NE.prototype,"version",void 0),hb([ib({type:TE})],NE.prototype,"kekid",void 0),hb([ib({type:BS})],NE.prototype,"keyEncryptionAlgorithm",void 0),hb([ib({type:km})],NE.prototype,"encryptedKey",void 0);class DE{constructor(e={}){this.version=kS.v0,this.keyEncryptionAlgorithm=new BS,this.encryptedKey=new km,Object.assign(this,e)}}hb([ib({type:my.Integer})],DE.prototype,"version",void 0),hb([ib({type:US,context:0,optional:!0})],DE.prototype,"keyDerivationAlgorithm",void 0),hb([ib({type:BS})],DE.prototype,"keyEncryptionAlgorithm",void 0),hb([ib({type:km})],DE.prototype,"encryptedKey",void 0);class ME{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],ME.prototype,"oriType",void 0),hb([ib({type:my.Any})],ME.prototype,"oriValue",void 0);let PE=class{constructor(e={}){Object.assign(this,e)}};var LE;hb([ib({type:UE,optional:!0})],PE.prototype,"ktri",void 0),hb([ib({type:RE,context:1,implicit:!0,optional:!0})],PE.prototype,"kari",void 0),hb([ib({type:NE,context:2,implicit:!0,optional:!0})],PE.prototype,"kekri",void 0),hb([ib({type:DE,context:3,implicit:!0,optional:!0})],PE.prototype,"pwri",void 0),hb([ib({type:ME,context:4,implicit:!0,optional:!0})],PE.prototype,"ori",void 0),PE=hb([sb({type:yy.Choice})],PE);let HE=LE=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,LE.prototype)}};var KE;HE=LE=hb([sb({type:yy.Set,itemType:PE})],HE);class QE{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],QE.prototype,"otherRevInfoFormat",void 0),hb([ib({type:my.Any})],QE.prototype,"otherRevInfo",void 0);let VE=class{constructor(e={}){this.other=new QE,Object.assign(this,e)}};hb([ib({type:QE,context:1,implicit:!0})],VE.prototype,"other",void 0),VE=hb([sb({type:yy.Choice})],VE);let FE=KE=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,KE.prototype)}};FE=KE=hb([sb({type:yy.Set,itemType:VE})],FE);class $E{constructor(e={}){Object.assign(this,e)}}var jE;hb([ib({type:yE,context:0,implicit:!0,optional:!0})],$E.prototype,"certs",void 0),hb([ib({type:FE,context:1,implicit:!0,optional:!0})],$E.prototype,"crls",void 0);let GE=jE=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,jE.prototype)}};GE=jE=hb([sb({type:yy.Set,itemType:TS})],GE);class qE{constructor(e={}){this.version=kS.v0,this.recipientInfos=new HE,this.encryptedContentInfo=new vE,Object.assign(this,e)}}hb([ib({type:my.Integer})],qE.prototype,"version",void 0),hb([ib({type:$E,context:0,implicit:!0,optional:!0})],qE.prototype,"originatorInfo",void 0),hb([ib({type:HE})],qE.prototype,"recipientInfos",void 0),hb([ib({type:vE})],qE.prototype,"encryptedContentInfo",void 0),hb([ib({type:GE,context:1,implicit:!0,optional:!0})],qE.prototype,"unprotectedAttrs",void 0);const zE="1.2.840.113549.1.7.2";var WE;let JE=WE=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,WE.prototype)}};JE=WE=hb([sb({type:yy.Set,itemType:xS})],JE);class YE{constructor(e={}){this.version=kS.v0,this.digestAlgorithms=new JE,this.encapContentInfo=new AE,this.signerInfos=new MS,Object.assign(this,e)}}hb([ib({type:my.Integer})],YE.prototype,"version",void 0),hb([ib({type:JE})],YE.prototype,"digestAlgorithms",void 0),hb([ib({type:AE})],YE.prototype,"encapContentInfo",void 0),hb([ib({type:yE,context:0,implicit:!0,optional:!0})],YE.prototype,"certificates",void 0),hb([ib({type:FE,context:1,implicit:!0,optional:!0})],YE.prototype,"crls",void 0),hb([ib({type:MS})],YE.prototype,"signerInfos",void 0);const XE="1.2.840.10045.2.1",ZE="1.2.840.10045.4.1",eC="1.2.840.10045.4.3.1",tC="1.2.840.10045.4.3.2",rC="1.2.840.10045.4.3.3",sC="1.2.840.10045.4.3.4",iC="1.2.840.10045.3.1.7",nC="1.3.132.0.34",oC="1.3.132.0.35";function aC(e){return new uS({algorithm:e})}const cC=aC(ZE),lC=(aC(eC),aC(tC)),hC=aC(rC),uC=aC(sC);let dC=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:my.ObjectIdentifier})],dC.prototype,"fieldType",void 0),hb([ib({type:my.Any})],dC.prototype,"parameters",void 0),dC=hb([sb({type:yy.Sequence})],dC);let fC=class{constructor(e={}){Object.assign(this,e)}};var pC;hb([ib({type:my.OctetString})],fC.prototype,"a",void 0),hb([ib({type:my.OctetString})],fC.prototype,"b",void 0),hb([ib({type:my.BitString,optional:!0})],fC.prototype,"seed",void 0),fC=hb([sb({type:yy.Sequence})],fC),function(e){e[e.ecpVer1=1]="ecpVer1"}(pC||(pC={}));let gC=class{constructor(e={}){this.version=pC.ecpVer1,Object.assign(this,e)}};hb([ib({type:my.Integer})],gC.prototype,"version",void 0),hb([ib({type:dC})],gC.prototype,"fieldID",void 0),hb([ib({type:fC})],gC.prototype,"curve",void 0),hb([ib({type:class extends km{}})],gC.prototype,"base",void 0),hb([ib({type:my.Integer,converter:Rm})],gC.prototype,"order",void 0),hb([ib({type:my.Integer,optional:!0})],gC.prototype,"cofactor",void 0),gC=hb([sb({type:yy.Sequence})],gC);let yC=class{constructor(e={}){Object.assign(this,e)}};hb([ib({type:my.ObjectIdentifier})],yC.prototype,"namedCurve",void 0),hb([ib({type:my.Null})],yC.prototype,"implicitCurve",void 0),hb([ib({type:gC})],yC.prototype,"specifiedCurve",void 0),yC=hb([sb({type:yy.Choice})],yC);class mC{constructor(e={}){this.version=1,this.privateKey=new km,Object.assign(this,e)}}hb([ib({type:my.Integer})],mC.prototype,"version",void 0),hb([ib({type:km})],mC.prototype,"privateKey",void 0),hb([ib({type:yC,context:0,optional:!0})],mC.prototype,"parameters",void 0),hb([ib({type:my.BitString,context:1,optional:!0})],mC.prototype,"publicKey",void 0);class bC{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.Integer,converter:Rm})],bC.prototype,"r",void 0),hb([ib({type:my.Integer,converter:Rm})],bC.prototype,"s",void 0);const AC="1.2.840.113549.1.1",IC=`${AC}.1`,vC=`${AC}.7`,wC=`${AC}.9`,SC=`${AC}.10`,EC=`${AC}.2`,CC=`${AC}.4`,kC=`${AC}.5`,xC=`${AC}.14`,_C=`${AC}.11`,BC=`${AC}.12`,RC=`${AC}.13`,OC=`${AC}.15`,UC=`${AC}.16`,TC="1.3.14.3.2.26",NC="2.16.840.1.101.3.4.2.4",DC="2.16.840.1.101.3.4.2.1",MC="2.16.840.1.101.3.4.2.2",PC="2.16.840.1.101.3.4.2.3",LC=`${AC}.8`;function HC(e){return new uS({algorithm:e,parameters:null})}HC("1.2.840.113549.2.2"),HC("1.2.840.113549.2.5");const KC=HC(TC),QC=(HC(NC),HC(DC),HC(MC),HC(PC),HC("2.16.840.1.101.3.4.2.5"),HC("2.16.840.1.101.3.4.2.6"),new uS({algorithm:LC,parameters:lb.serialize(KC)})),VC=new uS({algorithm:wC,parameters:lb.serialize(Nm.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});HC(IC),HC(EC),HC(CC),HC(kC),HC(OC),HC(UC),HC(BC),HC(RC),HC(OC),HC(UC);class FC{constructor(e={}){this.hashAlgorithm=new uS(KC),this.maskGenAlgorithm=new uS({algorithm:LC,parameters:lb.serialize(KC)}),this.pSourceAlgorithm=new uS(VC),Object.assign(this,e)}}hb([ib({type:uS,context:0,defaultValue:KC})],FC.prototype,"hashAlgorithm",void 0),hb([ib({type:uS,context:1,defaultValue:QC})],FC.prototype,"maskGenAlgorithm",void 0),hb([ib({type:uS,context:2,defaultValue:VC})],FC.prototype,"pSourceAlgorithm",void 0),new uS({algorithm:vC,parameters:lb.serialize(new FC)});class $C{constructor(e={}){this.hashAlgorithm=new uS(KC),this.maskGenAlgorithm=new uS({algorithm:LC,parameters:lb.serialize(KC)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}hb([ib({type:uS,context:0,defaultValue:KC})],$C.prototype,"hashAlgorithm",void 0),hb([ib({type:uS,context:1,defaultValue:QC})],$C.prototype,"maskGenAlgorithm",void 0),hb([ib({type:my.Integer,context:2,defaultValue:20})],$C.prototype,"saltLength",void 0),hb([ib({type:my.Integer,context:3,defaultValue:1})],$C.prototype,"trailerField",void 0),new uS({algorithm:SC,parameters:lb.serialize(new $C)});class jC{constructor(e={}){this.digestAlgorithm=new uS,this.digest=new km,Object.assign(this,e)}}var GC;hb([ib({type:uS})],jC.prototype,"digestAlgorithm",void 0),hb([ib({type:km})],jC.prototype,"digest",void 0);class qC{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.Integer,converter:Rm})],qC.prototype,"prime",void 0),hb([ib({type:my.Integer,converter:Rm})],qC.prototype,"exponent",void 0),hb([ib({type:my.Integer,converter:Rm})],qC.prototype,"coefficient",void 0);let zC=GC=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,GC.prototype)}};zC=GC=hb([sb({type:yy.Sequence,itemType:qC})],zC);class WC{constructor(e={}){this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.Integer})],WC.prototype,"version",void 0),hb([ib({type:my.Integer,converter:Rm})],WC.prototype,"modulus",void 0),hb([ib({type:my.Integer,converter:Rm})],WC.prototype,"publicExponent",void 0),hb([ib({type:my.Integer,converter:Rm})],WC.prototype,"privateExponent",void 0),hb([ib({type:my.Integer,converter:Rm})],WC.prototype,"prime1",void 0),hb([ib({type:my.Integer,converter:Rm})],WC.prototype,"prime2",void 0),hb([ib({type:my.Integer,converter:Rm})],WC.prototype,"exponent1",void 0),hb([ib({type:my.Integer,converter:Rm})],WC.prototype,"exponent2",void 0),hb([ib({type:my.Integer,converter:Rm})],WC.prototype,"coefficient",void 0),hb([ib({type:zC,optional:!0})],WC.prototype,"otherPrimeInfos",void 0);class JC{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}var YC;hb([ib({type:my.Integer,converter:Rm})],JC.prototype,"modulus",void 0),hb([ib({type:my.Integer,converter:Rm})],JC.prototype,"publicExponent",void 0),function(e){e[e.Transient=0]="Transient",e[e.Singleton=1]="Singleton",e[e.ResolutionScoped=2]="ResolutionScoped",e[e.ContainerScoped=3]="ContainerScoped"}(YC||(YC={}));const XC=YC;var ZC=function(e,t){return ZC=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},ZC(e,t)};function ek(e,t){function r(){this.constructor=e}ZC(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function tk(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],s=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function rk(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var s,i,n=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(e){i={error:e}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return o}function sk(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(rk(arguments[t]));return e}function ik(e){return!!e.useClass}function nk(e){return!!e.useFactory}var ok=function(){function e(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return e.prototype.createProxy=function(e){var t,r=this,s=!1;return new Proxy({},this.createHandler(function(){return s||(t=e(r.wrap()),s=!0),t}))},e.prototype.createHandler=function(e){var t={};return this.reflectMethods.forEach(function(r){t[r]=function(){for(var t=[],s=0;s<arguments.length;s++)t[s]=arguments[s];return t[0]=e(),Reflect[r].apply(void 0,sk(t))}}),t},e}();function ak(e){return"string"==typeof e||"symbol"==typeof e}function ck(e){return"object"==typeof e&&"token"in e&&"transform"in e}function lk(e){return!!e.useToken}function hk(e){return null!=e.useValue}var uk=function(){function e(){this._registryMap=new Map}return e.prototype.entries=function(){return this._registryMap.entries()},e.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},e.prototype.get=function(e){this.ensure(e);var t=this._registryMap.get(e);return t[t.length-1]||null},e.prototype.set=function(e,t){this.ensure(e),this._registryMap.get(e).push(t)},e.prototype.setAll=function(e,t){this._registryMap.set(e,t)},e.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},e.prototype.clear=function(){this._registryMap.clear()},e.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},e}();const dk=uk,fk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return ek(t,e),t}(dk),pk=function(){this.scopedResolutions=new Map};var gk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return ek(t,e),t}(dk),yk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return ek(t,e),t}(dk);const mk=function(){this.preResolution=new gk,this.postResolution=new yk};var bk=new Map,Ak=function(){function e(e){this.parent=e,this._registry=new fk,this.interceptors=new mk,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var s;if(void 0===r&&(r={lifecycle:XC.Transient}),this.ensureNotDisposed(),s=function(e){return ik(e)||hk(e)||lk(e)||nk(e)}(t)?t:{useClass:t},lk(s))for(var i=[e],n=s;null!=n;){var o=n.useToken;if(i.includes(o))throw new Error("Token registration cycle detected! "+sk(i,[o]).join(" -> "));i.push(o);var a=this._registry.get(o);n=a&&lk(a.provider)?a.provider:null}if((r.lifecycle===XC.Singleton||r.lifecycle==XC.ContainerScoped||r.lifecycle==XC.ResolutionScoped)&&(hk(s)||nk(s)))throw new Error('Cannot use lifecycle "'+XC[r.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:s,options:r}),this},e.prototype.registerType=function(e,t){return this.ensureNotDisposed(),ak(t)?this.register(e,{useToken:t}):this.register(e,{useClass:t})},e.prototype.registerInstance=function(e,t){return this.ensureNotDisposed(),this.register(e,{useValue:t})},e.prototype.registerSingleton=function(e,t){if(this.ensureNotDisposed(),ak(e)){if(ak(t))return this.register(e,{useToken:t},{lifecycle:XC.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:XC.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!ak(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:XC.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new pk),void 0===r&&(r=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&ak(e)){if(r)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),s){var i=this.resolveRegistration(s,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(function(e){return"function"==typeof e||e instanceof ok}(e))return i=this.construct(e,t),this.executePostResolutionInterceptor(e,i,"Single"),i;throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},e.prototype.executePreResolutionInterceptor=function(e,t){var r,s;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var n=tk(this.interceptors.preResolution.getAll(e)),o=n.next();!o.done;o=n.next()){var a=o.value;"Once"!=a.options.frequency&&i.push(a),a.callback(e,t)}}catch(e){r={error:e}}finally{try{o&&!o.done&&(s=n.return)&&s.call(n)}finally{if(r)throw r.error}}this.interceptors.preResolution.setAll(e,i)}},e.prototype.executePostResolutionInterceptor=function(e,t,r){var s,i;if(this.interceptors.postResolution.has(e)){var n=[];try{for(var o=tk(this.interceptors.postResolution.getAll(e)),a=o.next();!a.done;a=o.next()){var c=a.value;"Once"!=c.options.frequency&&n.push(c),c.callback(e,t,r)}}catch(e){s={error:e}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(s)throw s.error}}this.interceptors.postResolution.setAll(e,n)}},e.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===XC.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,s=e.options.lifecycle===XC.Singleton,i=e.options.lifecycle===XC.ContainerScoped,n=s||i;return r=hk(e.provider)?e.provider.useValue:lk(e.provider)?n?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):ik(e.provider)?n?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):nk(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===XC.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var s=this;void 0===t&&(t=new pk),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&ak(e)){if(r)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),i){var n=i.map(function(e){return s.resolveRegistration(e,t)});return this.executePostResolutionInterceptor(e,n,"All"),n}var o=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,o,"All"),o},e.prototype.isRegistered=function(e,t){return void 0===t&&(t=!1),this.ensureNotDisposed(),this._registry.has(e)||t&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},e.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},e.prototype.clearInstances=function(){var e,t;this.ensureNotDisposed();try{for(var r=tk(this._registry.entries()),s=r.next();!s.done;s=r.next()){var i=rk(s.value,2),n=i[0],o=i[1];this._registry.setAll(n,o.filter(function(e){return!hk(e.provider)}).map(function(e){return e.instance=void 0,e}))}}catch(t){e={error:t}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}},e.prototype.createChildContainer=function(){var t,r;this.ensureNotDisposed();var s=new e(this);try{for(var i=tk(this._registry.entries()),n=i.next();!n.done;n=i.next()){var o=rk(n.value,2),a=o[0],c=o[1];c.some(function(e){return e.options.lifecycle===XC.ContainerScoped})&&s._registry.setAll(a,c.map(function(e){return e.options.lifecycle===XC.ContainerScoped?{provider:e.provider,options:e.options}:e}))}}catch(e){t={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return s},e.prototype.beforeResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:t,options:r})},e.prototype.afterResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:t,options:r})},e.prototype.dispose=function(){return function(e,t,r,s){return new(r||(r=Promise))(function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((s=s.apply(e,t||[])).next())})}(this,void 0,void 0,function(){var e;return function(e,t){var r,s,i,n,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return n={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function a(n){return function(a){return function(n){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,s&&(i=2&n[0]?s.return:n[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,n[1])).done)return i;switch(s=0,i&&(n=[2&n[0],i.value]),n[0]){case 0:case 1:i=n;break;case 4:return o.label++,{value:n[1],done:!1};case 5:o.label++,s=n[1],n=[0];continue;case 7:n=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==n[0]&&2!==n[0])){o=0;continue}if(3===n[0]&&(!i||n[1]>i[0]&&n[1]<i[3])){o.label=n[1];break}if(6===n[0]&&o.label<i[1]){o.label=i[1],i=n;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(n);break}i[2]&&o.ops.pop(),o.trys.pop();continue}n=t.call(e,o)}catch(e){n=[6,e],s=0}finally{r=i=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,a])}}}(this,function(t){switch(t.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(t){var r=t.dispose();r&&e.push(r)}),[4,Promise.all(e)];case 1:return t.sent(),[2]}})})},e.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},e.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},e.prototype.construct=function(e,t){var r=this;if(e instanceof ok)return e.createProxy(function(e){return r.resolve(e,t)});var s,i=function(){var s=bk.get(e);if(!s||0===s.length){if(0===e.length)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var i=s.map(r.resolveParams(t,e));return new(e.bind.apply(e,sk([void 0],i)))}();return"function"!=typeof(s=i).dispose||s.dispose.length>0||this.disposables.add(i),i},e.prototype.resolveParams=function(e,t){var r=this;return function(s,i){var n,o,a,c;try{return"object"==typeof(c=s)&&"token"in c&&"multiple"in c?ck(s)?s.multiple?(n=r.resolve(s.transform)).transform.apply(n,sk([r.resolveAll(s.token,new pk,s.isOptional)],s.transformArgs)):(o=r.resolve(s.transform)).transform.apply(o,sk([r.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?r.resolveAll(s.token,new pk,s.isOptional):r.resolve(s.token,e,s.isOptional):ck(s)?(a=r.resolve(s.transform,e)).transform.apply(a,sk([r.resolve(s.token,e)],s.transformArgs)):r.resolve(s,e)}catch(e){throw new Error(function(e,t,r){var s,i,n=rk(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return function(e,t,r){return void 0===r&&(r=" "),sk([e],t.message.split("\n").map(function(e){return r+e})).join("\n")}("Cannot inject the dependency "+(i=t,(null===(s=void 0===n?null:n)?"at position #"+i:'"'+s.split(",")[i].trim()+'" at position #'+i)+' of "')+e.name+'" constructor. Reason:',r)}(t,i,e))}}},e.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},e}(),Ik=new Ak;const vk=function(e){return function(t){bk.set(t,function(e){var t=Reflect.getMetadata("design:paramtypes",e)||[],r=Reflect.getOwnMetadata("injectionTokens",e)||{};return Object.keys(r).forEach(function(e){t[+e]=r[e]}),t}(t)),e&&e.token&&(Array.isArray(e.token)?e.token.forEach(function(e){Ik.register(e,t)}):Ik.register(e.token,t))}};if("undefined"==typeof Reflect||!Reflect.getMetadata)throw new Error("tsyringe requires a reflect polyfill. Please add 'import \"reflect-metadata\"' to the top of your entry point.");var wk;class Sk{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}}hb([ib({type:my.ObjectIdentifier})],Sk.prototype,"attrId",void 0),hb([ib({type:my.Any,repeated:"set"})],Sk.prototype,"attrValues",void 0);let Ek=wk=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,wk.prototype)}};var Ck;Ek=wk=hb([sb({type:yy.Sequence,itemType:Sk})],Ek);let kk=Ck=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,Ck.prototype)}};kk=Ck=hb([sb({type:yy.Sequence,itemType:mE})],kk);class xk{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],xk.prototype,"certId",void 0),hb([ib({type:my.Any,context:0})],xk.prototype,"certValue",void 0);class _k{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],_k.prototype,"crlId",void 0),hb([ib({type:my.Any,context:0})],_k.prototype,"crltValue",void 0);class Bk extends km{}class Rk{constructor(e={}){this.encryptionAlgorithm=new uS,this.encryptedData=new Bk,Object.assign(this,e)}}var Ok,Uk;hb([ib({type:uS})],Rk.prototype,"encryptionAlgorithm",void 0),hb([ib({type:Bk})],Rk.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(Uk||(Uk={}));class Tk extends km{}let Nk=Ok=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,Ok.prototype)}};Nk=Ok=hb([sb({type:yy.Sequence,itemType:eS})],Nk);class Dk{constructor(e={}){this.version=Uk.v1,this.privateKeyAlgorithm=new uS,this.privateKey=new Tk,Object.assign(this,e)}}hb([ib({type:my.Integer})],Dk.prototype,"version",void 0),hb([ib({type:uS})],Dk.prototype,"privateKeyAlgorithm",void 0),hb([ib({type:Tk})],Dk.prototype,"privateKey",void 0),hb([ib({type:Nk,implicit:!0,context:0,optional:!0})],Dk.prototype,"attributes",void 0);let Mk=class extends Dk{};Mk=hb([sb({type:yy.Sequence})],Mk);let Pk=class extends Rk{};Pk=hb([sb({type:yy.Sequence})],Pk);class Lk{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],Lk.prototype,"secretTypeId",void 0),hb([ib({type:my.Any,context:0})],Lk.prototype,"secretValue",void 0);class Hk{constructor(e={}){this.mac=new jC,this.macSalt=new km,this.iterations=1,Object.assign(this,e)}}hb([ib({type:jC})],Hk.prototype,"mac",void 0),hb([ib({type:km})],Hk.prototype,"macSalt",void 0),hb([ib({type:my.Integer,defaultValue:1})],Hk.prototype,"iterations",void 0);class Kk{constructor(e={}){this.version=3,this.authSafe=new mE,this.macData=new Hk,Object.assign(this,e)}}var Qk;hb([ib({type:my.Integer})],Kk.prototype,"version",void 0),hb([ib({type:mE})],Kk.prototype,"authSafe",void 0),hb([ib({type:Hk,optional:!0})],Kk.prototype,"macData",void 0);class Vk{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:my.ObjectIdentifier})],Vk.prototype,"bagId",void 0),hb([ib({type:my.Any,context:0})],Vk.prototype,"bagValue",void 0),hb([ib({type:Sk,repeated:"set",optional:!0})],Vk.prototype,"bagAttributes",void 0);let Fk=Qk=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,Qk.prototype)}};var $k,jk,Gk;Fk=Qk=hb([sb({type:yy.Sequence,itemType:Vk})],Fk);const qk="1.2.840.113549.1.9",zk=`${qk}.7`,Wk=`${qk}.14`;let Jk=class extends xv{constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};hb([ib({type:my.IA5String})],Jk.prototype,"ia5String",void 0),Jk=hb([sb({type:yy.Choice})],Jk);let Yk=class extends mE{};Yk=hb([sb({type:yy.Sequence})],Yk);let Xk=class extends Kk{};Xk=hb([sb({type:yy.Sequence})],Xk);let Zk=class extends Rk{};Zk=hb([sb({type:yy.Sequence})],Zk);let ex=class{constructor(e=""){this.value=e}toString(){return this.value}};hb([ib({type:my.IA5String})],ex.prototype,"value",void 0),ex=hb([sb({type:yy.Choice})],ex);let tx=class extends Jk{};tx=hb([sb({type:yy.Choice})],tx);let rx=class extends xv{};rx=hb([sb({type:yy.Choice})],rx);let sx=class{constructor(e=new Date){this.value=e}};hb([ib({type:my.GeneralizedTime})],sx.prototype,"value",void 0),sx=hb([sb({type:yy.Choice})],sx);let ix=class extends xv{};ix=hb([sb({type:yy.Choice})],ix);let nx=class{constructor(e="M"){this.value=e}toString(){return this.value}};hb([ib({type:my.PrintableString})],nx.prototype,"value",void 0),nx=hb([sb({type:yy.Choice})],nx);let ox=class{constructor(e=""){this.value=e}toString(){return this.value}};hb([ib({type:my.PrintableString})],ox.prototype,"value",void 0),ox=hb([sb({type:yy.Choice})],ox);let ax=class extends ox{};ax=hb([sb({type:yy.Choice})],ax);let cx=class extends xv{};cx=hb([sb({type:yy.Choice})],cx);let lx=class{constructor(e=""){this.value=e}toString(){return this.value}};hb([ib({type:my.ObjectIdentifier})],lx.prototype,"value",void 0),lx=hb([sb({type:yy.Choice})],lx);let hx=class extends fS{};hx=hb([sb({type:yy.Choice})],hx);let ux=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};hb([ib({type:my.Integer})],ux.prototype,"value",void 0),ux=hb([sb({type:yy.Choice})],ux);let dx=class extends DS{};dx=hb([sb({type:yy.Sequence})],dx);let fx=class extends xv{};fx=hb([sb({type:yy.Choice})],fx);let px=$k=class extends mS{constructor(e){super(e),Object.setPrototypeOf(this,$k.prototype)}};px=$k=hb([sb({type:yy.Sequence})],px);let gx=jk=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,jk.prototype)}};gx=jk=hb([sb({type:yy.Set,itemType:TS})],gx);let yx=class{constructor(e=""){this.value=e}toString(){return this.value}};hb([ib({type:my.BmpString})],yx.prototype,"value",void 0),yx=hb([sb({type:yy.Choice})],yx);let mx=class extends uS{};mx=hb([sb({type:yy.Sequence})],mx);let bx=Gk=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,Gk.prototype)}};var Ax;bx=Gk=hb([sb({type:yy.Sequence,itemType:mx})],bx);let Ix=Ax=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,Ax.prototype)}};Ix=Ax=hb([sb({type:yy.Sequence,itemType:eS})],Ix);class vx{constructor(e={}){this.version=0,this.subject=new Uv,this.subjectPKInfo=new dS,this.attributes=new Ix,Object.assign(this,e)}}hb([ib({type:my.Integer})],vx.prototype,"version",void 0),hb([ib({type:Uv})],vx.prototype,"subject",void 0),hb([ib({type:dS})],vx.prototype,"subjectPKInfo",void 0),hb([ib({type:Ix,implicit:!0,context:0})],vx.prototype,"attributes",void 0);class wx{constructor(e={}){this.certificationRequestInfo=new vx,this.signatureAlgorithm=new uS,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}hb([ib({type:vx})],wx.prototype,"certificationRequestInfo",void 0),hb([ib({type:uS})],wx.prototype,"signatureAlgorithm",void 0),hb([ib({type:my.BitString})],wx.prototype,"signature",void 0);const Sx="crypto.algorithm",Ex="crypto.algorithmProvider";var Cx;Ik.registerSingleton(Ex,class{getAlgorithms(){return Ik.resolveAll(Sx)}toAsnAlgorithm(e){for(const t of this.getAlgorithms()){const r=t.toAsnAlgorithm(e);if(r)return r}if(/^[0-9.]+$/.test(e.name)){const t=new uS({algorithm:e.name});if("parameters"in e){const r=e;t.parameters=r.parameters}return t}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(const t of this.getAlgorithms()){const r=t.toWebAlgorithm(e);if(r)return r}return{name:e.algorithm,parameters:e.parameters}}});const kx="1.3.36.3.3.2.8.1.1",xx=`${kx}.1`,_x=`${kx}.2`,Bx=`${kx}.3`,Rx=`${kx}.4`,Ox=`${kx}.5`,Ux=`${kx}.6`,Tx=`${kx}.7`,Nx=`${kx}.8`,Dx=`${kx}.9`,Mx=`${kx}.10`,Px=`${kx}.11`,Lx=`${kx}.12`,Hx=`${kx}.13`,Kx=`${kx}.14`,Qx="brainpoolP160r1",Vx="brainpoolP160t1",Fx="brainpoolP192r1",$x="brainpoolP192t1",jx="brainpoolP224r1",Gx="brainpoolP224t1",qx="brainpoolP256r1",zx="brainpoolP256t1",Wx="brainpoolP320r1",Jx="brainpoolP320t1",Yx="brainpoolP384r1",Xx="brainpoolP384t1",Zx="brainpoolP512r1",e_="brainpoolP512t1",t_="ECDSA";let r_=Cx=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===t_.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return cC;case"sha-256":return lC;case"sha-384":return hC;case"sha-512":return uC}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=iC;break;case"K-256":t=Cx.SECP256K1;break;case"P-384":t=nC;break;case"P-521":t=oC;break;case Qx:t=xx;break;case Vx:t=_x;break;case Fx:t=Bx;break;case $x:t=Rx;break;case jx:t=Ox;break;case Gx:t=Ux;break;case qx:t=Tx;break;case zx:t=Nx;break;case Wx:t=Dx;break;case Jx:t=Mx;break;case Yx:t=Px;break;case Xx:t=Lx;break;case Zx:t=Hx;break;case e_:t=Kx}if(t)return new uS({algorithm:XE,parameters:lb.serialize(new yC({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case ZE:return{name:t_,hash:{name:"SHA-1"}};case tC:return{name:t_,hash:{name:"SHA-256"}};case rC:return{name:t_,hash:{name:"SHA-384"}};case sC:return{name:t_,hash:{name:"SHA-512"}};case XE:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(lb.parse(e.parameters,yC).namedCurve){case iC:return{name:t_,namedCurve:"P-256"};case Cx.SECP256K1:return{name:t_,namedCurve:"K-256"};case nC:return{name:t_,namedCurve:"P-384"};case oC:return{name:t_,namedCurve:"P-521"};case xx:return{name:t_,namedCurve:Qx};case _x:return{name:t_,namedCurve:Vx};case Bx:return{name:t_,namedCurve:Fx};case Rx:return{name:t_,namedCurve:$x};case Ox:return{name:t_,namedCurve:jx};case Ux:return{name:t_,namedCurve:Gx};case Tx:return{name:t_,namedCurve:qx};case Nx:return{name:t_,namedCurve:zx};case Dx:return{name:t_,namedCurve:Wx};case Mx:return{name:t_,namedCurve:Jx};case Px:return{name:t_,namedCurve:Yx};case Lx:return{name:t_,namedCurve:Xx};case Hx:return{name:t_,namedCurve:Zx};case Kx:return{name:t_,namedCurve:e_}}}return null}};r_.SECP256K1="1.3.132.0.10",r_=Cx=hb([vk()],r_),Ik.registerSingleton(Sx,r_);const s_=Symbol("name"),i_=Symbol("value");class n_{constructor(e,t={},r=""){this[s_]=e,this[i_]=r;for(const e in t)this[e]=t[e]}}n_.NAME=s_,n_.VALUE=i_;class o_{static toString(e){return this.items[e]||e}}o_.items={[TC]:"sha1",[NC]:"sha224",[DC]:"sha256",[MC]:"sha384",[PC]:"sha512",[IC]:"rsaEncryption",[kC]:"sha1WithRSAEncryption",[xC]:"sha224WithRSAEncryption",[_C]:"sha256WithRSAEncryption",[BC]:"sha384WithRSAEncryption",[RC]:"sha512WithRSAEncryption",[XE]:"ecPublicKey",[ZE]:"ecdsaWithSHA1",[eC]:"ecdsaWithSHA224",[tC]:"ecdsaWithSHA256",[rC]:"ecdsaWithSHA384",[sC]:"ecdsaWithSHA512",[Rw]:"TLS WWW server authentication",[Ow]:"TLS WWW client authentication",[Uw]:"Code Signing",[Tw]:"E-mail Protection",[Nw]:"Time Stamping",[Dw]:"OCSP Signing",[zE]:"Signed Data"};class a_{static serialize(e){return this.serializeObj(e).join("\n")}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,t=0){const r=[];let s=this.pad(t++),i="";const n=e[n_.VALUE];n&&(i=` ${n}`),r.push(`${s}${e[n_.NAME]}:${i}`),s=this.pad(t);for(const i in e){if("symbol"==typeof i)continue;const n=e[i],o=i?`${i}: `:"";if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)r.push(`${s}${o}${n}`);else if(n instanceof Date)r.push(`${s}${o}${n.toUTCString()}`);else if(Array.isArray(n))for(const e of n)e[n_.NAME]=i,r.push(...this.serializeObj(e,t));else if(n instanceof n_)n[n_.NAME]=i,r.push(...this.serializeObj(n,t));else if($p.isBufferSource(n))i?(r.push(`${s}${o}`),r.push(...this.serializeBufferSource(n,t+1))):r.push(...this.serializeBufferSource(n,t));else{if(!("toTextObject"in n))throw new TypeError("Cannot serialize data in text format. Unsupported type.");{const e=n.toTextObject();e[n_.NAME]=i,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),s=$p.toUint8Array(e),i=[];for(let e=0;e<s.length;){const t=[];for(let r=0;r<16&&e<s.length;r++){8===r&&t.push("");const i=s[e++].toString(16).padStart(2,"0");t.push(i)}i.push(`${r}${t.join(" ")}`)}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}a_.oidSerializer=o_,a_.algorithmSerializer=class{static toTextObject(e){const t=new n_("Algorithm Identifier",{},o_.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case XE:{const r=(new r_).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class c_{constructor(...e){if(1===e.length){const t=e[0];this.rawData=lb.serialize(t),this.onInit(t)}else{const t=lb.parse(e[0],e[1]);this.rawData=$p.toArrayBuffer(e[0]),this.onInit(t)}}equal(e){return e instanceof c_&&Zp(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return lb.toString(this.rawData);case"text":return a_.serialize(this.toTextObject());case"hex":return Yp.ToHex(this.rawData);case"base64":return Yp.ToBase64(this.rawData);case"base64url":return Yp.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new n_(this.getTextName(),{},e)}}c_.NAME="ASN";class l_ extends c_{constructor(...e){let t;t=$p.isBufferSource(e[0])?$p.toArrayBuffer(e[0]):lb.serialize(new yS({extnID:e[0],critical:e[1],extnValue:new km($p.toArrayBuffer(e[2]))})),super(t,yS)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[n_.NAME]===l_.NAME&&(e[n_.NAME]=o_.toString(this.type)),e}}var h_;class u_{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&void 0!==e.extractable}constructor(){this.items=new Map,this[h_]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(u_.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(u_.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=u_.DEFAULT){const t=this.items.get(e.toLowerCase());if(!t)throw new Error(`Cannot get Crypto by name '${e}'`);return t}set(e,t){if("string"==typeof e){if(!t)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),t)}else this.items.set(u_.DEFAULT,e);return this}}h_=Symbol.toStringTag,u_.DEFAULT="default";const d_=new u_,f_=/^[0-2](?:\.[1-9][0-9]*)+$/;class p_{constructor(e={}){this.items={};for(const t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return t=e,new RegExp(f_).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const g_=new p_;function y_(e,t){return`\\${Yp.ToHex(Yp.FromUtf8String(t)).toUpperCase()}`}g_.register("CN","2.5.4.3"),g_.register("L","2.5.4.7"),g_.register("ST","2.5.4.8"),g_.register("O","2.5.4.10"),g_.register("OU","2.5.4.11"),g_.register("C","2.5.4.6"),g_.register("DC","0.9.2342.19200300.100.1.25"),g_.register("E","1.2.840.113549.1.9.1"),g_.register("G","2.5.4.42"),g_.register("I","2.5.4.43"),g_.register("SN","2.5.4.4"),g_.register("T","2.5.4.12");class m_{static isASCII(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new p_,this.asn=new Uv;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const r=t[e];this.extraNames.register(e,r)}"string"==typeof e?this.asn=this.fromString(e):e instanceof Uv?this.asn=e:$p.isBufferSource(e)?this.asn=lb.parse(e,Uv):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||g_.findId(e),r=[];for(const e of this.asn)for(const s of e)s.type===t&&r.push(s.value.toString());return r}getName(e){return this.extraNames.get(e)||g_.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${Yp.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,y_)}`).join("+")).join(", ")}toJSON(){var e;const t=[];for(const r of this.asn){const s={};for(const t of r){const r=this.getName(t.type)||t.type;null!==(e=s[r])&&void 0!==e||(s[r]=[]),s[r].push(t.value.anyValue?`#${Yp.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(s)}return t}fromString(e){const t=new Uv,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let s=null,i=",";for(;s=r.exec(`${e},`);){let[,e,r]=s;const n=r[r.length-1];","!==n&&"+"!==n||(r=r.slice(0,r.length-1),s[3]=n);const o=s[3];e=this.getTypeOid(e);const a=this.createAttribute(e,r);"+"===i?t[t.length-1].push(a):t.push(new Rv([a])),i=o}return t}fromJSON(e){const t=new Uv;for(const r of e){const e=new Rv;for(const t in r){const s=this.getTypeOid(t),i=r[t];for(const t of i){const r=this.createAttribute(s,t);e.push(r)}}t.push(e)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,t){const r=new Bv({type:e});if("object"==typeof t)for(const e in t)switch(e){case"ia5String":r.value.ia5String=t[e];break;case"utf8String":r.value.utf8String=t[e];break;case"universalString":r.value.universalString=t[e];break;case"bmpString":r.value.bmpString=t[e];break;case"printableString":r.value.printableString=t[e]}else if("#"===t[0])r.value.anyValue=Yp.FromHex(t.slice(1));else{const s=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=s:m_.isPrintableString(s)?r.value.printableString=s:r.value.utf8String=s}return r}processStringValue(e){const t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/gi,"\n").replace(/\\0d/gi,"\r").replace(/\\0g/gi,"\t").replace(/\\(.)/g,"$1")}toArrayBuffer(){return lb.serialize(this.asn)}async getThumbprint(...e){var t;let r,s="SHA-1";return e.length>=1&&!(null===(t=e[0])||void 0===t?void 0:t.subtle)?(s=e[0]||s,r=e[1]||d_.get()):r=e[0]||d_.get(),await r.subtle.digest(s,this.toArrayBuffer())}}const b_="Cannot initialize GeneralName from ASN.1 data.",A_=`${b_} Unsupported string format in use.`,I_=`${b_} Value doesn't match to GUID regular expression.`,v_=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,w_="1.3.6.1.4.1.311.25.1",S_="1.3.6.1.4.1.311.20.2.3",E_="dns",C_="dn",k_="email",x_="ip",__="url",B_="guid",R_="upn",O_="id";class U_ extends c_{constructor(...e){let t;if(2===e.length)switch(e[0]){case C_:{const r=new m_(e[1]).toArrayBuffer(),s=lb.parse(r,Uv);t=new Mv({directoryName:s});break}case E_:t=new Mv({dNSName:e[1]});break;case k_:t=new Mv({rfc822Name:e[1]});break;case B_:{const r=new RegExp(v_,"i").exec(e[1]);if(!r)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const s=r.slice(1).map((e,t)=>t<3?Yp.ToHex(new Uint8Array(Yp.FromHex(e)).reverse()):e).join("");t=new Mv({otherName:new Nv({typeId:w_,value:lb.serialize(new km(Yp.FromHex(s)))})});break}case x_:t=new Mv({iPAddress:e[1]});break;case O_:t=new Mv({registeredID:e[1]});break;case R_:t=new Mv({otherName:new Nv({typeId:S_,value:lb.serialize(Pm.toASN(e[1]))})});break;case __:t=new Mv({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=$p.isBufferSource(e[0])?lb.parse(e[0],Mv):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=E_,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=k_,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=x_,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=__,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=O_,this.value=e.registeredID;else if(null!=e.directoryName)this.type=C_,this.value=new m_(e.directoryName).toString();else{if(null==e.otherName)throw new Error(A_);if(e.otherName.typeId===w_){this.type=B_;const t=lb.parse(e.otherName.value,km),r=new RegExp(v_,"i").exec(Yp.ToHex(t));if(!r)throw new Error(I_);this.value=r.slice(1).map((e,t)=>t<3?Yp.ToHex(new Uint8Array(Yp.FromHex(e)).reverse()):e).join("-")}else{if(e.otherName.typeId!==S_)throw new Error(A_);this.type=R_,this.value=lb.parse(e.otherName.value,xv).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case C_:case E_:case B_:case x_:case O_:case R_:case __:e=this.type.toUpperCase();break;case k_:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===O_&&(t=o_.toString(t)),new n_(e,void 0,t)}}class T_ extends c_{constructor(e){let t;if(e instanceof tw)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof Mv)r.push(t);else{const e=lb.parse(new U_(t.type,t.value).rawData,Mv);r.push(e)}t=new tw(r)}else{if(!$p.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=lb.parse(e,tw)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new U_(r)}catch{continue}t.push(e)}this.items=t}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){const e=super.toTextObjectEmpty();for(const t of this.items){const r=t.toTextObject();let s=e[r[n_.NAME]];Array.isArray(s)||(s=[],e[r[n_.NAME]]=s),s.push(r)}return e}}T_.NAME="GeneralNames";const N_="-{5}",D_="\\n",M_="\\n",P_=`${N_}BEGIN ([^${D_}]+(?=${N_}))${N_}${M_}(?:((?:[^:${D_}]+: (?:[^${D_}]+${M_}(?: +[^${D_}]+${M_})*))+))?${M_}?((?:[a-zA-Z0-9=+/]+${M_})+)${N_}END \\1${N_}`;class L_{static isPem(e){return"string"==typeof e&&new RegExp(P_,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(P_,"g"),r=[];let s=null;for(;s=t.exec(e);){const e=s[3].replace(new RegExp(`[${D_}]+`,"g"),""),t={type:s[1],headers:[],rawData:Yp.FromBase64(e)},i=s[2];if(i){const e=i.split(new RegExp(M_,"g"));let r=null;for(const s of e){const[e,i]=s.split(/:(.*)/);if(void 0===i){if(!r)throw new Error("Cannot parse PEM string. Incorrect header value");r.value+=e.trim()}else r&&t.headers.push(r),r={key:e,value:i.trim()}}r&&t.headers.push(r)}r.push(t)}return r}static decode(e){return this.decodeWithHeaders(e).map(e=>e.rawData)}static decodeFirst(e){const t=this.decode(e);if(!t.length)throw new RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){const r=new Array;return t?e.forEach(e=>{if(!$p.isBufferSource(e))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:t,rawData:$p.toArrayBuffer(e)}))}):e.forEach(e=>{if(!("type"in e))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(e))}),r.join("\n")}if(!t)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:$p.toArrayBuffer(e)})}static encodeStruct(e){var t;const r=e.type.toLocaleUpperCase(),s=[];if(s.push(`-----BEGIN ${r}-----`),null===(t=e.headers)||void 0===t?void 0:t.length){for(const t of e.headers)s.push(`${t.key}: ${t.value}`);s.push("")}const i=Yp.ToBase64(e.rawData);let n,o=0;const a=Array();for(;o<i.length&&(i.length-o<64?n=i.substring(o):(n=i.substring(o,o+64),o+=64),0!==n.length)&&(a.push(n),!(n.length<64)););return s.push(...a),s.push(`-----END ${r}-----`),s.join("\n")}}L_.CertificateTag="CERTIFICATE",L_.CrlTag="CRL",L_.CertificateRequestTag="CERTIFICATE REQUEST",L_.PublicKeyTag="PUBLIC KEY",L_.PrivateKeyTag="PRIVATE KEY";class H_ extends c_{static isAsnEncoded(e){return $p.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(L_.isPem(e))return L_.decode(e)[0];if(Yp.isHex(e))return Yp.FromHex(e);if(Yp.isBase64(e))return Yp.FromBase64(e);if(Yp.isBase64Url(e))return Yp.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=Yp.ToBinary(e);return L_.isPem(t)?L_.decode(t)[0]:Yp.isHex(t)?Yp.FromHex(t):Yp.isBase64(t)?Yp.FromBase64(t):Yp.isBase64Url(t)?Yp.FromBase64Url(t):$p.toArrayBuffer(e)}}constructor(...e){H_.isAsnEncoded(e[0])?super(H_.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?L_.encode(this.rawData,this.tag):super.toString(e)}}class K_ extends H_{static async create(e,t=d_.get()){if(e instanceof K_)return e;if(u_.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new K_(r)}if(e.publicKey)return e.publicKey;if($p.isBufferSource(e))return new K_(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){H_.isAsnEncoded(e)?super(e,dS):super(e),this.tag=L_.PublicKeyTag}async export(...e){let t,r=["verify"],s={hash:"SHA-256",...this.algorithm};e.length>1?(s=e[0]||s,r=e[1]||r,t=e[2]||d_.get()):t=e[0]||d_.get();let i=this.rawData;const n=lb.parse(this.rawData,dS);return n.algorithm.algorithm===SC&&(i=function(e){return e.algorithm=new uS({algorithm:IC,parameters:null}),lb.serialize(e)}(n)),t.subtle.importKey("spki",i,s,!0,r)}onInit(e){const t=Ik.resolve(Ex),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case IC:{const t=lb.parse(e.subjectPublicKey,JC),s=$p.toUint8Array(t.modulus);r.publicExponent=$p.toUint8Array(t.publicExponent),r.modulusLength=(s[0]?s:s.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){var t;let r,s="SHA-1";return e.length>=1&&!(null===(t=e[0])||void 0===t?void 0:t.subtle)?(s=e[0]||s,r=e[1]||d_.get()):r=e[0]||d_.get(),await r.subtle.digest(s,this.rawData)}async getKeyIdentifier(...e){let t,r="SHA-1";1===e.length?"string"==typeof e[0]?(r=e[0],t=d_.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=d_.get();const s=lb.parse(this.rawData,dS);return await t.subtle.digest(r,s.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=lb.parse(this.rawData,dS);return e.Algorithm=a_.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===XE?e["EC Point"]=t.subjectPublicKey:e["Raw Data"]=t.subjectPublicKey,e}}class Q_ extends l_{static async create(e,t=!1,r=d_.get()){if("name"in e&&"serialNumber"in e)return new Q_(e,t);const s=await K_.create(e,r),i=await s.getKeyIdentifier(r);return new Q_(Yp.ToHex(i),t)}constructor(...e){if($p.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new Yv({keyIdentifier:new Jv(Yp.FromHex(e[0]))});super(Wv,e[1],lb.serialize(t))}else{const t=e[0],r=t.name instanceof T_?lb.parse(t.name.rawData,tw):t.name,s=new Yv({authorityCertIssuer:r,authorityCertSerialNumber:Yp.FromHex(t.serialNumber)});super(Wv,e[1],lb.serialize(s))}}onInit(e){super.onInit(e);const t=lb.parse(e.extnValue,Yv);t.keyIdentifier&&(this.keyId=Yp.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Yp.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=lb.parse(this.value,Yv);return t.authorityCertIssuer&&(e["Authority Issuer"]=new T_(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}Q_.NAME="Authority Key Identifier";class V_ extends l_{constructor(...e){if($p.isBufferSource(e[0])){super(e[0]);const t=lb.parse(this.value,Zv);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new Zv({cA:e[0],pathLenConstraint:e[1]});super(Xv,e[2],lb.serialize(t)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),void 0!==this.pathLength&&(e["Path Length"]=this.pathLength),e}}var F_,$_;V_.NAME="Basic Constraints",function(e){e.serverAuth="1.3.6.1.5.5.7.3.1",e.clientAuth="1.3.6.1.5.5.7.3.2",e.codeSigning="1.3.6.1.5.5.7.3.3",e.emailProtection="1.3.6.1.5.5.7.3.4",e.timeStamping="1.3.6.1.5.5.7.3.8",e.ocspSigning="1.3.6.1.5.5.7.3.9"}(F_||(F_={}));class j_ extends l_{constructor(...e){if($p.isBufferSource(e[0])){super(e[0]);const t=lb.parse(this.value,Bw);this.usages=t.map(e=>e)}else{const t=new Bw(e[0]);super(_w,e[1],lb.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(e=>o_.toString(e)).join(", "),e}}j_.NAME="Extended Key Usages",function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}($_||($_={}));class G_ extends l_{constructor(...e){if($p.isBufferSource(e[0])){super(e[0]);const t=lb.parse(this.value,Fw);this.usages=t.toNumber()}else{const t=new Fw(e[0]);super(Kw,e[1],lb.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=lb.parse(this.value,Fw);return e[""]=t.toJSON().join(", "),e}}G_.NAME="Key Usages";class q_ extends l_{static async create(e,t=!1,r=d_.get()){const s=await K_.create(e,r),i=await s.getKeyIdentifier(r);return new q_(Yp.ToHex(i),t)}constructor(...e){if($p.isBufferSource(e[0])){super(e[0]);const t=lb.parse(this.value,iS);this.keyId=Yp.ToHex(t)}else{const t="string"==typeof e[0]?Yp.FromHex(e[0]):e[0],r=new iS(t);super(sS,e[1],lb.serialize(r)),this.keyId=Yp.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=lb.parse(this.value,iS);return e[""]=t,e}}q_.NAME="Subject Key Identifier";class z_ extends l_{constructor(...e){$p.isBufferSource(e[0])?super(e[0]):super(Xw,e[1],new T_(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=lb.parse(e.extnValue,Zw);this.names=new T_(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}z_.NAME="Subject Alternative Name";class W_{static register(e,t){this.items.set(e,t)}static create(e){const t=new l_(e),r=this.items.get(t.type);return r?new r(e):t}}W_.items=new Map;class J_ extends l_{constructor(...e){var t;if($p.isBufferSource(e[0])){super(e[0]);const t=lb.parse(this.value,dw);this.policies=t.map(e=>e.policyIdentifier)}else{const r=e[0],s=null!==(t=e[1])&&void 0!==t&&t,i=new dw(r.map(e=>new uw({policyIdentifier:e})));super(nw,s,lb.serialize(i)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new n_("",{},o_.toString(e))),e}}J_.NAME="Certificate Policies",W_.register(nw,J_);class Y_ extends l_{constructor(...e){var t;if($p.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map(e=>new Iw({distributionPoint:new Aw({fullName:[new Mv({uniformResourceIdentifier:e})]})})),r=new vw(t);super(yw,e[1],lb.serialize(r))}else{const t=new vw(e[0]);super(yw,e[1],lb.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=lb.parse(e.extnValue,vw);this.distributionPoints=t}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(e=>{var t;const r={};return e.distributionPoint&&(r[""]=null===(t=e.distributionPoint.fullName)||void 0===t?void 0:t.map(e=>new U_(e).toString()).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map(e=>e.toString()).join(", ")),r}),e}}Y_.NAME="CRL Distribution Points";class X_ extends l_{constructor(...e){var t,r,s,i;if($p.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof zv){const t=new zv(e[0]);super(Gv,e[1],lb.serialize(t))}else{const t=e[0],r=new zv;eB(r,t,Kv,"ocsp"),eB(r,t,Qv,"caIssuers"),eB(r,t,Vv,"timeStamping"),eB(r,t,Fv,"caRepository"),super(Gv,e[1],lb.serialize(r))}null!==(t=this.ocsp)&&void 0!==t||(this.ocsp=[]),null!==(r=this.caIssuers)&&void 0!==r||(this.caIssuers=[]),null!==(s=this.timeStamping)&&void 0!==s||(this.timeStamping=[]),null!==(i=this.caRepository)&&void 0!==i||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],lb.parse(e.extnValue,zv).forEach(e=>{switch(e.accessMethod){case Kv:this.ocsp.push(new U_(e.accessLocation));break;case Qv:this.caIssuers.push(new U_(e.accessLocation));break;case Vv:this.timeStamping.push(new U_(e.accessLocation));break;case Fv:this.caRepository.push(new U_(e.accessLocation))}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&Z_(e,"OCSP",this.ocsp),this.caIssuers.length&&Z_(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Z_(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Z_(e,"CA Repository",this.caRepository),e}}function Z_(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const s=new n_("");r.forEach((e,t)=>{const r=e.toTextObject(),i=`${r[n_.NAME]} ${t+1}`;let n=s[i];Array.isArray(n)||(n=[],s[i]=n),n.push(r)}),e[t]=s}}function eB(e,t,r,s){const i=t[s];i&&(Array.isArray(i)?i:[i]).forEach(t=>{"string"==typeof t&&(t=new U_("url",t)),e.push(new qv({accessMethod:r,accessLocation:lb.parse(t.rawData,Mv)}))})}X_.NAME="Authority Info Access";class tB extends c_{constructor(...e){let t;if($p.isBufferSource(e[0]))t=$p.toArrayBuffer(e[0]);else{const r=e[0],s=Array.isArray(e[1])?e[1].map(e=>$p.toArrayBuffer(e)):[];t=lb.serialize(new eS({type:r,values:s}))}super(t,eS)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new n_("",{"":e})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[n_.NAME]===tB.NAME&&(e[n_.NAME]=o_.toString(this.type)),e}}tB.NAME="Attribute";class rB extends tB{constructor(...e){var t;if($p.isBufferSource(e[0]))super(e[0]);else{const t=new fx({printableString:e[0]});super(zk,[lb.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=lb.parse(this.values[0],fx);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[n_.VALUE]=this.password,e}}rB.NAME="Challenge Password";class sB extends tB{constructor(...e){var t;if($p.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new mS;for(const e of t)r.push(lb.parse(e.rawData,yS));super(Wk,[lb.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=lb.parse(this.values[0],mS);this.items=e.map(e=>W_.create(lb.serialize(e)))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(const r of t)e[r[n_.NAME]]=r;return e}}sB.NAME="Extensions";class iB{static register(e,t){this.items.set(e,t)}static create(e){const t=new tB(e),r=this.items.get(t.type);return r?new r(e):t}}iB.items=new Map;const nB="crypto.signatureFormatter";var oB;let aB=oB=class{static createPssParams(e,t){const r=oB.getHashAlgorithm(e);return r?new $C({hashAlgorithm:r,maskGenAlgorithm:new uS({algorithm:LC,parameters:lb.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=Ik.resolve(Ex);return"string"==typeof e?t.toAsnAlgorithm({name:e}):"object"==typeof e&&e&&"name"in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if(!("hash"in e))return new uS({algorithm:IC,parameters:null});{let t;if("string"==typeof e.hash)t=e.hash;else{if(!e.hash||"object"!=typeof e.hash||!("name"in e.hash)||"string"!=typeof e.hash.name)throw new Error("Cannot get hash algorithm name");t=e.hash.name.toUpperCase()}switch(t.toLowerCase()){case"sha-1":return new uS({algorithm:kC,parameters:null});case"sha-256":return new uS({algorithm:_C,parameters:null});case"sha-384":return new uS({algorithm:BC,parameters:null});case"sha-512":return new uS({algorithm:RC,parameters:null})}}break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e)||"number"!=typeof e.saltLength)throw new Error("Cannot get 'saltLength' from 'alg' argument");const t=oB.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new uS({algorithm:SC,parameters:lb.serialize(t)})}return new uS({algorithm:SC,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case IC:return{name:"RSASSA-PKCS1-v1_5"};case kC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case _C:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case BC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case RC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case SC:if(e.parameters){const t=lb.parse(e.parameters,$C);return{name:"RSA-PSS",hash:Ik.resolve(Ex).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};aB=oB=hb([vk()],aB),Ik.registerSingleton(Sx,aB);let cB=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new uS({algorithm:TC});case"sha-256":return new uS({algorithm:DC});case"sha-384":return new uS({algorithm:MC});case"sha-512":return new uS({algorithm:PC})}return null}toWebAlgorithm(e){switch(e.algorithm){case TC:return{name:"SHA-1"};case DC:return{name:"SHA-256"};case MC:return{name:"SHA-384"};case PC:return{name:"SHA-512"}}return null}};cB=hb([vk()],cB),Ik.registerSingleton(Sx,cB);class lB{addPadding(e,t){const r=$p.toUint8Array(t),s=new Uint8Array(e);return s.set(r,e-r.length),s}removePadding(e,t=!1){let r=$p.toUint8Array(e);for(let e=0;e<r.length;e++)if(r[e]){r=r.slice(e);break}if(t&&r[0]>127){const e=new Uint8Array(r.length+1);return e.set(r,1),e.buffer}return r.buffer}toAsnSignature(e,t){if("ECDSA"===e.name){const r=e.namedCurve,s=lB.namedCurveSize.get(r)||lB.defaultNamedCurveSize,i=new bC,n=$p.toUint8Array(t);return i.r=this.removePadding(n.slice(0,s),!0),i.s=this.removePadding(n.slice(s,s+s),!0),lb.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=lb.parse(t,bC),s=e.namedCurve,i=lB.namedCurveSize.get(s)||lB.defaultNamedCurveSize;return Xp(this.addPadding(i,this.removePadding(r.r)),this.addPadding(i,this.removePadding(r.s)))}return null}}lB.namedCurveSize=new Map,lB.defaultNamedCurveSize=32;const hB="1.3.101.110",uB="1.3.101.111",dB="1.3.101.112",fB="1.3.101.113";let pB=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=dB;break;case"x25519":t=hB;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=dB;break;case"ed448":t=fB}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=hB;break;case"x448":t=uB}}return t?new uS({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case dB:return{name:"Ed25519"};case fB:return{name:"EdDSA",namedCurve:"Ed448"};case hB:return{name:"X25519"};case uB:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};pB=hb([vk()],pB),Ik.registerSingleton(Sx,pB);(class extends H_{constructor(e){H_.isAsnEncoded(e)?super(e,wx):super(e),this.tag=L_.CertificateRequestTag}onInit(e){this.tbs=lb.serialize(e.certificationRequestInfo),this.publicKey=new K_(e.certificationRequestInfo.subjectPKInfo);const t=Ik.resolve(Ex);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>iB.create(lb.serialize(e)));const r=this.getAttribute(Wk);this.extensions=[],r instanceof sB&&(this.extensions=r.items),this.subjectName=new m_(e.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(e){for(const t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(const t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=d_.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),s=Ik.resolveAll(nB).reverse();let i=null;for(const e of s)if(i=e.toWebSignature(t,this.signature),i)break;if(!i)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,r,i,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty(),t=lb.parse(this.rawData,wx),r=t.certificationRequestInfo,s=new n_("",{Version:`${bS[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new n_("");for(const t of this.attributes){const r=t.toTextObject();e[r[n_.NAME]]=r}s.Attributes=e}return e.Data=s,e.Signature=new n_("",{Algorithm:a_.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";var gB;(class extends H_{constructor(e){H_.isAsnEncoded(e)?super(e,IS):super(e),this.tag=L_.CertificateTag}onInit(e){const t=e.tbsCertificate;this.tbs=lb.serialize(t),this.serialNumber=Yp.ToHex(t.serialNumber),this.subjectName=new m_(t.subject),this.subject=new m_(t.subject).toString(),this.issuerName=new m_(t.issuer),this.issuer=this.issuerName.toString();const r=Ik.resolve(Ex);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signatureValue;const s=t.validity.notBefore.utcTime||t.validity.notBefore.generalTime;if(!s)throw new Error("Cannot get 'notBefore' value");this.notBefore=s;const i=t.validity.notAfter.utcTime||t.validity.notAfter.generalTime;if(!i)throw new Error("Cannot get 'notAfter' value");this.notAfter=i,this.extensions=[],t.extensions&&(this.extensions=t.extensions.map(e=>W_.create(lb.serialize(e)))),this.publicKey=new K_(t.subjectPublicKeyInfo)}getExtension(e){for(const t of this.extensions)if("string"==typeof e){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>"string"==typeof e?t.type===e:t instanceof e)}async verify(e={},t=d_.get()){let r,s;const i=e.publicKey;try{if(i)if("publicKey"in i)r={...i.publicKey.algorithm,...this.signatureAlgorithm},s=await i.publicKey.export(r,["verify"],t);else if(i instanceof K_)r={...i.algorithm,...this.signatureAlgorithm},s=await i.export(r,["verify"],t);else if($p.isBufferSource(i)){const e=new K_(i);r={...e.algorithm,...this.signatureAlgorithm},s=await e.export(r,["verify"],t)}else r={...i.algorithm,...this.signatureAlgorithm},s=i;else r={...this.publicKey.algorithm,...this.signatureAlgorithm},s=await this.publicKey.export(r,["verify"],t)}catch(e){return!1}const n=Ik.resolveAll(nB).reverse();let o=null;for(const e of n)if(o=e.toWebSignature(r,this.signature),o)break;if(!o)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const a=await t.subtle.verify(this.signatureAlgorithm,s,o,this.tbs);if(e.signatureOnly)return a;{const t=(e.date||new Date).getTime();return a&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t,r="SHA-1";return e[0]&&(e[0].subtle?t=e[0]:(r=e[0]||r,t=e[1])),null!=t||(t=d_.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=d_.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=lb.parse(this.rawData,IS),r=t.tbsCertificate,s=new n_("",{Version:`${bS[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":a_.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new n_("",{"Not Before":r.validity.notBefore.getTime(),"Not After":r.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(r.issuerUniqueID&&(s["Issuer Unique ID"]=r.issuerUniqueID),r.subjectUniqueID&&(s["Subject Unique ID"]=r.subjectUniqueID),this.extensions.length){const e=new n_("");for(const t of this.extensions){const r=t.toTextObject();e[r[n_.NAME]]=r}s.Extensions=e}return e.Data=s,e.Signature=new n_("",{Algorithm:a_.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}).NAME="Certificate",function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(gB||(gB={})),W_.register(Xv,V_),W_.register(_w,j_),W_.register(Kw,G_),W_.register(sS,q_),W_.register(Wv,Q_),W_.register(Xw,z_),W_.register(yw,Y_),W_.register(Gv,X_),iB.register(zk,rB),iB.register(Wk,sB),Ik.registerSingleton(nB,class{toAsnSignature(e,t){return $p.toArrayBuffer(t)}toWebSignature(e,t){return $p.toArrayBuffer(t)}}),Ik.registerSingleton(nB,lB),lB.namedCurveSize.set("P-256",32),lB.namedCurveSize.set("K-256",32),lB.namedCurveSize.set("P-384",48),lB.namedCurveSize.set("P-521",66),m.new(void 0,"networking");const yB=new class extends YA{constructor(){super(...arguments),this.subtle=new wv}getRandomValues(e){if(!ArrayBuffer.isView(e))throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'");const t=rI.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return iI().randomFillSync(t),e}};var mB,bB,AB;function IB(e){return ge(e)}d_.set(yB),(AB=mB||(mB={}))[AB.NoCertificate=0]="NoCertificate",AB[AB.NotEd25519=1]="NotEd25519",AB[AB.PublicKeyTypeMismatch=2]="PublicKeyTypeMismatch",AB[AB.AltNameMismatch=3]="AltNameMismatch",AB[AB.IncorrectSignature=4]="IncorrectSignature",function(e){e[e.Public=0]="Public",e[e.Private=1]="Private"}(bB||(bB={})),m.new(void 0,"net:peers"),m.new(void 0,"net"),m.new(void 0,"net"),m.new(void 0,"net"),m.new(void 0,"jamnps");const vB=IB(0);class wB extends G{hash;slot;static Codec=Ve.Class(wB,{hash:Ve.bytes(Rt).asOpaque(),slot:Ve.u32.asOpaque()});static create({hash:e,slot:t}){return new wB(e,t)}constructor(e,t){super(),this.hash=e,this.slot=t}}class SB{final;leafs;static Codec=Ve.Class(SB,{final:wB.Codec,leafs:Ve.sequenceVarLen(wB.Codec)});static create({final:e,leafs:t}){return new SB(e,t)}constructor(e,t){this.final=e,this.leafs=t}}class EB extends G{header;final;static Codec=Ve.Class(EB,{header:hs.Codec,final:wB.Codec});static create({header:e,final:t}){return new EB(e,t)}constructor(e,t){super(),this.header=e,this.final=t}}const CB=m.new(void 0,"protocol/up-0");class kB{getHandshake;onAnnouncement;kind=vB;handshakes=new Map;pendingHandshakes=new Map;constructor(e,t){this.getHandshake=e,this.onAnnouncement=t}onStreamMessage(e,t){const r=e.streamId;if(!this.handshakes.has(r)){const s=xe.decodeObject(SB.Codec,t);return this.handshakes.set(r,s),void(this.pendingHandshakes.delete(r)||(CB.log(`[${r}] <-- responding with a handshake.`),e.bufferAndSend(Te.encodeObject(SB.Codec,this.getHandshake()))))}const s=xe.decodeObject(EB.Codec,t);CB.info(`[${r}] got blocks announcement: ${s}`),this.onAnnouncement(s)}onClose(e){this.handshakes.delete(e)}sendHandshake(e,t){this.pendingHandshakes.set(e.streamId,!0),e.bufferAndSend(Te.encodeObject(SB.Codec,t))}sendAnnouncement(e,t){this.handshakes.has(e.streamId)?e.bufferAndSend(Te.encodeObject(EB.Codec,t)):CB.warn(`[${e.streamId}] no handshake yet, skipping announcement.`)}}var xB;IB(128),function(e){e[e.AscExcl=0]="AscExcl",e[e.DescIncl=1]="DescIncl"}(xB||(xB={}));class _B extends G{headerHash;direction;maxBlocks;static Codec=Ve.Class(_B,{headerHash:Ve.bytes(Rt).asOpaque(),direction:Ve.u8.convert(e=>ge(e),e=>{switch(e){case xB.AscExcl:return xB.AscExcl;case xB.DescIncl:return xB.DescIncl;default:throw new Error(`Invalid 'Direction' value: ${e}`)}}),maxBlocks:Ve.u32});static create({headerHash:e,direction:t,maxBlocks:r}){return new _B(e,t,r)}constructor(e,t,r){super(),this.headerHash=e,this.direction=t,this.maxBlocks=r}}m.new(void 0,"protocol/ce-128");const BB=IB(129),RB=Ve.bytes(64).convert(e=>re.fromBlob(e.raw,64),e=>new Ji(e.raw));class OB extends G{key;value;static Codec=Ve.Class(OB,{key:Ve.bytes(zi),value:Ve.blob});static create({key:e,value:t}){return new OB(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}class UB extends G{keyValuePairs;static Codec=Ve.Class(UB,{keyValuePairs:Ve.sequenceVarLen(OB.Codec)});static create({keyValuePairs:e}){return new UB(e)}constructor(e){super(),this.keyValuePairs=e}}class TB extends G{headerHash;startKey;endKey;maximumSize;static Codec=Ve.Class(TB,{headerHash:Ve.bytes(Rt).asOpaque(),startKey:Ve.bytes(zi),endKey:Ve.bytes(zi),maximumSize:Ve.u32});static create({headerHash:e,startKey:t,endKey:r,maximumSize:s}){return new TB(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.startKey=t,this.endKey=r,this.maximumSize=s}}const NB=m.new(void 0,"protocol/ce-129");class DB{isServer;getBoundaryNodes;getKeyValuePairs;kind=BB;boundaryNodes=new Map;onResponse=new Map;constructor(e=!1,t,r){if(this.isServer=e,this.getBoundaryNodes=t,this.getKeyValuePairs=r,e&&(void 0===t||void 0===r))throw new Error("getBoundaryNodes and getKeyValuePairs are required in server mode.")}onStreamMessage(e,t){if(this.isServer){if(NB.info(`[${e.streamId}][server]: Received request.`),void 0===this.getBoundaryNodes||void 0===this.getKeyValuePairs)return;const r=xe.decodeObject(TB.Codec,t),s=this.getBoundaryNodes(r.headerHash,r.startKey,r.endKey),i=this.getKeyValuePairs(r.headerHash,r.startKey,r.endKey);return NB.info(`[${e.streamId}][server]: <-- responding with boundary nodes and key value pairs.`),e.bufferAndSend(Te.encodeObject(Ve.sequenceVarLen(RB),s)),e.bufferAndSend(Te.encodeObject(UB.Codec,UB.create({keyValuePairs:i}))),void e.close()}if(!this.boundaryNodes.has(e.streamId))return this.boundaryNodes.set(e.streamId,xe.decodeObject(Ve.sequenceVarLen(RB),t)),void NB.info(`[${e.streamId}][client]: Received boundary nodes.`);this.onResponse.get(e.streamId)?.(xe.decodeObject(UB.Codec,t)),NB.info(`[${e.streamId}][client]: Received state values.`)}onClose(e){this.boundaryNodes.delete(e),this.onResponse.delete(e)}getStateByKey(e,t,r,s){if(this.onResponse.has(e.streamId))throw new Error("It is disallowed to use the same stream for multiple requests.");this.onResponse.set(e.streamId,s),e.bufferAndSend(Te.encodeObject(TB.Codec,TB.create({headerHash:t,startKey:r,endKey:r,maximumSize:Ae(4096)}))),e.close()}}IB(131),IB(132);class MB extends G{epochIndex;ticket;static Codec=Ve.Class(MB,{epochIndex:Ve.u32.asOpaque(),ticket:is.Codec});static create({epochIndex:e,ticket:t}){return new MB(e,t)}constructor(e,t){super(),this.epochIndex=e,this.ticket=t}}m.new(void 0,"protocol/ce-131-ce-132"),IB(133);class PB extends G{coreIndex;workPackage;static Codec=Ve.Class(PB,{coreIndex:Ve.u16.asOpaque(),workPackage:jr.Codec});static create({coreIndex:e,workPackage:t}){return new PB(e,t)}constructor(e,t){super(),this.coreIndex=e,this.workPackage=t}}m.new(void 0,"protocol/ce-133"),Ve.blob,IB(134);class LB extends G{coreIndex;segmentsRootMappings;static Codec=Ve.Class(LB,{coreIndex:Ve.u16.asOpaque(),segmentsRootMappings:Ve.sequenceVarLen(Xr.Codec)});static create({coreIndex:e,segmentsRootMappings:t}){return new LB(e,t)}constructor(e,t){super(),this.coreIndex=e,this.segmentsRootMappings=t}}class HB extends G{workReportHash;signature;static Codec=Ve.Class(HB,{workReportHash:Ve.bytes(Rt).asOpaque(),signature:Ve.bytes(Et).asOpaque()});static create({workReportHash:e,signature:t}){return new HB(e,t)}constructor(e,t){super(),this.workReportHash=e,this.signature=t}}m.new(void 0,"protocol/ce-134"),IB(135);class KB extends G{report;slot;signatures;static Codec=Ve.Class(KB,{report:Zr.Codec,slot:Ve.u32.asOpaque(),signatures:mr(e=>br(ts.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2}))});static create({report:e,slot:t,signatures:r}){return new KB(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.signatures=r}}m.new(void 0,"protocol/ce-135");const QB=t(import.meta.url)("node:net"),VB=t(import.meta.url)("node:path"),FB=t(import.meta.url)("node:buffer");var $B;!function(e){e[e.Msg=0]="Msg",e[e.Open=1]="Open",e[e.Close=2]="Close"}($B||($B={}));class jB{streamId;type;data;static Codec=Ve.Class(jB,{streamId:Ve.u32,type:Ve.u8.convert(e=>ge(e),e=>{switch(e){case $B.Msg:return $B.Msg;case $B.Open:return $B.Open;case $B.Close:return $B.Close;default:throw new Error(`Invalid 'StreamEnvelopeType' value: ${e}`)}}),data:Ve.blob});static create({streamId:e,type:t,data:r}){return new jB(e,t,r)}constructor(e,t,r){this.streamId=e,this.type=t,this.data=r}}class GB{streamByte;static Codec=Ve.Class(GB,{streamByte:Ve.u8});static create({streamByte:e}){return new GB(e)}constructor(e){this.streamByte=e}}const qB=m.new(void 0,"ext-ipc");class zB{streams=new Map;pendingStreams=new Map;streamHandlers=new Map;onEnd;sender;constructor(e){const t={finished:!1};t.listen=new Promise((e,r)=>{t.resolve=e,t.reject=r}),this.onEnd=t,this.sender=new JB(e)}registerHandlers(...e){for(const t of e)this.streamHandlers.set(t.kind,t)}withStreamOfKind(e,t){for(const[r,s]of this.streams.entries())if(s.kind===e)return void t(s,new WB(r,this.sender));throw new Error(`Missing handler for ${e}!`)}withNewStream(e,t){const r=this.streamHandlers.get(e);if(void 0===r)throw new Error(`Stream with unregistered handler of kind: ${e} was requested to be opened.`);const s=this.streams,i=function e(){const t=Math.floor(65536*Math.random());return s.has(t)?e():t}();this.streams.set(i,r),this.pendingStreams.set(i,!0);const n=new WB(i,this.sender);n.open(GB.create({streamByte:e})),t(r,n)}onSocketMessage(e){const t=xe.decodeObject(jB.Codec,e),r=t.streamId;qB.log(`[${r}] incoming message: ${t.type} ${t.data}`);const s=this.streams.get(r),i=new WB(r,this.sender);if(void 0===s){if(t.type!==$B.Open)return void qB.warn(`[${r}] (unknown) got invalid type ${t.type}.`);const e=xe.decodeObject(GB.Codec,t.data),s=this.streamHandlers.get(e.streamByte);return void 0!==s?(qB.log(`[${r}] new stream for ${s.kind}`),this.streams.set(r,s),void i.open(e)):void i.close()}if(t.type===$B.Close){const e=this.streams.get(r);return e?.onClose(r,!1),void this.streams.delete(r)}t.type===$B.Msg?s.onStreamMessage(i,t.data):this.pendingStreams.delete(r)||qB.warn(`[${r}] got invalid type ${t.type}.`)}onClose({error:e}){qB.log(`Closing the handler. Reason: ${void 0!==e?e.message:"close"}.`);for(const[t,r]of this.streams.entries())r.onClose(t,void 0===e);this.streams.clear(),this.onEnd.finished=!0,void 0!==e?this.onEnd.reject(e):this.onEnd.resolve()}waitForEnd(){return qB.log("Waiting for the handler to be closed."),this.onEnd.listen}}class WB{streamId;sender;constructor(e,t){this.streamId=e,this.sender=t}open(e){const t=Te.encodeObject(GB.Codec,e);this.sender.send(Te.encodeObject(jB.Codec,jB.create({streamId:this.streamId,type:$B.Open,data:t})))}bufferAndSend(e){return this.sender.send(Te.encodeObject(jB.Codec,jB.create({streamId:this.streamId,type:$B.Msg,data:e}))),!0}close(){this.sender.send(Te.encodeObject(jB.Codec,jB.create({streamId:this.streamId,type:$B.Close,data:te.blobFromNumbers([])})))}}class JB{socket;constructor(e){this.socket=e}send(e){!function(e,t){const r=new Uint8Array(YB);Te.create({destination:r}).i32(t.length),e.write(r),e.write(t)}(this.socket,e.raw)}close(){this.socket.end()}}const YB=4;function XB(e){const t=function(e){const t=new En.EventEmitter;let r=null;return e.bestHeader.on(e=>{const s=e.data.materialize(),i=e.hash,n=wB.create({hash:i,slot:s.timeSlotIndex});r=n,t.emit("announcement",EB.create({header:s,final:n}))}),function(e,t,r,s){const i="win32"===b.platform()?"\\\\.\\pipe\\typeberry":VB.join(b.tmpdir(),"typeberry.ipc"),n=m.new(void 0,"ext-ipc"),o=(0,QB.createServer)(i=>{n.log("Client connected");const o=new zB(i);o.registerHandlers(new kB(t,()=>{})),o.registerHandlers(new DB(!0,r,s));const a=e=>{if(!(e instanceof EB))throw new Error(`Invalid annoncement received: ${e}`);o.withStreamOfKind(vB,(t,r)=>{t.sendAnnouncement(r,e)})};e.on("announcement",a),i.on("data",function(e){let t=FB.Buffer.alloc(0),r=-1;return s=>{t=FB.Buffer.concat([t,s]);do{if(-1===r){if(t.length<YB)break;r=t.readUint32LE(),t=t.subarray(YB)}if(t.length<r)break;const s=t.subarray(0,r);t=t.subarray(r),r=-1,e(s)}while(t.length>0)}}(e=>{try{o.onSocketMessage(new Uint8Array(e))}catch(e){n.error(`Received invalid data on socket: ${e}. Closing connection.`),i.end()}})),i.on("end",()=>{n.log("Client disconnected"),o.onClose({}),e.off("annoucement",a)}),i.on("error",e=>{n.error(`Socket error: ${e}`),o.onClose({error:e}),i.end()})});try{O.unlinkSync(i)}catch{}const a=new AbortController;return o.listen({path:i,signal:a.signal},()=>{n.log(`IPC server is listening at ${i}`)}),o.on("error",e=>{throw e}),()=>{n.info("Closing IPC server."),o.close(),a.abort(),o.unref()}}(t,()=>{const e=r??wB.create({hash:re.zero(Rt).asOpaque(),slot:_r(0)});return SB.create({final:e,leafs:[]})},()=>[],(e,t)=>{let r=te.blobFromNumbers([255,255,0,0]);return re.fromBlob(Kt("0x83bd3bde264a79a2e67c487696c1d7f0b549da89").raw.subarray(0,zi),zi).isEqualTo(t)&&(r=te.blobFromNumbers([255,255,255,0])),[new OB(t,r)]})}(e);return()=>{t()}}const ZB=e=>e.endsWith(".json");function eR(e,t){const r=U().readFileSync(e),s=te.blobFrom(new Uint8Array(r));return xe.decodeObject(ys.Codec.View,s,t)}function tR(e,t){const r=U().readFileSync(e,"utf-8"),s=bs(JSON.parse(r),(i=t,Is.object({header:Gs,extrinsic:(n=i,Is.object({tickets:Qs,preimages:Hs,guarantees:Ps,assurances:ws(n),disputes:xs},({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})=>gs.create({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})))},({header:e,extrinsic:t})=>ys.create({header:e,extrinsic:t}))));var i,n;const o=Te.encodeObject(ys.Codec,s,t);return xe.decodeObject(ys.Codec.View,o,t)}const rR=JSON.parse('{"$schema":"./config-v1.schema.json","version":1,"flavor":"tiny","authorship":{"omit_seal_verification":false},"chain_spec":{"id":"typeberry-dev","bootnodes":["e3r2oc62zwfj3crnuifuvsxvbtlzetk4o5qyhetkhagsc2fgl2oka@127.0.0.1:40000","eecgwpgwq3noky4ijm4jmvjtmuzv44qvigciusxakq5epnrfj2utb@127.0.0.1:12345","en5ejs5b2tybkfh4ym5vpfh7nynby73xhtfzmazumtvcijpcsz6ma@127.0.0.1:12346","ekwmt37xecoq6a7otkm4ux5gfmm4uwbat4bg5m223shckhaaxdpqa@127.0.0.1:12347"],"genesis_header":"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da293d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e948e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260fafff16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea020000ffff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","genesis_state":{"01000000000000000000000000000000000000000000000000000000000000":"08000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","02000000000000000000000000000000000000000000000000000000000000":"0b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb00b27478648cd19b4f812f897a26976ecf312eac28508b4368d0c63ea949c7cb0","03000000000000000000000000000000000000000000000000000000000000":"00","04000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf426000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000085f9095f4abd040839d793d89ab5ff25c61e50c844ab6765e2c0b22373b5a8f6fbe5fc0cd61fdde580b3d44fe1be127197e33b91960b10d2c6fc75aec03f36e16c2a8204961097dbc2c5ba7655543385399cc9ef08bf2e520ccf3b0a7569d88492e630ae2b14e758ab0960e372172203f4c9a41777dadd529971d7ab9d23ab29fe0e9c85ec450505dde7f5ac038274cf01aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bc5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d48e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e33d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d03d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d05e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161df16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d3d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d0aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bcaa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bc3d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e300","05000000000000000000000000000000000000000000000000000000000000":"00000000","06000000000000000000000000000000000000000000000000000000000000":"6f6ad2224d7d58aec6573c623ab110700eaca20a48dc2965d535e466d524af2a835ac82bfa2ce8390bb50680d4b7a73dfa2a4cff6d8c30694b24a605f9574eafd2d34655ebcad804c56d2fd5f932c575b6a5dbb3f5652c5202bcc75ab9c2cc958a715731759b7fceaae288bcb70a605c31cbdfae83d0f4a45dfc2b2458dc9fae","07000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf4260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","08000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf4260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","09000000000000000000000000000000000000000000000000000000000000":"5e465beb01dbafe160ce8216047f2155dd0569f058afd52dcea601025a8d161d3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29b27150a1f1cd24bccc792ba7ba4220a1e8c36636e35a969d1d14b4c89bce7d1d463474fb186114a89dd70e88506fefc9830756c27a7845bec1cb6ee31e07211afd0dde34f0dc5d89231993cd323973faa23d84d521fd574e840b8617c75d1a1d0102aa3c71999137001a77464ced6bb2885c460be760c709009e26395716a52c8c52e6e23906a455b4264e7d0c75466e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003d5e5a51aab2b048f8686ecd79712a80e3265a114cc73f14bdb2a59233fb66d022351e22105a19aabb42589162ad7f1ea0df1c25cebf0e4a9fcd261301274862a2534be5b2f761dc898160a9b4762eb46bd171222f6cdf87f5127a9e8970a54c44fe7b2e12dda098854a9aaab03c3a47953085668673a84b0cedb4b0391ed6ae2deb1c3e04f0bc618a2bc1287d8599e8a1c47ff715cd4cbd3fe80e2607744d4514b491ed2ef76ae114ecb1af99ba6af32189bf0471c06aa3e6acdaf82e7a959cb24a5c1444cac3a6678f5182459fd8ce0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000aa2b95f7572875b0d0f186552ae745ba8222fc0b5bd456554bfe51c68938f8bce68e0cf7f26c59f963b5846202d2327cc8bc0c4eff8cb9abd4012f9a71decf008faee314528448651e50bea6d2e7e5d3176698fea0b932405a4ec0a19775e72325e44a6d28f99fba887e04eb818f13d1b73f75f0161644283df61e7fbaad7713fae0ef79fe92499202834c97f512d744515a57971badf2df62e23697e9fe347f168fed0adb9ace131f49bbd500a324e2469569423f37c5d3b430990204ae17b383fcd582cb864168c8b46be8d779e7ca00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f6190116d118d643a98878e294ccf62b509e214299931aad8ff9764181a4e33b3e0e096b02e2ec98a3441410aeddd78c95e27a0da6f411a09c631c0f2bea6e98dfdac3e2f604ecda637e4969a139ceb70c534bd5edc4210eb5ac71178c1d62f0c977197a2c6a9e8ada6a14395bc9aa3a384d35f40c3493e20cb7efaa799f66d1cedd5b2928f8e34438b07072bbae404d7dfcee3f457f9103173805ee163ba550854e4660ccec49e25fafdb00e6adfbc8e875de1a9541e1721e956b972ef2b135cc7f71682615e12bb7d6acd353d7681000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048e5fcdce10e0b64ec4eebd0d9211c7bac2f27ce54bca6f7776ff6fee86ab3e35c7f34a4bd4f2d04076a8c6f9060a0c8d2c6bdd082ceb3eda7df381cb260faffb78a95d81f6c7cdc517a36d81191b6f7718dcf44e76c0ce9fb724d3aea39fdb3c5f4ee31eb1f45e55b783b687b1e9087b092a18341c7cda102b4100685b0a014d55f1ccdb7600ec0db14bb90f7fc3126dc2625945bb44f302fc80df0c225546c06fa1952ef05bdc83ceb7a23373de0637cd9914272e3e3d1a455db6c48cc6b2b2c17e1dcf7cd1586a235821308aee0010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f16e5352840afb47e206b5c89f560f2611835855cf2e6ebad1acc9520a72591d837ce344bc9defceb0d7de7e9e9925096768b7adb4dad932e532eb6551e0ea02b0b9121622bf8a9a9e811ee926740a876dd0d9036f2f3060ebfab0c7c489a338a7728ee2da4a265696edcc389fe02b2caf20b5b83aeb64aaf4184bedf127f4eea1d737875854411d58ca4a2b69b066b0a0c09d2a0b7121ade517687c51954df913fe930c227723dd8f58aa2415946044dc3fb15c367a2185d0fc1f7d2bb102ff14a230d5f81cfc8ad445e51efddbf4260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","0a000000000000000000000000000000000000000000000000000000000000":"0000","0b000000000000000000000000000000000000000000000000000000000000":"00000000","0c000000000000000000000000000000000000000000000000000000000000":"00000000000000000000000000","0d000000000000000000000000000000000000000000000000000000000000":"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","0e000000000000000000000000000000000000000000000000000000000000":"000000000000000000000000","0f000000000000000000000000000000000000000000000000000000000000":"000000000000000000000000","ff000000000000000000000000000000000000000000000000000000000000":"15f8485e3a88e86182e63280720d5ec9892578f0e577fb1bcdda5cf49795081500e40b540200000064000000000000006400000000000000100500000000000004000000","00fe00ff00ff00ff6326432b5b3213dfd1609495e13c6b276cb474d6796453":"09626f6f74737472617000000000000000000020000a00000000000628023307320015","00fe00ff00ff00fff8485e3a88e86182e63280720d5ec9892578f0e577fb1b":"09626f6f747374726170000000000000020000200032040000050283ae7900300194012f027802280d00000028ae00000028ab029511e07b10187b15107b1608648664783309043307000001ac967c9566fc5106769587047d7833050159083a8489ff003305025329c0002d3305035329e000253305045329f0001d3305055329f800153305065329fc000d8898fe009a850801ac564564587b175010029c026478e45607c95707d88709e48707c98707887720d479098217c8750594983307000001da95072805330801821018821510821608951120320000951150ff7b10a8007b15a0007b169800330908ac98e7003309fcaa97e5015107e101958af8957508510a457d583306015908408489ff003306025329c0002d3306035329e000253306045329f0001d3306055329f800153306065329fc000d8898fe009a860801ae6a092890003306017b166457646864a6501004e501821a51077be4a607c9a70753176072c85a089576a09587607b1751064c7d783305015908378489ff003305025329c0002d3305035329e000253305045329f0001d3305055329f800153305065329fc000d8898fe009a850801ac562a016458501006810128073305330701e45608c95808e47808c97808330921ae981d33083307000001018210a8008215a000821698009511b00032008219c89505c857077c792051090933083307286e958adf957521510a547d573306015907378477ff003306025327c0002d3306035327e000253306045327f0001d3306055327f800153306065327fc000d8877fe009a7608017b1aac6a920064576468501008e6006478821a28073306330801c86507e46a09c96909e6890801c878088088fc330964330a640a0964757b1708481114951714330804951908330a040a0395171833098000330850100a4a330820a107330964951a1864570a0b81180833070000023b080000029889183b090300029889103b090200029888083b080100023308202806ff0000003307000001330832008d7a84aa07c8a70b510a0e647c0178c895cc01acbcfbc9a903843cf8c8cb0a580c1d8482ff0014090101010101010101ca920c017bbc95bb08acabfb843907520905280ec8a9090178a895aa01ac9afb320051089b0064797c77510791005127ff0090006c7a570a09330a330828735527c0000d330a01330b80284a5527e0000e330a02330b40ff283c5527f0000e330a03330b20ff282e5527f8000e330a04330b10ff28205527fc000e330a05330b08ff2812887afe00330b04ff93ab02ff85aa0701ae8a2b3308c8b70764ab01c8b90c7ccc97880895bbffd4c808520bf28aa903cf9707c88707320032000000002124492a21494a22212121212132154a9224a5909a248d88482422494924242424244426ad0a258924a524121212121222a3504d92a43022a292a44a52120909090909914585aa26c924a924494a1421a984909090903c54495a92241140962465495111942a24854421514814124544a6342549923a","0023000000000000478648cd19b4f812f897a26976ecf312eac28508b4368d":"0100000000","004b000400000000f324d112c31c3778a072940b55dd35f3a4b77e72d2d2db":"0100000000"}},"database_base_path":"./database"}'),sR=m.new(void 0,"jam");var iR;async function nR(e,t){if(!T.isMainThread)return void sR.error("The main binary cannot be running as a Worker!");const r={isAuthoring:!1,blocksToImport:e.command===k.Import?e.args.files:null,nodeName:e.args.nodeName,config:hR(e.args.configPath)},s=cR(r.config.flavor),{rootDb:i,dbPath:n,genesisHeaderHash:o}=lR(r.nodeName,r.config.chainSpec.genesisHeader,t(r.config.databaseBasePath));await async function(e,t,r,s){const i=new In(e,r),n=new Sn(e,r),o=i.getBestHeaderHash(),a=i.getPostStateRoot(o);if(sR.log(`🛢️ Best header hash: ${o}`),sR.log(`🛢️ Best state root: ${a}`),null!==a&&!a.isEqualTo(re.zero(Rt))&&!o.isEqualTo(re.zero(Rt)))return void await r.db.close();sR.log("🛢️ Database looks fresh. Initializing.");const c=xe.decodeObject(hs.Codec,s.genesisHeader,e),l=ys.create({header:hs.empty(),extrinsic:gs.create({tickets:[],preimages:[],assurances:[],guarantees:[],disputes:{verdicts:[],culprits:[],faults:[]}})}).extrinsic,h=ys.create({header:c,extrinsic:l}),u=xe.decodeObject(ys.Codec.View,Te.encodeObject(ys.Codec,h,e),e);sR.log(`🧬 Writing genesis block #${c.timeSlotIndex}: ${t}`);const{genesisStateSerialized:d,genesisStateRootHash:f}=function(e,t){const r=mn.fromEntries(Array.from(t.entries())),s=cn.fromTruncatedDictionaryUnsafe(r),i=Gi.fromStateEntries(e,s),n=s.getRootHash();return sR.info(`🧬 Genesis state root: ${n}`),{genesisState:i,genesisStateSerialized:s,genesisStateRootHash:n}}(e,s.genesisState);await i.insertBlock(new Ot(t,u)),await n.insertState(t,d),await i.setPostStateRoot(t,f),await i.setBestHeaderHash(t),await r.db.close()}(s,o,i,r.config.chainSpec);const a=await async function(){const e=Sh,t=new vh;return Qn(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/importer/index.ts"),e,"ready(main)",t)}(),c=XB({bestHeader:a.getState("ready(main)").onBestBlock}),l=new yr(s,n,r.config.authorship.omitSealVerification),h=a.transition((e,t)=>e.sendConfig(t,l)),u=aR(h,s,r.blocksToImport),d=await oR(r.isAuthoring,l,h);sR.info("[main]⌛ waiting for importer to finish");const f=await u;sR.log("[main] ☠️ Closing the extensions"),c(),sR.log("[main]⌛ waiting for tasks to finish"),await f.currentState().waitForWorkerToFinish(),sR.log("[main] ☠️ Closing the authorship module"),d(),sR.info("[main] ✅ Done.")}!function(e){e[e.InMemory=0]="InMemory",e[e.Lmdb=1]="Lmdb"}(iR||(iR={}));const oR=async(e,t,r)=>{if(!e)return()=>Promise.resolve();sR.info("✍️ Starting block generator.");const{generator:s,finish:i}=await async function(e){const t=(await async function(){const e=Rh,t=new _h;return Qn(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/block-generator/index.ts"),e,"ready(main)",t)}()).transition((t,r)=>t.sendConfig(r,e));return{generator:t,finish:()=>(t.transition((e,t)=>e.finish(t)),t.waitForState("finished"))}}(t);return r.doUntil("finished",async(e,t)=>{s.currentState().onBlock.on(r=>{sR.log(`✍️ Produced block. Size: [${r.length}]`),e.sendBlock(t,r)})}),i},aR=async(e,t,r)=>null===r?e.waitForState("finished"):(sR.info(`📖 Reading ${r.length} blocks`),e.transition((e,s)=>{const i=function*(e){const{chainSpec:t}=e;for(const r of e.files){const e=ZB(r)?tR(r,t):eR(r,t);yield e}}({files:r,chainSpec:t});for(const t of i)sR.log(`📖 Importing block: #${t.header.view().timeSlotIndex.materialize()}`),e.sendBlock(s,t.encoded().raw);return sR.info("All blocks scheduled to be imported."),e.finish(s)})),cR=e=>{if(e===Js.Full)return gr;if(e===Js.Tiny)return pr;throw new Error(`Unknown chain spec: ${e}. Possible options: ${[Js.Full,Js.Tiny]}`)};function lR(e,t,r,{readOnly:s=!1}={}){const i=Kt(e).toString().substring(2,10),n=Ht(t).asOpaque(),o=`${r}/${i}/${n.toString().substring(2,10)}`;sR.info(`🛢️ Opening database at ${o}`);try{return{dbPath:o,rootDb:new wn(o,s),genesisHeaderHash:n}}catch(e){throw new Error(`Unable to open database at ${o}: ${e}`)}}function hR(e){if(e===v)return bs(rR,Xs.fromJson);try{const t=U().readFileSync(e,"utf8");return bs(JSON.parse(t),Xs.fromJson)}catch(t){throw new Error(`Unable to load config file from ${e}: ${t}`)}}if("file:///home/runner/work/typeberry/typeberry/bin/jam/index.ts"===(0,c.pathToFileURL)(process.argv[1]).href){m.configureAll(process.env.JAM_LOG??"",l.LOG);const e="undefined/../..",t=t=>t.startsWith("/")?t:`${e}/${t}`;let r;try{r=_(process.argv.slice(2),t)}catch(e){console.error(`\n${e}\n`),console.info(S),process.exit(1)}nR(r,t).catch(e=>{console.error(`${e}`),process.exit(-1)})}let uR;m.configureAll(process.env.JAM_LOG??"",l.LOG);try{uR=_(process.argv.slice(2),dR)}catch(e){console.error(`\n${e}\n`),console.info(S),process.exit(1)}function dR(e){return e}nR(uR,dR).catch(e=>{console.error(`${e}`),process.exit(-1)});export{k as Command,w as DEFAULTS,v as DEV_CONFIG,iR as DatabaseKind,S as HELP,cR as getChainSpec,hR as loadConfig,nR as main,lR as openDatabase,_ as parseArgs};
3
3
  //# sourceMappingURL=typeberry.mjs.map