@typeberry/jam 0.0.1-ffaff74 → 0.0.1-ffdd6b4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- 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 g 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 g(e)}static fromDecimalDottedString(e){return new g(e)}static fromString(e){return g.fromDecimalDottedString(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new g(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 g.fromNumber(this.getValue()+1n)}previousIPNumber(){return g.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=g;class p extends f{constructor(e){if(super(),this.bitSize=32,this.maximumBitSize=i.Validator.THIRTY_TWO_BIT_SIZE,this.type="ASN","string"==typeof e)p.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 p(e)}static fromNumber(e){return new p(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new p(parseInt(e,2));throw Error(t[1].join(","))}toString(){let e=this.value.toString();return`${p.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 p(this.value.valueOf()+1n)}previousIPNumber(){return new p(this.value.valueOf()-1n)}static startWithASPrefix(e){return 0===e.indexOf(p.AS_PREFIX)}parseFromDotNotation(e){let t=e.split("."),r=parseInt(t[0]);return 65535*r+(parseInt(t[1])+r)}}t.Asn=p,p.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 g(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 g{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),g=l(e,n.__wbindgen_malloc),p=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,g,p,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,g=l(t,n.__wbindgen_malloc),p=c;n.batch_verify_tickets(a,h,f,g,p,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"),g=s(896).readFileSync(f),p=new WebAssembly.Module(g),y=new WebAssembly.Instance(p,{});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=p;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),g=e.exports.PERSONALBYTES=16;function p(e,t,r,i,o){if(!(this instanceof p))return new p(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===g,"personal must be exactly "+g+", 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(){}p.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)},p.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},p.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},p.prototype.final=p.prototype.digest,p.WASM=n,p.SUPPORTED="undefined"!=typeof WebAssembly,p.ready=function(e){return e||(e=y),o?o.then(()=>e(),e):e(new Error("WebAssembly not supported"))},p.prototype.ready=p.ready,p.prototype.getPartialHash=function(){return this._memory.slice(this.pointer,this.pointer+216)},p.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),g=new WebAssembly.Instance(f,o);n=g.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 g=u[s]^u[e],p=u[s+1]^u[e+1];u[s]=p,u[s+1]=g,n(u,r,s),g=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=g>>>24^p<<8,u[t+1]=p>>>24^g<<8,n(u,e,t),o(u,e,h,f),g=u[s]^u[e],p=u[s+1]^u[e+1],u[s]=g>>>16^p<<16,u[s+1]=p>>>16^g<<16,n(u,r,s),g=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=p>>>31^g<<1,u[t+1]=g>>>31^p<<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 g=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 p(e,t,r,s){g.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=e,g[0]=e,t&&(g[1]=t.length),g[2]=1,g[3]=1,r&&g.set(r,32),s&&g.set(s,48);for(var i=0;i<16;i++)this.h[i]=l[i]^a(g,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)}p.prototype.update=function(e){return s(e instanceof Uint8Array,"input must be Uint8Array or Buffer"),y(this,e),this},p.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},p.prototype.final=p.prototype.digest,p.ready=function(e){i.ready(function(){e()})};var b=p;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}}(),g=s?Symbol.for("@reflect-metadata:registry"):void 0,p=function(){var e;return!C(g)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[g]),C(e)&&(e=function(){var e,r,s,i;C(g)||void 0===t.Reflect||g 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:p};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 p(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(g)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,g,{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 p.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}}(p);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=p.getProvider(e,t);if(!C(s))return s;if(r){if(p.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:()=>mm,BaseBlock:()=>Op,BaseStringBlock:()=>Tp,BitString:()=>Oy,BmpString:()=>Xy,Boolean:()=>xy,CharacterString:()=>lm,Choice:()=>bm,Constructed:()=>wy,DATE:()=>dm,DateTime:()=>gm,Duration:()=>pm,EndOfContent:()=>Ey,Enumerated:()=>Py,GeneralString:()=>cm,GeneralizedTime:()=>um,GraphicString:()=>om,HexBlock:()=>Cp,IA5String:()=>nm,Integer:()=>My,Null:()=>Cy,NumericString:()=>tm,ObjectIdentifier:()=>Ky,OctetString:()=>By,Primitive:()=>my,PrintableString:()=>rm,RawData:()=>Im,RelativeObjectIdentifier:()=>Fy,Repeated:()=>Am,Sequence:()=>$y,Set:()=>jy,TIME:()=>ym,TeletexString:()=>sm,TimeOfDay:()=>fm,UTCTime:()=>hm,UniversalString:()=>em,Utf8String:()=>Jy,ValueBlock:()=>xp,VideotexString:()=>im,ViewWriter:()=>op,VisibleString:()=>am,compareSchema:()=>vm,fromBER:()=>Ay,verifySchema:()=>wm});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 g(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 g extends u{trace(e,t,r){}log(e,t,r){}info(e,t,r){this.push(l.INFO,e,t,r)}}const p={workingDir:"",defaultLevel:l.LOG,modules:new Map},y={options:p,transport:u.create(p.defaultLevel,p)};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 ge{data;bitLength;static fromBlob(e,t){return new ge(e,t)}static fromBytes(e,t){return new ge(e.raw,t)}static empty(e){const t=new Uint8Array(Math.ceil(e/8));return new ge(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 pe=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 ge.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 ge.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),g=!!(128&i);return!t&&0n===d&&g&&Ye("bad y coord 3"),g!==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),g=tt(h*d),p=tt(l*d),y=tt(u*h);return new st(f,g,y,p)}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),g=tt(s*a),p=tt((t+r)*(n+o)-u-d),y=tt(g-f),m=tt(g+f),b=tt(d-l*u),A=tt(p*y),I=tt(m*b),v=tt(p*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")},gt=(e,t)=>{let r=e;for(;t-- >0n;)r*=r,r%=Ge;return r},pt=19681161376707505956807079304988542015446066515923890162744021073123829784752n,yt=(e,t)=>{const r=tt(t*t*t),s=(e=>{const t=e*e%Ge*e%Ge,r=gt(t,2n)*t%Ge,s=gt(r,1n)*e%Ge,i=gt(s,5n)*s%Ge,n=gt(i,10n)*i%Ge,o=gt(n,20n)*n%Ge,a=gt(o,40n)*o%Ge,c=gt(a,80n)*a%Ge,l=gt(c,80n)*a%Ge,h=gt(l,10n)*i%Ge;return{pow_p_5_8:gt(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*pt),c=n===e,l=n===tt(-e),h=n===tt(-e*pt);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 gr=new fr({contestLength:10,coresCount:2,epochLength:12,maxTicketsPerExtrinsic:3,rotationPeriod:4,slotDuration:6,ticketsPerValidator:3,validatorsCount:6,numberECPiecesPerSegment:1026}),pr=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=pr,{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 gs=Ve.sequenceVarLen(fs.Codec);class ps extends G{tickets;preimages;guarantees;assurances;disputes;static Codec=Ve.Class(ps,{tickets:os,preimages:gs,guarantees:ss,assurances:wr,disputes:xr.Codec});static create({tickets:e,preimages:t,assurances:r,disputes:s,guarantees:i}){return new ps(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:ps.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 pe(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 ge.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 gi 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 gi.keys(Mr(s,e))}if(s===di.Tickets){const s=t.sequenceFixLen(ns.Codec,r);return gi.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 gi(di.Keys,e,void 0)}static tickets(e){return new gi(di.Tickets,void 0,e)}constructor(e,t,r){super(),this.kind=e,this.keys=t,this.tickets=r}}class pi{nextValidatorData;epochRoot;sealingKeySeries;ticketsAccumulator;static Codec=Ve.Class(pi,{nextValidatorData:Dr(ui.Codec),epochRoot:Ve.bytes(_t).asOpaque(),sealingKeySeries:gi.Codec,ticketsAccumulator:Ke(Ve.sequenceVarLen(ns.Codec)).convert(z,lr)});static create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s}){return new pi(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})}get hash(){switch(this.action.kind){case vi.Provide:return this.action.preimage.hash;case vi.Remove:return this.action.hash;case vi.UpdateOrAdd:return this.action.item.hash}throw F(this.action)}get length(){switch(this.action.kind){case vi.Provide:return Ae(this.action.preimage.blob.length);case vi.Remove:return this.action.length;case vi.UpdateOrAdd:return this.action.item.length}throw F(this.action)}}!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:gi.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:pi.Codec,extract:e=>pi.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),g=l.pop();for(;void 0!==g;)d=g?Yi.fromSubNodes(u,f):Yi.fromSubNodes(f,u),f=t.insert(d.node),g=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 gn,pn,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:gi.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"}(gn||(gn={}));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"}(pn||(pn={}));class bn{leaves;db;static fromLeavesBlob(e,t){if(e.length%64!=0)return Z.error(pn.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(pn.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(ps.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(gn.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 pi.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(ge.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})(),go=e=>Ae(e),po=e=>ve(e),yo=e=>"number"==typeof e&&e<2**32?go(e):po(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:go(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 ga(e,t){return(2n**64n+e-t)%2n**64n}function pa(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(pa(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(pa(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,ga(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,ga(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=po(this.initialGas.get())-po(this.gas.get());return e<0?this.initialGas.get():po(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=go(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 gc{code;registers;memory;metadata;static fromSpi(e,t,r){const{code:s,metadata:i}=r?pc(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 g=nc+lc(o),p=131072+(y=o,nc*Math.ceil(y/nc));var y;const m=p+lc(a),b=p+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,g,h),n>0&&fc(v,w,t),w<S&&fc(w,S)].filter(E),k=[a>0&&fc(p,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 gc(n,c,d,i)}static fromGeneric(e,t){const{code:r,metadata:s}=t?pc(e):{code:e},i=new io,n=new jo;return new gc(r,i,n,s)}constructor(e,t,r,s=new Uint8Array){this.code=e,this.registers=t,this.memory=r,this.metadata=s}}function pc(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?gi.tickets(this.outsideInSequencer(this.state.ticketsAccumulator)):this.isSameEpoch(e)?this.state.sealingKeySeries:gi.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{services;transfers;authorizationQueues=new Map;yieldedRoot=null;validatorsData=null;privilegedServices=null;constructor(e,t){this.services=e,this.transfers=t}static empty(){return new al({servicesUpdates:[],servicesRemoved:[],preimages:[],storage:[]},[])}static new(e){return new al(e,[])}static copyFrom(e){const t={servicesUpdates:[...e.services.servicesUpdates],servicesRemoved:[...e.services.servicesRemoved],preimages:[...e.services.preimages],storage:[...e.services.storage]},r=[...e.transfers],s=new al(t,r);for(const[t,r]of e.authorizationQueues)s.authorizationQueues.set(t,r);return s.yieldedRoot=e.yieldedRoot,s.validatorsData=null===e.validatorsData?null:[...e.validatorsData],s.privilegedServices=null===e.privilegedServices?null:{...e.privilegedServices},s}}const cl=19200;class ll{state;currentServiceId;updatedState;checkpointedState=null;nextNewServiceId;constructor(e,t,r,s=al.empty()){if(this.state=e,this.currentServiceId=t,this.updatedState=s,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(){const e=this.updatedState.services.servicesUpdates.find(e=>e.serviceId===this.currentServiceId);if(void 0!==e)return e.action.account;const t=this.state.getService(this.currentServiceId);return V(t,null!==t,"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.services.servicesRemoved.some(t=>t===e);if(t)return null;const r=this.updatedState.services.servicesUpdates.find(t=>t.serviceId===e&&t.action.kind===wi.Create);if(void 0!==r)return r.action.account;const s=this.state.getService(e);return null===s?null:s.getInfo()}getUpdatedPreimageStatus(e,t){const r=this.updatedState.services.preimages.findLast(r=>r.serviceId===this.currentServiceId&&r.hash.isEqualTo(e)&&BigInt(r.length)===t),s=()=>{const r=this.state.getService(this.currentServiceId),s=hl(t);if(null===s||null===r)return null;const i=r.getLookupHistory(e,s);return null===i?null:new Ii(e,s,i)};if(void 0===r)return s();const{action:i}=r;switch(i.kind){case vi.Provide:return new Ii(e,r.length,Ai([this.state.timeslot]));case vi.Remove:{const t=s();return null===t?null:new Ii(e,t.length,Ai([...t.slots,this.state.timeslot]))}case vi.UpdateOrAdd:return i.item}F(i)}isPreviousCodeExpired(e,t,r){const s=this.state.getService(e),i=hl(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-cl;return[c,c?"":"not expired"]}hasExistingPreimage(e,t){if(null===e)return!1;if(void 0!==this.updatedState.services.preimages.find(r=>r.serviceId===e&&r.hash.isEqualTo(t)))return!0;const r=this.state.getService(e);return void 0!==r&&(r?.hasPreimage(t)??!1)}addPreimageUpdate(e){this.updatedState.services.preimages.push(e)}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.getUpdatedPreimageStatus(e,t);return null===r?null:nl(r.slots)}requestPreimage(e,t){const r=this.getUpdatedPreimageStatus(e,t);if(null!==r){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?this.addPreimageUpdate(Ei.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new Ii(e,a,Ai([]))})):this.addPreimageUpdate(Ei.updateOrAdd({serviceId:this.currentServiceId,lookupHistory: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.updateCurrentServiceInfo(yi.create({...r,storageUtilisationBytes:t.value,storageUtilisationCount:e.value})),Z.ok(W))}updateCurrentServiceInfo(e){const t=this.updatedState.services.servicesUpdates.findIndex(e=>e.serviceId===this.currentServiceId),r=-1===t?0:1;this.updatedState.services.servicesUpdates.splice(t,r,Ci.update({serviceId:this.currentServiceId,serviceInfo:e}))}forgetPreimage(e,t){const r=this.currentServiceId,s=this.getUpdatedPreimageStatus(e,t);if(null===s)return Z.error(null);const i=nl(s.slots);if(i.status===Xc.Requested)return this.addPreimageUpdate(Ei.remove({serviceId:r,hash:s.hash,length:s.length})),Z.ok(W);const n=this.state.timeslot;return i.status===Xc.Unavailable?i.data[1]<n-cl?(this.addPreimageUpdate(Ei.remove({serviceId:r,hash:s.hash,length:s.length})),Z.ok(W)):Z.error(null):i.status===Xc.Available?(this.addPreimageUpdate(Ei.updateOrAdd({serviceId:r,lookupHistory:new Ii(s.hash,s.length,Ai([i.data[0],n]))})),Z.ok(W)):i.status===Xc.Reavailable?i.data[1]<n-cl?(this.addPreimageUpdate(Ei.updateOrAdd({serviceId:r,lookupHistory:new Ii(s.hash,s.length,Ai([i.data[2],n]))})),Z.ok(W)):Z.error(null):void F(i)}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.updateCurrentServiceInfo(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;return u<h||o.overflow?Z.error("insufficient funds"):(this.updatedState.services.servicesUpdates.push(Ci.create({serviceId:i,serviceInfo:yi.create({codeHash:e,balance:c,accumulateMinGas:r,onTransferMinGas:s,storageUtilisationBytes:o.value,storageUtilisationCount:n}),lookupHistory:new Ii(e.asOpaque(),a,Ai([]))})),this.updateCurrentServiceInfo(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.updateCurrentServiceInfo(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.getUpdatedPreimageStatus(s,ve(t.length));if(null===e||!Ii.isRequested(e))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.addPreimageUpdate(Ei.provide({serviceId:e,preimage:mi.create({hash:s,blob:t}),slot:this.state.timeslot})),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.updateCurrentServiceInfo(yi.create({...s,balance:l.value})),this.updatedState.services.servicesRemoved.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.services.storage.findIndex(t=>t.serviceId===r.serviceId&&t.key.isEqualTo(e)),i=-1===s?0:1;this.updatedState.services.storage.splice(s,i,r)}read(e,t){if(null===e)return null;if(this.currentServiceId===e){const r=this.updatedState.services.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.services.preimages.find(r=>r.serviceId===e&&r.hash.isEqualTo(t));if(void 0!==r&&r.action.kind===vi.Provide)return r.action.preimage.blob;const s=this.state.getService(e);return s?.getPreimage(t)??null}}function hl(e){return e>=2n**32n?null:Ae(Number(e))}function ul(e){const t=e.map(e=>e.workPackageSpec.hash);return cr.from(t)}const dl=Ve.object({serviceId:Ve.u32.asOpaque(),entropy:Ve.bytes(Rt).asOpaque(),timeslot:Ve.u32.asOpaque()});class fl{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 gl(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=gl(r,ul(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 gl(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 pl;!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"}(pl||(pl={}));class yl{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(pl.InvalidAnchor,`anchor: expected: ${e.parentHash}, got ${s}`);if(n>=o)return Z.error(pl.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(pl.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(pl.InvalidValidatorIndex);r.push({signature:e.signature.materialize(),key:i.ed25519,message:bl(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(pl.InvalidSignature,`invalid signatures at ${e.join(", ")}`)}return Z.ok(W)}}const ml=te.blobFromString("jam_available").raw;function bl(e,t){return te.blobFromParts(ml,Ht(te.blobFromParts(e.raw,t.raw)).raw)}const Al=te.blobFromString("peak");class Il{hasher;mountains;static empty(e){return new Il(e)}static fromPeaks(e,t){return new Il(e,t.peaks.reduce((e,t,r)=>(null!==t&&e.push(vl.fromPeak(t,2**r)),e),[]).reverse())}constructor(e,t=[]){this.hasher=e,this.mountains=t}append(e){let t=vl.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(Al,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 vl{peak;size;constructor(e,t){this.peak=e,this.size=t}static fromPeak(e,t){return new vl(e,t)}static fromChildren(e,t){const[r,s]=t,i=e.hashConcat(r.peak,s.peak),n=r.size+s.size;return new vl(i,n)}mergeWith(e,t){return vl.fromChildren(e,[this,t])}toString(){return`${this.size} @ ${this.peak}`}}var wl;!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"}(wl||(wl={}));class Sl extends G{static Codec=Ve.Class(Sl,{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 Sl({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 Sl(e)}}class El{static Codec=Ve.Class(El,{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 El({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 El(e)}}const Cl=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}),kl=new Map;class xl{entropyHash;operands;chainSpec;constructor(e,t,r){this.entropyHash=e,this.operands=t,this.chainSpec=r}constants(){return function(e){const t=kl.get(e);if(void 0!==t)return t;const r=Te.encodeObject(Cl,{B_I:ve(10n),B_L:ve(1n),B_S:ve(100n),C:me(e.coresCount),D:Ae(cl),E:Ae(e.epochLength),G_A:ve(zl),G_I:ve(5e7),G_R:ve(5e9),G_T:ve(Wl),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 kl.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(El.Codec),this.operands,this.chainSpec):Te.encodeObject(Ve.sequenceVarLen(Sl.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(Sl.Codec,t,this.chainSpec):Te.encodeObject(El.Codec,t,this.chainSpec)}allTransfers(){return null}oneTransfer(e){return null}}const _l=Ve.object({serviceId:Ve.u32.convert(e=>e,e=>e),gas:Ve.u64.convert(e=>ve(e),e=>Or(e))});class Bl{currentServiceId;index=Zn(0);gasCost=go(10);constructor(e){this.currentServiceId=e}execute(e,t){return t.set(7,ve(e.get())),Promise.resolve(void 0)}}const Rl=Re(ui.Codec.sizeHint),Ol=e=>ve(e);var Ul,Tl,Nl;!function(e){e[e.SourcePageFault=0]="SourcePageFault",e[e.DestinationPageFault=1]="DestinationPageFault",e[e.NoMachine=2]="NoMachine"}(Ul||(Ul={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidPage=1]="InvalidPage"}(Tl||(Tl={})),Symbol("Machine index not found."),Symbol("Too many segments already exported.");class Dl{currentServiceId;fetch;index=Zn(18);gasCost=go(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===Nl.Constants)return this.fetch.constants();if(t===Nl.Entropy)return this.fetch.entropy();if(t===Nl.AuthorizerTrace)return this.fetch.authorizerTrace();if(t===Nl.OtherWorkItemExtrinsics){const t=e.get(11),r=e.get(12);return this.fetch.workItemExtrinsic(t,r)}if(t===Nl.MyExtrinsics){const t=e.get(11);return this.fetch.workItemExtrinsic(null,t)}if(t===Nl.OtherWorkItemImports){const t=e.get(11),r=e.get(12);return this.fetch.workItemImport(t,r)}if(t===Nl.MyImports){const t=e.get(11);return this.fetch.workItemImport(null,t)}if(t===Nl.WorkPackage)return this.fetch.workPackage();if(t===Nl.Authorizer)return this.fetch.authorizer();if(t===Nl.AuthorizationToken)return this.fetch.authorizationToken();if(t===Nl.RefineContext)return this.fetch.refineContext();if(t===Nl.AllWorkItems)return this.fetch.allWorkItems();if(t===Nl.OneWorkItem){const t=e.get(11);return this.fetch.oneWorkItem(t)}if(t===Nl.WorkItemPayload){const t=e.get(11);return this.fetch.workItemPayload(t)}if(t===Nl.AllOperands)return this.fetch.allOperands();if(t===Nl.OneOperand){const t=e.get(11);return this.fetch.oneOperand(t)}if(t===Nl.AllTransfers)return this.fetch.allTransfers();if(t===Nl.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"}(Nl||(Nl={}));class Ml{currentServiceId;account;index=Zn(4);gasCost=go(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(Pl,{...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 Pl=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"),Ll=m.new(void 0,"host-calls"),Hl=new TextDecoder("utf8");class Kl{currentServiceId;index=Zn(100);gasCost=go(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),Ll.trace(`[${this.currentServiceId}] [${s}] ${Hl.decode(c)} ${Hl.decode(l)}`),Promise.resolve(void 0)}}class Ql{currentServiceId;account;index=Zn(1);gasCost=go(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 Vl{currentServiceId;account;index=Zn(2);gasCost=go(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),g=ke(d,u),p=ke(f,ve(u-g)),y=null===h?new Uint8Array(0):h.raw.subarray(Number(g),Number(g+p));if(r.storeFrom(o,y).isError)return eo.Panic;null!==h?t.set(7,u):t.set(7,qa.NONE)}}class Fl{currentServiceId;account;index=Zn(3);gasCost=go(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 $l=[class{currentServiceId;partialState;index=Zn(5);gasCost=go(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(_l.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(_l);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=go(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=go(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(Rl*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=go(10);gasHostCall;constructor(e,t){this.currentServiceId=e,this.partialState=t,this.gasHostCall=new Bl(e)}async execute(e,t){await this.gasHostCall.execute(e,t),this.partialState.checkpoint()}},class{currentServiceId;partialState;index=Zn(9);gasCost=go(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=go(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=go(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=go(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=go(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=go(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=go(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=go(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 jl,Gl;!function(e){e.IS_AUTHORIZED=Ol(0),e.REFINE=Ol(0),e.ACCUMULATE=Ol(5),e.ON_TRANSFER=Ol(10)}(jl||(jl={}));class ql{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=$l.map(s=>new s(e,t.partialState,r)),i=[new Bl(e),new Kl(e),new Vl(e,t.serviceExternalities),new Fl(e,t.serviceExternalities),new Dl(e,t.fetchExternalities),new Ql(e,t.serviceExternalities),new Ml(e,t.serviceExternalities)];return s.concat(i)}async run(e,t){const r=gc.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=ql.prepareAccumulateHostCalls(e,r,s);return new ql(t,i,jl.ACCUMULATE)}}!function(e){e[e.NoService=0]="NoService",e[e.NoPreimage=1]="NoPreimage"}(Gl||(Gl={}));const zl=10000000n,Wl=3500000000n,Jl=m.new(void 0,"accumulate"),Yl=Ve.object({slot:Ve.u32.asOpaque(),serviceId:Ve.u32.asOpaque(),operands:Ve.sequenceVarLen(El.Codec)}),Xl=Ve.object({slot:Ve.u32.asOpaque(),serviceId:Ve.u32.asOpaque(),operands:Ve.sequenceVarLen(Sl.Codec)}),Zl=Ve.object({slot:Ve.varU32.asOpaque(),serviceId:Ve.varU32.asOpaque(),operands:Ve.varU32});class eh{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 Jl.log(`Service with id ${t} not found.`),Z.error(Gl.NoService);const o=n.getInfo().codeHash,a=n.getPreimage(o.asOpaque());if(null===a)return Jl.log(`Code with hash ${o} not found for service ${t}.`),Z.error(Gl.NoPreimage);const c=function({serviceId:e,entropy:t,timeslot:r},s){const i=Ce(Ht(Te.encodeObject(dl,{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 ll(this.state,t,c),h={partialState:l,serviceExternalities:l,fetchExternalities:new xl(i,r,this.chainSpec)},u=ql.createAccumulateExecutor(t,a,h,this.chainSpec);let d=te.empty();d=K.is(D.V0_6_4)?Te.encodeObject(Yl,{slot:e,serviceId:t,operands:r},this.chainSpec):K.is(D.V0_6_5)?Te.encodeObject(Xl,{slot:e,serviceId:t,operands:r},this.chainSpec):Te.encodeObject(Zl,{slot:e,serviceId:t,operands:Ae(r.length)});const f=await u.run(d,yo(s)),[g,p]=l.getStateUpdates();if(f.hasStatus()){const e=f.status;if(e===Yn.OOG||e===Yn.PANIC)return Z.ok({stateUpdate:p,consumedGas:Or(f.consumedGas)})}if(f.hasMemorySlice()&&f.memorySlice.length===Rt){const e=re.fromBlob(f.memorySlice,Rt);g.yieldedRoot=e.asOpaque()}return Z.ok({stateUpdate:g,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(Sl.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);Jl.trace(`Accumulating service ${e}, items: ${i.length} at slot: ${r}.`);const o=await this.pvmAccumulateInvocation(r,e,i,n,s);return o.isError?(Jl.trace(`Accumulation failed for ${e}.`),{stateUpdate:null,consumedGas:n}):(Jl.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:g,yieldedRoots:p,pendingTransfers:y,stateUpdates:m,...b}=await this.accumulateSequentially(Or(e-d),o,r,s);return{accumulatedReports:Ae(i+f),gasCosts:a.concat(g),yieldedRoots:c.concat(p),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){const{authManager:t,manager:r,validatorsManager:s}=this.state.privilegedServices;let i=null;const n=this.state.authQueues.slice();let o=!1,a=null;const c=[];for(const[l,h]of e){if(l===r&&null!==h.privilegedServices){const{manager:e,authorizer:t,validators:r,autoAccumulate:s}=h.privilegedServices;Q(null===i,"Only one service can update privileged services!"),i=li.create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s.map(([e,t])=>ci.create({gasLimit:t,service:e}))})}if(l===t&&null!==h.authorizationQueues)for(const[e,t]of h.authorizationQueues)n[e]=t,o=!0;l===s&&null!==h.validatorsData&&(Q(null===a,"Only one service can update designated validators!"),a=h.validatorsData),c.push(h.services)}const l=c.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:[]}),h=new Set;for(const e of l.servicesUpdates)if(e.action.kind===wi.Create){if(h.has(e.serviceId))return Z.error("duplicate service created",`duplicate service ${e.serviceId} has been created!`);h.add(e.serviceId)}return Z.ok({...l,...null!==i?{privilegedServices:i}:{},...o?{authQueues:n}:{},...null!==a?{designatedValidatorData:a}:{}})}getAccumulationStateUpdate(e,t,r){const s=this.chainSpec.epochLength,i=r%s,n=ul(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]=gl(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]=gl(c[t],n)}return{recentlyAccumulated:a,accumulationQueue:Mr(c,this.chainSpec),timeslot:r}}getGasLimit(){const e=zl*BigInt(this.chainSpec.coresCount)+this.state.privilegedServices.autoAccumulateServices.reduce((e,{gasLimit:t})=>e+t,0n),t=Or(Wl>e?Wl:e);return Or(t)}async transition({reports:e,slot:t,entropy:r}){const s=new fl(this.chainSpec,this.state),i=s.getWorkReportsToAccumulateImmediately(e),n=s.getWorkReportsToAccumulateLater(e),o=gl(s.getQueueFromState(t).concat(n),ul(i)),a=s.enqueueReports(o),c=i.concat(a),l=this.getGasLimit(),{accumulatedReports:h,yieldedRoots:u,gasCosts:d,pendingTransfers:f,stateUpdates:g,...p}=await this.accumulateSequentially(l,c,t,r),y=c.slice(0,h),m=this.getAccumulationStateUpdate(y,n,t),b=this.mergeServiceStateUpdates(g);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 th{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 rh{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?Il.fromPeaks(this.hasher,r.mmr):Il.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 sh(e,t,r){return function(e,t,r){const s=ih(_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 ih(e,t){return Math.floor(e/t)}const nh=te.blobFromString("jam_guarantee").raw;function oh(e){return te.blobFromParts(nh,e.raw)}const ah=1e7;class ch{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(wl.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(wl.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(wl.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(wl.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(wl.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(wl.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(wl.BadValidatorIndex,`Invalid validator index: ${r}`);if(n.core!==a)return Z.error(wl.WrongAssignment,`Invalid core assignment for validator ${r}. Expected: ${n.core}, got: ${a}`);i.push({signature:s,key:n.ed25519,message:oh(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(wl.CoreEngaged,`Report pending availability at core: ${n}`);const o=e.authorizerHash;if(void 0===r[n].find(e=>e.isEqualTo(o)))return Z.error(wl.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(wl.BadServiceId,`No service with id: ${t.serviceId}`);const r=e.getInfo();if(t.gas<r.accumulateMinGas)return Z.error(wl.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>ah)return Z.error(wl.WorkReportGasTooHigh,`Total gas too high. Got: ${a.value} (ovfl: ${a.overflow}), maximal: ${ah}`)}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(wl.BadServiceId,`No service with id: ${r.serviceId}`);if(!r.codeHash.isEqualTo(e.getInfo().codeHash))return Z.error(wl.BadCodeHash,`Service (${r.serviceId}) code hash mismatch. Got: ${r.codeHash}, expected: ${e.getInfo().codeHash}`)}}if(n.size!==e.guarantees.length)return Z.error(wl.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(wl.AnchorNotRecent,`Anchor block ${r.anchor} not found in recent blocks.`);if(!t.postStateRoot.isEqualTo(r.stateRoot))return Z.error(wl.BadStateRoot,`Anchor state root mismatch. Got: ${r.stateRoot}, expected: ${t.postStateRoot}.`);const o=Il.fromPeaks(s,t.mmr).getSuperPeakHash();if(!o.isEqualTo(r.beefyRoot))return Z.error(wl.BadBeefyMmrRoot,`Invalid BEEFY super peak hash. Got: ${r.beefyRoot}, expected: ${o}. Anchor: ${t.headerHash}`);if(r.lookupAnchorSlot<e)return Z.error(wl.SegmentRootLookupInvalid,`Lookup anchor slot's too old. Got: ${r.lookupAnchorSlot}, minimal: ${e}`);if(!i.isInChain(r.lookupAnchor))return Z.error(wl.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(wl.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?wl.SegmentRootLookupInvalid:wl.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(wl.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(wl.BadSignature,`Invalid signatures for validators with keys: ${r.join(", ")}`)}getGuarantorAssignment(e,t){const r=this.chainSpec.epochLength,s=this.chainSpec.rotationPeriod,i=ih(e,s),n=ih(t,s),o=Math.max(0,i-1)*s;if(t>e)return Z.error(wl.FutureReportSlot,`Report slot is in future. Block ${e}, Report: ${t}`);if(t<o)return Z.error(wl.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=sh(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 lh{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),g=a[r].preImagesSize+f;a[r].preImagesSize=Ae(g);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 p=this.collectServiceIds(s.preimages,i.flatMap(e=>e.results),e.accumulationStatistics.keys(),e.transferStatistics.keys());for(const t of p){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:g,gasUsed:p}=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=g,b.accumulateGasUsed=p,b.onTransfersCount=y,b.onTransfersGasUsed=m,l.set(t,b)}return{statistics:o}}}class hh{blocks;constructor(e){this.blocks=e}isInChain(e){return null!==this.blocks.getHeader(e)}}var uh;!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"}(uh||(uh={}));const dh=(e,t)=>Z.taggedError(uh,e,t);class fh{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 lh(e,t),this.safrole=new sl(e,t,n),this.safroleSeal=new il(n),this.recentHistory=new rh(s,t),this.disputes=new Uc(e,t),this.reports=new ch(e,t,s,new hh(r)),this.assurances=new yl(e,t),this.accumulate=new eh(e,t),this.preimages=new Ic(t),this.authorization=new th(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 dh(uh.SafroleSeal,t);o=t.ok}const a=await this.disputes.transition(e.extrinsic.view().disputes.materialize());if(a.isError)return dh(uh.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 dh(uh.Reports,u);const{availabilityAssignment:d,...f}=u.ok.stateUpdate,g=await this.assurances.transition({assurances:e.extrinsic.view().assurances.view(),slot:n,parentHash:i.parentHeaderHash});if(g.isError)return dh(uh.Assurances,g);const{availabilityAssignment:p,...y}=g.ok.stateUpdate,m=await this.safrole.transition({slot:n,entropy:o,extrinsic:e.extrinsic.view().tickets.materialize()});if(m.isError)return dh(uh.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 dh(uh.Preimages,x);const{preimages:_,...B}=x.ok,R=await this.accumulate.transition({slot:n,reports:g.ok.availableReports,entropy:w[0]});if(R.isError)return dh(uh.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:g.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:gh(this.state.availabilityAssignment,d,l,p),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 gh(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 ph;!function(e){e[e.Verifier=0]="Verifier",e[e.Stf=1]="Stf",e[e.Update=2]="Update"}(ph||(ph={}));const yh=(e,t)=>Z.taggedError(ph,e,t);class mh{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 fh(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 yh(ph.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 yh(ph.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)}`),yh(ph.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 g=j("import:db"),p=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([p,m]),s.log(g()),await this.blocks.setBestHeaderHash(a),Z.ok(new Ot(a,e.header.view()))}bestBlockHash(){return this.blocks.getBestHeaderHash()}}const bh=m.new(void 0,"importer");class Ah 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 Ih 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 bh.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 vh=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 Ih,r=new Ln;return new Dn("importer",e,[e,t,r])}();On.receiveChannel(e,T.parentPort).then(e=>async function(e){vh.info(`📥 Importer starting ${e.currentState()}`);const t=await e.waitForState("ready(importer)"),r=await t.doUntil("finished",async(e,t)=>{vh.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 mh(r.chainSpec,new Ac(r.chainSpec,await wh,new Tt),vh,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(vh.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),vh.info(`🧊 Best block: #${r.data.timeSlotIndex.materialize()} (${r.hash})`)}else vh.log(`❌ Rejected block #${a}: ${X(h)}`);vh.log(l())}}finally{a=!1}}})});vh.info("📥 Importer finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>vh.error(e))}const wh=nr.create(),Sh=t(import.meta.url)("node:timers/promises");class Eh{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}=Eh.getLastHeaderAndState(r,s);this.lastHeaderHash=i,this.lastHeader=n,this.lastState=o}refreshLastHeaderAndState(){const{lastHeaderHash:e,lastHeader:t,lastState:r}=Eh.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=ps.create({tickets:[],preimages:[],guarantees:[],assurances:[],disputes:xr.create({verdicts:[],culprits:[],faults:[]})}),o=Te.encodeObject(ps.Codec,n,this.chainSpec),a=xe.decodeObject(ps.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 Ch=m.new(void 0,"block-generator");class kh 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):Ch.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 xh 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 _h=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 xh,r=new Ln;return new Dn("block-generator",e,[e,t,r])}();On.receiveChannel(e,T.parentPort).then(e=>async function(e){_h.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 Eh(r.chainSpec,await nr.create(),i,n);for(;!s();){o+=1;const r=await a.nextEncodedBlock();_h.trace(`Sending block ${o}`),e.sendBlock(t,r),await(0,Sh.setTimeout)(3e3)}});_h.info("Block Generator finished. Closing channel."),o.currentState().close(e)}(e)).catch(e=>{_h.error(e),void 0!==e.stack&&_h.error(e.stack),void 0!==e.cause&&_h.error(e.cause)})}const Bh=t(import.meta.url)("dgram");var Rh,Oh;(Oh=Rh||(Rh={}))[Oh.NOTSET=0]="NOTSET",Oh[Oh.DEBUG=1]="DEBUG",Oh[Oh.INFO=2]="INFO",Oh[Oh.WARN=3]="WARN",Oh[Oh.ERROR=4]="ERROR",Oh[Oh.SILENT=100]="SILENT";const Uh="captureStackTrace"in Error,Th="stackTraceLimit"in Error;function Nh(e){switch(e){case Rh.NOTSET:return"NOTSET";case Rh.DEBUG:return"DEBUG";case Rh.INFO:return"INFO";case Rh.WARN:return"WARN";case Rh.ERROR:return"ERROR";case Rh.SILENT:return"SILENT"}}function Dh(e,t){return"function"==typeof t?t():t}function Mh(e){return JSON.stringify(e,Dh)}const Ph=Symbol("level"),Lh=Symbol("key"),Hh=Symbol("keys"),Kh=Symbol("date"),Qh=Symbol("msg"),Vh=Symbol("stack"),Fh=Symbol("data"),$h=(function(e,...t){return r=>{let s=e[0];for(let i=0;i<t.length;i++){const n=t[i];if(n===Lh)s+=r.key;else if(n===Hh)s+=r.keys;else if(n===Kh)s+=r.date().toISOString();else if(n===Qh)null!=r.msg&&(s+=r.msg);else if(n===Ph)s+=Nh(r.level);else if(n===Fh)s+=Mh(r.data);else if(n===Vh){const e=r.stack();""!==e&&(s+="\n"+e)}else s+=n.toString();s+=e[i+1]}return s}})`${Ph}:${Lh}:${Qh}`,jh=class{formatter;constructor(e=$h){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)}},Gh=class extends jh{emit(e){console.error(e)}};class qh{key;level;filter;keys;handlers;parent;_loggers=new Map;loggersRegistry;constructor(e="root",t=Rh.NOTSET,r=[new Gh],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 qh(e,Rh.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!==Rh.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,{},Rh.DEBUG,t):this.log(e,t,Rh.DEBUG,r)}info(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Rh.INFO,t):this.log(e,t,Rh.INFO,r)}warn(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Rh.WARN,t):this.log(e,t,Rh.WARN,r)}error(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Rh.ERROR,t):this.log(e,t,Rh.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(Uh&&Th){Error.stackTraceLimit++;const t={};Error.captureStackTrace(t,qh.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 zh=qh;t(import.meta.url)("node:process");class Wh 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 Jh=Wh;class Yh extends Jh{constructor(e){super(Yh.name,e,arguments)}}const Xh=Yh;class Zh extends Jh{constructor(e){super(Zh.name,e,arguments)}}const eu=Zh;class tu extends Jh{constructor(e){super(tu.name,e,arguments)}}const ru=tu,su=Symbol("_eventTarget"),iu=Symbol("eventTarget"),nu=Symbol("_eventHandlers"),ou=Symbol("eventHandlers"),au=Symbol("_eventHandled"),cu=Symbol("eventHandled"),lu=Symbol("_handleEventError"),hu=Symbol("handleEventError");function uu(e){return{capture:!1,once:!1,passive:!1,..."boolean"==typeof e?{capture:e}:"object"==typeof e?e:void 0}}function du(e,t){return e.capture===t.capture}function fu(){return e=>{const t=class extends e{[su]=new EventTarget;[nu]=new Map;[au]=new WeakSet;[lu]=e=>{throw e.detail};constructor(...e){super(...e),this[su].addEventListener(ru.name,this[lu])}get[iu](){return this[su]}get[ou](){return this[nu]}get[cu](){return this[au]}get[hu](){return this[lu]}addEventListener(e,t,r){r=uu(r);const s=this;let i,n,o=!1;if("function"==typeof t||"function"==typeof t?.handleEvent){n=this[nu].get(e),void 0===n&&(n=new Set,this[nu].set(e,n));for(const e of n)if(e.callback===t&&(i=e.handler,du(e.options,r))){o=!0;break}}"function"==typeof t?null==i?(i=async function(e){let r;s[au].add(e);try{r=t.call(s,e)}catch(e){this.dispatchEvent(new ru({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new ru({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[au].add(e);try{r=t.handleEvent(e)}catch(e){this.dispatchEvent(new ru({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new ru({detail:e}))}return r},n.add({callback:t,options:r,handler:i})):o||n.add({callback:t,options:r,handler:i}):i=t,this[su].addEventListener(e,i,r),e===ru.name&&1===n?.size&&this[su].removeEventListener(ru.name,this[lu])}removeEventListener(e,t,r){let s,i,n;if(r=uu(r),null!=t){if(i=this[nu].get(e),void 0===i)return;for(const e of i)if(e.callback===t&&du(e.options,r)){s=e.handler,n=e;break}if(null==s)return}else s=t;this[su].removeEventListener(e,s,r),null!=i&&null!=n&&(i.delete(n),e===ru.name&&0===i.size&&this[su].addEventListener(ru.name,this[lu]))}dispatchEvent(e){if(Object.defineProperties(e,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),e instanceof ru)return this[su].dispatchEvent(e);{let t=this[su].dispatchEvent(e);if(t&&!this[au].has(e)){const r=new Xh({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[su].dispatchEvent(r)}if(t){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[su].dispatchEvent(r)}return t}}};return Object.defineProperty(t,"name",Object.getOwnPropertyDescriptor(e,"name")),t}}async function gu(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*pu(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 yu extends Promise{static get[Symbol.species](){return Promise}static resolve(e){return e instanceof yu?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=yu.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 mu=yu,bu=t(import.meta.url)("node:perf_hooks");var Au,Iu=(Au=function(e,t){return Au=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])},Au(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}Au(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),vu=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 Iu(t,e),t}(Error);const wu=class extends vu{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(bu.performance.timeOrigin+bu.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 Su(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=Su(s,t,r);if(e)return e}return Su(e.cause,t,r)}return e instanceof Error&&Su(e.cause,t,r)}class Eu extends wu{static description="Timer error"}class Cu extends Eu{static description="The timer has already ended"}class ku{_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 mu((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(bu.performance.timeOrigin+bu.performance.now()),this._scheduled=new Date(this.timestamp.getTime()+t)):(this.timeoutRef=setInterval(()=>{},2**31-1),this.timestamp=new Date(bu.performance.timeOrigin+bu.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()-(bu.performance.timeOrigin+bu.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 Cu;return this.reset(this._delay)}reset(e){if(null!=this._status)throw new Cu;clearTimeout(this.timeoutRef),this._delay=e,isFinite(e)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},e),this._scheduled=new Date(bu.performance.timeOrigin+bu.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 xu=ku;function _u(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Bu(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 xu(()=>{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 xu&&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 xu(()=>{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 mu((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 Ru extends wu{static description="Async locks error"}class Ou extends Ru{static description="Async locks timeout"}const Uu=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}:{},()=>Bu((e,t)=>{this._count++;const{p:r,resolveP:s,rejectP:i}=_u();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,Ou,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}:{},Bu((e,t)=>{const{p:r,resolveP:s,rejectP:i}=_u();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,Ou,r,[t])}withF(...e){const t=e.pop();return gu([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return pu([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()}}},Tu=class{semaphore=new Uu(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 gu([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return pu([this.lock(...e)],([e])=>t(e))}},Nu=class{readersLock=new Tu;writersLock=new Tu;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}:{},()=>Bu(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,Ou,e,[])}write(e){return e=null!=e?{...e}:{},()=>Bu(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,Ou,e,[])}waitForUnlock(e){const t=this.readersLock.waitForUnlock(e),r=this.writersLock.waitForUnlock(e);return mu.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 gu([this.read(...e)],([e])=>t(e))}withWriteF(...e){const t=e.pop();return gu([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 pu([this.read(...e)],([e])=>t(e))}withWriteG(...e){const t=e.pop();return pu([this.write(...e)],([e])=>t(e))}},Du=Symbol("_running"),Mu=Symbol("running"),Pu=Symbol("_destroyed"),Lu=Symbol("destroyed"),Hu=Symbol("_status"),Ku=Symbol("status"),Qu=Symbol("_statusP"),Vu=Symbol("statusP"),Fu=Symbol("resolveStatusP"),$u=Symbol("initLock"),ju=(async()=>{}).constructor,Gu=function*(){}.constructor,qu=async function*(){}.constructor,zu="captureStackTrace"in Error;function Wu(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Ju(e,t){if(null!=e.stack){const r=e.stack.slice(0,e.stack.indexOf("\n")+1);zu?Error.captureStackTrace(e,t):e.stack=(new Error).stack??"",e.stack=e.stack.replace(/[^\n]+\n/,r)}}class Yu extends Jh{}class Xu extends Yu{}class Zu extends Yu{}class ed extends Yu{}class td extends Yu{}class rd extends Yu{}class sd extends Yu{}class id extends wu{static description="Async init error"}class nd extends id{static description="Async init is not running"}class od extends id{static description="Async init is destroyed"}function ad({eventDestroy:e=rd,eventDestroyed:t=sd}={}){return r=>{const{p:s,resolveP:i}=Wu(),n=class extends(fu()(r)){[Pu]=!1;[Hu]=null;[Qu]=s;[Fu]=i;[$u]=new Nu;get[Lu](){return this[Pu]}get[Ku](){return this[Hu]}get[Vu](){return this[Qu]}async destroy(...r){return this[$u].withWriteF(async()=>{if(this[Pu])return;this[Hu]="destroying",this[Fu]("destroying");const{p:s,resolveP:i}=Wu();let n;return this[Qu]=s,this[Fu]=i,this.dispatchEvent(new e),"function"==typeof super.destroy&&(n=await super.destroy(...r)),this[Pu]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[Hu]=null,this[Fu](null);const{p:e,resolveP:t}=Wu();this[Qu]=e,this[Fu]=t})}};return Object.defineProperty(n,"name",Object.getOwnPropertyDescriptor(r,"name")),n}}function cd(e=new od,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 ju?async function(...s){if(this[$u].isLocked("write")&&null===this[Hu]&&await this[Qu],r.includes(this[Hu]))return a.apply(this,s);if(t)return this[$u].withReadF(async()=>{if(this[Pu])throw Ju(e,n[o]),e;return a.apply(this,s)});if(this[$u].isLocked("write")||this[Pu])throw Ju(e,n[o]),e;return a.apply(this,s)}:a instanceof Gu?function*(...t){if(r.includes(this[Hu]))return yield*a.apply(this,t);if(this[$u].isLocked("write")&&null!==this[Ku]||this[Pu])throw Ju(e,n[o]),e;return yield*a.apply(this,t)}:a instanceof qu?async function*(...s){if(this[$u].isLocked("write")&&null===this[Hu]&&await this[Qu],r.includes(this[Hu]))return yield*a.apply(this,s);if(t)return yield*this[$u].withReadG(()=>{if(this[Pu])throw Ju(e,n[o]),e;return a.apply(this,s)});if(this[$u].isLocked("write")||this[Pu])throw Ju(e,n[o]),e;return yield*a.apply(this,s)}:function(...t){if(r.includes(this[Hu]))return a.apply(this,t);if(this[$u].isLocked("write")&&null!==this[Ku]||this[Pu])throw Ju(e,n[o]),e;return a.apply(this,t)},Object.defineProperty(n[o],"name",{value:i}),n}}function ld({eventStart:e=Xu,eventStarted:t=Zu,eventStop:r=ed,eventStopped:s=td}={}){return i=>{const{p:n,resolveP:o}=Wu(),a=class extends(fu()(i)){[Du]=!1;[Hu]=null;[Qu]=n;[Fu]=o;[$u]=new Nu;get[Mu](){return this[Du]}get[Ku](){return this[Hu]}get[Vu](){return this[Qu]}async start(...r){return this[$u].withWriteF(async()=>{if(this[Du])return;this[Hu]="starting",this[Fu]("starting");const{p:s,resolveP:i}=Wu();let n;return this[Qu]=s,this[Fu]=i,this.dispatchEvent(new e),"function"==typeof super.start&&(n=await super.start(...r)),this[Du]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[Hu]=null,this[Fu](null);const{p:e,resolveP:t}=Wu();this[Qu]=e,this[Fu]=t})}async stop(...e){return this[$u].withWriteF(async()=>{if(!this[Du])return;this[Hu]="stopping",this[Fu]("stopping");const{p:t,resolveP:i}=Wu();let n;return this[Qu]=t,this[Fu]=i,this.dispatchEvent(new r),"function"==typeof super.stop&&(n=await super.stop(...e)),this[Du]=!1,this.dispatchEvent(new s),n}).finally(()=>{this[Hu]=null,this[Fu](null);const{p:e,resolveP:t}=Wu();this[Qu]=e,this[Fu]=t})}};return Object.defineProperty(a,"name",Object.getOwnPropertyDescriptor(i,"name")),a}}function hd(e=new nd,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 ju?async function(...s){if(this[$u].isLocked("write")&&null===this[Hu]&&await this[Qu],r.includes(this[Hu]))return a.apply(this,s);if(t)return this[$u].withReadF(async()=>{if(!this[Du])throw Ju(e,n[o]),e;return a.apply(this,s)});if(this[$u].isLocked("write")||!this[Du])throw Ju(e,n[o]),e;return a.apply(this,s)}:a instanceof Gu?function*(...t){if(r.includes(this[Hu]))return yield*a.apply(this,t);if(this[$u].isLocked("write")&&null!==this[Ku]||!this[Du])throw Ju(e,n[o]),e;return yield*a.apply(this,t)}:a instanceof qu?async function*(...s){if(this[$u].isLocked("write")&&null===this[Hu]&&await this[Qu],r.includes(this[Hu]))return yield*a.apply(this,s);if(t)return yield*this[$u].withReadG(()=>{if(!this[Du])throw Ju(e,n[o]),e;return a.apply(this,s)});if(this[$u].isLocked("write")||!this[Du])throw Ju(e,n[o]),e;return yield*a.apply(this,s)}:function(...t){if(r.includes(this[Hu]))return a.apply(this,t);if(this[$u].isLocked("write")&&null!==this[Ku]||!this[Du])throw Ju(e,n[o]),e;return a.apply(this,t)},Object.defineProperty(n[o],"name",{value:i}),n}}class ud 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 dd=ud;class fd{[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,dd.fromString(s),this)}),this._clientConnections.forEach((r,s)=>{e.bind(t)(r,dd.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:[dd.fromString(e),t]}}const s=t.next();if(!s.done){const[e,t]=s.value;return{done:!1,value:[dd.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 gd=fd,pd=t(import.meta.url)("process");var yd=o(928);const md=t(import.meta.url)("url"),bd=t(import.meta.url)("node:module").createRequire("file:///home/runner/work/typeberry/typeberry/node_modules/@matrixai/quic/dist/native/quiche.js"),Ad=md.fileURLToPath(new URL(o(810),o.b)),Id=yd.join(Ad,"../../"),vd=yd.join(Id,"prebuild");function wd(e){const t=e.map(e=>yd.join(vd,`quic-${e}.node`));for(const e of t){try{return bd(e)}catch(e){if("MODULE_NOT_FOUND"!==e.code)throw e}try{return bd(md.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 bd(e)}catch(e){if("MODULE_NOT_FOUND"!==e.code)throw e}try{return bd(md.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 Sd;switch(pd.platform){case"win32":switch(pd.arch){case"x64":Sd=wd(["win32-x64"]);break;case"ia32":Sd=wd(["win32-ia32"]);break;case"arm64":Sd=wd(["win32-arm64"]);break;default:throw new Error(`Unsupported architecture on Windows: ${pd.arch}`)}break;case"darwin":switch(pd.arch){case"x64":Sd=wd(["darwin-x64","darwin-x64+arm64","darwin-arm64+x64","darwin-universal"]);break;case"arm64":Sd=wd(["darwin-arm64","darwin-arm64+x64","darwin-x64+arm64","darwin-universal"]);break;default:throw new Error(`Unsupported architecture on macOS: ${pd.arch}`)}break;case"linux":switch(pd.arch){case"x64":Sd=wd(["linux-x64"]);break;case"arm64":Sd=wd(["linux-arm64"]);break;case"arm":Sd=wd(["linux-arm"]);break;default:throw new Error(`Unsupported architecture on Linux: ${pd.arch}`)}break;default:throw new Error(`Unsupported OS: ${pd.platform}, architecture: ${pd.arch}`)}const Ed=Sd,Cd=t(import.meta.url)("dns");var kd=o(618);class xd extends wu{static description="QUIC error"}class _d extends wu{static description="You should never see this error"}class Bd extends wu{static description="Host provided was not valid"}class Rd extends wu{static description="Port provided was not valid"}class Od extends xd{static description="QUIC config error"}class Ud extends xd{static description="QUIC Socket error"}class Td extends Ud{static description="QUIC Socket is not running"}class Nd extends Ud{static description="QUIC Socket has active connections"}class Dd extends Ud{static description="QUIC Socket cannot bind to the specified address"}class Md extends Ud{static description="QUIC Socket cannot send to the specified address"}class Pd extends Ud{static description="QUIC Socket internal error"}class Ld extends xd{static description="QUIC Client error"}class Hd extends Ld{static description="QUIC Client is destroyed"}class Kd extends Ld{static description="QUIC Client cannot be created with an unstarted shared QUIC socket"}class Qd extends Ld{static description="QUIC Client had a failure relating to an invalid argument"}class Vd extends Ld{static description="QUIC Client cannot be created with the specified host"}class Fd extends Ld{static description="QUIC Client internal error"}class $d extends xd{static description="QUIC Server error"}class jd extends $d{static description="QUIC Server is not running"}class Gd extends $d{static description="QUIC Server cannot start with an unstarted shared QUIC socket"}class qd extends $d{static description="QUIC Server creating a new connection"}class zd extends $d{static description="QUIC Server internal error"}class Wd extends $d{static description="QUIC Server is stopping"}class Jd extends xd{static description="QUIC Connection error"}class Yd extends Jd{static description="QUIC Connection is stopping"}class Xd extends Jd{static description="QUIC Connection is not running"}class Zd extends Jd{static description="QUIC Connection cannot be restarted because it has already been closed"}class ef extends xd{static description="QUIC Connection start requires data when it is a server connection"}class tf extends Jd{static description="QUIC connection invalid configuration"}class rf extends Jd{static description="QUIC Connection local error";constructor(e="",t){super(e,t)}}class sf extends rf{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class nf extends Jd{static description="QUIC Connection peer error";constructor(e="",t){super(e,t)}}class of extends rf{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class af extends Jd{static description="QUIC Connection max idle timeout exhausted"}class cf extends Jd{static description="QUIC Connection internal error"}class lf extends xd{static description="QUIC Stream error"}class hf extends lf{static description="QUIC Stream is destroyed"}class uf extends lf{static description="QUIC Stream locally closed readable side";constructor(e="",t){super(e,t)}}class df extends lf{static description="QUIC Stream locally closed writable side";constructor(e="",t){super(e,t)}}class ff extends lf{static description="QUIC Stream peer closed readable side";constructor(e="",t){super(e,t)}}class gf extends lf{static description="QUIC Stream peer closed writable side";constructor(e="",t){super(e,t)}}class pf extends lf{static description="QUIC Stream internal error"}class yf extends lf{static description="QUIC Stream limit has been reached"}const mf=new TextEncoder,bf=new TextDecoder("utf-8");function Af(e){throw new _d(e)}function If(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 vf(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function wf(e){const[t]=kd.Validator.isValidIPv4String(e);return t}function Sf(e){const[t]=kd.Validator.isValidIPv6String(e);return!!t||Ef(e)}function Ef(e){if(e.startsWith("::ffff:"))try{return kd.IPv6.fromString(e),!0}catch{if(wf(e.slice(7)))return!0}return!1}function Cf(e){if(!wf(e))throw new TypeError("Invalid IPv4 address");return"::ffff:"+e}function kf(e){const t=e.slice(7);if(wf(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 xf(e){const t=new kd.IPv4("0.0.0.0"),r=new kd.IPv6("::");if(Ef(e)){const r=kf(e);return new kd.IPv4(r).isEquals(t)?Cf("127.0.0.1"):e}return wf(e)&&new kd.IPv4(e).isEquals(t)?"127.0.0.1":Sf(e)&&new kd.IPv6(e).isEquals(r)?"::1":e}async function _f(e){return(await Cd.promises.lookup(e,{family:0,all:!1,verbatim:!0})).address}async function Bf(e,t){if(wf(e))return[e,"udp4"];if(Sf(e))return[e,"udp6"];try{return Bf(e=await t(e),t)}catch{throw new Bd}}function Rf(e){if(!function(e){return"number"==typeof e&&e>=0&&e<=65535}(e))throw new Rd;return e}function Of(e,t=0){let r;return r=wf(e)?`${e}:${t}`:Sf(e)?`[${e}]:${t}`:`${e}:${t}`,r}function Uf(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=Ef(e),a=Ef(r);if("ipv4&ipv6"===t&&"udp4"===s)return Cf(r);if("ipv4"===t){if(o){if("udp4"===s)return Cf(r);if("udp6"===s&&!a)throw new i(`Invalid target host ${r} from an IPv4 socket`)}else if("udp6"===s){if(a)return kf(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 Tf(e){const t=[];if("string"==typeof e)t.push(e.trim()+"\n");else if(e instanceof Uint8Array)t.push(bf.decode(e).trim()+"\n");else if(Array.isArray(e))for(const r of e)"string"==typeof r?t.push(r.trim()+"\n"):t.push(bf.decode(r).trim()+"\n");return t}function Nf(e){const t=e.replace(/-----BEGIN .*-----/,"").replace(/-----END .*-----/,"").replace(/\s+/g,""),r=Buffer.from(t,"base64");return new Uint8Array(r)}function Df(e){return`${e.name}${"description"in e?`: ${e.description}`:""}${void 0!==e.message?` - ${e.message}`:""}`}function Mf(e){let t;return null!=(t=e.message.match(/StreamStopped\((\d{1,16})\)/))&&parseInt(t[1])}function Pf(e){let t;return null!=(t=e.message.match(/StreamReset\((\d{1,16})\)/))&&parseInt(t[1])}function Lf(e,t=1e5){En.setMaxListeners(t,e)}class Hf extends Jh{}class Kf extends Hf{}class Qf extends Kf{}class Vf extends Kf{}class Ff extends Kf{}class $f extends Hf{}class jf extends $f{}class Gf extends Kf{}class qf extends $f{}class zf extends Hf{}class Wf extends zf{}class Jf extends zf{}class Yf extends zf{}class Xf extends Hf{}class Zf extends Xf{}class eg extends Xf{}class tg extends Xf{}class rg extends Xf{}class sg extends Xf{}class ig extends Hf{}class ng extends ig{}class og extends ig{}class ag extends ig{}class cg extends ig{}class lg extends ig{}var hg=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 ug=class{connectionMap=new gd;logger;server;resolveHostname;_host;_port;_type;_closed=!1;_closedP;resolveClosedP;socket;socketBind;socketClose;socketSend;handleEventQUICSocketError=e=>{const t=e.detail;this.logger.debug(Df(t))};handleEventQUICSocketClose=async()=>{await this.socketClose(),this._closed=!0,this.resolveClosedP(),this[Mu]&&await this.stop({force:!0})};handleSocketMessage=async(e,t)=>{let r;try{r=Ed.Header.fromSlice(e,Ed.MAX_CONN_ID_LEN)}catch(e){if("BufferTooShort"===e.message||"InvalidPacket"===e.message)return;throw e}const s=new dd(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(Su(e,e=>e instanceof Ud)){const t=new Pd("Failed to call accept connection due to socket send",{cause:e});return this.dispatchEvent(new Vf({detail:t})),void this.dispatchEvent(new Ff)}if(e instanceof qd)return;throw e}}};constructor({resolveHostname:e=_f,logger:t}){this.logger=t??new zh(this.constructor.name),this.resolveHostname=e;const{p:r,resolveP:s}=vf();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}={}){Lf(this[su]);let i=Of(e,t);this.logger.info(`Start ${this.constructor.name} on ${i}`);const[n,o]=await Bf(e,this.resolveHostname),a=Rf(t);this.socket=Bh.createSocket({type:o,reuseAddr:r,ipv6Only:s}),this.socketBind=If(this.socket.bind).bind(this.socket),this.socketClose=If(this.socket.close).bind(this.socket),this.socketSend=If(this.socket.send).bind(this.socket);const{p:c,rejectP:l}=vf();c.catch(()=>{}),this.socket.once("error",l);const h=this.socketBind(a,n);try{await Promise.race([h,c])}catch(t){throw new Dd(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||Ef(n)?this._type="ipv4":"udp6"===o&&(this._type="ipv6"):this._type="ipv4&ipv6",this.socket.on("message",this.handleSocketMessage),this.addEventListener(Vf.name,this.handleEventQUICSocketError),this.addEventListener(Ff.name,this.handleEventQUICSocketClose,{once:!0}),this._closed=!1,i=Of(this._host,this._port),this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({force:e=!1}={}){const t=Of(this._host,this._port);if(this.logger.info(`Stop ${this.constructor.name} on ${t}`),!e&&this.connectionMap.size>0)throw new Nd(`Cannot stop QUICSocket with ${this.connectionMap.size} active connection(s)`);this._closed||this.dispatchEvent(new Ff),await this._closedP;const{p:r,resolveP:s}=vf();this._closedP=r,this.resolveClosedP=s,this.removeEventListener(Vf.name,this.handleEventQUICSocketError),this.removeEventListener(Ff.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 Bf(r,this.resolveHostname);return s=xf(s),s=Uf(this._host,this._type,s,i,Md),e[t]=s,this.socketSend(...e)}async send_(...e){return this.socketSend(...e)}setServer(e){this.server=e}unsetServer(){delete this.server}};hg([hd(new Td)],ug.prototype,"host",null),hg([hd(new Td)],ug.prototype,"port",null),hg([hd(new Td)],ug.prototype,"type",null),hg([hd(new Td)],ug.prototype,"send",null),hg([hd(new Td)],ug.prototype,"send_",null),ug=hg([ld({eventStart:class extends Kf{},eventStarted:class extends Kf{},eventStop:class extends Kf{},eventStopped:Qf})],ug);const dg=ug,fg=new WeakMap;const gg=function(e,t,r){const s=e.name??e.constructor.name,i=e[t];if(fg.has(i))throw new TypeError(`\`${s}.${t.toString()}\` redeclares \`@context\` decorator`);fg.set(i,r)};class pg extends wu{static description="Contexts error"}class yg extends pg{static description="Aborted due to timer expiration"}const mg=function(e=!1,t=1/0,r=yg){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=fg.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 xu))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 xu(()=>{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 xu&&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 xu(()=>{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 mu((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}},bg=["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(":"),Ag=1/0,Ig={sigalgs:bg,verifyPeer:!0,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:Ed.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:Ed.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:Ed.MAX_CONNECTION_WINDOW,maxStreamWindow:Ed.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},vg={sigalgs:bg,verifyPeer:!1,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:Ed.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:Ed.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:Ed.MAX_CONNECTION_WINDOW,maxStreamWindow:Ed.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},wg=t(import.meta.url)("stream/web");var Sg=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 Eg=Symbol("abort readableP reason");let Cg=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 zh(`${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(og.name,a.handleEventQUICStreamError),a.addEventListener(ag.name,a.handleEventQUICStreamCloseRead,{once:!0}),a.addEventListener(cg.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 pf)throw this.logger.debug(Df(t)),t;t instanceof uf||t instanceof ff?this.dispatchEvent(new ag({detail:t})):(t instanceof df||t instanceof gf)&&this.dispatchEvent(new cg({detail:t}))};handleEventQUICStreamCloseRead=async()=>{this._readClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[Lu]||"destroying"===this[Ku]||await this.destroy({force:!1}))};handleEventQUICStreamCloseWrite=async()=>{this._writeClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[Lu]||"destroying"===this[Ku]||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}=vf();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 wg.ReadableStream({start:this.readableStart.bind(this)}):this.readable=new wg.ReadableStream({start:this.readableStart.bind(this),pull:this.readablePull.bind(this),cancel:this.readableCancel.bind(this)},new wg.CountQueuingStrategy({highWaterMark:1})),"uni"===this.type&&"peer"===this.initiated)this.writable=new wg.WritableStream({start:this.writableStart.bind(this)});else{this.writable=new wg.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===Mf(e)){if("StreamLimit"===e.message){const t="bidi"===this.type?s.initialMaxStreamsBidi:s.initialMaxStreamsUni;throw new yf(`Stream limit of ${t} has been reached`,{cause:e})}throw new pf(`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(og.name,this.handleEventQUICStreamError),this.removeEventListener(ag.name,this.handleEventQUICStreamCloseRead),this.removeEventListener(cg.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=Pf(e))){const e=this.codeToReason("read",t),r=new ff("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),this.rejectReadableP?.(e),void this.dispatchEvent(new og({detail:r}))}{const t=new pf("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.rejectReadableP?.(t),this.dispatchEvent(new og({detail:t})),t}}if(null===e){const e=new pf("Failed `streamRecv` on the readable stream");throw this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new og({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 ag),void this.rejectReadableP?.(Eg)}this.resolveReadableP?.()}write(){try{this.connection.conn.streamCapacity(this.streamId)}catch(e){let t;if(!1!==(t=Mf(e))){this.connection.conn.streamShutdown(this.streamId,Ed.Shutdown.Write,t);const e=this.codeToReason("write",t),r=new gf("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),this.rejectWritableP?.(e),void this.dispatchEvent(new og({detail:r}))}{const t=new pf("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.rejectWritableP?.(t),this.dispatchEvent(new og({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}=vf();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=Pf(e))){const e=this.codeToReason("read",t),r=new ff("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),void this.dispatchEvent(new og({detail:r}))}{const t=new pf("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.dispatchEvent(new og({detail:t})),t}}if(null===e){const e=new pf("Failed `streamRecv` on the readable stream because it is not readable");throw this.readableController.error(e),this.dispatchEvent(new og({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 ag)),this.dispatchEvent(new lg)}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=Mf(e))){const e=this.codeToReason("write",t),r=new gf("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new og({detail:r}))}{const t=new pf("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new og({detail:t})),t}}if(this.dispatchEvent(new lg),t<e.byteLength){e=e.subarray(t,e.byteLength);const{p:r,resolveP:s,rejectP:i}=vf();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=Mf(e))){const e=this.codeToReason("write",t),r=new gf("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new og({detail:r}))}{const t=new pf("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new og({detail:t})),t}}this.dispatchEvent(new cg),this.dispatchEvent(new lg)}readableCancel(e){if(this._readClosed)return;const t=this.reasonToCode("read",e);try{this.connection.conn.streamShutdown(this.streamId,Ed.Shutdown.Read,t)}catch(r){const e=new pf("Local stream readable could not be shutdown",{cause:r});throw this.readableController.error(e),this.dispatchEvent(new og({detail:e})),e}const r=new uf("Closing readable stream locally",{data:{code:t},cause:e});this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new og({detail:r})),this.dispatchEvent(new lg)}writableAbort(e){if(this._writeClosed)return;const t=this.reasonToCode("write",e);try{this.connection.conn.streamShutdown(this.streamId,Ed.Shutdown.Write,t)}catch(r){const e=new pf("Local stream writable could not be shutdown",{cause:r});throw this.writableController.error(e),this.dispatchEvent(new og({detail:e})),e}const r=new df("Closing writable stream locally",{data:{code:t},cause:e});this.writableController.error(e),this.rejectWritableP?.(e),this.dispatchEvent(new og({detail:r})),this.dispatchEvent(new lg)}};Sg([cd(new hf)],Cg.prototype,"meta",null),Sg([cd(new hf,!1,["destroying"])],Cg.prototype,"read",null),Sg([cd(new hf,!1,["destroying"])],Cg.prototype,"write",null),Cg=Sg([ad({eventDestroy:class extends ig{},eventDestroyed:ng})],Cg);const kg=Cg;var xg,_g,Bg,Rg,Og,Ug;!function(e){e[e.Reno=0]="Reno",e[e.CUBIC=1]="CUBIC",e[e.BBR=2]="BBR"}(xg||(xg={})),function(e){e[e.Read=0]="Read",e[e.Write=1]="Write"}(_g||(_g={})),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"}(Bg||(Bg={})),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"}(Rg||(Rg={})),(Ug=Og||(Og={}))[Ug.CloseNotify=256]="CloseNotify",Ug[Ug.UnexpectedMessage=266]="UnexpectedMessage",Ug[Ug.BadRecordMac=276]="BadRecordMac",Ug[Ug.RecordOverflow=278]="RecordOverflow",Ug[Ug.HandshakeFailure=296]="HandshakeFailure",Ug[Ug.BadCertificate=298]="BadCertificate",Ug[Ug.UnsupportedCertificate=299]="UnsupportedCertificate",Ug[Ug.CertificateRevoked=300]="CertificateRevoked",Ug[Ug.CertificateExpired=301]="CertificateExpired",Ug[Ug.CertificateUnknown=302]="CertificateUnknown",Ug[Ug.IllegalParameter=303]="IllegalParameter",Ug[Ug.UnknownCA=304]="UnknownCA",Ug[Ug.AccessDenied=305]="AccessDenied",Ug[Ug.DecodeError=306]="DecodeError",Ug[Ug.DecryptError=307]="DecryptError",Ug[Ug.ProtocolVersion=326]="ProtocolVersion",Ug[Ug.InsufficientSecurity=327]="InsufficientSecurity",Ug[Ug.InternalError=336]="InternalError",Ug[Ug.InappropriateFallback=342]="InappropriateFallback",Ug[Ug.UserCanceled=346]="UserCanceled",Ug[Ug.MissingExtension=365]="MissingExtension",Ug[Ug.UnsupportedExtension=366]="UnsupportedExtension",Ug[Ug.UnrecognizedName=368]="UnrecognizedName",Ug[Ug.BadCertificateStatusResponse=369]="BadCertificateStatusResponse",Ug[Ug.UnknownPSKIdentity=371]="UnknownPSKIdentity",Ug[Ug.CertificateRequired=372]="CertificateRequired",Ug[Ug.NoApplicationProtocol=376]="NoApplicationProtocol";var Tg=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 Ng=class{type;closedP;conn;streamMap=new Map;sendId;logger;socket;config;reasonToCode;codeToReason;recvLock=new Tu;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(Df(t)),t instanceof cf)throw t;this.dispatchEvent(new tg({detail:t}))};handleEventQUICConnectionClose=async e=>{const t=e.detail;this.secureEstablished||this.rejectSecureEstablishedP(t),t instanceof rf&&await this.send(),this[Mu]&&"stopping"!==this[Ku]&&await this.stop({force:!0})};handleEventQUICStream=e=>{e.detail instanceof Jh&&!(e.detail instanceof lg)&&this.dispatchEvent(e.detail.clone())};handleEventQUICStreamSend=async()=>{this[Mu]&&await this.send()};handleEventQUICStreamDestroyed=e=>{const t=e.target;t.removeEventListener(lg.name,this.handleEventQUICStreamSend),t.removeEventListener(eu.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 zh(`${this.constructor.name} ${t}`),this.sendId=t.toString(),null!=n.keepAliveIntervalTime&&0!==n.maxIdleTimeout&&n.keepAliveIntervalTime>=n.maxIdleTimeout)throw new tf("`keepAliveIntervalTime` must be less than `maxIdleTimeout`");const h=function(e){if(null!=e.key&&null==e.cert)throw new Od("The cert option must be set when key is set");if(null==e.key&&null!=e.cert)throw new Od("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 Od("The number of keys must match the number of certs");let t,r,s,i;if(null!=e.ca){const r=Tf(e.ca);t=mf.encode(r.join(""))}null!=e.key&&(r=Tf(e.key).map(e=>mf.encode(e))),null!=e.cert&&(s=Tf(e.cert).map(e=>mf.encode(e)));try{i=Ed.Config.withBoringSslCtx(e.verifyPeer,null!=e.verifyCallback,t,r,s,e.sigalgs)}catch(e){throw new Od(`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=Ed.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=Ed.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=Tf(this.config.cert);this.certDERs=e.map(Nf)}if(null!=this.config.ca){const e=Tf(this.config.ca);this.caDERs=e.map(Nf)}this.reasonToCode=a,this.codeToReason=c,this._remoteHost=i.host,this._remotePort=i.port;const{p:d,resolveP:f,rejectP:g}=vf();d.catch(()=>{}),this.secureEstablishedP=d,this.resolveSecureEstablishedP=()=>{this.secureEstablished=!0,f()},this.rejectSecureEstablishedP=g;const{p,resolveP:y}=vf();this.closedP=p,this.resolveClosedP=y}get connectionId(){const e=this.conn.sourceId();return new dd(e.buffer,e.byteOffset,e.byteLength)}get connectionIdPeer(){const e=this.conn.destinationId();return new dd(e.buffer,e.byteOffset,e.byteLength)}get connectionIdShared(){const e=this.conn.sourceId(),t=this.conn.destinationId();return Buffer.compare(e,t)<=0?new dd(Buffer.concat([e,t])):new dd(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 Zd;r.signal.throwIfAborted();const{p:s,rejectP:i}=vf();s.catch(()=>{});const n=()=>{i(r.signal.reason)};if(r.signal.addEventListener("abort",n),this.addEventListener(eg.name,this.handleEventQUICConnectionError),this.addEventListener(tg.name,this.handleEventQUICConnectionClose,{once:!0}),"client"===this.type)await this.send();else if("server"===this.type){if(null==e||null==t)throw new ef("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,Ed.Shutdown.Read,this.reasonToCode("read",e));for(const t of this.conn.writable())this.conn.streamShutdown(t,Ed.Shutdown.Write,this.reasonToCode("write",e));this.conn.close(!1,Rg.ApplicationError,Buffer.from(""));const t=this.conn.localError(),r=new rf("Failed to start QUIC connection due to start timeout",{data:t,cause:e});this.dispatchEvent(new eg({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 rf(i,{data:s});this.dispatchEvent(new eg({detail:n}))}await this.closedP,this.removeEventListener(eg.name,this.handleEventQUICConnectionError),this.removeEventListener(tg.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 cf("Failed connection recv due with unknown error",{cause:e});throw this.dispatchEvent(new eg({detail:t})),t}{let r;return r="TlsFail"===e.message?new sf("Failed connection due to native TLS verification",{cause:e,data:t}):new rf("Failed connection due to local error",{cause:e,data:t}),void this.dispatchEvent(new eg({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 cf("Failed connection send with unknown internal error",{cause:e});throw this.dispatchEvent(new eg({detail:t})),t}this.dispatchEvent(new sg({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 sf("Failed connection due to custom TLS verification",{data:e});return void this.dispatchEvent(new eg({detail:r}))}this.resolveSecureEstablishedP(),this.processStreams()}if("stopping"!==this[Ku]){const e=this.conn.peerError();if(null!=e){const t=`Peer closed with ${e.isApp?"application":"transport"} code ${e.errorCode}`;return void(e.errorCode>=Ed.CRYPTO_ERROR_START&&e.errorCode<=Ed.CRYPTO_ERROR_STOP?this.dispatchEvent(new eg({detail:new of(t,{data:e})})):this.dispatchEvent(new eg({detail:new nf(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:Af("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[Mu]||"stopping"===this[Ku]){this.conn.streamShutdown(e,_g.Write,this.reasonToCode("write",Yd)),this.conn.streamShutdown(e,_g.Read,this.reasonToCode("read",Yd));continue}this.isStreamUsed(e)&&Af("We should never repeat streamIds when creating streams"),t=kg.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${kg.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(lg.name,this.handleEventQUICStreamSend),t.addEventListener(ng.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(eu.name,this.handleEventQUICStream),this.dispatchEvent(new rg({detail:t}))}t.read()}for(const e of this.conn.writable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[Mu]||"stopping"===this[Ku]){this.conn.streamShutdown(e,_g.Write,this.reasonToCode("write",Yd)),this.conn.streamShutdown(e,_g.Read,this.reasonToCode("read",Yd));continue}if(this.isStreamUsed(e)){try{this.conn.streamSend(e,new Uint8Array,!1)}catch(e){if(!1!==Mf(e))continue;if("FinalSize"===e.message)continue;throw e}Af("We never expect a duplicate stream to be readable")}t=kg.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${kg.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(lg.name,this.handleEventQUICStreamSend),t.addEventListener(ng.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(eu.name,this.handleEventQUICStream),this.dispatchEvent(new rg({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 eg({detail:new af})));await this.send();const r=this.conn.timeout();null!=r&&(this.connTimeoutTimer=new xu({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 eg({detail:new af}))));null==this.connTimeoutTimer||"settled"===this.connTimeoutTimer.status?this.connTimeoutTimer=new xu({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)&&Af("We should never repeat streamIds when creating streams");const r=kg.createQUICStream({initiated:"local",streamId:t,connection:this,config:this.config,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${kg.name} ${t}`)});return this.streamMap.set(r.streamId,r),r.addEventListener(lg.name,this.handleEventQUICStreamSend),r.addEventListener(ng.name,this.handleEventQUICStreamDestroyed,{once:!0}),r.addEventListener(eu.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 xu({delay:e,handler:t,lazy:!0})))};this.keepAliveIntervalTimer=new xu({delay:e,handler:t,lazy:!0})}stopKeepAliveIntervalTimer(){this.keepAliveIntervalTimer?.cancel()}};var Dg,Mg;Tg([hd(new Xd)],Ng.prototype,"connectionIdPeer",null),Tg([hd(new Xd)],Ng.prototype,"connectionIdShared",null),Tg([mg(!0,Ag,class extends Jd{static description="QUIC Connection start timeout"}),(Dg=1,Mg=gg,function(e,t){Mg(e,t,Dg)})],Ng.prototype,"start",null),Tg([hd(new Xd,!1,["starting","stopping"])],Ng.prototype,"recv",null),Tg([hd(new Xd,!1,["starting","stopping"])],Ng.prototype,"send",null),Tg([hd(new Xd)],Ng.prototype,"newStream",null),Ng=Tg([ld({eventStart:class extends Xf{},eventStarted:class extends Xf{},eventStop:class extends Xf{},eventStopped:Zf})],Ng);const Pg=Ng;var Lg=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 Hg=class{isSocketShared;reasonToCode;codeToReason;minIdleTimeout;logger;socket;crypto;config;_closed=!1;_closedP;resolveClosedP;stopAbortController;handleEventQUICServerError=e=>{const t=e.detail;if(this.logger.info(Df(t)),t instanceof zd)throw t;this.dispatchEvent(new Yf({detail:t}))};handleEventQUICServerClose=async e=>{const t=e.detail;if(!(t instanceof Gd||this.isSocketShared)){this.socket.removeEventListener(Qf.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new zd("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new Jf({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[Mu]&&"stopping"!==this[Ku]&&(void 0!==t?await this.stop({isApp:!1,errorCode:Rg.InternalError,reason:Buffer.from(t.description),force:!0}):await this.stop({force:!0}))};handleEventQUICSocket=e=>{e.detail instanceof Jh&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new Gd;this.removeEventListener(eu.name,this.handleEventQUICSocket),this.dispatchEvent(new Jf({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof Jh&&!(e.detail instanceof sg)&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionSend=async e=>{if(this.socket[Mu]&&"stopping"!==this.socket[Ku])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 Gf(`${Gf.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new Jf({detail:new zd("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(sg.name,this.handleEventQUICConnectionSend),t.removeEventListener(eu.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({crypto:e,config:t,socket:r,resolveHostname:s=_f,reasonToCode:i,codeToReason:n,minIdleTimeout:o,logger:a}){this.logger=a??new zh(this.constructor.name),this.crypto=e,null==r?(this.socket=new dg({resolveHostname:s,logger:this.logger.getChild(dg.name)}),this.isSocketShared=!1):(this.socket=r,this.isSocketShared=!0),this.config={...vg,...t},this.reasonToCode=i,this.codeToReason=n,this.minIdleTimeout=o;const{p:c,resolveP:l}=vf();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,Lf(this.stopAbortController.signal),this.isSocketShared){if(!this.socket[Mu])throw new Gd;i=Of(this.socket.host,this.socket.port),this.logger.info(`Start ${this.constructor.name} on ${i}`)}else i=Of(e,t),this.logger.info(`Start ${this.constructor.name} on ${i}`),await this.socket.start({host:e,port:t,reuseAddr:r,ipv6Only:s}),i=Of(this.socket.host,this.socket.port);this.socket.setServer(this),this.addEventListener(Jf.name,this.handleEventQUICServerError),this.addEventListener(Yf.name,this.handleEventQUICServerClose,{once:!0}),this.socket.addEventListener(Qf.name,this.handleEventQUICSocketStopped,{once:!0}),this.isSocketShared||this.socket.addEventListener(eu.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[Mu]&&(i=Of(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 Wd),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 Yf),await this._closedP;const{p:o,resolveP:a}=vf();this._closedP=o,this.resolveClosedP=a,this.removeEventListener(Jf.name,this.handleEventQUICServerError),this.removeEventListener(Yf.name,this.handleEventQUICServerClose),this.socket.removeEventListener(Qf.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(eu.name,this.handleEventQUICSocket),this.logger.info(`Stopped ${this.constructor.name}${null!=i?` on ${i}`:""}`)}async acceptConnection(e,t,r,s){if(t.ty!==Ed.Type.Initial&&t.ty!==Ed.Type.ZeroRTT)return;const i=new dd(await this.crypto.ops.sign(this.crypto.key,r),0,Ed.MAX_CONN_ID_LEN),n=Of(e.host,e.port);if(!Ed.versionIsSupported(t.version)){const r=Buffer.allocUnsafe(Ed.MAX_DATAGRAM_SIZE),s=Ed.negotiateVersion(t.scid,t.dcid,r);try{await this.socket.send_(r,0,s,e.port,e.host)}catch(e){throw new qd(`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(Ed.MAX_DATAGRAM_SIZE),a=Ed.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 qd(`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 dd(t.dcid),l=new Pg({type:"server",scid:c,dcid:a,socket:this.socket,remoteInfo:e,config:{...this.config},reasonToCode:this.reasonToCode,codeToReason:this.codeToReason,logger:this.logger.getChild(`${Pg.name} ${i.toString()}`)});this.socket.connectionMap.set(l.connectionId,l),l.addEventListener(sg.name,this.handleEventQUICConnectionSend),l.addEventListener(Zf.name,this.handleEventQUICConnectionStopped,{once:!0}),l.addEventListener(eu.name,this.handleEventQUICConnection);try{await l.start({data:s,remoteInfo:e},{timer:this.minIdleTimeout,signal:this.stopAbortController?.signal})}catch(e){throw l.removeEventListener(sg.name,this.handleEventQUICConnectionSend),l.removeEventListener(Zf.name,this.handleEventQUICConnectionStopped),l.removeEventListener(eu.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(l.connectionId),new qd("Failed to start accepted connection",{cause:e})}return this.dispatchEvent(new Wf({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?dd.fromString(o.dcid):void 0}(e,t,this.crypto)}};Lg([hd(new jd)],Hg.prototype,"host",null),Lg([hd(new jd)],Hg.prototype,"port",null),Lg([hd(new jd)],Hg.prototype,"acceptConnection",null),Hg=Lg([ld({eventStart:class extends zf{},eventStarted:class extends zf{},eventStop:class extends zf{},eventStopped:class extends zf{}})],Hg);var Kg=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 Qg=class{static async createQUICClient({host:e,port:t,serverName:r,localHost:s="::",localPort:i=0,socket:n,crypto:o,config:a={},resolveHostname:c=_f,reuseAddr:l,ipv6Only:h,reasonToCode:u,codeToReason:d,logger:f=new zh(`${this.name}`)},g){let p=Of(e,t);f.info(`Create ${this.name} to ${p}`);const y={...Ig,...a},m=new ArrayBuffer(Ed.MAX_CONN_ID_LEN);await o.ops.randomBytes(m);const b=new dd(m);let[A,I]=await Bf(e,c);const v=Rf(t);let w,S;if(A=xf(A),null==n){const[e]=await Bf(s,c),t=Rf(i);n=new dg({resolveHostname:c,logger:f.getChild(dg.name)}),w=!1,await n.start({host:e,port:t,reuseAddr:l,ipv6Only:h})}else if(w=!0,!n[Mu])throw new Gd;try{A=Uf(n.host,n.type,A,I,Vd)}catch(e){throw w||await n.stop({force:!0}),e}try{S=new Pg({type:"client",scid:b,serverName:r??e,socket:n,remoteInfo:{host:A,port:v},config:y,reasonToCode:u,codeToReason:d,logger:f.getChild(`${Pg.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(eu.name,E.handleEventQUICSocket),n.addEventListener(Qf.name,E.handleEventQUICSocketStopped,{once:!0}),S.addEventListener(eu.name,E.handleEventQUICConnection),S.addEventListener(eg.name,E.handleEventQUICConnectionError),S.addEventListener(sg.name,E.handleEventQUICConnectionSend),S.addEventListener(Zf.name,E.handleEventQUICConnectionStopped,{once:!0}),E.addEventListener(jf.name,E.handleEventQUICClientError),E.addEventListener(qf.name,E.handleEventQUICClientClose,{once:!0}),n.connectionMap.set(S.connectionId,S);const C=new AbortController,k=()=>{C.abort(g.signal.reason)};g.signal.aborted?C.abort(g.signal.reason):g.signal.addEventListener("abort",k);const x=e=>{switch(e.detail.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":C.abort(new Qd(void 0,{cause:e.detail}))}};E.addEventListener(`${Gf.name}-${S.sendId}`,x);try{await S.start(void 0,{timer:g.timer,signal:C.signal})}catch(e){throw n.connectionMap.delete(S.connectionId),n.removeEventListener(Qf.name,E.handleEventQUICSocketStopped),w||(n.removeEventListener(eu.name,E.handleEventQUICSocket),await n.stop({force:!0})),S.removeEventListener(eu.name,E.handleEventQUICConnection),S.removeEventListener(eg.name,E.handleEventQUICConnectionError),S.removeEventListener(sg.name,E.handleEventQUICConnectionSend),S.removeEventListener(Zf.name,E.handleEventQUICConnectionStopped),E.removeEventListener(jf.name,E.handleEventQUICClientError),E.removeEventListener(qf.name,E.handleEventQUICClientClose),e}finally{g.signal.removeEventListener("abort",k),E.removeEventListener(`${Gf.name}-${S.sendId}`,x)}return p=Of(A,t),f.info(`Created ${this.name} to ${p}`),E}isSocketShared;connection;closedP;logger;socket;config;_closed=!1;resolveClosedP;handleEventQUICClientError=e=>{const t=e.detail;if(this.logger.info(Df(t)),t instanceof Fd||t instanceof cf)throw t;this.dispatchEvent(new qf({detail:t}))};handleEventQUICClientClose=async e=>{const t=e.detail;if(this.connection.removeEventListener(eg.name,this.handleEventQUICConnectionError),await this.connection.stop({isApp:!1,errorCode:Rg.InternalError,reason:Buffer.from(t.description),force:!0}),!(t instanceof Kd||this.isSocketShared)){this.socket.removeEventListener(Qf.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new Fd("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new jf({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[Lu]||"destroying"===this[Ku]||await this.destroy({force:!0})};handleEventQUICSocket=e=>{e.detail instanceof Jh&&!(e.detail instanceof sg)&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new Kd;this.removeEventListener(eu.name,this.handleEventQUICSocket),this.dispatchEvent(new jf({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof Jh&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionError=e=>{const t=e.detail;this.dispatchEvent(new jf({detail:t}))};handleEventQUICConnectionSend=async e=>{try{if(!this.socket[Mu]||"stopping"===this.socket[Ku])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 Gf(`${Gf.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new jf({detail:new Fd("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(eg.name,this.handleEventQUICConnectionError),t.removeEventListener(sg.name,this.handleEventQUICConnectionSend),t.removeEventListener(eu.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}=vf();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[Mu]&&(i=Of(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(jf.name,this.handleEventQUICClientError),this.removeEventListener(qf.name,this.handleEventQUICClientClose),this.socket.removeEventListener(Qf.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(eu.name,this.handleEventQUICSocket),this.logger.info(`Destroyed ${this.constructor.name}${null!=i?` to ${i}`:""}`)}};Kg([cd(new Hd)],Qg.prototype,"host",null),Kg([cd(new Hd)],Qg.prototype,"port",null),Kg([cd(new Hd)],Qg.prototype,"localHost",null),Kg([cd(new Hd)],Qg.prototype,"localPort",null),Kg([mg(!0,Ag,class extends Ld{static description="QUIC Client create timeout"}),function(e,t){return function(r,s){t(r,s,e)}}(1,gg)],Qg,"createQUICClient",null),Qg=Kg([ad({eventDestroy:class extends $f{},eventDestroyed:class extends $f{}})],Qg),t(import.meta.url)("node:crypto");class Vg{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=Vg.toUint8Array(e),s=Vg.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 Fg="string",$g=/^[0-9a-f\s]+$/i,jg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Gg=/^[a-zA-Z0-9-_]+$/;class qg{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=Vg.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return decodeURIComponent(escape(r))}}class zg{static toString(e,t=!1){const r=Vg.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 Wg{static isHex(e){return typeof e===Fg&&$g.test(e)}static isBase64(e){return typeof e===Fg&&jg.test(e)}static isBase64Url(e){return typeof e===Fg&&Gg.test(e)}static ToString(e,t="utf8"){const r=Vg.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 zg.toString(r,!0);case"utf16":case"utf16be":return zg.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 zg.fromString(e,!0);case"utf16":case"utf16be":return zg.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=Vg.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(!Wg.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(!Wg.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=Wg.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return qg.fromString(e);case"utf16":case"utf16be":return zg.fromString(e);case"utf16le":case"usc2":return zg.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=Wg.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return qg.toString(e);case"utf16":case"utf16be":return zg.toString(e);case"utf16le":case"usc2":return zg.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=Vg.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return r}static ToHex(e){const t=Vg.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(!Wg.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 zg.toString(e,t)}static FromUtf16String(e,t=!1){return zg.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 Jg(...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 Yg(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 Xg(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 Zg(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 ep(...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 tp(){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=Xg(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,Xg(n,8)-s}function rp(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 sp(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function ip(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 np(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)}Wg.DEFAULT_UTF8_ENCODING="utf8",Math.log(2);class op{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return ip(this.items)}}const ap=[new Uint8Array([1])],cp="0123456789",lp="name",hp="valueHexView",up="isHexOnly",dp="idBlock",fp="tagClass",gp="tagNumber",pp="isConstructed",yp="fromBER",mp="toBER",bp="local",Ap="",Ip=new ArrayBuffer(0),vp=new Uint8Array(0),wp="EndOfContent",Sp="OCTET STRING",Ep="BIT STRING";function Cp(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?Vg.toUint8Array(r.valueHex):vp}fromBER(e,t,r){const s=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!np(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",Ip)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Wg.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class kp{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=Ap,warnings:r=[],valueBeforeDecode:s=vp}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=Vg.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Wg.ToHex(this.valueBeforeDecodeView)}}}kp.NAME="baseBlock";class xp extends kp{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'")}}xp.NAME="valueBlock";class _p extends(Cp(kp)){constructor({idBlock:e={}}={}){var t,r,s,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?Vg.toUint8Array(e.valueHex):vp,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",Ip}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=Zg(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=Vg.toUint8Array(e);if(!np(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=Xg(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}}}_p.NAME="identificationBlock";class Bp extends kp{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=Vg.toUint8Array(e);if(!np(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=Xg(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=Zg(this.length,8);if(s.byteLength>127)return this.error="Too big length",Ip;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}}}Bp.NAME="lengthBlock";const Rp={};class Op extends kp{constructor({name:e=Ap,optional:t=!1,primitiveSchema:r,...s}={},i){super(s),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new _p(s),this.lenBlock=new Bp(s),this.valueBlock=i?new i(s):new xp(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 op;t||Up(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?Ip: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():Wg.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${Wg.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 Up(e){var t;if(e instanceof Rp.Constructed)for(const t of e.valueBlock.value)Up(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}Op.NAME="BaseBlock";class Tp extends Op{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Ap,...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}'`}}Tp.NAME="BaseStringBlock";class Np extends(Cp(xp)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var Dp,Mp,Pp,Lp,Hp,Kp,Qp,Vp,Fp,$p,jp,Gp,qp,zp,Wp,Jp,Yp,Xp,Zp,ey,ty,ry,sy,iy,ny,oy,ay,cy,ly,hy,uy,dy,fy,gy,py,yy;Np.NAME="PrimitiveValueBlock";class my extends Op{constructor(e={}){super(e,Np),this.idBlock.isConstructed=!1}}function by(e,t=0,r=e.length){const s=t;let i=new Op({},xp);const n=new kp;if(!np(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=Op;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=Rp.EndOfContent;break;case 1:a=Rp.Boolean;break;case 2:a=Rp.Integer;break;case 3:a=Rp.BitString;break;case 4:a=Rp.OctetString;break;case 5:a=Rp.Null;break;case 6:a=Rp.ObjectIdentifier;break;case 10:a=Rp.Enumerated;break;case 12:a=Rp.Utf8String;break;case 13:a=Rp.RelativeObjectIdentifier;break;case 14:a=Rp.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:a=Rp.Sequence;break;case 17:a=Rp.Set;break;case 18:a=Rp.NumericString;break;case 19:a=Rp.PrintableString;break;case 20:a=Rp.TeletexString;break;case 21:a=Rp.VideotexString;break;case 22:a=Rp.IA5String;break;case 23:a=Rp.UTCTime;break;case 24:a=Rp.GeneralizedTime;break;case 25:a=Rp.GraphicString;break;case 26:a=Rp.VisibleString;break;case 27:a=Rp.GeneralString;break;case 28:a=Rp.UniversalString;break;case 29:a=Rp.CharacterString;break;case 30:a=Rp.BmpString;break;case 31:a=Rp.DATE;break;case 32:a=Rp.TimeOfDay;break;case 33:a=Rp.DateTime;break;case 34:a=Rp.Duration;break;default:{const e=i.idBlock.isConstructed?new Rp.Constructed:new Rp.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else a=i.idBlock.isConstructed?Rp.Constructed:Rp.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 Ay(e){if(!e.byteLength){const e=new Op({},xp);return e.error="Input buffer has zero length",{offset:-1,result:e}}return by(Vg.toUint8Array(e).slice(),0,e.byteLength)}function Iy(e,t){return e?1:t}Dp=my,Rp.Primitive=Dp,my.NAME="PRIMITIVE";class vy extends xp{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const s=Vg.toUint8Array(e);if(!np(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(;Iy(this.isIndefiniteForm,r)>0;){const e=by(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===wp)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===wp?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){const r=t||new op;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?Ip:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}vy.NAME="ConstructedValueBlock";class wy extends Op{constructor(e={}){super(e,vy),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} :`}}Mp=wy,Rp.Constructed=Mp,wy.NAME="CONSTRUCTED";class Sy extends xp{fromBER(e,t,r){return t}toBER(e){return Ip}}Sy.override="EndOfContentValueBlock";class Ey extends Op{constructor(e={}){super(e,Sy),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Pp=Ey,Rp.EndOfContent=Pp,Ey.NAME=wp;class Cy extends Op{constructor(e={}){super(e,xp),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}`}}Lp=Cy,Rp.Null=Lp,Cy.NAME="NULL";class ky extends(Cp(xp)){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=Vg.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,r){const s=Vg.toUint8Array(e);return np(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,tp.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}ky.NAME="BooleanValueBlock";class xy extends Op{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,ky),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}Hp=xy,Rp.Boolean=Hp,xy.NAME="BOOLEAN";class _y extends(Cp(vy)){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=vy.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===wp){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==Sp)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?vy.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}_y.NAME="OctetStringValueBlock";class By extends Op{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},_y),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=by(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?wy.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${Wg.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 Kp&&e.push(t.valueBlock.valueHexView);return Vg.concat(e)}}Kp=By,Rp.OctetString=Kp,By.NAME=Sp;class Ry extends(Cp(vy)){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=vy.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(const e of this.value){const t=e.constructor.NAME;if(t===wp){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==Ep)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=Vg.toUint8Array(e);if(!np(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=by(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 vy.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Ip;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}}}Ry.NAME="BitStringValueBlock";class Oy extends Op{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=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 wy.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 Uy(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=ep(new Uint8Array([l%10]),n):n[o-h]=l%10;return r[0]>0&&(n=ep(r,n)),n}function Ty(e){if(e>=ap.length)for(let t=ap.length;t<=e;t++){const e=new Uint8Array([0]);let r=ap[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=ep(e,r)),ap.push(r)}return ap[e]}function Ny(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()}Qp=Oy,Rp.BitString=Qp,Oy.NAME=Ep;class Dy extends(Cp(xp)){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=tp.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=Zg(r-t,8,s);return new Uint8Array(e)[0]|=128,e}let i=Zg(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=Ny(Ty(s),r),n="-"):r=Uy(r,Ty(s))),s++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(o=!0),o&&(n+=cp.charAt(r[e]));return!1===o&&(n+=cp.charAt(0)),n}}Vp=Dy,Dy.NAME="IntegerValueBlock",Object.defineProperty(Vp.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class My extends Op{constructor(e={}){super(e,Dy),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return sp(),BigInt(this.valueBlock.toString())}static fromBigInt(e){sp();const t=BigInt(e),r=new op,s=t.toString(16).replace(/^-/,""),i=new Uint8Array(Wg.FromHex(s));if(t<0){const e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;const s=BigInt(`0x${Wg.ToHex(e)}`)+t,n=Vg.toUint8Array(Wg.FromHex(s.toString(16)));n[0]|=128,r.write(n)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);return new Fp({valueHex:r.final()})}convertToDER(){const e=new Fp({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Fp({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}Fp=My,Rp.Integer=Fp,My.NAME="INTEGER";class Py extends My{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}$p=Py,Rp.Enumerated=$p,Py.NAME="ENUMERATED";class Ly extends(Cp(xp)){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=Vg.toUint8Array(e);if(!np(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=Xg(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){sp();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=Zg(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",Ip;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=Wg.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}}}Ly.NAME="sidBlock";class Hy extends xp{constructor({value:e=Ap,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new Ly;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,Ip;t.push(s)}return ip(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 Ly;if(s>Number.MAX_SAFE_INTEGER){sp();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}}Hy.NAME="ObjectIdentifierValueBlock";class Ky extends Op{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Hy),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}jp=Ky,Rp.ObjectIdentifier=jp,Ky.NAME="OBJECT IDENTIFIER";class Qy extends(Cp(kp)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const s=Vg.toUint8Array(e);if(!np(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=Xg(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=Zg(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",Ip;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?Wg.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Qy.NAME="relativeSidBlock";class Vy extends xp{constructor({value:e=Ap,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new Qy;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,Ip;r.push(s)}return ip(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 Qy;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}}Vy.NAME="RelativeObjectIdentifierValueBlock";class Fy extends Op{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Vy),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Gp=Fy,Rp.RelativeObjectIdentifier=Gp,Fy.NAME="RelativeObjectIdentifier";class $y extends wy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}qp=$y,Rp.Sequence=qp,$y.NAME="SEQUENCE";class jy extends wy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}zp=jy,Rp.Set=zp,jy.NAME="SET";class Gy extends(Cp(xp)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Ap}toJSON(){return{...super.toJSON(),value:this.value}}}Gy.NAME="StringValueBlock";class qy extends Gy{}qy.NAME="SimpleStringValueBlock";class zy extends Tp{constructor({...e}={}){super(e,qy)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,Vg.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}}zy.NAME="SIMPLE STRING";class Wy extends zy{fromBuffer(e){this.valueBlock.valueHexView=Vg.toUint8Array(e);try{this.valueBlock.value=Wg.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=Wg.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Wg.FromUtf8String(e)),this.valueBlock.value=e}}Wy.NAME="Utf8StringValueBlock";class Jy extends Wy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}Wp=Jy,Rp.Utf8String=Wp,Jy.NAME="UTF8String";class Yy extends zy{fromBuffer(e){this.valueBlock.value=Wg.ToUtf16String(e),this.valueBlock.valueHexView=Vg.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Wg.FromUtf16String(e))}}Yy.NAME="BmpStringValueBlock";class Xy extends Yy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}Jp=Xy,Rp.BmpString=Jp,Xy.NAME="BMPString";class Zy extends zy{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=Zg(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}}Zy.NAME="UniversalStringValueBlock";class em extends Zy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Yp=em,Rp.UniversalString=Yp,em.NAME="UniversalString";class tm extends zy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}Xp=tm,Rp.NumericString=Xp,tm.NAME="NumericString";class rm extends zy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}Zp=rm,Rp.PrintableString=Zp,rm.NAME="PrintableString";class sm extends zy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}ey=sm,Rp.TeletexString=ey,sm.NAME="TeletexString";class im extends zy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}ty=im,Rp.VideotexString=ty,im.NAME="VideotexString";class nm extends zy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}ry=nm,Rp.IA5String=ry,nm.NAME="IA5String";class om extends zy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}sy=om,Rp.GraphicString=sy,om.NAME="GraphicString";class am extends zy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}iy=am,Rp.VisibleString=iy,am.NAME="VisibleString";class cm extends zy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}ny=cm,Rp.GeneralString=ny,cm.NAME="GeneralString";class lm extends zy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}oy=lm,Rp.CharacterString=oy,lm.NAME="CharacterString";class hm extends am{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,Vg.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]=rp(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=rp(this.month,2),e[2]=rp(this.day,2),e[3]=rp(this.hour,2),e[4]=rp(this.minute,2),e[5]=rp(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}}}ay=hm,Rp.UTCTime=ay,hm.NAME="UTCTime";class um extends hm{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(rp(this.year,4)),e.push(rp(this.month,2)),e.push(rp(this.day,2)),e.push(rp(this.hour,2)),e.push(rp(this.minute,2)),e.push(rp(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(rp(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}cy=um,Rp.GeneralizedTime=cy,um.NAME="GeneralizedTime";class dm extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}ly=dm,Rp.DATE=ly,dm.NAME="DATE";class fm extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}hy=fm,Rp.TimeOfDay=hy,fm.NAME="TimeOfDay";class gm extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}uy=gm,Rp.DateTime=uy,gm.NAME="DateTime";class pm extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}dy=pm,Rp.Duration=dy,pm.NAME="Duration";class ym extends Jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}fy=ym,Rp.TIME=fy,ym.NAME="TIME";class mm{constructor({name:e=Ap,optional:t=!1}={}){this.name=e,this.optional=t}}class bm extends mm{constructor({value:e=[],...t}={}){super(t),this.value=e}}class Am extends mm{constructor({value:e=new mm,local:t=!1,...r}={}){super(r),this.value=e,this.local=t}}class Im{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=Vg.toUint8Array(e)}constructor({data:e=vp}={}){this.dataView=Vg.toUint8Array(e)}fromBER(e,t,r){const s=t+r;return this.dataView=Vg.toUint8Array(e).subarray(t,s),s}toBER(e){return this.dataView.slice().buffer}}function vm(e,t,r){if(r instanceof bm){for(const s of r.value)if(vm(e,t,s).verified)return{verified:!0,result:e};{const e={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(lp)&&(e.name=r.name),e}}if(r instanceof mm)return r.hasOwnProperty(lp)&&(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(dp in r==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(yp in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(mp 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(fp))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(gp))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(pp))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(up 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(hp 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,Ap),r.name&&(e[r.name]=t)),r instanceof Rp.Constructed){let s=0,i={verified:!1,result:{error:"Unknown error"}},n=r.valueBlock.value.length;if(n>0&&r.valueBlock.value[0]instanceof Am&&(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,Ap),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,Ap),r.name&&(delete e[r.name],t.name=r.name)),t}}else if(r.valueBlock.value[0]instanceof Am){if(i=vm(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,Ap),r.name&&delete e[r.name]),i;s++}if(lp in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let s={};s=bp 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=vm(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,Ap),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,Ap),r.name&&(delete e[r.name],t.name=r.name)),t}return{verified:!0,result:e}}if(r.primitiveSchema&&hp in t.valueBlock){const s=by(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,Ap),r.name&&(delete e[r.name],t.name=r.name)),t}return vm(e,s.result,r.primitiveSchema)}return{verified:!0,result:e}}function wm(e,t){if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=by(Vg.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:vm(r.result,r.result,t)}(yy=gy||(gy={}))[yy.Sequence=0]="Sequence",yy[yy.Set=1]="Set",yy[yy.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"}(py||(py={}));class Sm{constructor(e,t=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if("number"==typeof e)this.fromNumber(e);else{if(!Vg.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=Vg.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof Oy))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 Oy({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new Oy({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 Em{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):Vg.isBufferSource(e)?this.buffer=Vg.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof By))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new By({valueHex:this.buffer})}toSchema(e){return new By({name:e})}}const Cm={fromASN:e=>e instanceof Cy?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new Cy;const t=Ay(e);if(t.result.error)throw new Error(t.result.error);return t.result}},km={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new My({value:+e})},xm={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new Py({value:e})},_m={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new My({valueHex:e})},Bm={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Oy({valueHex:e})},Rm={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Ky({value:e})},Om={fromASN:e=>e.valueBlock.value,toASN:e=>new xy({value:e})},Um={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new By({valueHex:e})},Tm={fromASN:e=>new Em(e.getValue()),toASN:e=>e.toASN()};function Nm(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}const Dm=Nm(Jy),Mm=Nm(Xy),Pm=Nm(em),Lm=Nm(tm),Hm=Nm(rm),Km=Nm(sm),Qm=Nm(im),Vm=Nm(nm),Fm=Nm(om),$m=Nm(am),jm=Nm(cm),Gm=Nm(lm),qm={fromASN:e=>e.toDate(),toASN:e=>new hm({valueDate:e})},zm={fromASN:e=>e.toDate(),toASN:e=>new um({valueDate:e})},Wm={fromASN:()=>null,toASN:()=>new Cy};function Jm(e){switch(e){case py.Any:return Cm;case py.BitString:return Bm;case py.BmpString:return Mm;case py.Boolean:return Om;case py.CharacterString:return Gm;case py.Enumerated:return xm;case py.GeneralString:return jm;case py.GeneralizedTime:return zm;case py.GraphicString:return Fm;case py.IA5String:return Vm;case py.Integer:return km;case py.Null:return Wm;case py.NumericString:return Lm;case py.ObjectIdentifier:return Rm;case py.OctetString:return Um;case py.PrintableString:return Hm;case py.TeletexString:return Km;case py.UTCTime:return qm;case py.UniversalString:return Pm;case py.Utf8String:return Dm;case py.VideotexString:return Qm;case py.VisibleString:return $m;default:return null}}function Ym(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||Ym(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function Xm(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||Xm(r)}return!1}function Zm(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 eb=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:gy.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=py[i.type],t=a[e];if(!t)throw new Error(`Cannot get ASN1 class by name '${e}'`);o=new t({name:n})}else Ym(i.type)?o=(new i.type).toSchema(n):i.optional?this.get(i.type).type===gy.Choice?o=new mm({name:n}):(o=this.create(i.type,!1),o.name=n):o=new mm({name:n});const c=!!i.optional||void 0!==i.defaultValue;if(i.repeated&&(o.name="",o=new("set"===i.repeated?jy:$y)({name:"",value:[new Am({name:n,value:o})]})),null!==i.context&&void 0!==i.context)if(i.implicit)if("number"==typeof i.type||Ym(i.type)){const e=i.repeated?wy:my;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 wy({name:e?"":n,optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}else s.push(new wy({optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:[o]}));else o.optional=c,s.push(o)}switch(r.type){case gy.Sequence:return new $y({value:s,name:""});case gy.Set:return new jy({value:s,name:""});case gy.Choice:return new bm({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}},tb=e=>t=>{let r;eb.has(t)?r=eb.get(t):(r=eb.createDefault(t),eb.set(t,r)),Object.assign(r,e)},rb=e=>(t,r)=>{let s;eb.has(t.constructor)?s=eb.get(t.constructor):(s=eb.createDefault(t.constructor),eb.set(t.constructor,s));const i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){const s=Jm(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 sb extends Error{constructor(){super(...arguments),this.schemas=[]}}class ib{static parse(e,t){const r=Ay(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(Ym(t))return(new t).fromASN(e);const s=eb.get(t);eb.cache(t);let i=s.schema;if(e.constructor===wy&&s.type!==gy.Choice){i=new wy({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:s.schema.valueBlock.value});for(const t in s.items)delete e[t]}const n=vm({},e,i);if(!n.verified)throw new sb(`Data does not match to ${t.name} ASN1 schema. ${n.result.error}`);const o=new t;if(Xm(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=Jm(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||Ym(c)){const s=null!==(r=i.converter)&&void 0!==r?r:Ym(c)?new c:null;if(!s)throw new Error("Converter is empty");if(i.repeated)if(i.implicit){const r=new("sequence"===i.repeated?$y:jy);r.valueBlock=t.valueBlock;const n=Ay(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(Ym(c))e=(new c).toSchema("");else{const t=py[c],r=a[t];if(!r)throw new Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=r.valueBlock,r=Ay(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 sb&&e.schemas.push(t.name),e}}}class nb{static serialize(e){return e instanceof Op?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&"object"==typeof e&&Ym(e))return e.toASN();if(!e||"object"!=typeof e)throw new TypeError("Parameter 1 should be type of Object.");const t=e.constructor,r=eb.get(t);eb.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=Jm(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&&Zm(this.serialize(n.defaultValue),this.serialize(o)))continue;const a=nb.toAsnItem(n,s,t,o);if("number"==typeof n.context)if(n.implicit)if(n.repeated||"number"!=typeof n.type&&!Ym(n.type))i.push(new wy({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:a.valueBlock.value}));else{const e={};e.valueHex=a instanceof Cy?a.valueBeforeDecodeView:a.valueBlock.toBER(),i.push(new my({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},...e}))}else i.push(new wy({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 gy.Sequence:s=new $y({value:i});break;case gy.Set:s=new jy({value:i});break;case gy.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 ${py[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?$y:jy)({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?$y:jy)({value:t})}else i=this.toASN(s);return i}}class ob extends Array{constructor(e=[]){if("number"==typeof e)super(e);else{super();for(const t of e)this.push(t)}}}class ab{static serialize(e){return nb.serialize(e)}static parse(e,t){return ib.parse(e,t)}static toString(e){const t=Ay(Vg.isBufferSource(e)?Vg.toArrayBuffer(e):ab.serialize(e));if(-1===t.offset)throw new Error(`Cannot decode ASN.1 data. ${t.result.error}`);return t.result.toString()}}function cb(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 lb extends Error{constructor(e,t){super(t?`${e}. See the inner exception for more details.`:e),this.message=e,this.innerError=t}}class hb extends lb{constructor(e,t,r){super(t,r),this.schema=e}}class ub extends hb{constructor(e,t,r){super(e,`JSON doesn't match to '${e.target.name}' schema. ${t}`,r)}}class db extends lb{}class fb extends lb{constructor(e,t,r){super(`Cannot serialize by '${e}' schema. ${t}`,r),this.schemaName=e}}class gb extends ub{constructor(e,t,r={}){super(e,"Some keys doesn't match to schema"),this.keys=t,this.errors=r}}var pb;function yb(e,t){if(!function(e,t){switch(t){case pb.Boolean:return"boolean"==typeof e;case pb.Number:return"number"==typeof e;case pb.String:return"string"==typeof e}return!0}(e,t))throw new TypeError(`Value must be ${pb[t]}`)}function mb(e){return e&&e.prototype?!(!e.prototype.toJSON||!e.prototype.fromJSON)||mb(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"}(pb||(pb={}));const bb="default",Ab=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 Ib{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 db("Incoming value must be string");if(!t.exec(e))throw new db(`Value doesn't match to pattern '${t.toString()}'`)}}class vb{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(yb(e,pb.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 db(`Value doesn't match to diapason [${e},${t}]`)}}}class wb{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(yb(e,pb.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 db(`Value doesn't match to diapason (${e},${t})`)}}}class Sb{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 db(`Value length must be more than ${this.minLength}.`);if(void 0!==this.maxLength&&e.length>this.maxLength)throw new db(`Value length must be less than ${this.maxLength}.`)}else if(e.length!==this.length)throw new db(`Value length must be exactly ${this.length}.`)}}class Eb{constructor(e){this.enumeration=e}validate(e){if(yb(e,pb.String),!this.enumeration.includes(e))throw new db(`Value must be one of ${this.enumeration.map(e=>`'${e}'`).join(", ")}`)}}class Cb{static checkValues(e,t){const r=Array.isArray(e)?e:[e];for(const s of r)for(const r of t.validations)r instanceof Sb&&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)yb(e,t.type)}}static getSchemaByName(e,t=bb){return{...e.names[bb],...e.names[t]}}}class kb extends Cb{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||bb;if(mb(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&&!Ab.has(s))throw new lb("Cannot get schema for `targetSchema` param");if(s=s||e.constructor,Ab.has(s)){const t=Ab.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 fb(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 fb?e:new fb(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 xb extends Cb{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||bb,i=new r;if(mb(i))return i.fromJSON(e);const n=Ab.get(r),o=this.getSchemaByName(n,s),a={};t.strictProperty&&!Array.isArray(e)&&xb.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 ub(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 ub||(e=new ub(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 gb(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 gb(r,n)}}const _b=(e={})=>(t,r)=>{const s=`Cannot set type for ${r} property of ${t.constructor.name} schema`;let i;Ab.has(t.constructor)?(i=Ab.get(t.constructor),i.target!==t.constructor&&(i=Ab.create(t.constructor),Ab.set(t.constructor,i))):(i=Ab.create(t.constructor),Ab.set(t.constructor,i));const n={type:pb.Any,validations:[]},o=Object.assign(n,e);if(o.validations=function(e){const t=[];return e.pattern&&t.push(new Ib(e.pattern)),e.type!==pb.Number&&e.type!==pb.Any||(void 0===e.minInclusive&&void 0===e.maxInclusive||t.push(new vb(e.minInclusive,e.maxInclusive)),void 0===e.minExclusive&&void 0===e.maxExclusive||t.push(new wb(e.minExclusive,e.maxExclusive)),void 0!==e.enumeration&&t.push(new Eb(e.enumeration))),(e.type===pb.String||e.repeated||e.type===pb.Any)&&(void 0===e.length&&void 0===e.minLength&&void 0===e.maxLength||t.push(new Sb(e.length,e.minLength,e.maxLength))),t}(o),"number"!=typeof o.type&&!Ab.has(o.type)&&!mb(o.type))throw new Error(`${s}. Assigning type doesn't have schema.`);let a;a=Array.isArray(e.schema)?e.schema:[e.schema||bb];for(const e of a)i.names[e]||(i.names[e]={}),i.names[e][r]=o};class Bb extends Error{}class Rb extends Bb{}class Ob extends Bb{constructor(e){super("Unsupported operation: "+(e?`${e}`:""))}}class Ub extends Bb{}class Tb extends Bb{constructor(e){super(`${e}: Missing required property`)}}class Nb{static toArrayBuffer(e){const t=e.replace(/-{5}(BEGIN|END) .*-{5}/g,"").replace("\r","").replace("\n","");return Wg.FromBase64(t)}static toUint8Array(e){const t=this.toArrayBuffer(e);return new Uint8Array(t)}static fromBufferSource(e,t){const r=Wg.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 Db{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 Ob("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 Ob("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 Ob("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 Ob("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 Ob("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 Ob("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 Ub("length: Is not multiple of 8")}async onDeriveBits(e,t,r,...s){throw new Ob("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 Bb("key: Is not extractable")}async onExportKey(e,t,...r){throw new Ob("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 Ob("importKey")}checkAlgorithmName(e){if(e.name.toLowerCase()!==this.name.toLowerCase())throw new Rb("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 Bb("key does not match that of operation")}checkRequiredProperty(e,t){if(!(t in e))throw new Tb(t)}checkHashAlgorithm(e,t){for(const r of t)if(r.toLowerCase()===e.name.toLowerCase())return;throw new Ub(`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(!Vg.isBufferSource(t))throw new TypeError("keyData: Is not ArrayBufferView or ArrayBuffer");var r}prepareData(e){return Vg.toArrayBuffer(e)}}class Mb extends Db{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 Pb extends Mb{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 Lb extends Mb{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 Ub("length: Must be more than 0")}}class Hb extends Mb{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 Ub("length: Must be more than 0")}}class Kb extends Mb{constructor(){super(...arguments),this.name="AES-ECB",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}}class Qb extends Mb{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 Ub("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 Ub("tagLength: Must be one of 32, 64, 96, 104, 112, 120 or 128")}}}class Vb extends Mb{constructor(){super(...arguments),this.name="AES-KW",this.usages=["wrapKey","unwrapKey"]}}class Fb extends Db{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 Ub(`algorithm.length: Must be ${this.keySizeBits}`)}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class $b extends Db{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=Wg.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 jb extends $b{constructor(){super(...arguments),this.name="RSASSA-PKCS1-v1_5",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class Gb extends $b{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 qb extends $b{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 zb extends Db{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 Ub(`namedCurve: Must be one of ${this.namedCurves.join(", ")}`)}}class Wb extends zb{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 Jb=["secret","private","public"];class Yb{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!==Jb.indexOf(e)}get[Symbol.toStringTag](){return"CryptoKey"}}class Xb extends zb{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 Yb))throw new TypeError("public: Is not a CryptoKey");if("public"!==e.public.type)throw new Ub("public: Is not a public key");if(e.public.algorithm.name!==this.name)throw new Ub(`public: Is not ${this.name} key`)}}class Zb extends Xb{constructor(){super(...arguments),this.name="ECDH-ES",this.namedCurves=["X25519","X448"]}}class eA extends zb{constructor(){super(...arguments),this.name="EdDSA",this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["Ed25519","Ed448"]}}let tA=class{constructor(e){e&&(this.value=e)}};cb([rb({type:py.ObjectIdentifier})],tA.prototype,"value",void 0),tA=cb([tb({type:gy.Choice})],tA);class rA{constructor(e){Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],rA.prototype,"algorithm",void 0),cb([rb({type:py.Any,optional:!0})],rA.prototype,"parameters",void 0);class sA{constructor(){this.version=0,this.privateKeyAlgorithm=new rA,this.privateKey=new ArrayBuffer(0)}}cb([rb({type:py.Integer})],sA.prototype,"version",void 0),cb([rb({type:rA})],sA.prototype,"privateKeyAlgorithm",void 0),cb([rb({type:py.OctetString})],sA.prototype,"privateKey",void 0),cb([rb({type:py.Any,optional:!0})],sA.prototype,"attributes",void 0);class iA{constructor(){this.publicKeyAlgorithm=new rA,this.publicKey=new ArrayBuffer(0)}}cb([rb({type:rA})],iA.prototype,"publicKeyAlgorithm",void 0),cb([rb({type:py.BitString})],iA.prototype,"publicKey",void 0);const nA={fromJSON:e=>Wg.FromBase64Url(e),toJSON:e=>Wg.ToBase64Url(new Uint8Array(e))},oA={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?Jg(new Uint8Array([0]).buffer,e):e;return new My({valueHex:t})}};class aA{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)}}cb([rb({type:py.Integer,converter:km})],aA.prototype,"version",void 0),cb([rb({type:py.Integer,converter:oA}),_b({name:"n",converter:nA})],aA.prototype,"modulus",void 0),cb([rb({type:py.Integer,converter:oA}),_b({name:"e",converter:nA})],aA.prototype,"publicExponent",void 0),cb([rb({type:py.Integer,converter:oA}),_b({name:"d",converter:nA})],aA.prototype,"privateExponent",void 0),cb([rb({type:py.Integer,converter:oA}),_b({name:"p",converter:nA})],aA.prototype,"prime1",void 0),cb([rb({type:py.Integer,converter:oA}),_b({name:"q",converter:nA})],aA.prototype,"prime2",void 0),cb([rb({type:py.Integer,converter:oA}),_b({name:"dp",converter:nA})],aA.prototype,"exponent1",void 0),cb([rb({type:py.Integer,converter:oA}),_b({name:"dq",converter:nA})],aA.prototype,"exponent2",void 0),cb([rb({type:py.Integer,converter:oA}),_b({name:"qi",converter:nA})],aA.prototype,"coefficient",void 0),cb([rb({type:py.Any,optional:!0})],aA.prototype,"otherPrimeInfos",void 0);class cA{constructor(){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0)}}cb([rb({type:py.Integer,converter:oA}),_b({name:"n",converter:nA})],cA.prototype,"modulus",void 0),cb([rb({type:py.Integer,converter:oA}),_b({name:"e",converter:nA})],cA.prototype,"publicExponent",void 0);let lA=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 Bb("Wrong ECPoint. Current version supports only Uncompressed (0x04) point");e=new Uint8Array(this.value.slice(1));const t=e.length/2;return{x:Wg.ToBase64Url(e.buffer.slice(0,0+t)),y:Wg.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=Wg.FromBase64Url(e.x),r=Wg.FromBase64Url(e.y),s=Jg(new Uint8Array([4]).buffer,t,r);return this.value=new Uint8Array(s).buffer,this}};cb([rb({type:py.OctetString})],lA.prototype,"value",void 0),lA=cb([tb({type:gy.Choice})],lA);class hA{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=Wg.FromBase64Url(e.d),"x"in e){const t=new lA;t.fromJSON(e);const r=nb.toASN(t);"valueHex"in r.valueBlock&&(this.publicKey=r.valueBlock.valueHex)}return this}toJSON(){const e={};return e.d=Wg.ToBase64Url(this.privateKey),this.publicKey&&Object.assign(e,new lA(this.publicKey).toJSON()),e}}cb([rb({type:py.Integer,converter:km})],hA.prototype,"version",void 0),cb([rb({type:py.OctetString})],hA.prototype,"privateKey",void 0),cb([rb({context:0,type:py.Any,optional:!0})],hA.prototype,"parameters",void 0),cb([rb({context:1,type:py.BitString,optional:!0})],hA.prototype,"publicKey",void 0);const uA={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 My({valueHex:e.buffer})}return new My({valueHex:e})}};var dA=Object.freeze({__proto__:null,AsnIntegerWithoutPaddingConverter:uA});class fA{static decodePoint(e,t){const r=Vg.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=Vg.toUint8Array(e.x),i=Vg.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=Vg.toUint8Array(e.r),i=Vg.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=Vg.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 gA{constructor(){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0)}static fromWebCryptoSignature(e){const t=e.byteLength/2,r=fA.decodeSignature(e,8*t),s=new gA;return s.r=Vg.toArrayBuffer(r.r),s.s=Vg.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 fA.encodeSignature(this,e).buffer}}cb([rb({type:py.Integer,converter:uA})],gA.prototype,"r",void 0),cb([rb({type:py.Integer,converter:uA})],gA.prototype,"s",void 0);class pA extends sA{}cb([rb({context:1,implicit:!0,type:py.BitString,optional:!0})],pA.prototype,"publicKey",void 0);let yA=class{constructor(){this.value=new ArrayBuffer(0)}fromJSON(e){if(!e.d)throw new Error("d: Missing required property");return this.value=Wg.FromBase64Url(e.d),this}toJSON(){return{d:Wg.ToBase64Url(this.value)}}};cb([rb({type:py.OctetString})],yA.prototype,"value",void 0),yA=cb([tb({type:gy.Choice})],yA);let mA=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){return{x:Wg.ToBase64Url(this.value)}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");return this.value=Wg.FromBase64Url(e.x),this}};cb([rb({type:py.BitString})],mA.prototype,"value",void 0),mA=cb([tb({type:gy.Choice})],mA);let bA=class{};cb([rb({type:py.OctetString}),_b({type:pb.String,converter:nA})],bA.prototype,"d",void 0),bA=cb([tb({type:gy.Choice})],bA);const AA="1.2.840.10045.3.1.7",IA="1.3.132.0",vA=`${IA}.34`,wA=`${IA}.35`,SA=`${IA}.10`,EA="1.3.36.3.3.2.8.1.1",CA=`${EA}.1`,kA=`${EA}.2`,xA=`${EA}.3`,_A=`${EA}.4`,BA=`${EA}.5`,RA=`${EA}.6`,OA=`${EA}.7`,UA=`${EA}.8`,TA=`${EA}.9`,NA=`${EA}.10`,DA=`${EA}.11`,MA=`${EA}.12`,PA=`${EA}.13`,LA=`${EA}.14`;var HA=Object.freeze({__proto__:null,AlgorithmIdentifier:rA,get CurvePrivateKey(){return bA},EcDsaSignature:gA,EcPrivateKey:hA,get EcPublicKey(){return lA},get EdPrivateKey(){return yA},get EdPublicKey(){return mA},get ObjectIdentifier(){return tA},OneAsymmetricKey:pA,PrivateKeyInfo:sA,PublicKeyInfo:iA,RsaPrivateKey:aA,RsaPublicKey:cA,converters:dA,idBrainpoolP160r1:CA,idBrainpoolP160t1:kA,idBrainpoolP192r1:xA,idBrainpoolP192t1:_A,idBrainpoolP224r1:BA,idBrainpoolP224t1:RA,idBrainpoolP256r1:OA,idBrainpoolP256t1:UA,idBrainpoolP320r1:TA,idBrainpoolP320t1:NA,idBrainpoolP384r1:DA,idBrainpoolP384t1:MA,idBrainpoolP512r1:PA,idBrainpoolP512t1:LA,idEd25519:"1.3.101.112",idEd448:"1.3.101.113",idEllipticCurve:IA,idSecp256k1:SA,idSecp256r1:AA,idSecp384r1:vA,idSecp521r1:wA,idVersionOne:EA,idX25519:"1.3.101.110",idX448:"1.3.101.111"});class KA{constructor(){}static register(e){const t=new tA;t.value=e.id;const r=ab.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}}KA.items=[],KA.names=[],KA.register({name:"P-256",id:AA,size:256}),KA.register({name:"P-384",id:vA,size:384}),KA.register({name:"P-521",id:wA,size:521}),KA.register({name:"K-256",id:SA,size:256}),KA.register({name:"brainpoolP160r1",id:CA,size:160}),KA.register({name:"brainpoolP160t1",id:kA,size:160}),KA.register({name:"brainpoolP192r1",id:xA,size:192}),KA.register({name:"brainpoolP192t1",id:_A,size:192}),KA.register({name:"brainpoolP224r1",id:BA,size:224}),KA.register({name:"brainpoolP224t1",id:RA,size:224}),KA.register({name:"brainpoolP256r1",id:OA,size:256}),KA.register({name:"brainpoolP256t1",id:UA,size:256}),KA.register({name:"brainpoolP320r1",id:TA,size:320}),KA.register({name:"brainpoolP320t1",id:NA,size:320}),KA.register({name:"brainpoolP384r1",id:DA,size:384}),KA.register({name:"brainpoolP384t1",id:MA,size:384}),KA.register({name:"brainpoolP512r1",id:PA,size:512}),KA.register({name:"brainpoolP512t1",id:LA,size:512});class QA extends Db{constructor(){super(...arguments),this.name="X25519",this.usages={privateKey:["deriveKey","deriveBits"],publicKey:[]}}checkAlgorithmParams(e){this.checkRequiredProperty(e,"public")}}class VA extends Db{constructor(){super(...arguments),this.name="Ed25519",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class FA extends Db{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 $A extends Db{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 jA extends Db{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"),!Vg.isBufferSource(e.salt))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"info"),!Vg.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 GA extends Db{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 qA extends GA{constructor(){super(...arguments),this.name="shake128",this.defaultLength=16}}class zA extends GA{constructor(){super(...arguments),this.name="shake256",this.defaultLength=32}}class WA{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=Wg.ToHex(e).toLowerCase();return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}}class JA{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 YA={jwk:["private","public","secret"],pkcs8:["private"],spki:["public"],raw:["secret","public"]},XA=["pkcs8","spki","raw"];class ZA{constructor(){this.providers=new JA}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=Vg.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=Vg.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=Vg.toArrayBuffer(i),c=Vg.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=Vg.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=Vg.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),!YA[t])throw new TypeError("Invalid keyFormat argument");if(!YA[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(!XA.includes(t))throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView or JsonWebKey)'");if(!Vg.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=Wg.FromUtf8String(e)}const o=this.prepareAlgorithm(s),a=Vg.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=Vg.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(Wg.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(ZA.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 Rb("Unrecognized name");return t}checkCryptoKey(e){if(!(e instanceof Yb))throw new TypeError("Key is not of type 'CryptoKey'")}}const eI=t(import.meta.url)("buffer"),tI=t(import.meta.url)("crypto");var rI=o.n(tI);const sI={fromJSON:e=>eI.Buffer.from(Wg.FromBase64Url(e)),toJSON:e=>Wg.ToBase64Url(e)};class iI extends Yb{constructor(){super(...arguments),this.data=eI.Buffer.alloc(0),this.algorithm={name:""},this.extractable=!1,this.type="secret",this.usages=[],this.kty="oct",this.alg=""}}cb([_b({name:"ext",type:pb.Boolean,optional:!0})],iI.prototype,"extractable",void 0),cb([_b({name:"key_ops",type:pb.String,repeated:!0,optional:!0})],iI.prototype,"usages",void 0),cb([_b({type:pb.String})],iI.prototype,"kty",void 0),cb([_b({type:pb.String,optional:!0})],iI.prototype,"alg",void 0);class nI extends iI{constructor(){super(...arguments),this.kty="oct",this.type="secret"}}class oI extends iI{}class aI extends nI{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 Rb("Unsupported algorithm name")}}set alg(e){}}cb([_b({name:"k",converter:sI})],aI.prototype,"data",void 0);class cI{static async generateKey(e,t,r){const s=new aI;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=rI().randomBytes(e.length>>3),s}static async exportKey(e,t){if(!(t instanceof aI))throw new Error("key: Is not AesCryptoKey");switch(e.toLowerCase()){case"jwk":return kb.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new Ub("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=xb.fromJSON(t,{targetSchema:aI});break;case"raw":n=new aI,n.data=eI.Buffer.from(t);break;default:throw new Ub("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 Ub("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,eI.Buffer.from(r));case"AES-CTR":return this.encryptAesCTR(e,t,eI.Buffer.from(r));case"AES-GCM":return this.encryptAesGCM(e,t,eI.Buffer.from(r));case"AES-KW":return this.encryptAesKW(e,t,eI.Buffer.from(r));case"AES-ECB":return this.encryptAesECB(e,t,eI.Buffer.from(r));default:throw new Ub("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof aI))throw new Error("key: Is not AesCryptoKey");switch(e.name.toUpperCase()){case"AES-CBC":return this.decryptAesCBC(e,t,eI.Buffer.from(r));case"AES-CTR":return this.decryptAesCTR(e,t,eI.Buffer.from(r));case"AES-GCM":return this.decryptAesGCM(e,t,eI.Buffer.from(r));case"AES-KW":return this.decryptAesKW(e,t,eI.Buffer.from(r));case"AES-ECB":return this.decryptAesECB(e,t,eI.Buffer.from(r));default:throw new Ub("algorithm: Is not recognized")}}static async encryptAesCBC(e,t,r){const s=rI().createCipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=eI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCBC(e,t,r){const s=rI().createDecipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=eI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesCTR(e,t,r){const s=rI().createCipheriv(`aes-${t.algorithm.length}-ctr`,t.data,eI.Buffer.from(e.counter));let i=s.update(r);return i=eI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCTR(e,t,r){const s=rI().createDecipheriv(`aes-${t.algorithm.length}-ctr`,t.data,new Uint8Array(e.counter));let i=s.update(r);return i=eI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesGCM(e,t,r){const s=rI().createCipheriv(`aes-${t.algorithm.length}-gcm`,t.data,eI.Buffer.from(e.iv),{authTagLength:(e.tagLength||128)>>3});e.additionalData&&s.setAAD(eI.Buffer.from(e.additionalData));let i=s.update(r);return i=eI.Buffer.concat([i,s.final(),s.getAuthTag()]),new Uint8Array(i).buffer}static async decryptAesGCM(e,t,r){const s=(e.tagLength||128)>>3,i=rI().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(eI.Buffer.from(e.additionalData)),i.setAuthTag(o);let a=i.update(n);return a=eI.Buffer.concat([a,i.final()]),new Uint8Array(a).buffer}static async encryptAesKW(e,t,r){const s=rI().createCipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=eI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesKW(e,t,r){const s=rI().createDecipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=eI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesECB(e,t,r){const s=rI().createCipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=eI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesECB(e,t,r){const s=rI().createDecipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=eI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}cI.AES_KW_IV=eI.Buffer.from("A6A6A6A6A6A6A6A6","hex");const lI=new WeakMap;function hI(e){const t=lI.get(e);if(!t)throw new Ub("Cannot get CryptoKey from secure storage");return t}function uI(e){const t=Yb.create(e.algorithm,e.type,e.extractable,e.usages);return Object.freeze(t),lI.set(t,e),t}class dI extends Pb{async onGenerateKey(e,t,r){return uI(await cI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return cI.encrypt(e,hI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return cI.decrypt(e,hI(t),new Uint8Array(r))}async onExportKey(e,t){return cI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await cI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(hI(e)instanceof aI))throw new TypeError("key: Is not a AesCryptoKey")}}const fI=eI.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),gI=eI.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,135]),pI=16;function yI(e){const t=eI.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 mI(e,t){const r=Math.min(e.length,t.length),s=eI.Buffer.alloc(r);for(let i=0;i<r;i++)s[i]=e[i]^t[i];return s}function bI(e,t){const r=rI().createCipheriv("aes"+(e.length<<3),e,fI),s=r.update(t);return r.final(),s}function AI(e,t){const r=eI.Buffer.alloc(pI),s=t*pI,i=s+pI;return e.copy(r,0,s,i),r}class II extends Lb{async onGenerateKey(e,t,r){return uI(await cI.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=bI(e,fI);let r=yI(t);128&t[0]&&(r=mI(r,gI));let s=yI(r);return 128&r[0]&&(s=mI(s,gI)),{subkey1:r,subkey2:s}}(e);let s,i,n=Math.ceil(t.length/pI);0===n?(n=1,s=!1):s=t.length%pI===0;const o=n-1;i=s?mI(AI(t,o),r.subkey1):mI(function(e,t){const r=eI.Buffer.alloc(pI),s=t*pI,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=fI;for(let r=0;r<o;r++)a=mI(c,AI(t,r)),c=bI(e,a);return a=mI(i,c),bI(e,a)}(hI(t).data,eI.Buffer.from(r));return new Uint8Array(s).buffer}async onVerify(e,t,r,s){const i=await this.sign(e,t,s);return 0===eI.Buffer.from(r).compare(eI.Buffer.from(i))}async onExportKey(e,t){return cI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await cI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(hI(e)instanceof aI))throw new TypeError("key: Is not a AesCryptoKey")}}class vI extends Hb{async onGenerateKey(e,t,r){return uI(await cI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return cI.encrypt(e,hI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return cI.decrypt(e,hI(t),new Uint8Array(r))}async onExportKey(e,t){return cI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await cI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(hI(e)instanceof aI))throw new TypeError("key: Is not a AesCryptoKey")}}class wI extends Qb{async onGenerateKey(e,t,r){return uI(await cI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return cI.encrypt(e,hI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return cI.decrypt(e,hI(t),new Uint8Array(r))}async onExportKey(e,t){return cI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await cI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(hI(e)instanceof aI))throw new TypeError("key: Is not a AesCryptoKey")}}class SI extends Vb{async onGenerateKey(e,t,r){return uI(await cI.generateKey({name:this.name,length:e.length},t,r))}async onExportKey(e,t){return cI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await cI.importKey(e,t,{name:r.name},s,i))}async onEncrypt(e,t,r){return cI.encrypt(e,hI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return cI.decrypt(e,hI(t),new Uint8Array(r))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(hI(e)instanceof aI))throw new TypeError("key: Is not a AesCryptoKey")}}class EI extends Kb{async onGenerateKey(e,t,r){return uI(await cI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return cI.encrypt(e,hI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return cI.decrypt(e,hI(t),new Uint8Array(r))}async onExportKey(e,t){return cI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await cI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(hI(e)instanceof aI))throw new TypeError("key: Is not a AesCryptoKey")}}class CI extends nI{get alg(){switch(this.algorithm.name.toUpperCase()){case"DES-CBC":return"DES-CBC";case"DES-EDE3-CBC":return"3DES-CBC";default:throw new Rb("Unsupported algorithm name")}}set alg(e){}}cb([_b({name:"k",converter:sI})],CI.prototype,"data",void 0);class kI{static async generateKey(e,t,r){const s=new CI;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=rI().randomBytes(e.length>>3),s}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return kb.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new Ub("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=xb.fromJSON(t,{targetSchema:CI});break;case"raw":n=new CI,n.data=eI.Buffer.from(t);break;default:throw new Ub("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,eI.Buffer.from(r));case"DES-EDE3-CBC":return this.encryptDesEDE3CBC(e,t,eI.Buffer.from(r));default:throw new Ub("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof CI))throw new Error("key: Is not DesCryptoKey");switch(e.name.toUpperCase()){case"DES-CBC":return this.decryptDesCBC(e,t,eI.Buffer.from(r));case"DES-EDE3-CBC":return this.decryptDesEDE3CBC(e,t,eI.Buffer.from(r));default:throw new Ub("algorithm: Is not recognized")}}static async encryptDesCBC(e,t,r){const s=rI().createCipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=eI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesCBC(e,t,r){const s=rI().createDecipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=eI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptDesEDE3CBC(e,t,r){const s=rI().createCipheriv("des-ede3-cbc",t.data,eI.Buffer.from(e.iv));let i=s.update(r);return i=eI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesEDE3CBC(e,t,r){const s=rI().createDecipheriv("des-ede3-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=eI.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}class xI extends Fb{constructor(){super(...arguments),this.keySizeBits=64,this.ivSize=8,this.name="DES-CBC"}async onGenerateKey(e,t,r){return uI(await kI.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return kI.encrypt(e,hI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return kI.decrypt(e,hI(t),new Uint8Array(r))}async onExportKey(e,t){return kI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){const n=await kI.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new Ub("keyData: Wrong key size");return uI(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(hI(e)instanceof CI))throw new TypeError("key: Is not a DesCryptoKey")}}class _I extends Fb{constructor(){super(...arguments),this.keySizeBits=192,this.ivSize=8,this.name="DES-EDE3-CBC"}async onGenerateKey(e,t,r){return uI(await kI.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return kI.encrypt(e,hI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return kI.decrypt(e,hI(t),new Uint8Array(r))}async onExportKey(e,t){return kI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){const n=await kI.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new Ub("keyData: Wrong key size");return uI(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(hI(e)instanceof CI))throw new TypeError("key: Is not a DesCryptoKey")}}function BI(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 Ub("algorithm: Is not recognized")}}class RI extends oI{constructor(){super(...arguments),this.type="private"}getKey(){const e=ib.parse(this.data,HA.PrivateKeyInfo);return ib.parse(e.privateKey,HA.RsaPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:BI(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,kb.toJSON(e))}fromJSON(e){const t=xb.fromJSON(e,{targetSchema:HA.RsaPrivateKey}),r=new HA.PrivateKeyInfo;r.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.privateKeyAlgorithm.parameters=null,r.privateKey=nb.serialize(t),this.data=eI.Buffer.from(nb.serialize(r))}}class OI extends oI{constructor(){super(...arguments),this.type="public"}getKey(){const e=ib.parse(this.data,HA.PublicKeyInfo);return ib.parse(e.publicKey,HA.RsaPublicKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:BI(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,kb.toJSON(e))}fromJSON(e){const t=xb.fromJSON(e,{targetSchema:HA.RsaPublicKey}),r=new HA.PublicKeyInfo;r.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.publicKeyAlgorithm.parameters=null,r.publicKey=nb.serialize(t),this.data=eI.Buffer.from(nb.serialize(r))}}class UI{static async generateKey(e,t,r){const s=new RI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new OI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=eI.Buffer.concat([eI.Buffer.alloc(4-e.publicExponent.byteLength,0),eI.Buffer.from(e.publicExponent)]).readInt32BE(0),o=rI().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 kb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;default:throw new Ub("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=xb.fromJSON(t,{targetSchema:HA.RsaPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=xb.fromJSON(t,{targetSchema:HA.RsaPublicKey});return this.importPublicKey(e,r,s,i)}case"spki":{const e=ib.parse(new Uint8Array(t),HA.PublicKeyInfo),n=ib.parse(e.publicKey,HA.RsaPublicKey);return this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=ib.parse(new Uint8Array(t),HA.PrivateKeyInfo),n=ib.parse(e.privateKey,HA.RsaPrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new Ub("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 Ub("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 Ub("algorithm: Is not recognized")}}static async encrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.encryptOAEP(e,t,r);throw new Ub("algorithm: Is not recognized")}static async decrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.decryptOAEP(e,t,r);throw new Ub("algorithm: Is not recognized")}static importPrivateKey(e,t,r,s){const i=new HA.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.privateKeyAlgorithm.parameters=null,i.privateKey=nb.serialize(e);const n=new RI;return n.data=eI.Buffer.from(nb.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 HA.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.publicKeyAlgorithm.parameters=null,i.publicKey=nb.serialize(e);const n=new OI;return n.data=eI.Buffer.from(nb.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 Ub("algorithm.hash: Is not recognized")}}static signRsa(e,t,r){const s=this.getCryptoAlgorithm(t.algorithm),i=rI().createSign(s);i.update(eI.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=rI().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=rI().createVerify(i);n.update(eI.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=rI().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:rI().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(rI().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:rI().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(rI().privateDecrypt(s,r)).buffer}}UI.publicKeyUsages=["verify","encrypt","wrapKey"],UI.privateKeyUsages=["sign","decrypt","unwrapKey"];class TI extends jb{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 UI.generateKey({...e,name:this.name},t,r);return{privateKey:uI(s.privateKey),publicKey:uI(s.publicKey)}}async onSign(e,t,r){return UI.sign(e,hI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return UI.verify(e,hI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return UI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await UI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=hI(e);if(!(r instanceof RI||r instanceof OI))throw new TypeError("key: Is not RSA CryptoKey")}}class NI extends Gb{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 UI.generateKey({...e,name:this.name},t,r);return{privateKey:uI(s.privateKey),publicKey:uI(s.publicKey)}}async onSign(e,t,r){return UI.sign(e,hI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return UI.verify(e,hI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return UI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await UI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=hI(e);if(!(r instanceof RI||r instanceof OI))throw new TypeError("key: Is not RSA CryptoKey")}}class DI{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=rI().createHash(r).update(eI.Buffer.from(t)).digest();return new Uint8Array(s).buffer}}class MI extends qb{async onGenerateKey(e,t,r){const s=await UI.generateKey({...e,name:this.name},t,r);return{privateKey:uI(s.privateKey),publicKey:uI(s.publicKey)}}async onEncrypt(e,t,r){const s=hI(t),i=new Uint8Array(r),n=Math.ceil(s.algorithm.modulusLength>>3),o=DI.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=rI().createHash(s.algorithm.hash.name.replace("-","")).update(Vg.toUint8Array(e.label||new Uint8Array(0))).digest();u.set(d,0),u[o+c]=1,rI().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 g=this.mgf1(s.algorithm.hash,u,h.length);for(let e=0;e<h.length;e++)h[e]^=g[e];s.pem||(s.pem=`-----BEGIN PUBLIC KEY-----\n${s.data.toString("base64")}\n-----END PUBLIC KEY-----`);const p=rI().publicEncrypt({key:s.pem,padding:rI().constants.RSA_NO_PADDING},eI.Buffer.from(l));return new Uint8Array(p).buffer}async onDecrypt(e,t,r){const s=hI(t),i=Math.ceil(s.algorithm.modulusLength>>3),n=DI.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=rI().privateDecrypt({key:s.pem,padding:rI().constants.RSA_NO_PADDING},eI.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=rI().createHash(s.algorithm.hash.name.replace("-","")).update(Vg.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 UI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await UI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=hI(e);if(!(r instanceof RI||r instanceof OI))throw new TypeError("key: Is not RSA CryptoKey")}mgf1(e,t,r=0){const s=DI.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=rI().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 PI extends Db{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 UI.generateKey({...e,name:this.name},t,r);return{privateKey:uI(s.privateKey),publicKey:uI(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=Wg.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=rI().publicEncrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onDecrypt(e,t,r){const s=this.toCryptoOptions(t),i=rI().privateDecrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onExportKey(e,t){return UI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await UI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=hI(e);if(!(r instanceof RI||r instanceof OI))throw new TypeError("key: Is not RSA CryptoKey")}toCryptoOptions(e){const t=e.type.toUpperCase();return{key:`-----BEGIN ${t} KEY-----\n${hI(e).data.toString("base64")}\n-----END ${t} KEY-----`,padding:rI().constants.RSA_PKCS1_PADDING}}}const LI={"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 HI(e){const t=LI[e];if(!t)throw new Ub(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class KI extends oI{constructor(){super(...arguments),this.type="private"}getKey(){const e=ib.parse(this.data,HA.PrivateKeyInfo);return ib.parse(e.privateKey,HA.EcPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,kb.toJSON(e))}fromJSON(e){if(!e.crv)throw new Ub("Cannot get named curve from JWK. Property 'crv' is required");const t=new HA.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",t.privateKeyAlgorithm.parameters=nb.serialize(new HA.ObjectIdentifier(HI(e.crv)));const r=xb.fromJSON(e,{targetSchema:HA.EcPrivateKey});return t.privateKey=nb.serialize(r),this.data=eI.Buffer.from(nb.serialize(t)),this}}class QI extends oI{constructor(){super(...arguments),this.type="public"}getKey(){const e=ib.parse(this.data,HA.PublicKeyInfo);return new HA.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,kb.toJSON(e))}fromJSON(e){if(!e.crv)throw new Ub("Cannot get named curve from JWK. Property 'crv' is required");const t=xb.fromJSON(e,{targetSchema:HA.EcPublicKey}),r=new HA.PublicKeyInfo;return r.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1",r.publicKeyAlgorithm.parameters=nb.serialize(new HA.ObjectIdentifier(HI(e.crv))),r.publicKey=nb.toASN(t).valueHex,this.data=eI.Buffer.from(nb.serialize(r)),this}}class VI extends Db{constructor(){super(...arguments),this.name="SHA-1",this.usages=[]}async onDigest(e,t){return DI.digest(e,t)}}class FI extends Db{constructor(){super(...arguments),this.name="SHA-256",this.usages=[]}async onDigest(e,t){return DI.digest(e,t)}}class $I extends Db{constructor(){super(...arguments),this.name="SHA-384",this.usages=[]}async onDigest(e,t){return DI.digest(e,t)}}class jI extends Db{constructor(){super(...arguments),this.name="SHA-512",this.usages=[]}async onDigest(e,t){return DI.digest(e,t)}}class GI extends Db{constructor(){super(...arguments),this.name="SHA3-256",this.usages=[]}async onDigest(e,t){return DI.digest(e,t)}}class qI extends Db{constructor(){super(...arguments),this.name="SHA3-384",this.usages=[]}async onDigest(e,t){return DI.digest(e,t)}}class zI extends Db{constructor(){super(...arguments),this.name="SHA3-512",this.usages=[]}async onDigest(e,t){return DI.digest(e,t)}}class WI{static async generateKey(e,t,r){const s=new KI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new QI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=rI().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=DI.getAlgorithmName(e.hash),i=rI().createSign(s);i.update(eI.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=ib.parse(o,HA.EcDsaSignature);return fA.encodeSignature(a,KA.get(t.algorithm.namedCurve).size).buffer}static async verify(e,t,r,s){const i=DI.getAlgorithmName(e.hash),n=rI().createVerify(i);n.update(eI.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 HA.EcDsaSignature,c=KA.get(t.algorithm.namedCurve),l=fA.decodeSignature(r,c.size);a.r=Vg.toArrayBuffer(l.r),a.s=Vg.toArrayBuffer(l.s);const h=eI.Buffer.from(nb.serialize(a));return n.verify(o,h)}static async deriveBits(e,t,r){const s=this.getOpenSSLNamedCurve(t.algorithm.namedCurve),i=rI().createECDH(s),n=ib.parse(t.data,HA.PrivateKeyInfo),o=ib.parse(n.privateKey,HA.EcPrivateKey);i.setPrivateKey(eI.Buffer.from(o.privateKey));const a=ib.parse(e.public.data,HA.PublicKeyInfo),c=i.computeSecret(eI.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 kb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return ib.parse(t.data,HA.PublicKeyInfo).publicKey;default:throw new Ub("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=xb.fromJSON(t,{targetSchema:HA.EcPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=xb.fromJSON(t,{targetSchema:HA.EcPublicKey});return this.importPublicKey(e,r,s,i)}case"raw":{const e=new HA.EcPublicKey(t);return this.importPublicKey(e,r,s,i)}case"spki":{const e=ib.parse(new Uint8Array(t),HA.PublicKeyInfo),n=new HA.EcPublicKey(e.publicKey);return this.assertKeyParameters(e.publicKeyAlgorithm.parameters,r.namedCurve),this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=ib.parse(new Uint8Array(t),HA.PrivateKeyInfo),n=ib.parse(e.privateKey,HA.EcPrivateKey);return this.assertKeyParameters(e.privateKeyAlgorithm.parameters,r.namedCurve),this.importPrivateKey(n,r,s,i)}default:throw new Ub("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static assertKeyParameters(e,t){if(!e)throw new Bb("Key info doesn't have required parameters");let r="";try{r=ib.parse(e,HA.ObjectIdentifier).value}catch(e){throw new Bb("Cannot read key info parameters")}if(HI(t)!==r)throw new Bb("Key info parameter doesn't match to named curve")}static async importPrivateKey(e,t,r,s){const i=new HA.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",i.privateKeyAlgorithm.parameters=nb.serialize(new HA.ObjectIdentifier(HI(t.namedCurve))),i.privateKey=nb.serialize(e);const n=new KI;return n.data=eI.Buffer.from(nb.serialize(i)),n.algorithm=Object.assign({},t),n.extractable=r,n.usages=s,n}static async importPublicKey(e,t,r,s){const i=new HA.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1";const n=HI(t.namedCurve);i.publicKeyAlgorithm.parameters=nb.serialize(new HA.ObjectIdentifier(n)),i.publicKey=e.value;const o=new QI;return o.data=eI.Buffer.from(nb.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}}}WI.publicKeyUsages=["verify"],WI.privateKeyUsages=["sign","deriveKey","deriveBits"];class JI extends Wb{constructor(){super(...arguments),this.namedCurves=KA.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 WI.generateKey({...e,name:this.name},t,r);return{privateKey:uI(s.privateKey),publicKey:uI(s.publicKey)}}async onSign(e,t,r){return WI.sign(e,hI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return WI.verify(e,hI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return WI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await WI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=hI(e);if(!(r instanceof KI||r instanceof QI))throw new TypeError("key: Is not EC CryptoKey")}}class YI extends Xb{constructor(){super(...arguments),this.namedCurves=KA.names}async onGenerateKey(e,t,r){const s=await WI.generateKey({...e,name:this.name},t,r);return{privateKey:uI(s.privateKey),publicKey:uI(s.publicKey)}}async onExportKey(e,t){return WI.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await WI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=hI(e);if(!(r instanceof KI||r instanceof QI))throw new TypeError("key: Is not EC CryptoKey")}async onDeriveBits(e,t,r){return await WI.deriveBits({...e,public:hI(e.public)},hI(t),r)}}const XI={[HA.idEd448]:"Ed448",ed448:HA.idEd448,[HA.idX448]:"X448",x448:HA.idX448,[HA.idEd25519]:"Ed25519",ed25519:HA.idEd25519,[HA.idX25519]:"X25519",x25519:HA.idX25519};function ZI(e){const t=XI[e.toLowerCase()];if(!t)throw new Ub(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class ev extends oI{constructor(){super(...arguments),this.type="private"}getKey(){const e=ib.parse(this.data,HA.PrivateKeyInfo);return ib.parse(e.privateKey,HA.CurvePrivateKey)}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,kb.toJSON(e))}fromJSON(e){if(!e.crv)throw new Ub("Cannot get named curve from JWK. Property 'crv' is required");const t=new HA.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm=ZI(e.crv);const r=xb.fromJSON(e,{targetSchema:HA.CurvePrivateKey});return t.privateKey=nb.serialize(r),this.data=eI.Buffer.from(nb.serialize(t)),this}}class tv extends oI{constructor(){super(...arguments),this.type="public"}getKey(){return ib.parse(this.data,HA.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:Wg.ToBase64Url(e)})}fromJSON(e){if(!e.crv)throw new Ub("Cannot get named curve from JWK. Property 'crv' is required");if(!e.x)throw new Ub("Cannot get property from JWK. Property 'x' is required");const t=new HA.PublicKeyInfo;return t.publicKeyAlgorithm.algorithm=ZI(e.crv),t.publicKey=Wg.FromBase64Url(e.x),this.data=eI.Buffer.from(nb.serialize(t)),this}}class rv{static async generateKey(e,t,r){const s=new ev;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new tv;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=e.namedCurve.toLowerCase(),o=rI().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=rI().sign(null,eI.Buffer.from(r),s);return Vg.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 rI().verify(null,eI.Buffer.from(s),i,eI.Buffer.from(r))}static async deriveBits(e,t,r){const s=rI().createPublicKey({key:e.public.data,format:"der",type:"spki"}),i=rI().createPrivateKey({key:t.data,format:"der",type:"pkcs8"}),n=rI().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 kb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return ib.parse(t.data,HA.PublicKeyInfo).publicKey;default:throw new Ub("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=xb.fromJSON(t,{targetSchema:HA.CurvePrivateKey});return this.importPrivateKey(e,r,s,i)}if(!e.x)throw new TypeError("keyData: Cannot get required 'x' filed");return this.importPublicKey(Wg.FromBase64Url(e.x),r,s,i)}case"raw":return this.importPublicKey(t,r,s,i);case"spki":{const e=ib.parse(new Uint8Array(t),HA.PublicKeyInfo);return this.importPublicKey(e.publicKey,r,s,i)}case"pkcs8":{const e=ib.parse(new Uint8Array(t),HA.PrivateKeyInfo),n=ib.parse(e.privateKey,HA.CurvePrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new Ub("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static importPrivateKey(e,t,r,s){const i=new ev;return i.fromJSON({crv:t.namedCurve,d:Wg.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 tv;return i.fromJSON({crv:t.namedCurve,x:Wg.ToBase64Url(e)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}}rv.publicKeyUsages=["verify"],rv.privateKeyUsages=["sign","deriveKey","deriveBits"];class sv extends eA{async onGenerateKey(e,t,r){const s=await rv.generateKey({name:this.name,namedCurve:e.namedCurve.replace(/^ed/i,"Ed")},t,r);return{privateKey:uI(s.privateKey),publicKey:uI(s.publicKey)}}async onSign(e,t,r){return rv.sign(e,hI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return rv.verify(e,hI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return rv.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await rv.importKey(e,t,{...r,name:this.name},s,i))}}class iv extends Zb{async onGenerateKey(e,t,r){const s=await rv.generateKey({name:this.name,namedCurve:e.namedCurve.toUpperCase()},t,r);return{privateKey:uI(s.privateKey),publicKey:uI(s.publicKey)}}async onDeriveBits(e,t,r){return await rv.deriveBits({...e,public:hI(e.public)},hI(t),r)}async onExportKey(e,t){return rv.exportKey(e,hI(t))}async onImportKey(e,t,r,s,i){return uI(await rv.importKey(e,t,{...r,name:this.name},s,i))}}class nv extends iI{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 ov extends nv{constructor(){super(...arguments),this.type="private"}toJWK(){const e=rI().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"}),t=Nb.toUint8Array(this.data.toString()),r=ab.parse(t,HA.PrivateKeyInfo),s=ab.parse(r.privateKey,HA.EdPrivateKey).value;return{...super.toJWK(),...e,d:Buffer.from(new Uint8Array(s)).toString("base64url")}}}class av extends nv{constructor(){super(...arguments),this.type="public"}toJWK(){const e=rI().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"});return{...super.toJWK(),...e}}}class cv{static async generateKey(e,t,r){const s=e.name.toLowerCase(),i=rI().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 ov(n,t,o,i.privateKey),publicKey:new av(n,!0,a,i.publicKey)}}static async sign(e,t,r){const s=rI().sign(null,Buffer.from(r),t.data);return Vg.toArrayBuffer(s)}static async verify(e,t,r,s){return rI().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 Nb.toArrayBuffer(t.data.toString());case"raw":{const e=t.toJWK();return Wg.FromBase64Url(e.x)}default:return Promise.reject(new Ub("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 HA.EdPrivateKey;t.value=Vg.toArrayBuffer(Buffer.from(e.d,"base64url"));const n=new HA.PrivateKeyInfo;n.privateKeyAlgorithm.algorithm="ed25519"===r.name.toLowerCase()?HA.idEd25519:HA.idX25519,n.privateKey=ab.serialize(t);const o=ab.serialize(n),a=Nb.fromBufferSource(o,"PRIVATE KEY");return new ov(r,s,i,a)}if(e.x){const t=rI().createPublicKey({format:"jwk",key:e}).export({format:"pem",type:"spki"});return new av(r,s,i,t)}throw new Ub("keyData: Cannot import JWK. 'd' or 'x' must be presented")}case"pkcs8":{const e=Nb.fromBufferSource(t,"PRIVATE KEY");return new ov(r,s,i,e)}case"spki":{const e=Nb.fromBufferSource(t,"PUBLIC KEY");return new av(r,s,i,e)}case"raw":{const e=t,n=rI().createPublicKey({format:"jwk",key:{kty:"OKP",crv:"ed25519"===r.name.toLowerCase()?"Ed25519":"X25519",x:Wg.ToBase64Url(e)}}).export({format:"pem",type:"spki"});return new av(r,s,i,n)}default:return Promise.reject(new Ub("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}}cv.privateKeyUsages=["sign","deriveBits","deriveKey"],cv.publicKeyUsages=["verify"];class lv extends VA{async onGenerateKey(e,t,r){const s=await cv.generateKey(e,t,r);return{privateKey:uI(s.privateKey),publicKey:uI(s.publicKey)}}async onSign(e,t,r){const s=hI(t);return cv.sign(e,s,new Uint8Array(r))}onVerify(e,t,r,s){const i=hI(t);return cv.verify(e,i,new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){const r=hI(t);return cv.exportKey(e,r)}async onImportKey(e,t,r,s,i){return uI(await cv.importKey(e,t,r,s,i))}}class hv extends QA{async onGenerateKey(e,t,r){const s=await cv.generateKey(e,t,r);return{privateKey:uI(s.privateKey),publicKey:uI(s.publicKey)}}async onDeriveBits(e,t,r){const s=hI(t),i=hI(e.public),n=rI().createPublicKey({key:i.data.toString(),format:"pem",type:"spki"}),o=rI().createPrivateKey({key:s.data.toString(),format:"pem",type:"pkcs8"}),a=rI().diffieHellman({publicKey:n,privateKey:o});return new Uint8Array(a).buffer.slice(0,r>>3)}async onExportKey(e,t){const r=hI(t);return cv.exportKey(e,r)}async onImportKey(e,t,r,s,i){return uI(await cv.importKey(e,t,r,s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(hI(e)instanceof nv))throw new TypeError("key: Is not a Ed25519CryptoKey")}}class uv extends iI{}class dv extends $A{async onDeriveBits(e,t,r){return new Promise((s,i)=>{const n=Vg.toArrayBuffer(e.salt),o=e.hash.name.replace("-","");rI().pbkdf2(hI(t).data,eI.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 uv;return e.data=eI.Buffer.from(t),e.algorithm={name:this.name},e.extractable=!1,e.usages=i,uI(e)}throw new Ub("format: Must be 'raw'")}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(hI(e)instanceof uv))throw new TypeError("key: Is not PBKDF CryptoKey")}}class fv extends iI{get alg(){return`HS${this.algorithm.hash.name.toUpperCase().replace("SHA-","")}`}set alg(e){}}cb([_b({name:"k",converter:sI})],fv.prototype,"data",void 0);class gv extends FA{async onGenerateKey(e,t,r){const s=(e.length||this.getDefaultLength(e.hash.name))>>3<<3,i=new fv;return i.algorithm={...e,length:s,name:this.name},i.extractable=t,i.usages=r,i.data=rI().randomBytes(s>>3),uI(i)}async onSign(e,t,r){const s=DI.getAlgorithmName(t.algorithm.hash),i=rI().createHmac(s,hI(t).data).update(eI.Buffer.from(r)).digest();return new Uint8Array(i).buffer}async onVerify(e,t,r,s){const i=DI.getAlgorithmName(t.algorithm.hash);return 0===rI().createHmac(i,hI(t).data).update(eI.Buffer.from(s)).digest().compare(eI.Buffer.from(r))}async onImportKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=xb.fromJSON(t,{targetSchema:fv});break;case"raw":n=new fv,n.data=eI.Buffer.from(t);break;default:throw new Ub("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,uI(n)}async onExportKey(e,t){switch(e.toLowerCase()){case"jwk":return kb.toJSON(hI(t));case"raw":return new Uint8Array(hI(t).data).buffer;default:throw new Ub("format: Must be 'jwk' or 'raw'")}}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(hI(e)instanceof fv))throw new TypeError("key: Is not HMAC CryptoKey")}}class pv extends iI{}class yv extends jA{async onImportKey(e,t,r,s,i){if("raw"!==e.toLowerCase())throw new Ub("Operation not supported");const n=new pv;return n.data=eI.Buffer.from(t),n.algorithm={name:this.name},n.extractable=s,n.usages=i,uI(n)}async onDeriveBits(e,t,r){const s=e.hash.name.replace("-",""),i=rI().createHash(s).digest().length,n=r/8,o=Vg.toUint8Array(e.info),a=rI().createHmac(s,Vg.toUint8Array(e.salt)).update(Vg.toUint8Array(hI(t).data)).digest(),c=[eI.Buffer.alloc(0)],l=Math.ceil(n/i)+1;for(let e=1;e<l;++e)c.push(rI().createHmac(s,a).update(eI.Buffer.concat([c[e-1],o,eI.Buffer.from([e])])).digest());return eI.Buffer.concat(c).slice(0,n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(hI(e)instanceof pv))throw new TypeError("key: Is not HKDF CryptoKey")}}class mv{static digest(e,t){const r=rI().createHash(e.name.toLowerCase(),{outputLength:e.length}).update(eI.Buffer.from(t)).digest();return new Uint8Array(r).buffer}}class bv extends qA{async onDigest(e,t){return mv.digest(e,t)}}class Av extends zA{async onDigest(e,t){return mv.digest(e,t)}}class Iv extends ZA{constructor(){var e;super(),this.providers.set(new dI),this.providers.set(new vI),this.providers.set(new wI),this.providers.set(new II),this.providers.set(new SI),this.providers.set(new EI),rI().getCiphers().includes("des-cbc")&&this.providers.set(new xI),this.providers.set(new _I),this.providers.set(new TI),this.providers.set(new NI),this.providers.set(new MI),this.providers.set(new PI),this.providers.set(new JI),this.providers.set(new YI),this.providers.set(new VI),this.providers.set(new FI),this.providers.set(new $I),this.providers.set(new jI),this.providers.set(new dv),this.providers.set(new gv),this.providers.set(new yv);const t=null===(e=/^v(\d+)/.exec(pd.version))||void 0===e?void 0:e[1];t&&parseInt(t,10)>=12&&(this.providers.set(new bv),this.providers.set(new Av));const r=rI().getHashes();r.includes("sha3-256")&&this.providers.set(new GI),r.includes("sha3-384")&&this.providers.set(new qI),r.includes("sha3-512")&&this.providers.set(new zI),t&&parseInt(t,10)>=14&&(this.providers.set(new sv),this.providers.set(new iv),this.providers.set(new lv),this.providers.set(new hv))}}var vv,wv,Sv;o(909);class Ev{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(Wg.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 Cv=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};cb([rb({type:py.TeletexString})],Cv.prototype,"teletexString",void 0),cb([rb({type:py.PrintableString})],Cv.prototype,"printableString",void 0),cb([rb({type:py.UniversalString})],Cv.prototype,"universalString",void 0),cb([rb({type:py.Utf8String})],Cv.prototype,"utf8String",void 0),cb([rb({type:py.BmpString})],Cv.prototype,"bmpString",void 0),Cv=cb([tb({type:gy.Choice})],Cv);let kv=class extends Cv{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Wg.ToHex(this.anyValue):super.toString())}};cb([rb({type:py.IA5String})],kv.prototype,"ia5String",void 0),cb([rb({type:py.Any})],kv.prototype,"anyValue",void 0),kv=cb([tb({type:gy.Choice})],kv);class xv{constructor(e={}){this.type="",this.value=new kv,Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],xv.prototype,"type",void 0),cb([rb({type:kv})],xv.prototype,"value",void 0);let _v=vv=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,vv.prototype)}};_v=vv=cb([tb({type:gy.Set,itemType:xv})],_v);let Bv=wv=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,wv.prototype)}};Bv=wv=cb([tb({type:gy.Sequence,itemType:_v})],Bv);let Rv=Sv=class extends Bv{constructor(e){super(e),Object.setPrototypeOf(this,Sv.prototype)}};Rv=Sv=cb([tb({type:gy.Sequence})],Rv);const Ov={fromASN:e=>Ev.toString(Um.fromASN(e)),toASN:e=>Um.toASN(Ev.fromString(e))};class Uv{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],Uv.prototype,"typeId",void 0),cb([rb({type:py.Any,context:0})],Uv.prototype,"value",void 0);class Tv{constructor(e={}){this.partyName=new Cv,Object.assign(this,e)}}cb([rb({type:Cv,optional:!0,context:0,implicit:!0})],Tv.prototype,"nameAssigner",void 0),cb([rb({type:Cv,context:1,implicit:!0})],Tv.prototype,"partyName",void 0);let Nv=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:Uv,context:0,implicit:!0})],Nv.prototype,"otherName",void 0),cb([rb({type:py.IA5String,context:1,implicit:!0})],Nv.prototype,"rfc822Name",void 0),cb([rb({type:py.IA5String,context:2,implicit:!0})],Nv.prototype,"dNSName",void 0),cb([rb({type:py.Any,context:3,implicit:!0})],Nv.prototype,"x400Address",void 0),cb([rb({type:Rv,context:4,implicit:!1})],Nv.prototype,"directoryName",void 0),cb([rb({type:Tv,context:5})],Nv.prototype,"ediPartyName",void 0),cb([rb({type:py.IA5String,context:6,implicit:!0})],Nv.prototype,"uniformResourceIdentifier",void 0),cb([rb({type:py.OctetString,context:7,implicit:!0,converter:Ov})],Nv.prototype,"iPAddress",void 0),cb([rb({type:py.ObjectIdentifier,context:8,implicit:!0})],Nv.prototype,"registeredID",void 0),Nv=cb([tb({type:gy.Choice})],Nv);const Dv="1.3.6.1.5.5.7",Mv=`${Dv}.3`,Pv=`${Dv}.48`,Lv=`${Pv}.1`,Hv=`${Pv}.2`,Kv=`${Pv}.3`,Qv=`${Pv}.5`,Vv="2.5.29";var Fv;const $v=`${Dv}.1.1`;class jv{constructor(e={}){this.accessMethod="",this.accessLocation=new Nv,Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],jv.prototype,"accessMethod",void 0),cb([rb({type:Nv})],jv.prototype,"accessLocation",void 0);let Gv=Fv=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,Fv.prototype)}};Gv=Fv=cb([tb({type:gy.Sequence,itemType:jv})],Gv);const qv=`${Vv}.35`;class zv extends Em{}class Wv{constructor(e={}){e&&Object.assign(this,e)}}cb([rb({type:zv,context:0,optional:!0,implicit:!0})],Wv.prototype,"keyIdentifier",void 0),cb([rb({type:Nv,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Wv.prototype,"authorityCertIssuer",void 0),cb([rb({type:py.Integer,context:2,optional:!0,implicit:!0,converter:_m})],Wv.prototype,"authorityCertSerialNumber",void 0);const Jv=`${Vv}.19`;class Yv{constructor(e={}){this.cA=!1,Object.assign(this,e)}}var Xv;cb([rb({type:py.Boolean,defaultValue:!1})],Yv.prototype,"cA",void 0),cb([rb({type:py.Integer,optional:!0})],Yv.prototype,"pathLenConstraint",void 0);let Zv=Xv=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,Xv.prototype)}};var ew;Zv=Xv=cb([tb({type:gy.Sequence,itemType:Nv})],Zv);let tw=ew=class extends Zv{constructor(e){super(e),Object.setPrototypeOf(this,ew.prototype)}};var rw;tw=ew=cb([tb({type:gy.Sequence})],tw);const sw=`${Vv}.32`;let iw=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};cb([rb({type:py.IA5String})],iw.prototype,"ia5String",void 0),cb([rb({type:py.VisibleString})],iw.prototype,"visibleString",void 0),cb([rb({type:py.BmpString})],iw.prototype,"bmpString",void 0),cb([rb({type:py.Utf8String})],iw.prototype,"utf8String",void 0),iw=cb([tb({type:gy.Choice})],iw);class nw{constructor(e={}){this.organization=new iw,this.noticeNumbers=[],Object.assign(this,e)}}cb([rb({type:iw})],nw.prototype,"organization",void 0),cb([rb({type:py.Integer,repeated:"sequence"})],nw.prototype,"noticeNumbers",void 0);class ow{constructor(e={}){Object.assign(this,e)}}cb([rb({type:nw,optional:!0})],ow.prototype,"noticeRef",void 0),cb([rb({type:iw,optional:!0})],ow.prototype,"explicitText",void 0);let aw=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:py.IA5String})],aw.prototype,"cPSuri",void 0),cb([rb({type:ow})],aw.prototype,"userNotice",void 0),aw=cb([tb({type:gy.Choice})],aw);class cw{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],cw.prototype,"policyQualifierId",void 0),cb([rb({type:py.Any})],cw.prototype,"qualifier",void 0);class lw{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],lw.prototype,"policyIdentifier",void 0),cb([rb({type:cw,repeated:"sequence",optional:!0})],lw.prototype,"policyQualifiers",void 0);let hw=rw=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,rw.prototype)}};hw=rw=cb([tb({type:gy.Sequence,itemType:lw})],hw);let uw=class{constructor(e=0){this.value=e}};cb([rb({type:py.Integer})],uw.prototype,"value",void 0),uw=cb([tb({type:gy.Choice})],uw);let dw=class extends uw{};var fw;dw=cb([tb({type:gy.Choice})],dw);const gw=`${Vv}.31`;var pw;!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"}(pw||(pw={}));class yw extends Sm{toJSON(){const e=[],t=this.toNumber();return t&pw.aACompromise&&e.push("aACompromise"),t&pw.affiliationChanged&&e.push("affiliationChanged"),t&pw.cACompromise&&e.push("cACompromise"),t&pw.certificateHold&&e.push("certificateHold"),t&pw.cessationOfOperation&&e.push("cessationOfOperation"),t&pw.keyCompromise&&e.push("keyCompromise"),t&pw.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&pw.superseded&&e.push("superseded"),t&pw.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let mw=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:Nv,context:0,repeated:"sequence",implicit:!0})],mw.prototype,"fullName",void 0),cb([rb({type:_v,context:1,implicit:!0})],mw.prototype,"nameRelativeToCRLIssuer",void 0),mw=cb([tb({type:gy.Choice})],mw);class bw{constructor(e={}){Object.assign(this,e)}}cb([rb({type:mw,context:0,optional:!0})],bw.prototype,"distributionPoint",void 0),cb([rb({type:yw,context:1,optional:!0,implicit:!0})],bw.prototype,"reasons",void 0),cb([rb({type:Nv,context:2,optional:!0,repeated:"sequence",implicit:!0})],bw.prototype,"cRLIssuer",void 0);let Aw=fw=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,fw.prototype)}};var Iw;Aw=fw=cb([tb({type:gy.Sequence,itemType:bw})],Aw);let vw=Iw=class extends Aw{constructor(e){super(e),Object.setPrototypeOf(this,Iw.prototype)}};vw=Iw=cb([tb({type:gy.Sequence,itemType:bw})],vw);class ww{constructor(e={}){this.onlyContainsUserCerts=ww.ONLY,this.onlyContainsCACerts=ww.ONLY,this.indirectCRL=ww.ONLY,this.onlyContainsAttributeCerts=ww.ONLY,Object.assign(this,e)}}var Sw;ww.ONLY=!1,cb([rb({type:mw,context:0,optional:!0})],ww.prototype,"distributionPoint",void 0),cb([rb({type:py.Boolean,context:1,defaultValue:ww.ONLY,implicit:!0})],ww.prototype,"onlyContainsUserCerts",void 0),cb([rb({type:py.Boolean,context:2,defaultValue:ww.ONLY,implicit:!0})],ww.prototype,"onlyContainsCACerts",void 0),cb([rb({type:yw,context:3,optional:!0,implicit:!0})],ww.prototype,"onlySomeReasons",void 0),cb([rb({type:py.Boolean,context:4,defaultValue:ww.ONLY,implicit:!0})],ww.prototype,"indirectCRL",void 0),cb([rb({type:py.Boolean,context:5,defaultValue:ww.ONLY,implicit:!0})],ww.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"}(Sw||(Sw={}));let Ew=class{constructor(e=Sw.unspecified){this.reason=Sw.unspecified,this.reason=e}toJSON(){return Sw[this.reason]}toString(){return this.toJSON()}};var Cw;cb([rb({type:py.Enumerated})],Ew.prototype,"reason",void 0),Ew=cb([tb({type:gy.Choice})],Ew);const kw=`${Vv}.37`;let xw=Cw=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,Cw.prototype)}};xw=Cw=cb([tb({type:gy.Sequence,itemType:py.ObjectIdentifier})],xw);const _w=`${Mv}.1`,Bw=`${Mv}.2`,Rw=`${Mv}.3`,Ow=`${Mv}.4`,Uw=`${Mv}.8`,Tw=`${Mv}.9`;let Nw=class{constructor(e=new ArrayBuffer(0)){this.value=e}};cb([rb({type:py.Integer,converter:_m})],Nw.prototype,"value",void 0),Nw=cb([tb({type:gy.Choice})],Nw);let Dw=class{constructor(e){this.value=new Date,e&&(this.value=e)}};var Mw;cb([rb({type:py.GeneralizedTime})],Dw.prototype,"value",void 0),Dw=cb([tb({type:gy.Choice})],Dw);let Pw=Mw=class extends Zv{constructor(e){super(e),Object.setPrototypeOf(this,Mw.prototype)}};Pw=Mw=cb([tb({type:gy.Sequence})],Pw);const Lw=`${Vv}.15`;var Hw,Kw;!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"}(Hw||(Hw={}));class Qw extends Sm{toJSON(){const e=this.toNumber(),t=[];return e&Hw.cRLSign&&t.push("crlSign"),e&Hw.dataEncipherment&&t.push("dataEncipherment"),e&Hw.decipherOnly&&t.push("decipherOnly"),e&Hw.digitalSignature&&t.push("digitalSignature"),e&Hw.encipherOnly&&t.push("encipherOnly"),e&Hw.keyAgreement&&t.push("keyAgreement"),e&Hw.keyCertSign&&t.push("keyCertSign"),e&Hw.keyEncipherment&&t.push("keyEncipherment"),e&Hw.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}}class Vw{constructor(e={}){this.base=new Nv,this.minimum=0,Object.assign(this,e)}}cb([rb({type:Nv})],Vw.prototype,"base",void 0),cb([rb({type:py.Integer,context:0,defaultValue:0,implicit:!0})],Vw.prototype,"minimum",void 0),cb([rb({type:py.Integer,context:1,optional:!0,implicit:!0})],Vw.prototype,"maximum",void 0);let Fw=Kw=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,Kw.prototype)}};Fw=Kw=cb([tb({type:gy.Sequence,itemType:Vw})],Fw);class $w{constructor(e={}){Object.assign(this,e)}}cb([rb({type:Fw,context:0,optional:!0,implicit:!0})],$w.prototype,"permittedSubtrees",void 0),cb([rb({type:Fw,context:1,optional:!0,implicit:!0})],$w.prototype,"excludedSubtrees",void 0);class jw{constructor(e={}){Object.assign(this,e)}}var Gw;cb([rb({type:py.Integer,context:0,implicit:!0,optional:!0,converter:_m})],jw.prototype,"requireExplicitPolicy",void 0),cb([rb({type:py.Integer,context:1,implicit:!0,optional:!0,converter:_m})],jw.prototype,"inhibitPolicyMapping",void 0);class qw{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],qw.prototype,"issuerDomainPolicy",void 0),cb([rb({type:py.ObjectIdentifier})],qw.prototype,"subjectDomainPolicy",void 0);let zw=Gw=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,Gw.prototype)}};var Ww;zw=Gw=cb([tb({type:gy.Sequence,itemType:qw})],zw);const Jw=`${Vv}.17`;let Yw=Ww=class extends Zv{constructor(e){super(e),Object.setPrototypeOf(this,Ww.prototype)}};Yw=Ww=cb([tb({type:gy.Sequence})],Yw);class Xw{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}}var Zw;cb([rb({type:py.ObjectIdentifier})],Xw.prototype,"type",void 0),cb([rb({type:py.Any,repeated:"set"})],Xw.prototype,"values",void 0);let eS=Zw=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,Zw.prototype)}};eS=Zw=cb([tb({type:gy.Sequence,itemType:Xw})],eS);const tS=`${Vv}.14`;class rS extends zv{}class sS{constructor(e={}){Object.assign(this,e)}}var iS,nS;cb([rb({type:py.GeneralizedTime,context:0,implicit:!0,optional:!0})],sS.prototype,"notBefore",void 0),cb([rb({type:py.GeneralizedTime,context:1,implicit:!0,optional:!0})],sS.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(iS||(iS={}));class oS extends Sm{toJSON(){const e=[],t=this.toNumber();return t&iS.pKIXCertificate&&e.push("pKIXCertificate"),t&iS.newExtensions&&e.push("newExtensions"),t&iS.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class aS{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new oS,Object.assign(this,e)}}cb([rb({type:py.GeneralString})],aS.prototype,"entrustVers",void 0),cb([rb({type:oS})],aS.prototype,"entrustInfoFlags",void 0);let cS=nS=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,nS.prototype)}};cS=nS=cb([tb({type:gy.Sequence,itemType:jv})],cS);class lS{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof lS&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Yg(e.parameters,this.parameters)||e.parameters===this.parameters)}}cb([rb({type:py.ObjectIdentifier})],lS.prototype,"algorithm",void 0),cb([rb({type:py.Any,optional:!0})],lS.prototype,"parameters",void 0);class hS{constructor(e={}){this.algorithm=new lS,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:lS})],hS.prototype,"algorithm",void 0),cb([rb({type:py.BitString})],hS.prototype,"subjectPublicKey",void 0);let uS=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}};cb([rb({type:py.UTCTime})],uS.prototype,"utcTime",void 0),cb([rb({type:py.GeneralizedTime})],uS.prototype,"generalTime",void 0),uS=cb([tb({type:gy.Choice})],uS);class dS{constructor(e){this.notBefore=new uS(new Date),this.notAfter=new uS(new Date),e&&(this.notBefore=new uS(e.notBefore),this.notAfter=new uS(e.notAfter))}}var fS;cb([rb({type:uS})],dS.prototype,"notBefore",void 0),cb([rb({type:uS})],dS.prototype,"notAfter",void 0);class gS{constructor(e={}){this.extnID="",this.critical=gS.CRITICAL,this.extnValue=new Em,Object.assign(this,e)}}gS.CRITICAL=!1,cb([rb({type:py.ObjectIdentifier})],gS.prototype,"extnID",void 0),cb([rb({type:py.Boolean,defaultValue:gS.CRITICAL})],gS.prototype,"critical",void 0),cb([rb({type:Em})],gS.prototype,"extnValue",void 0);let pS=fS=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,fS.prototype)}};var yS;pS=fS=cb([tb({type:gy.Sequence,itemType:gS})],pS),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(yS||(yS={}));class mS{constructor(e={}){this.version=yS.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new lS,this.issuer=new Rv,this.validity=new dS,this.subject=new Rv,this.subjectPublicKeyInfo=new hS,Object.assign(this,e)}}cb([rb({type:py.Integer,context:0,defaultValue:yS.v1})],mS.prototype,"version",void 0),cb([rb({type:py.Integer,converter:_m})],mS.prototype,"serialNumber",void 0),cb([rb({type:lS})],mS.prototype,"signature",void 0),cb([rb({type:Rv})],mS.prototype,"issuer",void 0),cb([rb({type:dS})],mS.prototype,"validity",void 0),cb([rb({type:Rv})],mS.prototype,"subject",void 0),cb([rb({type:hS})],mS.prototype,"subjectPublicKeyInfo",void 0),cb([rb({type:py.BitString,context:1,implicit:!0,optional:!0})],mS.prototype,"issuerUniqueID",void 0),cb([rb({type:py.BitString,context:2,implicit:!0,optional:!0})],mS.prototype,"subjectUniqueID",void 0),cb([rb({type:pS,context:3,optional:!0})],mS.prototype,"extensions",void 0);class bS{constructor(e={}){this.tbsCertificate=new mS,this.signatureAlgorithm=new lS,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:mS})],bS.prototype,"tbsCertificate",void 0),cb([rb({type:lS})],bS.prototype,"signatureAlgorithm",void 0),cb([rb({type:py.BitString})],bS.prototype,"signatureValue",void 0);class AS{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new uS,Object.assign(this,e)}}cb([rb({type:py.Integer,converter:_m})],AS.prototype,"userCertificate",void 0),cb([rb({type:uS})],AS.prototype,"revocationDate",void 0),cb([rb({type:gS,optional:!0,repeated:"sequence"})],AS.prototype,"crlEntryExtensions",void 0);class IS{constructor(e={}){this.signature=new lS,this.issuer=new Rv,this.thisUpdate=new uS,Object.assign(this,e)}}cb([rb({type:py.Integer,optional:!0})],IS.prototype,"version",void 0),cb([rb({type:lS})],IS.prototype,"signature",void 0),cb([rb({type:Rv})],IS.prototype,"issuer",void 0),cb([rb({type:uS})],IS.prototype,"thisUpdate",void 0),cb([rb({type:uS,optional:!0})],IS.prototype,"nextUpdate",void 0),cb([rb({type:AS,repeated:"sequence",optional:!0})],IS.prototype,"revokedCertificates",void 0),cb([rb({type:gS,optional:!0,context:0,repeated:"sequence"})],IS.prototype,"crlExtensions",void 0);class vS{constructor(e={}){this.tbsCertList=new IS,this.signatureAlgorithm=new lS,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:IS})],vS.prototype,"tbsCertList",void 0),cb([rb({type:lS})],vS.prototype,"signatureAlgorithm",void 0),cb([rb({type:py.BitString})],vS.prototype,"signature",void 0);class wS{constructor(e={}){this.issuer=new Rv,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:Rv})],wS.prototype,"issuer",void 0),cb([rb({type:py.Integer,converter:_m})],wS.prototype,"serialNumber",void 0);let SS=class{constructor(e={}){Object.assign(this,e)}};var ES;cb([rb({type:rS,context:0,implicit:!0})],SS.prototype,"subjectKeyIdentifier",void 0),cb([rb({type:wS})],SS.prototype,"issuerAndSerialNumber",void 0),SS=cb([tb({type:gy.Choice})],SS),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"}(ES||(ES={}));let CS=class extends lS{};CS=cb([tb({type:gy.Sequence})],CS);let kS=class extends lS{};kS=cb([tb({type:gy.Sequence})],kS);let xS=class extends lS{};xS=cb([tb({type:gy.Sequence})],xS);let _S=class extends lS{};_S=cb([tb({type:gy.Sequence})],_S);let BS=class extends lS{};BS=cb([tb({type:gy.Sequence})],BS);let RS=class extends lS{};RS=cb([tb({type:gy.Sequence})],RS);class OS{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}}var US;cb([rb({type:py.ObjectIdentifier})],OS.prototype,"attrType",void 0),cb([rb({type:py.Any,repeated:"set"})],OS.prototype,"attrValues",void 0);class TS{constructor(e={}){this.version=ES.v0,this.sid=new SS,this.digestAlgorithm=new CS,this.signatureAlgorithm=new kS,this.signature=new Em,Object.assign(this,e)}}cb([rb({type:py.Integer})],TS.prototype,"version",void 0),cb([rb({type:SS})],TS.prototype,"sid",void 0),cb([rb({type:CS})],TS.prototype,"digestAlgorithm",void 0),cb([rb({type:OS,repeated:"set",context:0,implicit:!0,optional:!0})],TS.prototype,"signedAttrs",void 0),cb([rb({type:kS})],TS.prototype,"signatureAlgorithm",void 0),cb([rb({type:Em})],TS.prototype,"signature",void 0),cb([rb({type:OS,repeated:"set",context:1,implicit:!0,optional:!0})],TS.prototype,"unsignedAttrs",void 0);let NS=US=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,US.prototype)}};NS=US=cb([tb({type:gy.Set,itemType:TS})],NS);let DS=class extends uS{};DS=cb([tb({type:gy.Choice})],DS);let MS=class extends TS{};MS=cb([tb({type:gy.Sequence})],MS);class PS{constructor(e={}){this.acIssuer=new Nv,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}var LS;cb([rb({type:Nv})],PS.prototype,"acIssuer",void 0),cb([rb({type:py.Integer})],PS.prototype,"acSerial",void 0),cb([rb({type:Xw,repeated:"sequence"})],PS.prototype,"attrs",void 0);let HS=LS=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,LS.prototype)}};HS=LS=cb([tb({type:gy.Sequence,itemType:py.ObjectIdentifier})],HS);class KS{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}}cb([rb({type:py.Integer,optional:!0})],KS.prototype,"pathLenConstraint",void 0),cb([rb({type:HS,implicit:!0,context:0,optional:!0})],KS.prototype,"permittedAttrs",void 0),cb([rb({type:HS,implicit:!0,context:1,optional:!0})],KS.prototype,"excludedAttrs",void 0),cb([rb({type:py.Boolean,defaultValue:!0})],KS.prototype,"permitUnSpecified",void 0);class QS{constructor(e={}){this.issuer=new Zv,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}var VS;cb([rb({type:Zv})],QS.prototype,"issuer",void 0),cb([rb({type:py.Integer,converter:_m})],QS.prototype,"serial",void 0),cb([rb({type:py.BitString,optional:!0})],QS.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}(VS||(VS={}));class FS{constructor(e={}){this.digestedObjectType=VS.publicKey,this.digestAlgorithm=new lS,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.Enumerated})],FS.prototype,"digestedObjectType",void 0),cb([rb({type:py.ObjectIdentifier,optional:!0})],FS.prototype,"otherObjectTypeID",void 0),cb([rb({type:lS})],FS.prototype,"digestAlgorithm",void 0),cb([rb({type:py.BitString})],FS.prototype,"objectDigest",void 0);class $S{constructor(e={}){Object.assign(this,e)}}cb([rb({type:Zv,optional:!0})],$S.prototype,"issuerName",void 0),cb([rb({type:QS,context:0,implicit:!0,optional:!0})],$S.prototype,"baseCertificateID",void 0),cb([rb({type:FS,context:1,implicit:!0,optional:!0})],$S.prototype,"objectDigestInfo",void 0);let jS=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:Nv,repeated:"sequence"})],jS.prototype,"v1Form",void 0),cb([rb({type:$S,context:0,implicit:!0})],jS.prototype,"v2Form",void 0),jS=cb([tb({type:gy.Choice})],jS);class GS{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}cb([rb({type:py.GeneralizedTime})],GS.prototype,"notBeforeTime",void 0),cb([rb({type:py.GeneralizedTime})],GS.prototype,"notAfterTime",void 0);class qS{constructor(e={}){Object.assign(this,e)}}var zS,WS,JS;cb([rb({type:QS,implicit:!0,context:0,optional:!0})],qS.prototype,"baseCertificateID",void 0),cb([rb({type:Zv,implicit:!0,context:1,optional:!0})],qS.prototype,"entityName",void 0),cb([rb({type:FS,implicit:!0,context:2,optional:!0})],qS.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(zS||(zS={}));class YS{constructor(e={}){this.version=zS.v2,this.holder=new qS,this.issuer=new jS,this.signature=new lS,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new GS,this.attributes=[],Object.assign(this,e)}}cb([rb({type:py.Integer})],YS.prototype,"version",void 0),cb([rb({type:qS})],YS.prototype,"holder",void 0),cb([rb({type:jS})],YS.prototype,"issuer",void 0),cb([rb({type:lS})],YS.prototype,"signature",void 0),cb([rb({type:py.Integer,converter:_m})],YS.prototype,"serialNumber",void 0),cb([rb({type:GS})],YS.prototype,"attrCertValidityPeriod",void 0),cb([rb({type:Xw,repeated:"sequence"})],YS.prototype,"attributes",void 0),cb([rb({type:py.BitString,optional:!0})],YS.prototype,"issuerUniqueID",void 0),cb([rb({type:pS,optional:!0})],YS.prototype,"extensions",void 0);class XS{constructor(e={}){this.acinfo=new YS,this.signatureAlgorithm=new lS,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:YS})],XS.prototype,"acinfo",void 0),cb([rb({type:lS})],XS.prototype,"signatureAlgorithm",void 0),cb([rb({type:py.BitString})],XS.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"}(WS||(WS={}));class ZS extends Sm{}class eE{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier,implicit:!0,context:0})],eE.prototype,"type",void 0),cb([rb({type:py.Any,implicit:!0,context:1})],eE.prototype,"value",void 0);class tE{constructor(e={}){this.policyId="",this.classList=new ZS(WS.unclassified),Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],tE.prototype,"policyId",void 0),cb([rb({type:ZS,defaultValue:new ZS(WS.unclassified)})],tE.prototype,"classList",void 0),cb([rb({type:eE,repeated:"set"})],tE.prototype,"securityCategories",void 0);class rE{constructor(e={}){Object.assign(this,e)}}cb([rb({type:Em})],rE.prototype,"cotets",void 0),cb([rb({type:py.ObjectIdentifier})],rE.prototype,"oid",void 0),cb([rb({type:py.Utf8String})],rE.prototype,"string",void 0);class sE{constructor(e={}){this.values=[],Object.assign(this,e)}}cb([rb({type:Zv,implicit:!0,context:0,optional:!0})],sE.prototype,"policyAuthority",void 0),cb([rb({type:rE,repeated:"sequence"})],sE.prototype,"values",void 0);class iE{constructor(e={}){this.targetCertificate=new QS,Object.assign(this,e)}}cb([rb({type:QS})],iE.prototype,"targetCertificate",void 0),cb([rb({type:Nv,optional:!0})],iE.prototype,"targetName",void 0),cb([rb({type:FS,optional:!0})],iE.prototype,"certDigestInfo",void 0);let nE=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:Nv,context:0,implicit:!0})],nE.prototype,"targetName",void 0),cb([rb({type:Nv,context:1,implicit:!0})],nE.prototype,"targetGroup",void 0),cb([rb({type:iE,context:2,implicit:!0})],nE.prototype,"targetCert",void 0),nE=cb([tb({type:gy.Choice})],nE);let oE=JS=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,JS.prototype)}};var aE;oE=JS=cb([tb({type:gy.Sequence,itemType:nE})],oE);let cE=aE=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,aE.prototype)}};cE=aE=cb([tb({type:gy.Sequence,itemType:oE})],cE);class lE{constructor(e={}){Object.assign(this,e)}}cb([rb({type:Zv,implicit:!0,context:0,optional:!0})],lE.prototype,"roleAuthority",void 0),cb([rb({type:Nv,implicit:!0,context:1})],lE.prototype,"roleName",void 0);class hE{constructor(e={}){this.service=new Nv,this.ident=new Nv,Object.assign(this,e)}}var uE;cb([rb({type:Nv})],hE.prototype,"service",void 0),cb([rb({type:Nv})],hE.prototype,"ident",void 0),cb([rb({type:Em,optional:!0})],hE.prototype,"authInfo",void 0);class dE{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],dE.prototype,"otherCertFormat",void 0),cb([rb({type:py.Any})],dE.prototype,"otherCert",void 0);let fE=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:bS})],fE.prototype,"certificate",void 0),cb([rb({type:XS,context:2,implicit:!0})],fE.prototype,"v2AttrCert",void 0),cb([rb({type:dE,context:3,implicit:!0})],fE.prototype,"other",void 0),fE=cb([tb({type:gy.Choice})],fE);let gE=uE=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,uE.prototype)}};gE=uE=cb([tb({type:gy.Set,itemType:fE})],gE);class pE{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],pE.prototype,"contentType",void 0),cb([rb({type:py.Any,context:0})],pE.prototype,"content",void 0);let yE=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:Em})],yE.prototype,"single",void 0),cb([rb({type:py.Any})],yE.prototype,"any",void 0),yE=cb([tb({type:gy.Choice})],yE);class mE{constructor(e={}){this.eContentType="",Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],mE.prototype,"eContentType",void 0),cb([rb({type:yE,context:0,optional:!0})],mE.prototype,"eContent",void 0);let bE=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:Em,context:0,implicit:!0,optional:!0})],bE.prototype,"value",void 0),cb([rb({type:Em,converter:Tm,context:0,implicit:!0,optional:!0,repeated:"sequence"})],bE.prototype,"constructedValue",void 0),bE=cb([tb({type:gy.Choice})],bE);class AE{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new _S,Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],AE.prototype,"contentType",void 0),cb([rb({type:_S})],AE.prototype,"contentEncryptionAlgorithm",void 0),cb([rb({type:bE,optional:!0})],AE.prototype,"encryptedContent",void 0);class IE{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}}var vE;cb([rb({type:py.ObjectIdentifier})],IE.prototype,"keyAttrId",void 0),cb([rb({type:py.Any,optional:!0})],IE.prototype,"keyAttr",void 0);class wE{constructor(e={}){this.subjectKeyIdentifier=new rS,Object.assign(this,e)}}cb([rb({type:rS})],wE.prototype,"subjectKeyIdentifier",void 0),cb([rb({type:py.GeneralizedTime,optional:!0})],wE.prototype,"date",void 0),cb([rb({type:IE,optional:!0})],wE.prototype,"other",void 0);let SE=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:wE,context:0,implicit:!0,optional:!0})],SE.prototype,"rKeyId",void 0),cb([rb({type:wS,optional:!0})],SE.prototype,"issuerAndSerialNumber",void 0),SE=cb([tb({type:gy.Choice})],SE);class EE{constructor(e={}){this.rid=new SE,this.encryptedKey=new Em,Object.assign(this,e)}}cb([rb({type:SE})],EE.prototype,"rid",void 0),cb([rb({type:Em})],EE.prototype,"encryptedKey",void 0);let CE=vE=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,vE.prototype)}};CE=vE=cb([tb({type:gy.Sequence,itemType:EE})],CE);class kE{constructor(e={}){this.algorithm=new lS,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:lS})],kE.prototype,"algorithm",void 0),cb([rb({type:py.BitString})],kE.prototype,"publicKey",void 0);let xE=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:rS,context:0,implicit:!0,optional:!0})],xE.prototype,"subjectKeyIdentifier",void 0),cb([rb({type:kE,context:1,implicit:!0,optional:!0})],xE.prototype,"originatorKey",void 0),cb([rb({type:wS,optional:!0})],xE.prototype,"issuerAndSerialNumber",void 0),xE=cb([tb({type:gy.Choice})],xE);class _E{constructor(e={}){this.version=ES.v3,this.originator=new xE,this.keyEncryptionAlgorithm=new xS,this.recipientEncryptedKeys=new CE,Object.assign(this,e)}}cb([rb({type:py.Integer})],_E.prototype,"version",void 0),cb([rb({type:xE,context:0})],_E.prototype,"originator",void 0),cb([rb({type:Em,context:1,optional:!0})],_E.prototype,"ukm",void 0),cb([rb({type:xS})],_E.prototype,"keyEncryptionAlgorithm",void 0),cb([rb({type:CE})],_E.prototype,"recipientEncryptedKeys",void 0);let BE=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:rS,context:0,implicit:!0})],BE.prototype,"subjectKeyIdentifier",void 0),cb([rb({type:wS})],BE.prototype,"issuerAndSerialNumber",void 0),BE=cb([tb({type:gy.Choice})],BE);class RE{constructor(e={}){this.version=ES.v0,this.rid=new BE,this.keyEncryptionAlgorithm=new xS,this.encryptedKey=new Em,Object.assign(this,e)}}cb([rb({type:py.Integer})],RE.prototype,"version",void 0),cb([rb({type:BE})],RE.prototype,"rid",void 0),cb([rb({type:xS})],RE.prototype,"keyEncryptionAlgorithm",void 0),cb([rb({type:Em})],RE.prototype,"encryptedKey",void 0);class OE{constructor(e={}){this.keyIdentifier=new Em,Object.assign(this,e)}}cb([rb({type:Em})],OE.prototype,"keyIdentifier",void 0),cb([rb({type:py.GeneralizedTime,optional:!0})],OE.prototype,"date",void 0),cb([rb({type:IE,optional:!0})],OE.prototype,"other",void 0);class UE{constructor(e={}){this.version=ES.v4,this.kekid=new OE,this.keyEncryptionAlgorithm=new xS,this.encryptedKey=new Em,Object.assign(this,e)}}cb([rb({type:py.Integer})],UE.prototype,"version",void 0),cb([rb({type:OE})],UE.prototype,"kekid",void 0),cb([rb({type:xS})],UE.prototype,"keyEncryptionAlgorithm",void 0),cb([rb({type:Em})],UE.prototype,"encryptedKey",void 0);class TE{constructor(e={}){this.version=ES.v0,this.keyEncryptionAlgorithm=new xS,this.encryptedKey=new Em,Object.assign(this,e)}}cb([rb({type:py.Integer})],TE.prototype,"version",void 0),cb([rb({type:RS,context:0,optional:!0})],TE.prototype,"keyDerivationAlgorithm",void 0),cb([rb({type:xS})],TE.prototype,"keyEncryptionAlgorithm",void 0),cb([rb({type:Em})],TE.prototype,"encryptedKey",void 0);class NE{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],NE.prototype,"oriType",void 0),cb([rb({type:py.Any})],NE.prototype,"oriValue",void 0);let DE=class{constructor(e={}){Object.assign(this,e)}};var ME;cb([rb({type:RE,optional:!0})],DE.prototype,"ktri",void 0),cb([rb({type:_E,context:1,implicit:!0,optional:!0})],DE.prototype,"kari",void 0),cb([rb({type:UE,context:2,implicit:!0,optional:!0})],DE.prototype,"kekri",void 0),cb([rb({type:TE,context:3,implicit:!0,optional:!0})],DE.prototype,"pwri",void 0),cb([rb({type:NE,context:4,implicit:!0,optional:!0})],DE.prototype,"ori",void 0),DE=cb([tb({type:gy.Choice})],DE);let PE=ME=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,ME.prototype)}};var LE;PE=ME=cb([tb({type:gy.Set,itemType:DE})],PE);class HE{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],HE.prototype,"otherRevInfoFormat",void 0),cb([rb({type:py.Any})],HE.prototype,"otherRevInfo",void 0);let KE=class{constructor(e={}){this.other=new HE,Object.assign(this,e)}};cb([rb({type:HE,context:1,implicit:!0})],KE.prototype,"other",void 0),KE=cb([tb({type:gy.Choice})],KE);let QE=LE=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,LE.prototype)}};QE=LE=cb([tb({type:gy.Set,itemType:KE})],QE);class VE{constructor(e={}){Object.assign(this,e)}}var FE;cb([rb({type:gE,context:0,implicit:!0,optional:!0})],VE.prototype,"certs",void 0),cb([rb({type:QE,context:1,implicit:!0,optional:!0})],VE.prototype,"crls",void 0);let $E=FE=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,FE.prototype)}};$E=FE=cb([tb({type:gy.Set,itemType:OS})],$E);class jE{constructor(e={}){this.version=ES.v0,this.recipientInfos=new PE,this.encryptedContentInfo=new AE,Object.assign(this,e)}}cb([rb({type:py.Integer})],jE.prototype,"version",void 0),cb([rb({type:VE,context:0,implicit:!0,optional:!0})],jE.prototype,"originatorInfo",void 0),cb([rb({type:PE})],jE.prototype,"recipientInfos",void 0),cb([rb({type:AE})],jE.prototype,"encryptedContentInfo",void 0),cb([rb({type:$E,context:1,implicit:!0,optional:!0})],jE.prototype,"unprotectedAttrs",void 0);const GE="1.2.840.113549.1.7.2";var qE;let zE=qE=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,qE.prototype)}};zE=qE=cb([tb({type:gy.Set,itemType:CS})],zE);class WE{constructor(e={}){this.version=ES.v0,this.digestAlgorithms=new zE,this.encapContentInfo=new mE,this.signerInfos=new NS,Object.assign(this,e)}}cb([rb({type:py.Integer})],WE.prototype,"version",void 0),cb([rb({type:zE})],WE.prototype,"digestAlgorithms",void 0),cb([rb({type:mE})],WE.prototype,"encapContentInfo",void 0),cb([rb({type:gE,context:0,implicit:!0,optional:!0})],WE.prototype,"certificates",void 0),cb([rb({type:QE,context:1,implicit:!0,optional:!0})],WE.prototype,"crls",void 0),cb([rb({type:NS})],WE.prototype,"signerInfos",void 0);const JE="1.2.840.10045.2.1",YE="1.2.840.10045.4.1",XE="1.2.840.10045.4.3.1",ZE="1.2.840.10045.4.3.2",eC="1.2.840.10045.4.3.3",tC="1.2.840.10045.4.3.4",rC="1.2.840.10045.3.1.7",sC="1.3.132.0.34",iC="1.3.132.0.35";function nC(e){return new lS({algorithm:e})}const oC=nC(YE),aC=(nC(XE),nC(ZE)),cC=nC(eC),lC=nC(tC);let hC=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:py.ObjectIdentifier})],hC.prototype,"fieldType",void 0),cb([rb({type:py.Any})],hC.prototype,"parameters",void 0),hC=cb([tb({type:gy.Sequence})],hC);let uC=class{constructor(e={}){Object.assign(this,e)}};var dC;cb([rb({type:py.OctetString})],uC.prototype,"a",void 0),cb([rb({type:py.OctetString})],uC.prototype,"b",void 0),cb([rb({type:py.BitString,optional:!0})],uC.prototype,"seed",void 0),uC=cb([tb({type:gy.Sequence})],uC),function(e){e[e.ecpVer1=1]="ecpVer1"}(dC||(dC={}));let fC=class{constructor(e={}){this.version=dC.ecpVer1,Object.assign(this,e)}};cb([rb({type:py.Integer})],fC.prototype,"version",void 0),cb([rb({type:hC})],fC.prototype,"fieldID",void 0),cb([rb({type:uC})],fC.prototype,"curve",void 0),cb([rb({type:class extends Em{}})],fC.prototype,"base",void 0),cb([rb({type:py.Integer,converter:_m})],fC.prototype,"order",void 0),cb([rb({type:py.Integer,optional:!0})],fC.prototype,"cofactor",void 0),fC=cb([tb({type:gy.Sequence})],fC);let gC=class{constructor(e={}){Object.assign(this,e)}};cb([rb({type:py.ObjectIdentifier})],gC.prototype,"namedCurve",void 0),cb([rb({type:py.Null})],gC.prototype,"implicitCurve",void 0),cb([rb({type:fC})],gC.prototype,"specifiedCurve",void 0),gC=cb([tb({type:gy.Choice})],gC);class pC{constructor(e={}){this.version=1,this.privateKey=new Em,Object.assign(this,e)}}cb([rb({type:py.Integer})],pC.prototype,"version",void 0),cb([rb({type:Em})],pC.prototype,"privateKey",void 0),cb([rb({type:gC,context:0,optional:!0})],pC.prototype,"parameters",void 0),cb([rb({type:py.BitString,context:1,optional:!0})],pC.prototype,"publicKey",void 0);class yC{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.Integer,converter:_m})],yC.prototype,"r",void 0),cb([rb({type:py.Integer,converter:_m})],yC.prototype,"s",void 0);const mC="1.2.840.113549.1.1",bC=`${mC}.1`,AC=`${mC}.7`,IC=`${mC}.9`,vC=`${mC}.10`,wC=`${mC}.2`,SC=`${mC}.4`,EC=`${mC}.5`,CC=`${mC}.14`,kC=`${mC}.11`,xC=`${mC}.12`,_C=`${mC}.13`,BC=`${mC}.15`,RC=`${mC}.16`,OC="1.3.14.3.2.26",UC="2.16.840.1.101.3.4.2.4",TC="2.16.840.1.101.3.4.2.1",NC="2.16.840.1.101.3.4.2.2",DC="2.16.840.1.101.3.4.2.3",MC=`${mC}.8`;function PC(e){return new lS({algorithm:e,parameters:null})}PC("1.2.840.113549.2.2"),PC("1.2.840.113549.2.5");const LC=PC(OC),HC=(PC(UC),PC(TC),PC(NC),PC(DC),PC("2.16.840.1.101.3.4.2.5"),PC("2.16.840.1.101.3.4.2.6"),new lS({algorithm:MC,parameters:ab.serialize(LC)})),KC=new lS({algorithm:IC,parameters:ab.serialize(Um.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});PC(bC),PC(wC),PC(SC),PC(EC),PC(BC),PC(RC),PC(xC),PC(_C),PC(BC),PC(RC);class QC{constructor(e={}){this.hashAlgorithm=new lS(LC),this.maskGenAlgorithm=new lS({algorithm:MC,parameters:ab.serialize(LC)}),this.pSourceAlgorithm=new lS(KC),Object.assign(this,e)}}cb([rb({type:lS,context:0,defaultValue:LC})],QC.prototype,"hashAlgorithm",void 0),cb([rb({type:lS,context:1,defaultValue:HC})],QC.prototype,"maskGenAlgorithm",void 0),cb([rb({type:lS,context:2,defaultValue:KC})],QC.prototype,"pSourceAlgorithm",void 0),new lS({algorithm:AC,parameters:ab.serialize(new QC)});class VC{constructor(e={}){this.hashAlgorithm=new lS(LC),this.maskGenAlgorithm=new lS({algorithm:MC,parameters:ab.serialize(LC)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}cb([rb({type:lS,context:0,defaultValue:LC})],VC.prototype,"hashAlgorithm",void 0),cb([rb({type:lS,context:1,defaultValue:HC})],VC.prototype,"maskGenAlgorithm",void 0),cb([rb({type:py.Integer,context:2,defaultValue:20})],VC.prototype,"saltLength",void 0),cb([rb({type:py.Integer,context:3,defaultValue:1})],VC.prototype,"trailerField",void 0),new lS({algorithm:vC,parameters:ab.serialize(new VC)});class FC{constructor(e={}){this.digestAlgorithm=new lS,this.digest=new Em,Object.assign(this,e)}}var $C;cb([rb({type:lS})],FC.prototype,"digestAlgorithm",void 0),cb([rb({type:Em})],FC.prototype,"digest",void 0);class jC{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.Integer,converter:_m})],jC.prototype,"prime",void 0),cb([rb({type:py.Integer,converter:_m})],jC.prototype,"exponent",void 0),cb([rb({type:py.Integer,converter:_m})],jC.prototype,"coefficient",void 0);let GC=$C=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,$C.prototype)}};GC=$C=cb([tb({type:gy.Sequence,itemType:jC})],GC);class qC{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)}}cb([rb({type:py.Integer})],qC.prototype,"version",void 0),cb([rb({type:py.Integer,converter:_m})],qC.prototype,"modulus",void 0),cb([rb({type:py.Integer,converter:_m})],qC.prototype,"publicExponent",void 0),cb([rb({type:py.Integer,converter:_m})],qC.prototype,"privateExponent",void 0),cb([rb({type:py.Integer,converter:_m})],qC.prototype,"prime1",void 0),cb([rb({type:py.Integer,converter:_m})],qC.prototype,"prime2",void 0),cb([rb({type:py.Integer,converter:_m})],qC.prototype,"exponent1",void 0),cb([rb({type:py.Integer,converter:_m})],qC.prototype,"exponent2",void 0),cb([rb({type:py.Integer,converter:_m})],qC.prototype,"coefficient",void 0),cb([rb({type:GC,optional:!0})],qC.prototype,"otherPrimeInfos",void 0);class zC{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}var WC;cb([rb({type:py.Integer,converter:_m})],zC.prototype,"modulus",void 0),cb([rb({type:py.Integer,converter:_m})],zC.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"}(WC||(WC={}));const JC=WC;var YC=function(e,t){return YC=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])},YC(e,t)};function XC(e,t){function r(){this.constructor=e}YC(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function ZC(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 ek(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 tk(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(ek(arguments[t]));return e}function rk(e){return!!e.useClass}function sk(e){return!!e.useFactory}var ik=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,tk(t))}}),t},e}();function nk(e){return"string"==typeof e||"symbol"==typeof e}function ok(e){return"object"==typeof e&&"token"in e&&"transform"in e}function ak(e){return!!e.useToken}function ck(e){return null!=e.useValue}var lk=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 hk=lk,uk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return XC(t,e),t}(hk),dk=function(){this.scopedResolutions=new Map};var fk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return XC(t,e),t}(hk),gk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return XC(t,e),t}(hk);const pk=function(){this.preResolution=new fk,this.postResolution=new gk};var yk=new Map,mk=function(){function e(e){this.parent=e,this._registry=new uk,this.interceptors=new pk,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var s;if(void 0===r&&(r={lifecycle:JC.Transient}),this.ensureNotDisposed(),s=function(e){return rk(e)||ck(e)||ak(e)||sk(e)}(t)?t:{useClass:t},ak(s))for(var i=[e],n=s;null!=n;){var o=n.useToken;if(i.includes(o))throw new Error("Token registration cycle detected! "+tk(i,[o]).join(" -> "));i.push(o);var a=this._registry.get(o);n=a&&ak(a.provider)?a.provider:null}if((r.lifecycle===JC.Singleton||r.lifecycle==JC.ContainerScoped||r.lifecycle==JC.ResolutionScoped)&&(ck(s)||sk(s)))throw new Error('Cannot use lifecycle "'+JC[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(),nk(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(),nk(e)){if(nk(t))return this.register(e,{useToken:t},{lifecycle:JC.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:JC.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!nk(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:JC.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new dk),void 0===r&&(r=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&nk(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 ik}(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=ZC(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=ZC(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===JC.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,s=e.options.lifecycle===JC.Singleton,i=e.options.lifecycle===JC.ContainerScoped,n=s||i;return r=ck(e.provider)?e.provider.useValue:ak(e.provider)?n?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):rk(e.provider)?n?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):sk(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===JC.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var s=this;void 0===t&&(t=new dk),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&nk(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=ZC(this._registry.entries()),s=r.next();!s.done;s=r.next()){var i=ek(s.value,2),n=i[0],o=i[1];this._registry.setAll(n,o.filter(function(e){return!ck(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=ZC(this._registry.entries()),n=i.next();!n.done;n=i.next()){var o=ek(n.value,2),a=o[0],c=o[1];c.some(function(e){return e.options.lifecycle===JC.ContainerScoped})&&s._registry.setAll(a,c.map(function(e){return e.options.lifecycle===JC.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 ik)return e.createProxy(function(e){return r.resolve(e,t)});var s,i=function(){var s=yk.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,tk([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?ok(s)?s.multiple?(n=r.resolve(s.transform)).transform.apply(n,tk([r.resolveAll(s.token,new dk,s.isOptional)],s.transformArgs)):(o=r.resolve(s.transform)).transform.apply(o,tk([r.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?r.resolveAll(s.token,new dk,s.isOptional):r.resolve(s.token,e,s.isOptional):ok(s)?(a=r.resolve(s.transform,e)).transform.apply(a,tk([r.resolve(s.token,e)],s.transformArgs)):r.resolve(s,e)}catch(e){throw new Error(function(e,t,r){var s,i,n=ek(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return function(e,t,r){return void 0===r&&(r=" "),tk([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}(),bk=new mk;const Ak=function(e){return function(t){yk.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){bk.register(e,t)}):bk.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 Ik;class vk{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}}cb([rb({type:py.ObjectIdentifier})],vk.prototype,"attrId",void 0),cb([rb({type:py.Any,repeated:"set"})],vk.prototype,"attrValues",void 0);let wk=Ik=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,Ik.prototype)}};var Sk;wk=Ik=cb([tb({type:gy.Sequence,itemType:vk})],wk);let Ek=Sk=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,Sk.prototype)}};Ek=Sk=cb([tb({type:gy.Sequence,itemType:pE})],Ek);class Ck{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],Ck.prototype,"certId",void 0),cb([rb({type:py.Any,context:0})],Ck.prototype,"certValue",void 0);class kk{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],kk.prototype,"crlId",void 0),cb([rb({type:py.Any,context:0})],kk.prototype,"crltValue",void 0);class xk extends Em{}class _k{constructor(e={}){this.encryptionAlgorithm=new lS,this.encryptedData=new xk,Object.assign(this,e)}}var Bk,Rk;cb([rb({type:lS})],_k.prototype,"encryptionAlgorithm",void 0),cb([rb({type:xk})],_k.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(Rk||(Rk={}));class Ok extends Em{}let Uk=Bk=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,Bk.prototype)}};Uk=Bk=cb([tb({type:gy.Sequence,itemType:Xw})],Uk);class Tk{constructor(e={}){this.version=Rk.v1,this.privateKeyAlgorithm=new lS,this.privateKey=new Ok,Object.assign(this,e)}}cb([rb({type:py.Integer})],Tk.prototype,"version",void 0),cb([rb({type:lS})],Tk.prototype,"privateKeyAlgorithm",void 0),cb([rb({type:Ok})],Tk.prototype,"privateKey",void 0),cb([rb({type:Uk,implicit:!0,context:0,optional:!0})],Tk.prototype,"attributes",void 0);let Nk=class extends Tk{};Nk=cb([tb({type:gy.Sequence})],Nk);let Dk=class extends _k{};Dk=cb([tb({type:gy.Sequence})],Dk);class Mk{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],Mk.prototype,"secretTypeId",void 0),cb([rb({type:py.Any,context:0})],Mk.prototype,"secretValue",void 0);class Pk{constructor(e={}){this.mac=new FC,this.macSalt=new Em,this.iterations=1,Object.assign(this,e)}}cb([rb({type:FC})],Pk.prototype,"mac",void 0),cb([rb({type:Em})],Pk.prototype,"macSalt",void 0),cb([rb({type:py.Integer,defaultValue:1})],Pk.prototype,"iterations",void 0);class Lk{constructor(e={}){this.version=3,this.authSafe=new pE,this.macData=new Pk,Object.assign(this,e)}}var Hk;cb([rb({type:py.Integer})],Lk.prototype,"version",void 0),cb([rb({type:pE})],Lk.prototype,"authSafe",void 0),cb([rb({type:Pk,optional:!0})],Lk.prototype,"macData",void 0);class Kk{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:py.ObjectIdentifier})],Kk.prototype,"bagId",void 0),cb([rb({type:py.Any,context:0})],Kk.prototype,"bagValue",void 0),cb([rb({type:vk,repeated:"set",optional:!0})],Kk.prototype,"bagAttributes",void 0);let Qk=Hk=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,Hk.prototype)}};var Vk,Fk,$k;Qk=Hk=cb([tb({type:gy.Sequence,itemType:Kk})],Qk);const jk="1.2.840.113549.1.9",Gk=`${jk}.7`,qk=`${jk}.14`;let zk=class extends Cv{constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};cb([rb({type:py.IA5String})],zk.prototype,"ia5String",void 0),zk=cb([tb({type:gy.Choice})],zk);let Wk=class extends pE{};Wk=cb([tb({type:gy.Sequence})],Wk);let Jk=class extends Lk{};Jk=cb([tb({type:gy.Sequence})],Jk);let Yk=class extends _k{};Yk=cb([tb({type:gy.Sequence})],Yk);let Xk=class{constructor(e=""){this.value=e}toString(){return this.value}};cb([rb({type:py.IA5String})],Xk.prototype,"value",void 0),Xk=cb([tb({type:gy.Choice})],Xk);let Zk=class extends zk{};Zk=cb([tb({type:gy.Choice})],Zk);let ex=class extends Cv{};ex=cb([tb({type:gy.Choice})],ex);let tx=class{constructor(e=new Date){this.value=e}};cb([rb({type:py.GeneralizedTime})],tx.prototype,"value",void 0),tx=cb([tb({type:gy.Choice})],tx);let rx=class extends Cv{};rx=cb([tb({type:gy.Choice})],rx);let sx=class{constructor(e="M"){this.value=e}toString(){return this.value}};cb([rb({type:py.PrintableString})],sx.prototype,"value",void 0),sx=cb([tb({type:gy.Choice})],sx);let ix=class{constructor(e=""){this.value=e}toString(){return this.value}};cb([rb({type:py.PrintableString})],ix.prototype,"value",void 0),ix=cb([tb({type:gy.Choice})],ix);let nx=class extends ix{};nx=cb([tb({type:gy.Choice})],nx);let ox=class extends Cv{};ox=cb([tb({type:gy.Choice})],ox);let ax=class{constructor(e=""){this.value=e}toString(){return this.value}};cb([rb({type:py.ObjectIdentifier})],ax.prototype,"value",void 0),ax=cb([tb({type:gy.Choice})],ax);let cx=class extends uS{};cx=cb([tb({type:gy.Choice})],cx);let lx=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};cb([rb({type:py.Integer})],lx.prototype,"value",void 0),lx=cb([tb({type:gy.Choice})],lx);let hx=class extends TS{};hx=cb([tb({type:gy.Sequence})],hx);let ux=class extends Cv{};ux=cb([tb({type:gy.Choice})],ux);let dx=Vk=class extends pS{constructor(e){super(e),Object.setPrototypeOf(this,Vk.prototype)}};dx=Vk=cb([tb({type:gy.Sequence})],dx);let fx=Fk=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,Fk.prototype)}};fx=Fk=cb([tb({type:gy.Set,itemType:OS})],fx);let gx=class{constructor(e=""){this.value=e}toString(){return this.value}};cb([rb({type:py.BmpString})],gx.prototype,"value",void 0),gx=cb([tb({type:gy.Choice})],gx);let px=class extends lS{};px=cb([tb({type:gy.Sequence})],px);let yx=$k=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,$k.prototype)}};var mx;yx=$k=cb([tb({type:gy.Sequence,itemType:px})],yx);let bx=mx=class extends ob{constructor(e){super(e),Object.setPrototypeOf(this,mx.prototype)}};bx=mx=cb([tb({type:gy.Sequence,itemType:Xw})],bx);class Ax{constructor(e={}){this.version=0,this.subject=new Rv,this.subjectPKInfo=new hS,this.attributes=new bx,Object.assign(this,e)}}cb([rb({type:py.Integer})],Ax.prototype,"version",void 0),cb([rb({type:Rv})],Ax.prototype,"subject",void 0),cb([rb({type:hS})],Ax.prototype,"subjectPKInfo",void 0),cb([rb({type:bx,implicit:!0,context:0})],Ax.prototype,"attributes",void 0);class Ix{constructor(e={}){this.certificationRequestInfo=new Ax,this.signatureAlgorithm=new lS,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}cb([rb({type:Ax})],Ix.prototype,"certificationRequestInfo",void 0),cb([rb({type:lS})],Ix.prototype,"signatureAlgorithm",void 0),cb([rb({type:py.BitString})],Ix.prototype,"signature",void 0);const vx="crypto.algorithm",wx="crypto.algorithmProvider";var Sx;bk.registerSingleton(wx,class{getAlgorithms(){return bk.resolveAll(vx)}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 lS({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 Ex="1.3.36.3.3.2.8.1.1",Cx=`${Ex}.1`,kx=`${Ex}.2`,xx=`${Ex}.3`,_x=`${Ex}.4`,Bx=`${Ex}.5`,Rx=`${Ex}.6`,Ox=`${Ex}.7`,Ux=`${Ex}.8`,Tx=`${Ex}.9`,Nx=`${Ex}.10`,Dx=`${Ex}.11`,Mx=`${Ex}.12`,Px=`${Ex}.13`,Lx=`${Ex}.14`,Hx="brainpoolP160r1",Kx="brainpoolP160t1",Qx="brainpoolP192r1",Vx="brainpoolP192t1",Fx="brainpoolP224r1",$x="brainpoolP224t1",jx="brainpoolP256r1",Gx="brainpoolP256t1",qx="brainpoolP320r1",zx="brainpoolP320t1",Wx="brainpoolP384r1",Jx="brainpoolP384t1",Yx="brainpoolP512r1",Xx="brainpoolP512t1",Zx="ECDSA";let e_=Sx=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===Zx.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return oC;case"sha-256":return aC;case"sha-384":return cC;case"sha-512":return lC}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=rC;break;case"K-256":t=Sx.SECP256K1;break;case"P-384":t=sC;break;case"P-521":t=iC;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;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}if(t)return new lS({algorithm:JE,parameters:ab.serialize(new gC({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case YE:return{name:Zx,hash:{name:"SHA-1"}};case ZE:return{name:Zx,hash:{name:"SHA-256"}};case eC:return{name:Zx,hash:{name:"SHA-384"}};case tC:return{name:Zx,hash:{name:"SHA-512"}};case JE:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(ab.parse(e.parameters,gC).namedCurve){case rC:return{name:Zx,namedCurve:"P-256"};case Sx.SECP256K1:return{name:Zx,namedCurve:"K-256"};case sC:return{name:Zx,namedCurve:"P-384"};case iC:return{name:Zx,namedCurve:"P-521"};case Cx:return{name:Zx,namedCurve:Hx};case kx:return{name:Zx,namedCurve:Kx};case xx:return{name:Zx,namedCurve:Qx};case _x:return{name:Zx,namedCurve:Vx};case Bx:return{name:Zx,namedCurve:Fx};case Rx:return{name:Zx,namedCurve:$x};case Ox:return{name:Zx,namedCurve:jx};case Ux:return{name:Zx,namedCurve:Gx};case Tx:return{name:Zx,namedCurve:qx};case Nx:return{name:Zx,namedCurve:zx};case Dx:return{name:Zx,namedCurve:Wx};case Mx:return{name:Zx,namedCurve:Jx};case Px:return{name:Zx,namedCurve:Yx};case Lx:return{name:Zx,namedCurve:Xx}}}return null}};e_.SECP256K1="1.3.132.0.10",e_=Sx=cb([Ak()],e_),bk.registerSingleton(vx,e_);const t_=Symbol("name"),r_=Symbol("value");class s_{constructor(e,t={},r=""){this[t_]=e,this[r_]=r;for(const e in t)this[e]=t[e]}}s_.NAME=t_,s_.VALUE=r_;class i_{static toString(e){return this.items[e]||e}}i_.items={[OC]:"sha1",[UC]:"sha224",[TC]:"sha256",[NC]:"sha384",[DC]:"sha512",[bC]:"rsaEncryption",[EC]:"sha1WithRSAEncryption",[CC]:"sha224WithRSAEncryption",[kC]:"sha256WithRSAEncryption",[xC]:"sha384WithRSAEncryption",[_C]:"sha512WithRSAEncryption",[JE]:"ecPublicKey",[YE]:"ecdsaWithSHA1",[XE]:"ecdsaWithSHA224",[ZE]:"ecdsaWithSHA256",[eC]:"ecdsaWithSHA384",[tC]:"ecdsaWithSHA512",[_w]:"TLS WWW server authentication",[Bw]:"TLS WWW client authentication",[Rw]:"Code Signing",[Ow]:"E-mail Protection",[Uw]:"Time Stamping",[Tw]:"OCSP Signing",[GE]:"Signed Data"};class n_{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[s_.VALUE];n&&(i=` ${n}`),r.push(`${s}${e[s_.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[s_.NAME]=i,r.push(...this.serializeObj(e,t));else if(n instanceof s_)n[s_.NAME]=i,r.push(...this.serializeObj(n,t));else if(Vg.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[s_.NAME]=i,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),s=Vg.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)}}n_.oidSerializer=i_,n_.algorithmSerializer=class{static toTextObject(e){const t=new s_("Algorithm Identifier",{},i_.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case JE:{const r=(new e_).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class o_{constructor(...e){if(1===e.length){const t=e[0];this.rawData=ab.serialize(t),this.onInit(t)}else{const t=ab.parse(e[0],e[1]);this.rawData=Vg.toArrayBuffer(e[0]),this.onInit(t)}}equal(e){return e instanceof o_&&Yg(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return ab.toString(this.rawData);case"text":return n_.serialize(this.toTextObject());case"hex":return Wg.ToHex(this.rawData);case"base64":return Wg.ToBase64(this.rawData);case"base64url":return Wg.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 s_(this.getTextName(),{},e)}}o_.NAME="ASN";class a_ extends o_{constructor(...e){let t;t=Vg.isBufferSource(e[0])?Vg.toArrayBuffer(e[0]):ab.serialize(new gS({extnID:e[0],critical:e[1],extnValue:new Em(Vg.toArrayBuffer(e[2]))})),super(t,gS)}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[s_.NAME]===a_.NAME&&(e[s_.NAME]=i_.toString(this.type)),e}}var c_;class l_{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[c_]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(l_.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(l_.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=l_.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(l_.DEFAULT,e);return this}}c_=Symbol.toStringTag,l_.DEFAULT="default";const h_=new l_,u_=/^[0-2](?:\.[1-9][0-9]*)+$/;class d_{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(u_).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const f_=new d_;function g_(e,t){return`\\${Wg.ToHex(Wg.FromUtf8String(t)).toUpperCase()}`}f_.register("CN","2.5.4.3"),f_.register("L","2.5.4.7"),f_.register("ST","2.5.4.8"),f_.register("O","2.5.4.10"),f_.register("OU","2.5.4.11"),f_.register("C","2.5.4.6"),f_.register("DC","0.9.2342.19200300.100.1.25"),f_.register("E","1.2.840.113549.1.9.1"),f_.register("G","2.5.4.42"),f_.register("I","2.5.4.43"),f_.register("SN","2.5.4.4"),f_.register("T","2.5.4.12");class p_{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 d_,this.asn=new Rv;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 Rv?this.asn=e:Vg.isBufferSource(e)?this.asn=ab.parse(e,Rv):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||f_.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)||f_.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${Wg.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,g_)}`).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?`#${Wg.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(s)}return t}fromString(e){const t=new Rv,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 _v([a])),i=o}return t}fromJSON(e){const t=new Rv;for(const r of e){const e=new _v;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 xv({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=Wg.FromHex(t.slice(1));else{const s=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=s:p_.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 ab.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]||h_.get()):r=e[0]||h_.get(),await r.subtle.digest(s,this.toArrayBuffer())}}const y_="Cannot initialize GeneralName from ASN.1 data.",m_=`${y_} Unsupported string format in use.`,b_=`${y_} Value doesn't match to GUID regular expression.`,A_=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,I_="1.3.6.1.4.1.311.25.1",v_="1.3.6.1.4.1.311.20.2.3",w_="dns",S_="dn",E_="email",C_="ip",k_="url",x_="guid",__="upn",B_="id";class R_ extends o_{constructor(...e){let t;if(2===e.length)switch(e[0]){case S_:{const r=new p_(e[1]).toArrayBuffer(),s=ab.parse(r,Rv);t=new Nv({directoryName:s});break}case w_:t=new Nv({dNSName:e[1]});break;case E_:t=new Nv({rfc822Name:e[1]});break;case x_:{const r=new RegExp(A_,"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?Wg.ToHex(new Uint8Array(Wg.FromHex(e)).reverse()):e).join("");t=new Nv({otherName:new Uv({typeId:I_,value:ab.serialize(new Em(Wg.FromHex(s)))})});break}case C_:t=new Nv({iPAddress:e[1]});break;case B_:t=new Nv({registeredID:e[1]});break;case __:t=new Nv({otherName:new Uv({typeId:v_,value:ab.serialize(Dm.toASN(e[1]))})});break;case k_:t=new Nv({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=Vg.isBufferSource(e[0])?ab.parse(e[0],Nv):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=w_,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=E_,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=C_,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=k_,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=B_,this.value=e.registeredID;else if(null!=e.directoryName)this.type=S_,this.value=new p_(e.directoryName).toString();else{if(null==e.otherName)throw new Error(m_);if(e.otherName.typeId===I_){this.type=x_;const t=ab.parse(e.otherName.value,Em),r=new RegExp(A_,"i").exec(Wg.ToHex(t));if(!r)throw new Error(b_);this.value=r.slice(1).map((e,t)=>t<3?Wg.ToHex(new Uint8Array(Wg.FromHex(e)).reverse()):e).join("-")}else{if(e.otherName.typeId!==v_)throw new Error(m_);this.type=__,this.value=ab.parse(e.otherName.value,Cv).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case S_:case w_:case x_:case C_:case B_:case __:case k_:e=this.type.toUpperCase();break;case E_:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===B_&&(t=i_.toString(t)),new s_(e,void 0,t)}}class O_ extends o_{constructor(e){let t;if(e instanceof Zv)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof Nv)r.push(t);else{const e=ab.parse(new R_(t.type,t.value).rawData,Nv);r.push(e)}t=new Zv(r)}else{if(!Vg.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=ab.parse(e,Zv)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new R_(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[s_.NAME]];Array.isArray(s)||(s=[],e[r[s_.NAME]]=s),s.push(r)}return e}}O_.NAME="GeneralNames";const U_="-{5}",T_="\\n",N_="\\n",D_=`${U_}BEGIN ([^${T_}]+(?=${U_}))${U_}${N_}(?:((?:[^:${T_}]+: (?:[^${T_}]+${N_}(?: +[^${T_}]+${N_})*))+))?${N_}?((?:[a-zA-Z0-9=+/]+${N_})+)${U_}END \\1${U_}`;class M_{static isPem(e){return"string"==typeof e&&new RegExp(D_,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(D_,"g"),r=[];let s=null;for(;s=t.exec(e);){const e=s[3].replace(new RegExp(`[${T_}]+`,"g"),""),t={type:s[1],headers:[],rawData:Wg.FromBase64(e)},i=s[2];if(i){const e=i.split(new RegExp(N_,"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(!Vg.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:Vg.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:Vg.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=Wg.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")}}M_.CertificateTag="CERTIFICATE",M_.CrlTag="CRL",M_.CertificateRequestTag="CERTIFICATE REQUEST",M_.PublicKeyTag="PUBLIC KEY",M_.PrivateKeyTag="PRIVATE KEY";class P_ extends o_{static isAsnEncoded(e){return Vg.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(M_.isPem(e))return M_.decode(e)[0];if(Wg.isHex(e))return Wg.FromHex(e);if(Wg.isBase64(e))return Wg.FromBase64(e);if(Wg.isBase64Url(e))return Wg.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=Wg.ToBinary(e);return M_.isPem(t)?M_.decode(t)[0]:Wg.isHex(t)?Wg.FromHex(t):Wg.isBase64(t)?Wg.FromBase64(t):Wg.isBase64Url(t)?Wg.FromBase64Url(t):Vg.toArrayBuffer(e)}}constructor(...e){P_.isAsnEncoded(e[0])?super(P_.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?M_.encode(this.rawData,this.tag):super.toString(e)}}class L_ extends P_{static async create(e,t=h_.get()){if(e instanceof L_)return e;if(l_.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new L_(r)}if(e.publicKey)return e.publicKey;if(Vg.isBufferSource(e))return new L_(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){P_.isAsnEncoded(e)?super(e,hS):super(e),this.tag=M_.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]||h_.get()):t=e[0]||h_.get();let i=this.rawData;const n=ab.parse(this.rawData,hS);return n.algorithm.algorithm===vC&&(i=function(e){return e.algorithm=new lS({algorithm:bC,parameters:null}),ab.serialize(e)}(n)),t.subtle.importKey("spki",i,s,!0,r)}onInit(e){const t=bk.resolve(wx),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case bC:{const t=ab.parse(e.subjectPublicKey,zC),s=Vg.toUint8Array(t.modulus);r.publicExponent=Vg.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]||h_.get()):r=e[0]||h_.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=h_.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=h_.get();const s=ab.parse(this.rawData,hS);return await t.subtle.digest(r,s.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=ab.parse(this.rawData,hS);return e.Algorithm=n_.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===JE?e["EC Point"]=t.subjectPublicKey:e["Raw Data"]=t.subjectPublicKey,e}}class H_ extends a_{static async create(e,t=!1,r=h_.get()){if("name"in e&&"serialNumber"in e)return new H_(e,t);const s=await L_.create(e,r),i=await s.getKeyIdentifier(r);return new H_(Wg.ToHex(i),t)}constructor(...e){if(Vg.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new Wv({keyIdentifier:new zv(Wg.FromHex(e[0]))});super(qv,e[1],ab.serialize(t))}else{const t=e[0],r=t.name instanceof O_?ab.parse(t.name.rawData,Zv):t.name,s=new Wv({authorityCertIssuer:r,authorityCertSerialNumber:Wg.FromHex(t.serialNumber)});super(qv,e[1],ab.serialize(s))}}onInit(e){super.onInit(e);const t=ab.parse(e.extnValue,Wv);t.keyIdentifier&&(this.keyId=Wg.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Wg.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=ab.parse(this.value,Wv);return t.authorityCertIssuer&&(e["Authority Issuer"]=new O_(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}H_.NAME="Authority Key Identifier";class K_ extends a_{constructor(...e){if(Vg.isBufferSource(e[0])){super(e[0]);const t=ab.parse(this.value,Yv);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new Yv({cA:e[0],pathLenConstraint:e[1]});super(Jv,e[2],ab.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 Q_,V_;K_.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"}(Q_||(Q_={}));class F_ extends a_{constructor(...e){if(Vg.isBufferSource(e[0])){super(e[0]);const t=ab.parse(this.value,xw);this.usages=t.map(e=>e)}else{const t=new xw(e[0]);super(kw,e[1],ab.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(e=>i_.toString(e)).join(", "),e}}F_.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"}(V_||(V_={}));class $_ extends a_{constructor(...e){if(Vg.isBufferSource(e[0])){super(e[0]);const t=ab.parse(this.value,Qw);this.usages=t.toNumber()}else{const t=new Qw(e[0]);super(Lw,e[1],ab.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=ab.parse(this.value,Qw);return e[""]=t.toJSON().join(", "),e}}$_.NAME="Key Usages";class j_ extends a_{static async create(e,t=!1,r=h_.get()){const s=await L_.create(e,r),i=await s.getKeyIdentifier(r);return new j_(Wg.ToHex(i),t)}constructor(...e){if(Vg.isBufferSource(e[0])){super(e[0]);const t=ab.parse(this.value,rS);this.keyId=Wg.ToHex(t)}else{const t="string"==typeof e[0]?Wg.FromHex(e[0]):e[0],r=new rS(t);super(tS,e[1],ab.serialize(r)),this.keyId=Wg.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=ab.parse(this.value,rS);return e[""]=t,e}}j_.NAME="Subject Key Identifier";class G_ extends a_{constructor(...e){Vg.isBufferSource(e[0])?super(e[0]):super(Jw,e[1],new O_(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=ab.parse(e.extnValue,Yw);this.names=new O_(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}G_.NAME="Subject Alternative Name";class q_{static register(e,t){this.items.set(e,t)}static create(e){const t=new a_(e),r=this.items.get(t.type);return r?new r(e):t}}q_.items=new Map;class z_ extends a_{constructor(...e){var t;if(Vg.isBufferSource(e[0])){super(e[0]);const t=ab.parse(this.value,hw);this.policies=t.map(e=>e.policyIdentifier)}else{const r=e[0],s=null!==(t=e[1])&&void 0!==t&&t,i=new hw(r.map(e=>new lw({policyIdentifier:e})));super(sw,s,ab.serialize(i)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new s_("",{},i_.toString(e))),e}}z_.NAME="Certificate Policies",q_.register(sw,z_);class W_ extends a_{constructor(...e){var t;if(Vg.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map(e=>new bw({distributionPoint:new mw({fullName:[new Nv({uniformResourceIdentifier:e})]})})),r=new Aw(t);super(gw,e[1],ab.serialize(r))}else{const t=new Aw(e[0]);super(gw,e[1],ab.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=ab.parse(e.extnValue,Aw);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 R_(e).toString()).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map(e=>e.toString()).join(", ")),r}),e}}W_.NAME="CRL Distribution Points";class J_ extends a_{constructor(...e){var t,r,s,i;if(Vg.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Gv){const t=new Gv(e[0]);super($v,e[1],ab.serialize(t))}else{const t=e[0],r=new Gv;X_(r,t,Lv,"ocsp"),X_(r,t,Hv,"caIssuers"),X_(r,t,Kv,"timeStamping"),X_(r,t,Qv,"caRepository"),super($v,e[1],ab.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=[],ab.parse(e.extnValue,Gv).forEach(e=>{switch(e.accessMethod){case Lv:this.ocsp.push(new R_(e.accessLocation));break;case Hv:this.caIssuers.push(new R_(e.accessLocation));break;case Kv:this.timeStamping.push(new R_(e.accessLocation));break;case Qv:this.caRepository.push(new R_(e.accessLocation))}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&Y_(e,"OCSP",this.ocsp),this.caIssuers.length&&Y_(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Y_(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Y_(e,"CA Repository",this.caRepository),e}}function Y_(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const s=new s_("");r.forEach((e,t)=>{const r=e.toTextObject(),i=`${r[s_.NAME]} ${t+1}`;let n=s[i];Array.isArray(n)||(n=[],s[i]=n),n.push(r)}),e[t]=s}}function X_(e,t,r,s){const i=t[s];i&&(Array.isArray(i)?i:[i]).forEach(t=>{"string"==typeof t&&(t=new R_("url",t)),e.push(new jv({accessMethod:r,accessLocation:ab.parse(t.rawData,Nv)}))})}J_.NAME="Authority Info Access";class Z_ extends o_{constructor(...e){let t;if(Vg.isBufferSource(e[0]))t=Vg.toArrayBuffer(e[0]);else{const r=e[0],s=Array.isArray(e[1])?e[1].map(e=>Vg.toArrayBuffer(e)):[];t=ab.serialize(new Xw({type:r,values:s}))}super(t,Xw)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new s_("",{"":e})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[s_.NAME]===Z_.NAME&&(e[s_.NAME]=i_.toString(this.type)),e}}Z_.NAME="Attribute";class eB extends Z_{constructor(...e){var t;if(Vg.isBufferSource(e[0]))super(e[0]);else{const t=new ux({printableString:e[0]});super(Gk,[ab.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=ab.parse(this.values[0],ux);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[s_.VALUE]=this.password,e}}eB.NAME="Challenge Password";class tB extends Z_{constructor(...e){var t;if(Vg.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new pS;for(const e of t)r.push(ab.parse(e.rawData,gS));super(qk,[ab.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=ab.parse(this.values[0],pS);this.items=e.map(e=>q_.create(ab.serialize(e)))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(const r of t)e[r[s_.NAME]]=r;return e}}tB.NAME="Extensions";class rB{static register(e,t){this.items.set(e,t)}static create(e){const t=new Z_(e),r=this.items.get(t.type);return r?new r(e):t}}rB.items=new Map;const sB="crypto.signatureFormatter";var iB;let nB=iB=class{static createPssParams(e,t){const r=iB.getHashAlgorithm(e);return r?new VC({hashAlgorithm:r,maskGenAlgorithm:new lS({algorithm:MC,parameters:ab.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=bk.resolve(wx);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 lS({algorithm:bC,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 lS({algorithm:EC,parameters:null});case"sha-256":return new lS({algorithm:kC,parameters:null});case"sha-384":return new lS({algorithm:xC,parameters:null});case"sha-512":return new lS({algorithm:_C,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=iB.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new lS({algorithm:vC,parameters:ab.serialize(t)})}return new lS({algorithm:vC,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case bC:return{name:"RSASSA-PKCS1-v1_5"};case EC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case kC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case xC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case _C:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case vC:if(e.parameters){const t=ab.parse(e.parameters,VC);return{name:"RSA-PSS",hash:bk.resolve(wx).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};nB=iB=cb([Ak()],nB),bk.registerSingleton(vx,nB);let oB=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new lS({algorithm:OC});case"sha-256":return new lS({algorithm:TC});case"sha-384":return new lS({algorithm:NC});case"sha-512":return new lS({algorithm:DC})}return null}toWebAlgorithm(e){switch(e.algorithm){case OC:return{name:"SHA-1"};case TC:return{name:"SHA-256"};case NC:return{name:"SHA-384"};case DC:return{name:"SHA-512"}}return null}};oB=cb([Ak()],oB),bk.registerSingleton(vx,oB);class aB{addPadding(e,t){const r=Vg.toUint8Array(t),s=new Uint8Array(e);return s.set(r,e-r.length),s}removePadding(e,t=!1){let r=Vg.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=aB.namedCurveSize.get(r)||aB.defaultNamedCurveSize,i=new yC,n=Vg.toUint8Array(t);return i.r=this.removePadding(n.slice(0,s),!0),i.s=this.removePadding(n.slice(s,s+s),!0),ab.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=ab.parse(t,yC),s=e.namedCurve,i=aB.namedCurveSize.get(s)||aB.defaultNamedCurveSize;return Jg(this.addPadding(i,this.removePadding(r.r)),this.addPadding(i,this.removePadding(r.s)))}return null}}aB.namedCurveSize=new Map,aB.defaultNamedCurveSize=32;const cB="1.3.101.110",lB="1.3.101.111",hB="1.3.101.112",uB="1.3.101.113";let dB=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=hB;break;case"x25519":t=cB;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=hB;break;case"ed448":t=uB}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=cB;break;case"x448":t=lB}}return t?new lS({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case hB:return{name:"Ed25519"};case uB:return{name:"EdDSA",namedCurve:"Ed448"};case cB:return{name:"X25519"};case lB:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};dB=cb([Ak()],dB),bk.registerSingleton(vx,dB);(class extends P_{constructor(e){P_.isAsnEncoded(e)?super(e,Ix):super(e),this.tag=M_.CertificateRequestTag}onInit(e){this.tbs=ab.serialize(e.certificationRequestInfo),this.publicKey=new L_(e.certificationRequestInfo.subjectPKInfo);const t=bk.resolve(wx);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>rB.create(ab.serialize(e)));const r=this.getAttribute(qk);this.extensions=[],r instanceof tB&&(this.extensions=r.items),this.subjectName=new p_(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=h_.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),s=bk.resolveAll(sB).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=ab.parse(this.rawData,Ix),r=t.certificationRequestInfo,s=new s_("",{Version:`${yS[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new s_("");for(const t of this.attributes){const r=t.toTextObject();e[r[s_.NAME]]=r}s.Attributes=e}return e.Data=s,e.Signature=new s_("",{Algorithm:n_.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";var fB;(class extends P_{constructor(e){P_.isAsnEncoded(e)?super(e,bS):super(e),this.tag=M_.CertificateTag}onInit(e){const t=e.tbsCertificate;this.tbs=ab.serialize(t),this.serialNumber=Wg.ToHex(t.serialNumber),this.subjectName=new p_(t.subject),this.subject=new p_(t.subject).toString(),this.issuerName=new p_(t.issuer),this.issuer=this.issuerName.toString();const r=bk.resolve(wx);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=>q_.create(ab.serialize(e)))),this.publicKey=new L_(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=h_.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 L_)r={...i.algorithm,...this.signatureAlgorithm},s=await i.export(r,["verify"],t);else if(Vg.isBufferSource(i)){const e=new L_(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=bk.resolveAll(sB).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=h_.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=h_.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=ab.parse(this.rawData,bS),r=t.tbsCertificate,s=new s_("",{Version:`${yS[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":n_.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new s_("",{"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 s_("");for(const t of this.extensions){const r=t.toTextObject();e[r[s_.NAME]]=r}s.Extensions=e}return e.Data=s,e.Signature=new s_("",{Algorithm:n_.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"}(fB||(fB={})),q_.register(Jv,K_),q_.register(kw,F_),q_.register(Lw,$_),q_.register(tS,j_),q_.register(qv,H_),q_.register(Jw,G_),q_.register(gw,W_),q_.register($v,J_),rB.register(Gk,eB),rB.register(qk,tB),bk.registerSingleton(sB,class{toAsnSignature(e,t){return Vg.toArrayBuffer(t)}toWebSignature(e,t){return Vg.toArrayBuffer(t)}}),bk.registerSingleton(sB,aB),aB.namedCurveSize.set("P-256",32),aB.namedCurveSize.set("K-256",32),aB.namedCurveSize.set("P-384",48),aB.namedCurveSize.set("P-521",66),m.new(void 0,"networking");const gB=new class extends WA{constructor(){super(...arguments),this.subtle=new Iv}getRandomValues(e){if(!ArrayBuffer.isView(e))throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'");const t=eI.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return rI().randomFillSync(t),e}};var pB,yB,mB;function bB(e){return pe(e)}h_.set(gB),(mB=pB||(pB={}))[mB.NoCertificate=0]="NoCertificate",mB[mB.NotEd25519=1]="NotEd25519",mB[mB.PublicKeyTypeMismatch=2]="PublicKeyTypeMismatch",mB[mB.AltNameMismatch=3]="AltNameMismatch",mB[mB.IncorrectSignature=4]="IncorrectSignature",function(e){e[e.Public=0]="Public",e[e.Private=1]="Private"}(yB||(yB={})),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 AB=bB(0);class IB extends G{hash;slot;static Codec=Ve.Class(IB,{hash:Ve.bytes(Rt).asOpaque(),slot:Ve.u32.asOpaque()});static create({hash:e,slot:t}){return new IB(e,t)}constructor(e,t){super(),this.hash=e,this.slot=t}}class vB{final;leafs;static Codec=Ve.Class(vB,{final:IB.Codec,leafs:Ve.sequenceVarLen(IB.Codec)});static create({final:e,leafs:t}){return new vB(e,t)}constructor(e,t){this.final=e,this.leafs=t}}class wB extends G{header;final;static Codec=Ve.Class(wB,{header:hs.Codec,final:IB.Codec});static create({header:e,final:t}){return new wB(e,t)}constructor(e,t){super(),this.header=e,this.final=t}}const SB=m.new(void 0,"protocol/up-0");class EB{getHandshake;onAnnouncement;kind=AB;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(vB.Codec,t);return this.handshakes.set(r,s),void(this.pendingHandshakes.delete(r)||(SB.log(`[${r}] <-- responding with a handshake.`),e.bufferAndSend(Te.encodeObject(vB.Codec,this.getHandshake()))))}const s=xe.decodeObject(wB.Codec,t);SB.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(vB.Codec,t))}sendAnnouncement(e,t){this.handshakes.has(e.streamId)?e.bufferAndSend(Te.encodeObject(wB.Codec,t)):SB.warn(`[${e.streamId}] no handshake yet, skipping announcement.`)}}var CB;bB(128),function(e){e[e.AscExcl=0]="AscExcl",e[e.DescIncl=1]="DescIncl"}(CB||(CB={}));class kB extends G{headerHash;direction;maxBlocks;static Codec=Ve.Class(kB,{headerHash:Ve.bytes(Rt).asOpaque(),direction:Ve.u8.convert(e=>pe(e),e=>{switch(e){case CB.AscExcl:return CB.AscExcl;case CB.DescIncl:return CB.DescIncl;default:throw new Error(`Invalid 'Direction' value: ${e}`)}}),maxBlocks:Ve.u32});static create({headerHash:e,direction:t,maxBlocks:r}){return new kB(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 xB=bB(129),_B=Ve.bytes(64).convert(e=>re.fromBlob(e.raw,64),e=>new Ji(e.raw));class BB extends G{key;value;static Codec=Ve.Class(BB,{key:Ve.bytes(zi),value:Ve.blob});static create({key:e,value:t}){return new BB(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}class RB extends G{keyValuePairs;static Codec=Ve.Class(RB,{keyValuePairs:Ve.sequenceVarLen(BB.Codec)});static create({keyValuePairs:e}){return new RB(e)}constructor(e){super(),this.keyValuePairs=e}}class OB extends G{headerHash;startKey;endKey;maximumSize;static Codec=Ve.Class(OB,{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 OB(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.startKey=t,this.endKey=r,this.maximumSize=s}}const UB=m.new(void 0,"protocol/ce-129");class TB{isServer;getBoundaryNodes;getKeyValuePairs;kind=xB;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(UB.info(`[${e.streamId}][server]: Received request.`),void 0===this.getBoundaryNodes||void 0===this.getKeyValuePairs)return;const r=xe.decodeObject(OB.Codec,t),s=this.getBoundaryNodes(r.headerHash,r.startKey,r.endKey),i=this.getKeyValuePairs(r.headerHash,r.startKey,r.endKey);return UB.info(`[${e.streamId}][server]: <-- responding with boundary nodes and key value pairs.`),e.bufferAndSend(Te.encodeObject(Ve.sequenceVarLen(_B),s)),e.bufferAndSend(Te.encodeObject(RB.Codec,RB.create({keyValuePairs:i}))),void e.close()}if(!this.boundaryNodes.has(e.streamId))return this.boundaryNodes.set(e.streamId,xe.decodeObject(Ve.sequenceVarLen(_B),t)),void UB.info(`[${e.streamId}][client]: Received boundary nodes.`);this.onResponse.get(e.streamId)?.(xe.decodeObject(RB.Codec,t)),UB.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(OB.Codec,OB.create({headerHash:t,startKey:r,endKey:r,maximumSize:Ae(4096)}))),e.close()}}bB(131),bB(132);class NB extends G{epochIndex;ticket;static Codec=Ve.Class(NB,{epochIndex:Ve.u32.asOpaque(),ticket:is.Codec});static create({epochIndex:e,ticket:t}){return new NB(e,t)}constructor(e,t){super(),this.epochIndex=e,this.ticket=t}}m.new(void 0,"protocol/ce-131-ce-132"),bB(133);class DB extends G{coreIndex;workPackage;static Codec=Ve.Class(DB,{coreIndex:Ve.u16.asOpaque(),workPackage:jr.Codec});static create({coreIndex:e,workPackage:t}){return new DB(e,t)}constructor(e,t){super(),this.coreIndex=e,this.workPackage=t}}m.new(void 0,"protocol/ce-133"),Ve.blob,bB(134);class MB extends G{coreIndex;segmentsRootMappings;static Codec=Ve.Class(MB,{coreIndex:Ve.u16.asOpaque(),segmentsRootMappings:Ve.sequenceVarLen(Xr.Codec)});static create({coreIndex:e,segmentsRootMappings:t}){return new MB(e,t)}constructor(e,t){super(),this.coreIndex=e,this.segmentsRootMappings=t}}class PB extends G{workReportHash;signature;static Codec=Ve.Class(PB,{workReportHash:Ve.bytes(Rt).asOpaque(),signature:Ve.bytes(Et).asOpaque()});static create({workReportHash:e,signature:t}){return new PB(e,t)}constructor(e,t){super(),this.workReportHash=e,this.signature=t}}m.new(void 0,"protocol/ce-134"),bB(135);class LB extends G{report;slot;signatures;static Codec=Ve.Class(LB,{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 LB(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 HB=t(import.meta.url)("node:net"),KB=t(import.meta.url)("node:path"),QB=t(import.meta.url)("node:buffer");var VB;!function(e){e[e.Msg=0]="Msg",e[e.Open=1]="Open",e[e.Close=2]="Close"}(VB||(VB={}));class FB{streamId;type;data;static Codec=Ve.Class(FB,{streamId:Ve.u32,type:Ve.u8.convert(e=>pe(e),e=>{switch(e){case VB.Msg:return VB.Msg;case VB.Open:return VB.Open;case VB.Close:return VB.Close;default:throw new Error(`Invalid 'StreamEnvelopeType' value: ${e}`)}}),data:Ve.blob});static create({streamId:e,type:t,data:r}){return new FB(e,t,r)}constructor(e,t,r){this.streamId=e,this.type=t,this.data=r}}class $B{streamByte;static Codec=Ve.Class($B,{streamByte:Ve.u8});static create({streamByte:e}){return new $B(e)}constructor(e){this.streamByte=e}}const jB=m.new(void 0,"ext-ipc");class GB{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 zB(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 qB(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 qB(i,this.sender);n.open($B.create({streamByte:e})),t(r,n)}onSocketMessage(e){const t=xe.decodeObject(FB.Codec,e),r=t.streamId;jB.log(`[${r}] incoming message: ${t.type} ${t.data}`);const s=this.streams.get(r),i=new qB(r,this.sender);if(void 0===s){if(t.type!==VB.Open)return void jB.warn(`[${r}] (unknown) got invalid type ${t.type}.`);const e=xe.decodeObject($B.Codec,t.data),s=this.streamHandlers.get(e.streamByte);return void 0!==s?(jB.log(`[${r}] new stream for ${s.kind}`),this.streams.set(r,s),void i.open(e)):void i.close()}if(t.type===VB.Close){const e=this.streams.get(r);return e?.onClose(r,!1),void this.streams.delete(r)}t.type===VB.Msg?s.onStreamMessage(i,t.data):this.pendingStreams.delete(r)||jB.warn(`[${r}] got invalid type ${t.type}.`)}onClose({error:e}){jB.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 jB.log("Waiting for the handler to be closed."),this.onEnd.listen}}class qB{streamId;sender;constructor(e,t){this.streamId=e,this.sender=t}open(e){const t=Te.encodeObject($B.Codec,e);this.sender.send(Te.encodeObject(FB.Codec,FB.create({streamId:this.streamId,type:VB.Open,data:t})))}bufferAndSend(e){return this.sender.send(Te.encodeObject(FB.Codec,FB.create({streamId:this.streamId,type:VB.Msg,data:e}))),!0}close(){this.sender.send(Te.encodeObject(FB.Codec,FB.create({streamId:this.streamId,type:VB.Close,data:te.blobFromNumbers([])})))}}class zB{socket;constructor(e){this.socket=e}send(e){!function(e,t){const r=new Uint8Array(WB);Te.create({destination:r}).i32(t.length),e.write(r),e.write(t)}(this.socket,e.raw)}close(){this.socket.end()}}const WB=4;function JB(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=IB.create({hash:i,slot:s.timeSlotIndex});r=n,t.emit("announcement",wB.create({header:s,final:n}))}),function(e,t,r,s){const i="win32"===b.platform()?"\\\\.\\pipe\\typeberry":KB.join(b.tmpdir(),"typeberry.ipc"),n=m.new(void 0,"ext-ipc"),o=(0,HB.createServer)(i=>{n.log("Client connected");const o=new GB(i);o.registerHandlers(new EB(t,()=>{})),o.registerHandlers(new TB(!0,r,s));const a=e=>{if(!(e instanceof wB))throw new Error(`Invalid annoncement received: ${e}`);o.withStreamOfKind(AB,(t,r)=>{t.sendAnnouncement(r,e)})};e.on("announcement",a),i.on("data",function(e){let t=QB.Buffer.alloc(0),r=-1;return s=>{t=QB.Buffer.concat([t,s]);do{if(-1===r){if(t.length<WB)break;r=t.readUint32LE(),t=t.subarray(WB)}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??IB.create({hash:re.zero(Rt).asOpaque(),slot:_r(0)});return vB.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 BB(t,r)]})}(e);return()=>{t()}}const YB=e=>e.endsWith(".json");function XB(e,t){const r=U().readFileSync(e),s=te.blobFrom(new Uint8Array(r));return xe.decodeObject(ys.Codec.View,s,t)}function ZB(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})=>ps.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 eR=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"}'),tR=m.new(void 0,"jam");var rR;async function sR(e,t){if(!T.isMainThread)return void tR.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:cR(e.args.configPath)},s=oR(r.config.flavor),{rootDb:i,dbPath:n,genesisHeaderHash:o}=aR(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(tR.log(`🛢️ Best header hash: ${o}`),tR.log(`🛢️ Best state root: ${a}`),null!==a&&!a.isEqualTo(re.zero(Rt))&&!o.isEqualTo(re.zero(Rt)))return void await r.db.close();tR.log("🛢️ Database looks fresh. Initializing.");const c=xe.decodeObject(hs.Codec,s.genesisHeader,e),l=ys.create({header:hs.empty(),extrinsic:ps.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);tR.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 tR.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=vh,t=new Ah;return Qn(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/importer/index.ts"),e,"ready(main)",t)}(),c=JB({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=nR(h,s,r.blocksToImport),d=await iR(r.isAuthoring,l,h);tR.info("[main]⌛ waiting for importer to finish");const f=await u;tR.log("[main] ☠️ Closing the extensions"),c(),tR.log("[main]⌛ waiting for tasks to finish"),await f.currentState().waitForWorkerToFinish(),tR.log("[main] ☠️ Closing the authorship module"),d(),tR.info("[main] ✅ Done.")}!function(e){e[e.InMemory=0]="InMemory",e[e.Lmdb=1]="Lmdb"}(rR||(rR={}));const iR=async(e,t,r)=>{if(!e)return()=>Promise.resolve();tR.info("✍️ Starting block generator.");const{generator:s,finish:i}=await async function(e){const t=(await async function(){const e=_h,t=new kh;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=>{tR.log(`✍️ Produced block. Size: [${r.length}]`),e.sendBlock(t,r)})}),i},nR=async(e,t,r)=>null===r?e.waitForState("finished"):(tR.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=YB(r)?ZB(r,t):XB(r,t);yield e}}({files:r,chainSpec:t});for(const t of i)tR.log(`📖 Importing block: #${t.header.view().timeSlotIndex.materialize()}`),e.sendBlock(s,t.encoded().raw);return tR.info("All blocks scheduled to be imported."),e.finish(s)})),oR=e=>{if(e===Js.Full)return pr;if(e===Js.Tiny)return gr;throw new Error(`Unknown chain spec: ${e}. Possible options: ${[Js.Full,Js.Tiny]}`)};function aR(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)}`;tR.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 cR(e){if(e===v)return bs(eR,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)}sR(r,t).catch(e=>{console.error(`${e}`),process.exit(-1)})}let lR;m.configureAll(process.env.JAM_LOG??"",l.LOG);try{lR=_(process.argv.slice(2),hR)}catch(e){console.error(`\n${e}\n`),console.info(S),process.exit(1)}function hR(e){return e}sR(lR,hR).catch(e=>{console.error(`${e}`),process.exit(-1)});export{k as Command,w as DEFAULTS,v as DEV_CONFIG,rR as DatabaseKind,S as HELP,oR as getChainSpec,cR as loadConfig,sR as main,aR as openDatabase,_ as parseArgs};
|
|
2
|
+
import{fileURLToPath as e}from"node:url";import{createRequire as t}from"node:module";import*as r from"lmdb";import*as s from"minimist";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),a=r(8),o=r(8),c=r(8),l=r(154),d=r(984),u=r(872),h=r(984);class f{getValue(){return this.value}toBinaryString(){return o.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 g 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 g(e)}static fromDecimalDottedString(e){return new g(e)}static fromString(e){return g.fromDecimalDottedString(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new g(a.parseBinaryStringToBigInt(e));throw Error(t[1].join(","))}toString(){return this.octets.map(e=>e.toString()).join(this.separator)}getOctets(){return this.octets}nextIPNumber(){return g.fromNumber(this.getValue()+1n)}previousIPNumber(){return g.fromNumber(this.getValue()-1n)}toIPv4MappedIPv6(){let e="1".repeat(16)+this.toBinaryString();return b.fromBinaryString(e)}constructFromDecimalDottedString(e){let t,r,[a,o]=i.Validator.isValidIPv4String(e);if(!a)throw new Error(o.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=o.leftPadWithZeroBit(e,32)),e.match(/.{1,8}/g).map(e=>s.Octet.fromString(a.parseBinaryStringToBigInt(e).toString()))}}t.IPv4=g;class p extends f{constructor(e){if(super(),this.bitSize=32,this.maximumBitSize=i.Validator.THIRTY_TWO_BIT_SIZE,this.type="ASN","string"==typeof e)p.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 p(e)}static fromNumber(e){return new p(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new p(parseInt(e,2));throw Error(t[1].join(","))}toString(){let e=this.value.toString();return`${p.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 p(this.value.valueOf()+1n)}previousIPNumber(){return new p(this.value.valueOf()-1n)}static startWithASPrefix(e){return 0===e.indexOf(p.AS_PREFIX)}parseFromDotNotation(e){let t=e.split("."),r=parseInt(t[0]);return 65535*r+(parseInt(t[1])+r)}}t.Asn=p,p.AS_PREFIX="AS";class b 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 b(e)}static fromHexadecatet(e){return new b(e)}static fromString(e){return b.fromHexadecatet(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0]){let t=o.leftPadWithZeroBit(e,128);return new b(a.parseBinaryStringToBigInt(t))}throw Error(t[1].join(","))}static fromIPv4(e){return e.toIPv4MappedIPv6()}static fromIPv4DotDecimalString(e){return new g(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 b.fromBigInt(this.getValue()+1n)}previousIPNumber(){return b.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${h.hexadectetNotationToBinaryString(e)}`),s]}binaryStringToHexadecatets(e){let t=d.binaryStringToHexadecimalString(e);for(;t.length%4!=0;)t="0"+t;return t.match(/.{1,4}/g).map(e=>l.Hexadecatet.fromString(e))}}t.IPv6=b;class m extends g{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 a=e.split(".");this.octets=a.map(e=>s.Octet.fromString(e));let o=n.dottedDecimalNotationToBinaryString(e);this.prefix=(o.match(/1/g)||[]).length,this.value=BigInt(`0b${o}`)}static fromDecimalDottedString(e){return new m(e)}}t.IPv4Mask=m;class y extends b{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 a=h.hexadectetNotationToBinaryString(s);this.prefix=(a.match(/1/g)||[]).length,this.value=BigInt(`0b${a}`),this.value=BigInt(`0b${h.hexadectetNotationToBinaryString(s)}`)}static fromHexadecatet(e){return new y(e)}}t.IPv6Mask=y,t.isIPv4=function(e){return 32===e.bitSize}},239:(t,r,s)=>{var i=e(import.meta.url+"/..").slice(0,-1);let n,a=null;function o(){return null!==a&&0!==a.byteLength||(a=new Uint8Array(n.memory.buffer)),a}let c=0;function l(e,t){const r=t(1*e.length,1)>>>0;return o().set(e,r/1),c=e.length,r}let d=null;function u(){return null!==d&&0!==d.byteLength||(d=new Int32Array(n.memory.buffer)),d}function h(e,t){return e>>>=0,o().subarray(e/1,e/1+t)}t.exports.ring_commitment=function(e){try{const i=n.__wbindgen_add_to_stack_pointer(-16),a=l(e,n.__wbindgen_malloc),o=c;n.ring_commitment(i,a,o);var t=u()[i/4+0],r=u()[i/4+1],s=h(t,r).slice();return n.__wbindgen_free(t,1*r,1),s}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.derive_public_key=function(e){try{const i=n.__wbindgen_add_to_stack_pointer(-16),a=l(e,n.__wbindgen_malloc),o=c;n.derive_public_key(i,a,o);var t=u()[i/4+0],r=u()[i/4+1],s=h(t,r).slice();return n.__wbindgen_free(t,1*r,1),s}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.verify_seal=function(e,t,r,s,i){try{const f=n.__wbindgen_add_to_stack_pointer(-16),g=l(e,n.__wbindgen_malloc),p=c,b=l(r,n.__wbindgen_malloc),m=c,y=l(s,n.__wbindgen_malloc),A=c,I=l(i,n.__wbindgen_malloc),v=c;n.verify_seal(f,g,p,t,b,m,y,A,I,v);var a=u()[f/4+0],o=u()[f/4+1],d=h(a,o).slice();return n.__wbindgen_free(a,1*o,1),d}finally{n.__wbindgen_add_to_stack_pointer(16)}},t.exports.batch_verify_tickets=function(e,t,r){try{const o=n.__wbindgen_add_to_stack_pointer(-16),d=l(e,n.__wbindgen_malloc),f=c,g=l(t,n.__wbindgen_malloc),p=c;n.batch_verify_tickets(o,d,f,g,p,r);var s=u()[o/4+0],i=u()[o/4+1],a=h(s,i).slice();return n.__wbindgen_free(s,1*i,1),a}finally{n.__wbindgen_add_to_stack_pointer(16)}};const f=s(928).join(i,"bandersnatch_bg.wasm"),g=s(896).readFileSync(f),p=new WebAssembly.Module(g),b=new WebAssembly.Instance(p,{});n=b.exports,t.exports.__wasm=n},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 a=e[t.charCodeAt(i++)],o=e[t.charCodeAt(i++)],c=e[t.charCodeAt(i++)],l=e[t.charCodeAt(i++)];s[n++]=a<<2|o>>4,s[n++]=o<<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},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),a=r(660);class o{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 o(e,e)}static fromCidrRange(e){return new o(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]=a.Validator.isValidIPv4String(r),[c]=a.Validator.isValidIPv4String(i),[l]=a.Validator.isValidIPv6String(r),[d]=a.Validator.isValidIPv6String(i);if(n&&c)return new o(s.IPv4.fromDecimalDottedString(r),s.IPv4.fromDecimalDottedString(i));if(l&&d)return new o(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 o(e.getFirst(),e.getLast());if(this.isOverlapping(e))return this.getFirst().isLessThan(e.getFirst())?new o(this.getFirst(),e.getLast()):new o(e.getFirst(),this.getLast());if(this.contains(e))return new o(this.getFirst(),this.getLast());if(e.contains(this))return new o(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 o(e.getFirst(),this.getLast());throw new Error("Range to prepend must be adjacent")}append(e){if(this.getLast().nextIPNumber().isEquals(e.getFirst()))return new o(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 o(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),a=s.isIPv4(i)?s.IPv4.fromNumber(n):s.IPv6.fromBigInt(n);return new o(i,a)}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 o(this.getFirst(),e.getFirst().previousIPNumber()))}catch(e){}try{t.push(new o(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 d(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=o;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 o(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]=a.Validator.isValidIPv4CidrNotation(e);if(!t){let e=r.filter(e=>""!==e);throw new Error(e.join(" and "))}let n=e.split("/"),o=n[0],c=BigInt(parseInt(n[1]));return new l(s.IPv4.fromDecimalDottedString(o),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=a.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 d extends c{constructor(e,t){super(),this.ipv6=e,this.cidrPrefix=t,this.bitValue=128n}static fromCidr(e){let[t,r]=a.Validator.isValidIPv6CidrNotation(e);if(!t)throw new Error(r.filter(e=>""!==e).toString());let n=e.split("/"),o=n[0],c=BigInt(parseInt(n[1]));return new d(s.IPv6.fromHexadecatet(o),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 d(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 d(r,t),n=s.getLast().nextIPNumber();return[s,new d(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 d(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 d(new s.IPv6(t),this.cidrPrefix)}}previousRange(){if(this.hasPreviousRange()){let e=this.getSize(),t=this.getFirst().getValue()-e;return new d(new s.IPv6(t),this.cidrPrefix)}}}t.IPv6CidrRange=d;let u=(e,t)=>{let r=Number(e.bitValue.valueOf()),i=BigInt(`0b${"1".repeat(r)}`),a=e.cidrPrefix.toMask().getValue(),o=n.leftPadWithZeroBit((a^i).toString(2),r);return h(e)?s.IPv4.fromNumber(t.getValue()|n.parseBinaryStringToBigInt(o)):s.IPv6.fromBigInt(t.getValue()|n.parseBinaryStringToBigInt(o))};function h(e){return 32n===e.bitValue.valueOf()}t.isIPv4CidrRange=h},429:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},493:e=>{e.exports="data:application/javascript;base64,aW1wb3J0IHsgdHNJbXBvcnQgfSBmcm9tICJ0c3gvZXNtL2FwaSI7CmF3YWl0IHRzSW1wb3J0KCIuL2luZGV4LnRzIiwgaW1wb3J0Lm1ldGEudXJsKTsK"},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),a=r(984),o=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-d(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-d(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=>o.Hexadecatet.fromString(a.binaryStringToHexadecimalString(e))).map(e=>e.toString()).join(":")}}function d(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,a="undefined"!=typeof WebAssembly&&r(259)().then(e=>{n=e}),o=64,c=[];e.exports=p;var l=e.exports.BYTES_MIN=16,d=e.exports.BYTES_MAX=64,u=(e.exports.BYTES=32,e.exports.KEYBYTES_MIN=16),h=e.exports.KEYBYTES_MAX=64,f=(e.exports.KEYBYTES=32,e.exports.SALTBYTES=16),g=e.exports.PERSONALBYTES=16;function p(e,t,r,i,a){if(!(this instanceof p))return new p(e,t,r,i,a);if(!n)throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");e||(e=32),!0!==a&&(s(e>=l,"digestLength must be at least "+l+", was given "+e),s(e<=d,"digestLength must be at most "+d+", 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<=h,"key must be at least "+h+", 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===g,"personal must be exactly "+g+", was given "+i.length))),c.length||(c.push(o),o+=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,o,o+t.length),this._memory[this.pointer+200]=128)}function b(){}p.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)},p.prototype.update=function(e){return s(!1===this.finalized,"Hash instance finalized"),s(e instanceof Uint8Array,"input must be Uint8Array or Buffer"),o+e.length>this._memory.length&&this._realloc(o+e.length),this._memory.set(e,o),n.blake2b_update(this.pointer,o,o+e.length),this},p.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},p.prototype.final=p.prototype.digest,p.WASM=n,p.SUPPORTED="undefined"!=typeof WebAssembly,p.ready=function(e){return e||(e=b),a?a.then(()=>e(),e):e(new Error("WebAssembly not supported"))},p.prototype.ready=p.ready,p.prototype.getPartialHash=function(){return this._memory.slice(this.pointer,this.pointer+216)},p.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,a={};a.__wbindgen_placeholder__=t.exports;let o=null;function c(){return null!==o&&0!==o.byteLength||(o=new Uint8Array(n.memory.buffer)),o}let l=0;function d(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=d(e,n.__wbindgen_malloc),r=l,s=n.verify_ed25519(t,r);var i,a,o=(i=s[0],a=s[1],i>>>=0,c().subarray(i/1,i/1+a)).slice();return n.__wbindgen_free(s[0],1*s[1],1),o},t.exports.verify_ed25519_batch=function(e){const t=d(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"),h=s(896).readFileSync(u),f=new WebAssembly.Module(h),g=new WebAssembly.Instance(f,a);n=g.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),a=r(984),o=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=o.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),[a,o]=c.isValidPrefixValue(BigInt(s),"IPv4"),l=i&&a,d=n.concat(o);return l?[l,[]]:[l,d]}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,a.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("/"),a=n[0],o=n[1],l=BigInt(`0b${r(a)}`),d=(l&BigInt(`0b${s(parseInt(o))}`))===l;return d?[d,[]]:[d,[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${o.hexadectetNotationToBinaryString(e)}`)>=BigInt(`0b${o.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],[a,o]=t(i),[l,d]=t(n),u=a&&l;if(u&&r(i,n))return[!1,[c.invalidRangeFirstNotGreaterThanLastMessage]];let h=o.concat(d);return u?[u,[]]:[u,h]}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 a(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 o(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function c(e,t,r,s,i,o){var c=h[i],l=h[i+1],d=h[o],f=h[o+1];n(u,e,t),a(u,e,c,l);var g=u[s]^u[e],p=u[s+1]^u[e+1];u[s]=p,u[s+1]=g,n(u,r,s),g=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=g>>>24^p<<8,u[t+1]=p>>>24^g<<8,n(u,e,t),a(u,e,d,f),g=u[s]^u[e],p=u[s+1]^u[e+1],u[s]=g>>>16^p<<16,u[s+1]=p>>>16^g<<16,n(u,r,s),g=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=p>>>31^g<<1,u[t+1]=g>>>31^p<<1}var l=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),d=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),h=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++)h[r]=o(e.b,4*r);for(r=0;r<12;r++)c(0,8,16,24,d[16*r+0],d[16*r+1]),c(2,10,18,26,d[16*r+2],d[16*r+3]),c(4,12,20,28,d[16*r+4],d[16*r+5]),c(6,14,22,30,d[16*r+6],d[16*r+7]),c(0,10,20,30,d[16*r+8],d[16*r+9]),c(2,12,22,24,d[16*r+10],d[16*r+11]),c(4,14,16,26,d[16*r+12],d[16*r+13]),c(6,8,18,28,d[16*r+14],d[16*r+15]);for(r=0;r<16;r++)e.h[r]=e.h[r]^u[r]^u[r+16]}var g=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 p(e,t,r,s){g.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=e,g[0]=e,t&&(g[1]=t.length),g[2]=1,g[3]=1,r&&g.set(r,32),s&&g.set(s,48);for(var i=0;i<16;i++)this.h[i]=l[i]^o(g,4*i);t&&(b(this,t),this.c=128)}function b(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)}p.prototype.update=function(e){return s(e instanceof Uint8Array,"input must be Uint8Array or Buffer"),b(this,e),this},p.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},p.prototype.final=p.prototype.digest,p.ready=function(e){i.ready(function(){e()})};var y=p;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 y(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)})},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],a=i.split(":").filter(e=>""!==e),o=n.split(":").filter(e=>""!==e),c=(e=>{let t=[];for(let r=0;r<e;r++)t.push("0000");return t.join(":")})(8-(a.length+o.length)),l=t(a);""!==l&&(l+=":");let d=t(o);return""!==d&&(d=":"+d),`${l}${c}${d}${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",a="function"==typeof Object.create,o={__proto__:[]}instanceof Array,c=!a&&!o,l={create:a?function(){return Q(Object.create(null))}:o?function(){return Q({__proto__:null})}:function(){return Q({})},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]}},d=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,a)},t.prototype.entries=function(){return new r(this._keys,this._values,o)},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 a(e,t){return t}function o(e,t){return[e,t]}}(),h="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@@"+a()}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 a(){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}}(),g=s?Symbol.for("@reflect-metadata:registry"):void 0,p=function(){var e;return!C(g)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[g]),C(e)&&(e=function(){var e,r,s,i;C(g)||void 0===t.Reflect||g 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,a=new f,o={isProviderFor:function(e,t){var r=a.get(e);return!(C(r)||!r.has(t))||!!i(e,t).length&&(C(r)&&(r=new h,a.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:s,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:n};return o}(t.Reflect));var n=new f,a={registerProvider:o,getProvider:l,setProvider:p};return a;function o(t){if(!Object.isExtensible(a))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 h),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 a=M(i);;){var o=L(a);if(!o)return;var c=P(o);if(c.isProviderFor(t,n))return H(a),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 d(e){if(C(e))throw new TypeError;return r===e||s===e||!C(i)&&i.has(e)}function p(e,t,r){if(!d(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(g)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,g,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}(),b=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)&&_(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()),a=0;;){var o=L(n);if(!o)return r.length=a,r;var c=P(o);try{r[a]=c}catch(e){try{H(n)}finally{throw e}}a++}},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 a=t.get(r);C(a)||(a.delete(i),0===a.size&&t.delete(a))}return!0}};return p.registerProvider(r),r;function s(s,i,n){var a=t.get(s),o=!1;if(C(a)){if(!n)return;a=new u,t.set(s,a),o=!0}var c=a.get(i);if(C(c)){if(!n)return;if(c=new u,a.set(i,c),!e.setProvider(s,i,r))throw a.delete(i),o&&t.delete(s),new Error("Wrong provider for target.")}return c}}(p);function m(e,t,r){if(y(e,t,r))return!0;var s=V(t);return!k(s)&&m(e,s,r)}function y(e,t,r){var s=K(t,r,!1);return!C(s)&&_(s.OrdinaryHasOwnMetadata(e,t,r))}function A(e,t,r){if(y(e,t,r))return I(e,t,r);var s=V(t);return k(s)?void 0:A(e,s,r)}function I(e,t,r){var s=K(t,r,!1);if(!C(s))return s.OrdinaryGetOwnMetadata(e,t,r)}function v(e,t,r,s){K(r,s,!0).OrdinaryDefineOwnMetadata(e,t,r,s)}function w(e,t){var r=S(e,t),s=V(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 h,a=[],o=0,c=r;o<c.length;o++){var l=c[o];n.has(l)||(n.add(l),a.push(l))}for(var d=0,u=i;d<u.length;d++)l=u[d],n.has(l)||(n.add(l),a.push(l));return a}function S(e,t){var r=K(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 B(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 _(e){return!!e}function R(e){var t=B(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 V(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===d)return t;if(t!==d)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 K(e,t,r){var s=p.getProvider(e,t);if(!C(s))return s;if(r){if(p.setProvider(e,t,b))return b;throw new Error("Illegal state.")}}function Q(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)),y(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=K(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 a,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 a=i.isIPv4Prefix(r)?i.IPv4Prefix.fromNumber(r.getValue()+1n):i.IPv6Prefix.fromNumber(r.getValue()+1n);return t(e,a,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 a{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 a(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 a(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 a(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 a(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,a),r.exports}a.m=i,a.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return a.d(t,{a:t}),t},a.d=(e,t)=>{for(var r in t)a.o(t,r)&&!a.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},a.b=new URL("./",import.meta.url);var o={};a.r(o),a.d(o,{Any:()=>$d,BaseBlock:()=>il,BaseStringBlock:()=>al,BitString:()=>id,BmpString:()=>Cd,Boolean:()=>ed,CharacterString:()=>Md,Choice:()=>Gd,Constructed:()=>Wl,DATE:()=>Hd,DateTime:()=>Kd,Duration:()=>Qd,EndOfContent:()=>Yl,Enumerated:()=>dd,GeneralString:()=>Dd,GeneralizedTime:()=>Ld,GraphicString:()=>Td,HexBlock:()=>Xc,IA5String:()=>Ud,Integer:()=>ld,Null:()=>Xl,NumericString:()=>Bd,ObjectIdentifier:()=>fd,OctetString:()=>rd,Primitive:()=>$l,PrintableString:()=>_d,RawData:()=>qd,RelativeObjectIdentifier:()=>bd,Repeated:()=>jd,Sequence:()=>md,Set:()=>yd,TIME:()=>Fd,TeletexString:()=>Rd,TimeOfDay:()=>Vd,UTCTime:()=>Pd,UniversalString:()=>xd,Utf8String:()=>Sd,ValueBlock:()=>el,VideotexString:()=>Od,ViewWriter:()=>Tc,VisibleString:()=>Nd,compareSchema:()=>zd,fromBER:()=>jl,verifySchema:()=>Wd});var c={};a.r(c),a.d(c,{Announcement:()=>LS,Handler:()=>VS,Handshake:()=>PS,HashAndSlot:()=>MS,STREAM_KIND:()=>DS});var l={};a.r(l),a.d(l,{Handler:()=>XS,KeyValuePair:()=>zS,STREAM_KIND:()=>jS,StateRequest:()=>JS,StateResponse:()=>WS});const d=t(import.meta.url)("node:url");var u,h,f;!function(e){e[e.Less=-1]="Less",e[e.Equal=0]="Equal",e[e.Greater=1]="Greater"}(u||(u={}));class g{value;constructor(e){this.value=e}static Less=new g(u.Less);static Greater=new g(u.Greater);static Equal=new g(u.Equal);isLess(){return this.value===u.Less}isGreater(){return this.value===u.Greater}isEqual(){return this.value===u.Equal}isNotEqual(){return!this.isEqual()}isGreaterOrEqual(){return this.isEqual()||this.isGreater()}isLessOrEqual(){return this.isEqual()||this.isLess()}}!function(e){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-preview",e.V0_7_1="0.7.1-preview"}(h||(h={})),function(e){e.W3F_DAVXY="w3f-davxy",e.W3F="w3f",e.JAMDUNA="jamduna",e.JAVAJAM="javajam"}(f||(f={}));const p=f.W3F,b=[h.V0_6_5,h.V0_6_6,h.V0_6_7,h.V0_7_0,h.V0_7_1],m="undefined"==typeof process?{}:process.env,y=h.V0_6_7;let A=function(e){if(void 0===e)return;const t=e;if(!Object.values(h).includes(t))throw new Error(`Configured environment variable GP_VERSION is unknown: '${e}'. Use one of: ${b}`);return t}(m.GP_VERSION),I=m.TEST_SUITE??p;class v{static override(e){A=e}static overrideSuite(e){I=e}static is(...e){return void 0===A?e.includes(y):e.includes(A)}static isSuite(e,t){if(void 0===I)return!1;const r=void 0===t||v.is(t);return e===I&&r}static isGreaterOrEqual(e){const t=b.indexOf(e);if(-1===t)throw new Error(`Invalid version: ${e}. Not found amongst supported versions: ${b}`);return v.is(...b.slice(t))}static isLessThan(e){return!v.isGreaterOrEqual(e)}static selectIfGreaterOrEqual({fallback:e,versions:t}){for(const e of b.toReversed()){const r=t[e];if(void 0!==r&&v.isGreaterOrEqual(e))return r}return e}}function w(e,t){if(!e)throw new Error(`Assertion failure: ${t??""}`)}function S(e,t,r){if(function(e,t){return t}(0,t))return e;throw new Error(`Assertion failure: ${r??""}`)}function E(e){throw new Error(`Unexpected value: ${e}`)}function C(e){const t=Object.keys(e);if(t.length>0)throw new Error(`Unexpected keys: ${t.join(", ")}`)}function k(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=>k(e))}]`;if(e instanceof Map)return k(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&&B.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(k(e[r]))}`,s+=n?",":"");return s+=n?"}":"\n}",s}const x="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 B{toString(){return k(this)}}function _(e){return e}function R(e){return e}const O=Symbol("ok");class U{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}) - ${T(this.error)}`}}const T=e=>{return null!==(t=e)&&"object"==typeof t&&"kind"in t&&"error"in t?e instanceof U?e.toString():`${e.kind} - ${T(e.error)}`:`${e}`;var t};function N(e){return e.isOk?`OK: ${"symbol"==typeof e.ok?e.ok.toString():e.ok}`:`${e.details}\nError: ${T(e.error)}`}const D={ok:e=>(w(void 0!==e,"`Ok` type cannot be undefined."),{isOk:!0,isError:!1,ok:e}),error:(e,t="")=>(w(void 0!==e,"`Error` type cannot be undefined."),{isOk:!1,isError:!0,error:e,details:t}),taggedError:(e,t,r)=>D.error(new U(t,r.error,e),r.details)},M=(t(import.meta.url)("node:assert"),Symbol("compare using"));class P{[M](){return this.toString()}raw;length=0;constructor(e){this.raw=e,this.length=e.byteLength}toString(){return function(e){const t=e=>e>=j?String.fromCharCode(e+Q-j):String.fromCharCode(e+V);let r="0x";for(const s of e)r+=t(s>>>4),r+=t(15&s);return r}(this.raw)}toJSON(){return this.toString()}asText(){return(new TextDecoder).decode(this.raw)}isEqualTo(e){return this.length===e.length&&z(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 g.Less;if(r[e]>s[e])return g.Greater}return this.length<e.length?g.Less:this.length>e.length?g.Greater:g.Equal}static empty(){return new P(new Uint8Array)}static blobFromString(e){const t=new TextEncoder;return P.blobFrom(t.encode(e))}static blobFrom(e){return new P(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 P(i)}static blobFromNumbers(e){w(void 0===e.find(e=>(255&e)!==e),"BytesBlob.blobFromNumbers used with non-byte number array.");const t=new Uint8Array(e);return new P(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]=H(t)}return new P(s)}static parseBlob(e){if(!e.startsWith("0x"))throw new Error(`Missing 0x prefix: ${e}.`);return P.parseBlobNoPrefix(e.substring(2))}*chunks(e){for(let t=0;t<this.length;t+=e)yield P.blobFrom(this.raw.subarray(t,t+e))}}class L extends P{length;constructor(e,t){super(e),w(e.byteLength===t,`Given buffer has incorrect size ${e.byteLength} vs expected ${t}`),this.length=t}static fromBlob(e,t){return new L(e,t)}static fromNumbers(e,t){w(void 0===e.find(e=>(255&e)!==e),"Bytes.fromNumbers used with non-byte number array.");const r=new Uint8Array(e);return new L(r,t)}static zero(e){return new L(new Uint8Array(e),e)}static fill(e,t){w((255&t)===t,"Input has to be a byte.");const r=L.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=P.parseBlobNoPrefix(e);return new L(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=P.parseBlob(e);return new L(r.raw,t)}isEqualTo(e){return w(this.length===e.length,"Comparing incorrectly typed bytes!"),z(this.raw,e.raw)}asOpaque(){return this}}function H(e){return w(2===e.length,"Two-character string expected"),q(e.charCodeAt(0))<<4|q(e.charCodeAt(1))}const V="0".charCodeAt(0),K="9".charCodeAt(0),Q="a".charCodeAt(0),F="f".charCodeAt(0),$="A".charCodeAt(0),G="F".charCodeAt(0),j=10;function q(e){if(e>=V&&e<=K)return e-V;if(e>=Q&&e<=F)return e-Q+j;if(e>=$&&e<=G)return e-$+j;throw new Error(`Invalid characters in hex byte string: ${String.fromCharCode(e)}`)}function z(e,t){for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}const W=(e,t)=>e.compare(t);class J{data;bitLength;static fromBlob(e,t){return new J(e,t)}static fromBytes(e,t){return new J(e.raw,t)}static empty(e){const t=new Uint8Array(Math.ceil(e/8));return new J(t,e)}byteLength;constructor(e,t){this.data=e,this.bitLength=t,w(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){w(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){w(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){w(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 Y=Symbol("no key");function X(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]=X(t,s,`${r}.${e}`);return n}if("optional"===s)return null==e?e:X(e,t[1],r);if("object"===s)return Z(t[1],e,r);if("string"===s)return Z(t[1],X(e,s,r),r);if("number"===s){const s=t[0];return Z(t[1],X(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,a=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]=X(t,a[e],`${r}.${e}`)}else Array.isArray(a[e])&&"optional"===a[e][0]&&(i[e]=Y);const o=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 a=[],o=e=>void 0!==e?`"${e}"`:"<missing>";for(const[e,t]of Object.entries(i))3!==t&&"undefined"!==e&&a.push(1===t?[o(e),o(void 0)]:[o(void 0),o(e)]);return a}(i,t);if(o.length>0)throw new Error(`[${r}] Unexpected or missing keys: ${o.join(" | ")}\n Data: ${Object.keys(i)}\n Schema: ${Object.keys(t)}`);for(const e of Object.keys(i))i[e]===Y&&delete i[e];return i}function Z(e,t,r){try{return e(t,r)}catch(e){throw new Error(`[${r}] Error while parsing the value: ${e}`)}}var ee;!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]=X(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,a]of Object.entries(r))i.set(X(n,e,`${s}.key`),X(a,t,`${s}.value`));return i})},e.object=function(e,t){return r((r,s)=>{const i=X(r,e,s);return t(i)})}}(ee||(ee={}));const te=e=>S(e,re(e),`input must have one-byte representation, got ${e}`),re=e=>(255&e)===e,se=e=>S(e,ie(e),`input must have two-byte representation, got ${e}`),ie=e=>(65535&e)===e,ne=e=>S(e,ae(e),`input must have four-byte representation, got ${e}`),ae=e=>(4294967295&e)>>>0===e,oe=e=>{const t=BigInt(e);return S(t,ce(t),`input must have eight-byte representation, got ${e}`)},ce=e=>(18446744073709551615n&e)===e;function le(...e){let t=0n;for(const r of e)t+=r;const r=!ce(t);return t&=0xffffffffffffffffn,{overflow:r,value:oe(t)}}function de(e){return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}function ue(e){return w(4===e.length,"Input must be a Uint8Array of length 4"),e[0]|e[1]<<8|e[2]<<16|e[3]<<24}const he=(e,...t)=>t.reduce((e,t)=>t>e?e:t,e);class fe{source;offset;context;static fromBytesBlob(e,t){return new fe(e.raw,t)}static fromBlob(e){return new fe(e)}static decodeObject(e,t,r){const s=t instanceof P?fe.fromBytesBlob(t):fe.fromBlob(t);s.attachContext(r);const i=s.object(e);return s.finish(),i}static decodeSequence(e,t,r){const s=t instanceof P?fe.fromBytesBlob(t):fe.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 fe(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,L.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=pe(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=pe(e);if(this.offset+=1,0===t)return oe(e);if(this.ensureHasBytes(t),this.offset+=t,8===t)return oe(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 oe(r)}bytes(e){if(0===e)return L.zero(e);this.ensureHasBytes(e);const t=this.source.subarray(this.offset,this.offset+e);return this.offset+=e,L.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,P.blobFrom(t)}bitVecFixLen(e){if(0===e)return J.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 J.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):(w(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(w(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 ge=[255,254,252,248,240,224,192,128];function pe(e){w(e>=0&&e<256,`Incorrect byte value: ${e}`);for(let t=0;t<ge.length;t++)if(e>=ge[t])return 8-t;return 0}function be(e){return w(e.isExact,"The value is not exact size estimation!"),e.bytes}function me(e,t){return{bytes:e.bytes+t.bytes,isExact:e.isExact&&t.isExact}}const ye=10485760;class Ae{destination;buffer;static create(e){if(void 0!==e&&"destination"in e)return new Ae(e.destination);const t=e?.expectedLength??512,r=new ArrayBuffer(Math.min(ye,t),{maxByteLength:ye}),s=new Uint8Array(r);return new Ae(s,r)}static encodeObject(e,t,r){const s=Ae.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 P.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;w(e<t,"Only for numbers up to 2**64 - 1"),w(-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(ne(e?1:0))}prepareIntegerN(e,t){const r=2**(8*t);w(e<r,`Only for numbers up to 2**${8*t} - 1`),w(-e<=r/2,"Only for numbers down to -2**"+(8*t-1)),this.ensureBigEnough(t)}varU32(e){w(e>=0,"Only for natural numbers."),w(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(ne(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(L.fromBlob(t,t.length))}bitVecVarLen(e){const t=e.bitLength;this.varU32(ne(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){w(t.length<=2**32,"Wow, that's a nice long sequence you've got here."),this.varU32(ne(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}){w(e>=0,"Negative length given");const r=this.offset+e;if(r>ye){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(ye,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 Ie{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=pe(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 ve(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 we{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 Se{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 P.blobFromNumbers([]);if(this.lastDecodedFieldIdx<e.length-1){const t=e[e.length-1];this.decodeUpTo(t)}return P.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];w(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 Ie(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 we(()=>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 S(s,void 0!==s,"Last item must be set, since the loop turns at least once.")}}class Ee{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=S(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?P.blobFromNumbers([]):(this.lastDecodedIdx<this.length-1&&this.decodeUpTo(this.length-1),P.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset,this.decoder.bytesRead())))}decodeUpTo(e){w(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 Ie(this.decoder);for(let s=this.lastDecodedIdx+1;s<=e;s++){const e=r.decoder.clone(),i=this.descriptor;t=new we(()=>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 S(t,void 0!==t,"Last item must be set, since the loop turns at least once.")}}class Ce{name;sizeHint;encode;decode;skip;View;static withView(e,t,r,s,i,n){return new Ce(e,t,r,s,i,n)}static new(e,t,r,s,i){return new Ce(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 Ie(e));const r=e.bytesRead();return P.blobFrom(e.source.subarray(t,r))}convert(e,t){return new Ce(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=>(w(Array.isArray(e),`Non-arrays are not supported as 'readonly': got ${typeof e}, ${e}`),e),e=>e)}function xe(e){return{bytes:e,isExact:!0}}var Be,_e;function Re(e,t){for(const r in e)"string"==typeof r&&r in e&&t(r,e[r])}function Oe(e){return e.View!==e}(_e=Be||(Be={})).bytes=(()=>{const e=new Map;return t=>{let r=e.get(t);return void 0===r&&(r=Ce.new(`Bytes<${t}>`,xe(t),(e,t)=>e.bytes(t),e=>e.bytes(t),e=>e.bytes(t)),e.set(t,r)),r}})(),_e.varU32=Ce.new("var_u32",{bytes:4,isExact:!1},(e,t)=>e.varU32(t),e=>e.varU32(),e=>e.varU32()),_e.varU64=Ce.new("var_u64",{bytes:8,isExact:!1},(e,t)=>e.varU64(t),e=>e.varU64(),e=>e.varU64()),_e.u64=Ce.withView("u64",xe(8),(e,t)=>e.i64(t),e=>e.u64(),e=>e.u64(),_e.bytes(8)),_e.u32=Ce.withView("u32",xe(4),(e,t)=>e.i32(t),e=>e.u32(),e=>e.u32(),_e.bytes(4)),_e.u24=Ce.withView("u24",xe(3),(e,t)=>e.i24(t),e=>e.u24(),e=>e.u24(),_e.bytes(3)),_e.u16=Ce.withView("u16",xe(2),(e,t)=>e.i16(t),e=>e.u16(),e=>e.u16(),_e.bytes(2)),_e.u8=Ce.new("u8",xe(1),(e,t)=>e.i8(t),e=>e.u8(),e=>e.u8()),_e.i64=Ce.withView("u64",xe(8),(e,t)=>e.i64(t),e=>e.i64(),e=>e.u64(),_e.bytes(8)),_e.i32=Ce.withView("i32",xe(4),(e,t)=>e.i32(t),e=>e.i32(),e=>e.u32(),_e.bytes(4)),_e.i24=Ce.withView("i24",xe(3),(e,t)=>e.i24(t),e=>e.i24(),e=>e.u24(),_e.bytes(3)),_e.i16=Ce.withView("i16",xe(2),(e,t)=>e.i16(t),e=>e.i16(),e=>e.u16(),_e.bytes(2)),_e.i8=Ce.new("i8",xe(1),(e,t)=>e.i8(t),e=>e.i8(),e=>e.u8()),_e.bool=Ce.new("bool",xe(1),(e,t)=>e.bool(t),e=>e.bool(),e=>e.bool()),_e.blob=Ce.new("BytesBlob",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(t),e=>e.bytesBlob(),e=>e.bytesBlob()),_e.string=Ce.withView("string",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(P.blobFrom((new TextEncoder).encode(t))),e=>new TextDecoder("utf8",{fatal:!0}).decode(e.bytesBlob().raw),e=>e.bytesBlob(),_e.blob),_e.bitVecVarLen=Ce.new("BitVec[?]",{bytes:8,isExact:!1},(e,t)=>e.bitVecVarLen(t),e=>e.bitVecVarLen(),e=>e.bitVecVarLen()),_e.bitVecFixLen=e=>Ce.new(`BitVec[${e}]`,xe(e>>>3),(e,t)=>e.bitVecFixLen(t),t=>t.bitVecFixLen(e),t=>t.bitVecFixLen(e)),_e.optional=e=>{const t=Ce.new(`Optional<${e.name}>`,me({bytes:1,isExact:!1},e.sizeHint),(t,r)=>t.optional(e,r),t=>t.optional(e),t=>t.optional(e));return Oe(e)?Ce.withView(t.name,t.sizeHint,t.encode,t.decode,t.skip,_e.optional(e.View)):t},_e.sequenceVarLen=(e,t={minLength:0,maxLength:2**32-1})=>{const r=`Sequence<${e.name}>[?]`,s=t.typicalLength??64;return Ce.withView(r,{bytes:s*e.sizeHint.bytes,isExact:!1},(s,i)=>{ve(t,i.length,r),s.sequenceVarLen(e,i)},s=>{const i=s.varU32();return ve(t,i,r),s.sequenceFixLen(e,i)},s=>{const i=s.decoder.varU32();return ve(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 ve(t,s,i),r.sequenceFixLen(e,s)};return Ce.new(i,r,(e,r)=>{ve(t,r.length,i);const s=r.encoded();e.bytes(L.fromBlob(s.raw,s.length))},t=>{const r=new Ee(t.clone(),e);return n(new Ie(t)),r},n)}(e,t))},_e.sequenceFixLen=(e,t)=>Ce.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 Ce.new(n,r,(e,t)=>{const r=t.encoded();e.bytes(L.fromBlob(r.raw,r.length))},r=>{const i=new Ee(r.clone(),e,t);return s(new Ie(r)),i},s)}(e,{fixedLength:t})),_e.dictionary=(e,t,{sortKeys:r,fixedLength:s})=>{const i=Ce.new(`Dictionary<${e.name}, ${t.name}>[${s??"?"}]`,{bytes:void 0!==s?s*me(e.sizeHint,t.sizeHint).bytes:32*(me(e.sizeHint,t.sizeHint).bytes??0),isExact:void 0!==s&&e.sizeHint.isExact&&t.sizeHint.isExact},(i,n)=>{const a=Array.from(n.entries());a.sort((e,t)=>r(e[0],t[0])),void 0!==s&&0!==s||i.varU32(ne(a.length));for(const[r,s]of a)e.encode(i,r),t.encode(i,s)},i=>{const n=new Map,a=s??i.varU32();let o=null;for(let s=0;s<a;s+=1){const s=e.decode(i),a=t.decode(i);if(n.has(s))throw new Error(`Duplicate item in the dictionary encoding: "${s}"!`);if(null!==o&&r(o,s)>=0)throw new Error(`The keys in dictionary encoding are not sorted "${o}" >= "${s}"!`);n.set(s,a),o=s}return n},r=>{const i=s??r.decoder.varU32();r.sequenceFixLen(e,i),r.sequenceFixLen(t,i)});return Oe(t)?Ce.withView(i.name,i.sizeHint,i.encode,i.decode,i.skip,_e.dictionary(e,t.View,{sortKeys:r,fixedLength:s})):i},_e.custom=({name:e,sizeHint:t={bytes:0,isExact:!1}},r,s,i)=>Ce.new(e,t,r,s,i),_e.select=({name:e,sizeHint:t},r)=>Ce.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),_e.object=(e,t="object",r=e=>e)=>_e.Class({name:t,create:r},e),_e.Class=(e,t)=>{let r=xe(0);Re(t,(e,t)=>{r=me(r,t.sizeHint)});const s=e=>{if(r.isExact)return e.decoder.skip(r.bytes);Re(t,(t,r)=>{r.skip(e)})},i=function(e,t,r,s){class i extends Se{constructor(r){super(r,e,t)}}return Re(t,e=>{"string"==typeof e&&Object.defineProperty(i.prototype,e,{get:function(){return this.get(e)}})}),Ce.new(`View<${e.name}>`,r,(e,t)=>{const r=t.encoded();e.bytes(L.fromBlob(r.raw,r.length))},e=>{const t=new i(e.clone());return s(new Ie(e)),t},s)}(e,t,r,s);return Ce.withView(e.name,r,(e,r)=>{Re(t,(t,s)=>{const i=r[t];s.encode(e,i)})},r=>{const s={};return Re(t,(e,t)=>{const i=t.decode(r);s[e]=i}),e.create(s)},s,i)};var Ue=a(239);const Te=32,Ne=96,De=144,Me=144,Pe=32,Le=31;class He extends B{hash;data;constructor(e,t){super(),this.hash=e,this.data=t}}class Ve extends He{encoded;constructor(e,t,r){super(e,t),this.encoded=r}}class Ke{emptyHash(){return L.zero(Pe)}}const Qe=new Ke;var Fe,$e=a(675),Ge=a.n($e);function je(e,t=Qe){const r=t.emptyHash();if(0===e.length)return r.asOpaque();const s=Ge()(Pe);for(const t of e)s?.update(t instanceof P?t.raw:t);return s?.digest(r.raw),r.asOpaque()}function qe(e,t=Qe){const r=Ge()(Pe),s=e instanceof P?e.raw:e;r?.update(s);const i=t.emptyHash();return r?.digest(i.raw),i}function ze(e,t=Qe){return qe(P.blobFromString(e),t)}function We(e,t,r,s){return new(r||(r=Promise))(function(i,n){function a(e){try{c(s.next(e))}catch(e){n(e)}}function o(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(a,o)}c((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class Je{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 We(this,void 0,void 0,function*(){const t=yield this.lock();try{return yield Promise.resolve(e())}finally{t()}})}}const Ye="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Xe=null!==(Fe=Ye.Buffer)&&void 0!==Fe?Fe:null,Ze=Ye.TextEncoder?new Ye.TextEncoder:null;function et(e,t){return(15&e)+(e>>6|e>>3&8)<<4|(15&t)+(t>>6|t>>3&8)}const tt="a".charCodeAt(0)-10,rt="0".charCodeAt(0);function st(e,t,r){let s=0;for(let i=0;i<r;i++){let r=t[i]>>>4;e[s++]=r>9?r+tt:r+rt,r=15&t[i],e[s++]=r>9?r+tt:r+rt}return String.fromCharCode.apply(null,e)}const it=null!==Xe?e=>{if("string"==typeof e){const t=Xe.from(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.length)}if(Xe.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 Ze.encode(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")},nt=new Uint8Array(256);for(let e=0;e<64;e++)nt["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;function at(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=nt[e.charCodeAt(t)],n=nt[e.charCodeAt(t+1)],a=nt[e.charCodeAt(t+2)],o=nt[e.charCodeAt(t+3)];s[i]=r<<2|n>>4,i+=1,s[i]=(15&n)<<4|a>>2,i+=1,s[i]=(3&a)<<6|63&o,i+=1}return s}const ot=16384,ct=new Je,lt=new Map;function dt(e,t){return We(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),a=ct.dispatch(()=>We(this,void 0,void 0,function*(){if(!lt.has(e.name)){const t=at(e.data),r=WebAssembly.compile(t);lt.set(e.name,r)}const t=yield lt.get(e.name);r=yield WebAssembly.instantiate(t,{})})),o=(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+ot);t+=i.length,s.set(i),r.exports.Hash_Update(i.length)}})(it(e))},l=new Uint8Array(2*t),d=(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):st(l,s,t)},u=e=>"string"==typeof e?e.length<4096:e.byteLength<ot;let h=u;switch(e.name){case"argon2":case"scrypt":h=()=>!0;break;case"blake2b":case"blake2s":h=(e,t)=>t<=512&&u(e);break;case"blake3":h=(e,t)=>0===t&&u(e);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":h=()=>!1}return yield(()=>We(this,void 0,void 0,function*(){r||(yield a);const e=r.exports.Hash_GetBuffer(),t=r.exports.memory.buffer;s=new Uint8Array(t,e,ot)}))(),{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:o,update:c,digest:d,save:()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");const t=r.exports.Hash_GetState(),s=n(),a=r.exports.memory.buffer,o=new Uint8Array(a,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]=et(t.charCodeAt(r),t.charCodeAt(r+1))}}(c,e.hash),c.set(o,4),c},load:t=>{if(!(t instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");const s=r.exports.Hash_GetState(),a=n(),o=4+a,c=r.exports.memory.buffer;if(t.length!==o)throw new Error(`Bad state length (expected ${o} 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]!==et(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,a).set(l),i=!0},calculate:(e,i=null,n=null)=>{if(!h(e,i))return o(i),c(e),d("hex",n);const a=it(e);return s.set(a),r.exports.Hash_Calculate(a.length,i,n),st(l,s,t)},hashLength:t}})}new Je,new Je,new DataView(new ArrayBuffer(4)),new Je,new Je,new Je,new Je,new Uint8Array(8),new Je,new Je,new Je;var ut={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 ht(e){return[224,256,384,512].includes(e)?null:new Error("Invalid variant! Valid values: 224, 256, 384, 512")}new Je,new Je,new Je,new Je,new Je,new Je,new Je,new Je,new Uint8Array(8),new Je,new Uint8Array(8),new Je,new Uint8Array(8),new Je,new Je,new Je;class ft{hasher;static async create(){return new ft(await function(e=512){if(ht(e))return Promise.reject(ht(e));const t=e/8;return dt(ut,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 gt(e,t){e.hasher.init();for(const r of t)e.hasher.update(r.raw);return L.fromBlob(e.hasher.digest("binary"),Pe)}class pt{map=new Map;constructor(){}static new(){return new pt}static fromEntries(e){const t=new pt;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])}toJSON(){return Object.fromEntries(this)}set(e,t){this.map.set(e.toString(),[e,t])}delete(e){return this.map.delete(e.toString())}}class bt{map;static viewDictionaryKeys(e){return new bt(e)}static from(e){const t=bt.new();return t.insertAll(e),t}static new(){return new bt}constructor(e=pt.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 mt(e){return e}class yt extends Array{fixedLength;constructor(...e){super(...e),this.fixedLength=this.length}static new(e,t){w(e.length===t,`Expected an array of size: ${t}, got: ${e.length}`);const r=new yt(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 yt.new(r,t)}toString(){return k(Array.from(this))}}class At{array;comparator;static fromArray(e,t=[]){const r=t.slice();return r.sort((t,r)=>e(t,r).value),new At(r,e)}static fromSortedArray(e,t=[]){const r=t.length;if(0===r)return new At([],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 At(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,a=r(t[n],e);if(a.isEqual())return{idx:n,isEqual:!0};a.isLess()?s=n+1:i=n}return{idx:s,isEqual:!1}}static fromTwoSortedCollections(e,t){w(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,a=n.length,o=new Array(i+a);let c=0,l=0,d=0;for(;c<i&&l<a;)r(s[c],n[l]).isLess()?o[d++]=s[c++]:(r(s[c],n[l]).isGreater()||(o[d++]=s[c++]),o[d++]=n[l++]);for(;c<i;)o[d++]=s[c++];for(;l<a;)o[d++]=n[l++];return At.fromSortedArray(r,o)}*[Symbol.iterator](){for(const e of this.array)yield e}}class It extends At{static fromArray(e,t=[]){if(0===t.length)return new It([],e);const r=t.toSorted((t,r)=>e(t,r).value),s=r.length,i=[r[0]];for(let t=1;t<s;t++)e(r[t-1],r[t]).isEqual()||i.push(r[t]);return new It(i,e)}static fromArrayUnique(e,t){const r=t.toSorted((t,r)=>e(t,r).value),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 It(r,e)}static fromSortedArray(e,t=[]){if(0===t.length)return new It([],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 It(r,e)}insert(e){const t=this.binarySearch(e);t.isEqual||this.array.splice(t.idx,0,e)}replace(e){const t=this.binarySearch(e),r=t.isEqual?1:0;this.array.splice(t.idx,r,e)}static fromTwoSortedCollections(e,t){w(e.comparator===t.comparator,"Cannot merge arrays if they do not use the same comparator");const r=e.comparator;if(0===e.length)return It.fromSortedArray(r,t.array);if(0===t.length)return It.fromSortedArray(r,e.array);const s=At.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,It.fromSortedArray(r,s)}}class vt{dict;static fromEntries(e){const t=Array.from(e).map(([e,t])=>{const r=L.zero(Pe).asOpaque();return r.raw.set(e.raw.subarray(0,Le)),[r,t]});return new vt(pt.fromEntries(t))}truncatedKey=L.zero(Pe).asOpaque();constructor(e){this.dict=e}[M](){return this.dict}get size(){return this.dict.size}get(e){return this.truncatedKey.raw.set(e.raw.subarray(0,Le)),this.dict.get(this.truncatedKey)}has(e){return this.truncatedKey.raw.set(e.raw.subarray(0,Le)),this.dict.has(this.truncatedKey)}set(e,t){const r=L.zero(Pe);r.raw.set(e.raw.subarray(0,Le)),this.dict.set(r.asOpaque(),t)}delete(e){this.truncatedKey.raw.set(e.raw.subarray(0,Le)),this.dict.delete(this.truncatedKey)}values(){return this.dict.values()}*entries(){for(const[e,t]of this.dict.entries())yield[L.fromBlob(e.raw.subarray(0,Le),Le).asOpaque(),t]}[Symbol.iterator](){return this.entries()}}class wt extends B{validatorsCount;thirdOfValidators;validatorsSuperMajority;coresCount;preimageExpungePeriod;slotDuration;epochLength;contestLength;ticketsPerValidator;maxTicketsPerExtrinsic;rotationPeriod;numberECPiecesPerSegment;erasureCodedPieceSize;maxBlockGas;maxRefineGas;constructor(e){super(),this.validatorsCount=e.validatorsCount,this.thirdOfValidators=se(Math.floor(e.validatorsCount/3)),this.validatorsSuperMajority=se(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,this.preimageExpungePeriod=e.preimageExpungePeriod,this.erasureCodedPieceSize=ne(4104/e.numberECPiecesPerSegment),this.maxBlockGas=e.maxBlockGas,this.maxRefineGas=e.maxRefineGas}}const St=new wt({validatorsCount:se(6),coresCount:se(2),epochLength:ne(12),contestLength:ne(10),maxTicketsPerExtrinsic:te(3),rotationPeriod:se(4),slotDuration:se(6),ticketsPerValidator:te(3),numberECPiecesPerSegment:ne(1026),preimageExpungePeriod:ne(32),maxBlockGas:oe(2e7),maxRefineGas:oe(1e9)}),Et=new wt({validatorsCount:se(1023),coresCount:se(341),epochLength:ne(600),contestLength:ne(500),maxTicketsPerExtrinsic:te(16),rotationPeriod:se(10),slotDuration:se(6),ticketsPerValidator:te(2),numberECPiecesPerSegment:ne(6),preimageExpungePeriod:ne(19200),maxBlockGas:oe(35e8),maxRefineGas:oe(5e9)});class Ct{chainSpec;dbPath;omitSealVerification;static reInit(e){const{chainSpec:t,dbPath:r,omitSealVerification:s}=e;return new Ct(new wt(t),r,s)}constructor(e,t,r=!1){this.chainSpec=e,this.dbPath=t,this.omitSealVerification=r}}function kt(e){const t=Et,{name:r,sizeHint:s}=e(t),i=new Map;return Be.select({name:r,sizeHint:{bytes:s.bytes,isExact:!1}},s=>{if(s instanceof wt){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 xt=(e,t,r)=>"fixedLength"in t?ke(Be.sequenceFixLen(e,t.fixedLength)).convert(R,mt):ke(Be.sequenceVarLen(e,t)).convert(R,mt),Bt=(e,t)=>{const r=r=>{if(t!==r)throw new Error(`[${e.name}] Invalid size of fixed-size array. Got ${r}, expected: ${t}`)};return Be.sequenceFixLen(e,t).convert(e=>(r(e.length),e),e=>(r(e.length),yt.new(e,t)))},_t=(e,t,{typicalLength:r=32,compare:s=(e,r)=>t(e).compare(t(r))}={})=>Ce.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(ne(i.length));for(const r of i)e.encode(t,r)},r=>{const i=pt.new(),n=r.varU32();let a=null;for(let o=0;o<n;o+=1){const n=e.decode(r),o=t(n);if(i.has(o))throw new Error(`Duplicate item in the dictionary encoding: "${o}"!`);if(null!==a&&s(a,n).isGreaterOrEqual())throw new Error(`The keys in dictionary encoding are not sorted "${a}" >= "${n}"!`);i.set(o,n),a=n}return i},t=>{const r=t.decoder.varU32();t.sequenceFixLen(e,r)});class Rt extends B{attempt;signature;static Codec=Be.Class(Rt,{attempt:Be.u8.asOpaque(),signature:Be.bytes(784).asOpaque()});static create({attempt:e,signature:t}){return new Rt(e,t)}constructor(e,t){super(),this.attempt=e,this.signature=t}}class Ot extends B{id;attempt;static Codec=Be.Class(Ot,{id:Be.bytes(Pe),attempt:Be.u8.asOpaque()});static create({id:e,attempt:t}){return new Ot(e,t)}constructor(e,t){super(),this.id=e,this.attempt=t}}const Ut=xt(Rt.Codec,{minLength:0,maxLength:16,typicalLength:16});var Tt;!function(e){e.bytesN=e=>ee.fromString(t=>L.parseBytes(t,e).asOpaque()),e.bytesNNoPrefix=e=>ee.fromString(t=>L.parseBytesNoPrefix(t,e).asOpaque()),e.bytes32=()=>ee.fromString(e=>L.parseBytes(e,32).asOpaque()),e.bytes32NoPrefix=()=>ee.fromString(e=>L.parseBytesNoPrefix(e,32).asOpaque()),e.bytesBlob=ee.fromString(P.parseBlob),e.bytesBlobNoPrefix=ee.fromString(P.parseBlobNoPrefix),e.ed25519Signature=ee.fromString(e=>L.parseBytes(e,64).asOpaque()),e.ticketAttempt=ee.fromNumber(e=>{if(0!==e&&1!==e&&2!==e)throw new Error("Invalid TicketAttempt value.");return te(e)}),e.uint8Array=ee.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=ee.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=ee.fromAny(e=>BigInt(e))}(Tt||(Tt={}));const Nt=2n**255n-19n,Dt=2n**252n+27742317777372353535851937790883648493n,Mt=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Pt=0x6666666666666666666666666666666666666666666666666666666666666658n,Lt={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Nt,n:Dt,h:8,Gx:Mt,Gy:Pt},Ht=(e="")=>{throw new Error(e)},Vt=e=>"string"==typeof e,Kt=(e,t)=>!(e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name)(e)||"number"==typeof t&&t>0&&e.length!==t?Ht("Uint8Array of valid length expected"):e,Qt=e=>new Uint8Array(e),Ft=(e,t)=>Kt(Vt(e)?Xt(e):Qt(Kt(e)),t),$t=(e,t=Nt)=>{let r=e%t;return r>=0n?r:t+r},Gt=e=>e instanceof jt?e:Ht("Point expected");class jt{constructor(e,t,r,s){this.ex=e,this.ey=t,this.ez=r,this.et=s}static fromAffine(e){return new jt(e.x,e.y,1n,$t(e.x*e.y))}static fromHex(e,t=!1){const{d:r}=Lt,s=(e=Ft(e,32)).slice(),i=e[31];s[31]=-129&i;const n=er(s);!t||0n<=n&&n<2n**256n||Ht("bad y coord 1"),t||0n<=n&&n<Nt||Ht("bad y coord 2");const a=$t(n*n),o=$t(a-1n),c=$t(r*a+1n);let{isValid:l,value:d}=nr(o,c);l||Ht("bad y coordinate 3");const u=1n==(1n&d),h=!!(128&i);return!t&&0n===d&&h&&Ht("bad y coord 3"),h!==u&&(d=$t(-d)),new jt(d,n,1n,$t(d*n))}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:a}=Gt(e),o=$t(t*a),c=$t(i*s),l=$t(r*a),d=$t(n*s);return o===c&&l===d}is0(){return this.equals(zt)}negate(){return new jt($t(-this.ex),this.ey,this.ez,$t(-this.et))}double(){const{ex:e,ey:t,ez:r}=this,{a:s}=Lt,i=$t(e*e),n=$t(t*t),a=$t(2n*$t(r*r)),o=$t(s*i),c=e+t,l=$t($t(c*c)-i-n),d=o+n,u=d-a,h=o-n,f=$t(l*u),g=$t(d*h),p=$t(l*h),b=$t(u*d);return new jt(f,g,b,p)}add(e){const{ex:t,ey:r,ez:s,et:i}=this,{ex:n,ey:a,ez:o,et:c}=Gt(e),{a:l,d}=Lt,u=$t(t*n),h=$t(r*a),f=$t(i*d*c),g=$t(s*o),p=$t((t+r)*(n+a)-u-h),b=$t(g-f),m=$t(g+f),y=$t(h-l*u),A=$t(p*b),I=$t(m*y),v=$t(p*y),w=$t(b*m);return new jt(A,I,w,v)}mul(e,t=!0){if(0n===e)return!0===t?Ht("cannot multiply by 0"):zt;if("bigint"==typeof e&&0n<e&&e<Dt||Ht("invalid scalar, must be < L"),!t&&this.is0()||1n===e)return this;if(this.equals(qt))return pr(e).p;let r=zt,s=qt;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(Lt.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(Dt/2n,!1).double();return e=e.add(this),e.is0()}toAffine(){const{ex:e,ey:t,ez:r}=this;if(this.equals(zt))return{x:0n,y:1n};const s=rr(r,Nt);return 1n!==$t(r*s)&&Ht("invalid inverse"),{x:$t(e*s),y:$t(t*s)}}toRawBytes(){const{x:e,y:t}=this.toAffine(),r=Zt(t);return r[31]|=1n&e?128:0,r}toHex(){return Jt(this.toRawBytes())}}jt.BASE=new jt(Mt,Pt,1n,$t(Mt*Pt)),jt.ZERO=new jt(0n,1n,1n,0n);const{BASE:qt,ZERO:zt}=jt,Wt=(e,t)=>e.toString(16).padStart(t,"0"),Jt=e=>Array.from(Kt(e)).map(e=>Wt(e,2)).join(""),Yt=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0,Xt=e=>{const t="hex invalid";if(!Vt(e))return Ht(t);const r=e.length,s=r/2;if(r%2)return Ht(t);const i=Qt(s);for(let r=0,n=0;r<s;r++,n+=2){const s=Yt(e.charCodeAt(n)),a=Yt(e.charCodeAt(n+1));if(void 0===s||void 0===a)return Ht(t);i[r]=16*s+a}return i},Zt=e=>Xt(Wt(e,64)).reverse(),er=e=>BigInt("0x"+Jt(Qt(Kt(e)).reverse())),tr=(...e)=>{const t=Qt(e.reduce((e,t)=>e+Kt(t).length,0));let r=0;return e.forEach(e=>{t.set(e,r),r+=e.length}),t},rr=(e,t)=>{(0n===e||t<=0n)&&Ht("no inverse n="+e+" mod="+t);let r=$t(e,t),s=t,i=0n,n=1n,a=1n,o=0n;for(;0n!==r;){const e=s/r,t=s%r,c=i-a*e,l=n-o*e;s=r,r=t,i=a,n=o,a=c,o=l}return 1n===s?$t(i,t):Ht("no inverse")},sr=(e,t)=>{let r=e;for(;t-- >0n;)r*=r,r%=Nt;return r},ir=19681161376707505956807079304988542015446066515923890162744021073123829784752n,nr=(e,t)=>{const r=$t(t*t*t),s=(e=>{const t=e*e%Nt*e%Nt,r=sr(t,2n)*t%Nt,s=sr(r,1n)*e%Nt,i=sr(s,5n)*s%Nt,n=sr(i,10n)*i%Nt,a=sr(n,20n)*n%Nt,o=sr(a,40n)*a%Nt,c=sr(o,80n)*o%Nt,l=sr(c,80n)*o%Nt,d=sr(l,10n)*i%Nt;return{pow_p_5_8:sr(d,2n)*e%Nt,b2:t}})(e*$t(r*r*t)).pow_p_5_8;let i=$t(e*r*s);const n=$t(t*i*i),a=i,o=$t(i*ir),c=n===e,l=n===$t(-e),d=n===$t(-e*ir);return c&&(i=a),(l||d)&&(i=o),1n==(1n&$t(i))&&(i=$t(-i)),{isValid:c||l,value:i}},ar=e=>$t(er(e),Dt);let or;const cr=(...e)=>fr.sha512Async(...e),lr=e=>{const t=e.slice(0,32);t[0]&=248,t[31]&=127,t[31]|=64;const r=e.slice(32,64),s=ar(t),i=qt.mul(s),n=i.toRawBytes();return{head:t,prefix:r,scalar:s,point:i,pointBytes:n}},dr=e=>cr(Ft(e,32)).then(lr);function ur(e,t){return e?cr(t.hashable).then(t.finish):t.finish(((...e)=>"function"==typeof or?or(...e):Ht("etc.sha512Sync not set"))(t.hashable))}const hr=()=>"object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,fr={bytesToHex:Jt,hexToBytes:Xt,concatBytes:tr,mod:$t,invert:rr,randomBytes:(e=32)=>{const t=hr();return t&&t.getRandomValues||Ht("crypto.getRandomValues must be defined"),t.getRandomValues(Qt(e))},sha512Async:async(...e)=>{const t=hr(),r=t&&t.subtle;r||Ht("etc.sha512Async or crypto.subtle must be defined");const s=tr(...e);return Qt(await r.digest("SHA-512",s.buffer))},sha512Sync:void 0};let gr;Object.defineProperties(fr,{sha512Sync:{configurable:!1,get:()=>or,set(e){or||(or=e)}}});const pr=e=>{const t=gr||(gr=(()=>{const e=[];let t=qt,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=zt,i=qt;const n=BigInt(255),a=BigInt(8);for(let o=0;o<33;o++){const c=128*o;let l=Number(e&n);e>>=a,l>128&&(l-=256,e+=1n);const d=c,u=c+Math.abs(l)-1,h=o%2!=0,f=l<0;0===l?i=i.add(r(h,t[d])):s=s.add(r(f,t[u]))}return{p:s,f:i}};var br=a(625);const mr=32,yr=64;class Ar{pubKey;_privKey;constructor(e,t){this.pubKey=e,this._privKey=t}}async function Ir(e){const t=await(r=e.raw,dr(r).then(e=>e.pointBytes));var r;return new Ar(L.fromBlob(t,mr).asOpaque(),e.asOpaque())}async function vr(e,t){const r=await(async(e,t)=>{const r=Ft(e),s=await dr(t);return ur(!0,((e,t,r)=>{const{pointBytes:s,scalar:i}=e,n=ar(t),a=qt.mul(n).toRawBytes();return{hashable:tr(a,s,r),finish:e=>{const t=$t(n+ar(e)*i,Dt);return Kt(tr(a,Zt(t)),64)}}})(s,await cr(s.prefix,r),r))})(t.raw,e._privKey.raw);return L.fromBlob(r,yr).asOpaque()}async function wr(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+=mr,r.set(n.raw,s),s+=yr;const e=i.length;w(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,br.verify_ed25519)(r)).map(e=>1===e);return Promise.resolve(i)}const Sr=L.blobFromString("jam_val_key_ed25519");L.blobFromString("jam_val_key_bandersnatch");class Er extends B{anchor;bitfield;validatorIndex;signature;static Codec=Be.Class(Er,{anchor:Be.bytes(Pe).asOpaque(),bitfield:kt(e=>Be.bitVecFixLen(e.coresCount)),validatorIndex:Be.u16.asOpaque(),signature:Be.bytes(yr).asOpaque()});static create({anchor:e,bitfield:t,validatorIndex:r,signature:s}){return new Er(e,t,r,s)}constructor(e,t,r,s){super(),this.anchor=e,this.bitfield=t,this.validatorIndex=r,this.signature=s}}const Cr=kt(e=>xt(Er.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2})),kr=e=>ee.array((e=>ee.object({anchor:Tt.bytes32(),bitfield:ee.fromString(t=>{const r=Math.ceil(e.coresCount/8);return J.fromBytes(L.parseBytes(t,r),e.coresCount)}),validator_index:"number",signature:Tt.ed25519Signature},({anchor:e,bitfield:t,validator_index:r,signature:s})=>Er.create({anchor:e,bitfield:t,validatorIndex:r,signature:s})))(e));class xr extends B{workReportHash;wasConsideredValid;key;signature;static Codec=Be.Class(xr,{workReportHash:Be.bytes(Pe).asOpaque(),wasConsideredValid:Be.bool,key:Be.bytes(mr).asOpaque(),signature:Be.bytes(yr).asOpaque()});static create({workReportHash:e,wasConsideredValid:t,key:r,signature:s}){return new xr(e,t,r,s)}constructor(e,t,r,s){super(),this.workReportHash=e,this.wasConsideredValid=t,this.key=r,this.signature=s}}class Br extends B{workReportHash;key;signature;static Codec=Be.Class(Br,{workReportHash:Be.bytes(Pe).asOpaque(),key:Be.bytes(mr).asOpaque(),signature:Be.bytes(yr).asOpaque()});static create({workReportHash:e,key:t,signature:r}){return new Br(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.key=t,this.signature=r}}class _r extends B{isWorkReportValid;index;signature;static Codec=Be.Class(_r,{isWorkReportValid:Be.bool,index:Be.u16.asOpaque(),signature:Be.bytes(yr).asOpaque()});static create({isWorkReportValid:e,index:t,signature:r}){return new _r(e,t,r)}constructor(e,t,r){super(),this.isWorkReportValid=e,this.index=t,this.signature=r}}class Rr extends B{workReportHash;votesEpoch;votes;static Codec=Be.Class(Rr,{workReportHash:Be.bytes(Pe).asOpaque(),votesEpoch:Be.u32.asOpaque(),votes:kt(e=>ke(Be.sequenceFixLen(_r.Codec,e.validatorsSuperMajority)).convert(R,mt))});static create({workReportHash:e,votesEpoch:t,votes:r}){return new Rr(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.votesEpoch=t,this.votes=r}}class Or extends B{verdicts;culprits;faults;static Codec=Be.Class(Or,{verdicts:Be.sequenceVarLen(Rr.Codec),culprits:Be.sequenceVarLen(Br.Codec),faults:Be.sequenceVarLen(xr.Codec)});static create({verdicts:e,culprits:t,faults:r}){return new Or(e,t,r)}constructor(e,t,r){super(),this.verdicts=e,this.culprits=t,this.faults=r}}const Ur=e=>ne(e),Tr=e=>se(e),Nr=e=>ne(e),Dr=e=>oe(e),Mr=e=>se(e),Pr=e=>ne(e);function Lr(e,t){return w(e.length===t.validatorsCount,`Invalid per-validator array length. Expected ${t.validatorsCount}, got: ${e.length}`),e}const Hr=e=>kt(t=>xt(e,{fixedLength:t.validatorsCount}));function Vr(e,t){return w(e.length===t.epochLength,`Invalid per-epoch-block array length. Expected ${t.epochLength}, got: ${e.length}`),e}const Kr=e=>kt(t=>xt(e,{fixedLength:t.epochLength}));class Qr extends B{anchor;stateRoot;beefyRoot;lookupAnchor;lookupAnchorSlot;prerequisites;static Codec=Be.Class(Qr,{anchor:Be.bytes(Pe).asOpaque(),stateRoot:Be.bytes(Pe).asOpaque(),beefyRoot:Be.bytes(Pe).asOpaque(),lookupAnchor:Be.bytes(Pe).asOpaque(),lookupAnchorSlot:Be.u32.asOpaque(),prerequisites:Be.sequenceVarLen(Be.bytes(Pe).asOpaque())});static create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n}){return new Qr(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}}const Fr=2048;class $r extends B{treeRoot;index;static Codec=Be.Class($r,{treeRoot:Be.bytes(Pe),index:Be.u16.asOpaque()});static create({treeRoot:e,index:t}){return new $r(e,t)}constructor(e,t){super(),this.treeRoot=e,this.index=t}}class Gr extends B{hash;len;static Codec=Be.Class(Gr,{hash:Be.bytes(Pe).asOpaque(),len:Be.u32});static create({hash:e,len:t}){return new Gr(e,t)}constructor(e,t){super(),this.hash=e,this.len=t}}class jr extends B{service;codeHash;payload;refineGasLimit;accumulateGasLimit;importSegments;extrinsic;exportCount;static Codec=v.isGreaterOrEqual(h.V0_7_0)?Be.Class(jr,{service:Be.u32.asOpaque(),codeHash:Be.bytes(Pe).asOpaque(),refineGasLimit:Be.u64.asOpaque(),accumulateGasLimit:Be.u64.asOpaque(),exportCount:Be.u16,payload:Be.blob,importSegments:xt($r.Codec,{minLength:0,maxLength:Fr,typicalLength:Fr}),extrinsic:Be.sequenceVarLen(Gr.Codec)}):Be.Class(jr,{service:Be.u32.asOpaque(),codeHash:Be.bytes(Pe).asOpaque(),payload:Be.blob,refineGasLimit:Be.u64.asOpaque(),accumulateGasLimit:Be.u64.asOpaque(),importSegments:xt($r.Codec,{minLength:0,maxLength:Fr,typicalLength:Fr}),extrinsic:Be.sequenceVarLen(Gr.Codec),exportCount:Be.u16});static create({service:e,codeHash:t,payload:r,refineGasLimit:s,accumulateGasLimit:i,importSegments:n,extrinsic:a,exportCount:o}){return new jr(e,t,r,s,i,n,a,o)}constructor(e,t,r,s,i,n,a,o){super(),this.service=e,this.codeHash=t,this.payload=r,this.refineGasLimit=s,this.accumulateGasLimit=i,this.importSegments=n,this.extrinsic=a,this.exportCount=o}}function qr(e){return S(e,e>=zr&&e<=Wr,`WorkItemsCount: Expected '${zr} <= count <= ${Wr}' got ${e}`)}const zr=1,Wr=16;class Jr extends B{authorization;authCodeHost;authCodeHash;parametrization;context;items;static Codec=v.isGreaterOrEqual(h.V0_7_0)?Be.Class(Jr,{authCodeHost:Be.u32.asOpaque(),authCodeHash:Be.bytes(Pe).asOpaque(),context:Qr.Codec,authorization:Be.blob,parametrization:Be.blob,items:Be.sequenceVarLen(jr.Codec).convert(e=>e,e=>yt.new(e,qr(e.length)))}):Be.Class(Jr,{authorization:Be.blob,authCodeHost:Be.u32.asOpaque(),authCodeHash:Be.bytes(Pe).asOpaque(),parametrization:Be.blob,context:Qr.Codec,items:Be.sequenceVarLen(jr.Codec).convert(e=>e,e=>yt.new(e,qr(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 Yr,Xr;(Xr=Yr||(Yr={}))[Xr.ok=0]="ok",Xr[Xr.outOfGas=1]="outOfGas",Xr[Xr.panic=2]="panic",Xr[Xr.badCode=3]="badCode",Xr[Xr.codeOversize=4]="codeOversize";class Zr extends B{kind;okBlob;static Codec=Be.custom({name:"WorkExecResult",sizeHint:{bytes:1,isExact:!1}},(e,t)=>{e.varU32(ne(t.kind)),t.kind===Yr.ok&&null!==t.okBlob&&e.bytesBlob(t.okBlob)},e=>{const t=e.varU32();if(t===Yr.ok){const r=e.bytesBlob();return new Zr(t,r)}if(t>Yr.codeOversize)throw new Error(`Invalid WorkExecResultKind: ${t}`);return new Zr(t)},e=>{e.decoder.varU32()===Yr.ok&&e.bytesBlob()});constructor(e,t=null){super(),this.kind=e,this.okBlob=t}}class es extends B{gasUsed;importedSegments;extrinsicCount;extrinsicSize;exportedSegments;static Codec=Be.Class(es,{gasUsed:Be.varU64.asOpaque(),importedSegments:Be.varU32,extrinsicCount:Be.varU32,extrinsicSize:Be.varU32,exportedSegments:Be.varU32});static create({gasUsed:e,importedSegments:t,extrinsicCount:r,extrinsicSize:s,exportedSegments:i}){return new es(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 ts{serviceId;codeHash;payloadHash;gas;result;load;static Codec=Be.Class(ts,{serviceId:Be.u32.asOpaque(),codeHash:Be.bytes(Pe).asOpaque(),payloadHash:Be.bytes(Pe),gas:Be.u64.asOpaque(),result:Zr.Codec,load:es.Codec});static create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n}){return new ts(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 rs extends B{hash;length;erasureRoot;exportsRoot;exportsCount;static Codec=Be.Class(rs,{hash:Be.bytes(Pe).asOpaque(),length:Be.u32,erasureRoot:Be.bytes(Pe),exportsRoot:Be.bytes(Pe).asOpaque(),exportsCount:Be.u16});static create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i}){return new rs(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 ss extends B{workPackageHash;segmentTreeRoot;static Codec=Be.Class(ss,{workPackageHash:Be.bytes(Pe).asOpaque(),segmentTreeRoot:Be.bytes(Pe).asOpaque()});constructor(e,t){super(),this.workPackageHash=e,this.segmentTreeRoot=t}static create({workPackageHash:e,segmentTreeRoot:t}){return new ss(e,t)}}class is extends B{workPackageSpec;context;coreIndex;authorizerHash;authorizationOutput;segmentRootLookup;results;authorizationGasUsed;static Codec;static create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:n,results:a,authorizationGasUsed:o}){return new is(e,t,r,s,i,n,a,o)}constructor(e,t,r,s,i,n,a,o){super(),this.workPackageSpec=e,this.context=t,this.coreIndex=r,this.authorizerHash=s,this.authorizationOutput=i,this.segmentRootLookup=n,this.results=a,this.authorizationGasUsed=o}}const ns=Be.Class(is,{workPackageSpec:rs.Codec,context:Qr.Codec,coreIndex:Be.varU32.convert(e=>ne(e),e=>{if(!ie(e))throw new Error(`Core index exceeds U16: ${e}`);return Mr(e)}),authorizerHash:Be.bytes(Pe).asOpaque(),authorizationGasUsed:Be.varU64.asOpaque(),authorizationOutput:Be.blob,segmentRootLookup:ke(Be.sequenceVarLen(ss.Codec)),results:Be.sequenceVarLen(ts.Codec).convert(e=>e,e=>yt.new(e,qr(e.length)))}),as=Be.Class(is,{workPackageSpec:rs.Codec,context:Qr.Codec,coreIndex:v.isGreaterOrEqual(h.V0_6_5)&&!v.isSuite(f.JAMDUNA,h.V0_6_5)?Be.varU32.convert(e=>ne(e),e=>{if(!ie(e))throw new Error(`Core index exceeds U16: ${e}`);return Mr(e)}):Be.u16.asOpaque(),authorizerHash:Be.bytes(Pe).asOpaque(),authorizationOutput:Be.blob,segmentRootLookup:ke(Be.sequenceVarLen(ss.Codec)),results:Be.sequenceVarLen(ts.Codec).convert(e=>e,e=>yt.new(e,qr(e.length))),authorizationGasUsed:Be.varU64.asOpaque()});is.Codec=v.isGreaterOrEqual(h.V0_7_0)?ns:as;const os=[2,3];class cs extends B{validatorIndex;signature;static Codec=Be.Class(cs,{validatorIndex:Be.u16.asOpaque(),signature:Be.bytes(yr).asOpaque()});static create({validatorIndex:e,signature:t}){return new cs(e,t)}constructor(e,t){super(),this.validatorIndex=e,this.signature=t}}class ls extends B{report;slot;credentials;static Codec=Be.Class(ls,{report:is.Codec,slot:Be.u32.asOpaque(),credentials:xt(cs.Codec,{minLength:os[0],maxLength:os[1],typicalLength:os[1]})});static create({report:e,slot:t,credentials:r}){return new ls(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.credentials=r}}const ds=kt(e=>xt(ls.Codec,{minLength:0,maxLength:e.coresCount,typicalLength:e.coresCount}));class us extends B{bandersnatch;ed25519;static Codec=Be.Class(us,{bandersnatch:Be.bytes(Te).asOpaque(),ed25519:Be.bytes(mr).asOpaque()});static create({bandersnatch:e,ed25519:t}){return new us(e,t)}constructor(e,t){super(),this.bandersnatch=e,this.ed25519=t}}class hs extends B{entropy;ticketsEntropy;validators;static Codec=Be.Class(hs,{entropy:Be.bytes(Pe).asOpaque(),ticketsEntropy:Be.bytes(Pe).asOpaque(),validators:Hr(us.Codec)});static create({entropy:e,ticketsEntropy:t,validators:r}){return new hs(e,t,r)}constructor(e,t,r){super(),this.entropy=e,this.ticketsEntropy=t,this.validators=r}}const fs=e=>{const t=e.encoded().raw,r=t.length-Ne;return P.blobFrom(t.subarray(0,r))},gs={parentHeaderHash:Be.bytes(Pe).asOpaque(),priorStateRoot:Be.bytes(Pe).asOpaque(),extrinsicHash:Be.bytes(Pe).asOpaque(),timeSlotIndex:Be.u32.asOpaque(),epochMarker:Be.optional(hs.Codec),ticketsMarker:Be.optional(Kr(Ot.Codec)),offendersMarker:Be.sequenceVarLen(Be.bytes(mr).asOpaque()),bandersnatchBlockAuthorIndex:Be.u16.asOpaque(),entropySource:Be.bytes(Ne).asOpaque(),seal:Be.bytes(Ne).asOpaque()};class ps extends B{static Codec=Be.Class(ps,v.isLessThan(h.V0_7_0)?gs:{parentHeaderHash:Be.bytes(Pe).asOpaque(),priorStateRoot:Be.bytes(Pe).asOpaque(),extrinsicHash:Be.bytes(Pe).asOpaque(),timeSlotIndex:Be.u32.asOpaque(),epochMarker:Be.optional(hs.Codec),ticketsMarker:Be.optional(Kr(Ot.Codec)),bandersnatchBlockAuthorIndex:Be.u16.asOpaque(),entropySource:Be.bytes(Ne).asOpaque(),offendersMarker:Be.sequenceVarLen(Be.bytes(mr).asOpaque()),seal:Be.bytes(Ne).asOpaque()});static create(e){return Object.assign(ps.empty(),e)}parentHeaderHash=L.zero(Pe).asOpaque();priorStateRoot=L.zero(Pe).asOpaque();extrinsicHash=L.zero(Pe).asOpaque();timeSlotIndex=Ur(0);epochMarker=null;ticketsMarker=null;bandersnatchBlockAuthorIndex=Tr(0);entropySource=L.zero(Ne).asOpaque();offendersMarker=[];seal=L.zero(Ne).asOpaque();constructor(){super()}static empty(){return new ps}}class bs extends He{static Codec=Be.Class(bs,{hash:Be.bytes(Pe).asOpaque(),data:ps.Codec.View});static create({hash:e,data:t}){return new He(e,t)}}const ms=bs.Codec;class ys extends B{requester;blob;static Codec=Be.Class(ys,{requester:Be.u32.asOpaque(),blob:Be.blob});static create({requester:e,blob:t}){return new ys(e,t)}constructor(e,t){super(),this.requester=e,this.blob=t}}const As=Be.sequenceVarLen(ys.Codec);class Is extends B{tickets;preimages;guarantees;assurances;disputes;static Codec=Be.Class(Is,{tickets:Ut,preimages:As,guarantees:ds,assurances:Cr,disputes:Or.Codec});static create({tickets:e,preimages:t,assurances:r,disputes:s,guarantees:i}){return new Is(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 vs extends B{header;extrinsic;static Codec=Be.Class(vs,{header:ps.Codec,extrinsic:Is.Codec});static create({header:e,extrinsic:t}){return new vs(e,t)}constructor(e,t){super(),this.header=e,this.extrinsic=t}}const ws=ee.object({target:Tt.bytes32(),vote:"boolean",key:Tt.bytes32(),signature:Tt.ed25519Signature},({target:e,vote:t,key:r,signature:s})=>xr.create({workReportHash:e,wasConsideredValid:t,key:r,signature:s})),Ss=ee.object({target:Tt.bytes32(),key:Tt.bytes32(),signature:Tt.ed25519Signature},({target:e,key:t,signature:r})=>Br.create({workReportHash:e,key:t,signature:r})),Es=ee.object({vote:"boolean",index:"number",signature:Tt.ed25519Signature},({vote:e,index:t,signature:r})=>_r.create({isWorkReportValid:e,index:t,signature:r})),Cs=ee.object({target:Tt.bytes32(),age:"number",votes:ee.array(Es)},({target:e,age:t,votes:r})=>Rr.create({workReportHash:e,votesEpoch:t,votes:r})),ks=ee.object({verdicts:ee.array(Cs),culprits:ee.array(Ss),faults:ee.array(ws)},({verdicts:e,culprits:t,faults:r})=>Or.create({verdicts:e,culprits:t,faults:r})),xs=ee.object({anchor:Tt.bytes32(),state_root:Tt.bytes32(),beefy_root:Tt.bytes32(),lookup_anchor:Tt.bytes32(),lookup_anchor_slot:"number",prerequisites:ee.array(Tt.bytes32())},({anchor:e,state_root:t,beefy_root:r,lookup_anchor:s,lookup_anchor_slot:i,prerequisites:n})=>Qr.create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n})),Bs=ee.object({ok:ee.optional(ee.fromString(P.parseBlob)),out_of_gas:ee.optional(ee.fromAny(()=>null)),panic:ee.optional(ee.fromAny(()=>null)),bad_code:ee.optional(ee.fromAny(()=>null)),code_oversize:ee.optional(ee.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(ne(Yr.ok),t);if(null===r)return new Zr(ne(Yr.outOfGas));if(null===s)return new Zr(ne(Yr.panic));if(null===i)return new Zr(ne(Yr.badCode));if(null===n)return new Zr(ne(Yr.codeOversize));throw new Error("Invalid WorkExecResult")}),_s=ee.object({gas_used:ee.fromNumber(e=>Dr(e)),imports:"number",extrinsic_count:"number",extrinsic_size:"number",exports:"number"},({gas_used:e,imports:t,extrinsic_count:r,extrinsic_size:s,exports:i})=>es.create({gasUsed:Dr(e),importedSegments:ne(t),extrinsicCount:ne(r),extrinsicSize:ne(s),exportedSegments:ne(i)})),Rs=ee.object({service_id:"number",code_hash:Tt.bytes32(),payload_hash:Tt.bytes32(),accumulate_gas:ee.fromNumber(e=>Dr(e)),result:Bs,refine_load:_s},({service_id:e,code_hash:t,payload_hash:r,accumulate_gas:s,result:i,refine_load:n})=>ts.create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n})),Os=ee.object({hash:Tt.bytes32(),length:"number",erasure_root:Tt.bytes32(),exports_root:Tt.bytes32(),exports_count:"number"},({hash:e,length:t,erasure_root:r,exports_root:s,exports_count:i})=>rs.create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i})),Us=ee.object({work_package_hash:Tt.bytes32(),segment_tree_root:Tt.bytes32()},({work_package_hash:e,segment_tree_root:t})=>ss.create({workPackageHash:e,segmentTreeRoot:t})),Ts=ee.object({package_spec:Os,context:xs,core_index:"number",authorizer_hash:Tt.bytes32(),auth_output:ee.fromString(P.parseBlob),segment_root_lookup:ee.array(Us),results:ee.array(Rs),auth_gas_used:ee.fromNumber(e=>Dr(e))},({package_spec:e,context:t,core_index:r,authorizer_hash:s,auth_output:i,results:n,segment_root_lookup:a,auth_gas_used:o})=>{const c=yt.new(n,qr(n.length));return is.create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:a,results:c,authorizationGasUsed:o})}),Ns=ee.object({validator_index:"number",signature:Tt.ed25519Signature},({validator_index:e,signature:t})=>cs.create({validatorIndex:e,signature:t})),Ds=ee.object({report:Ts,slot:"number",signatures:ee.array(Ns)},({report:e,slot:t,signatures:r})=>ls.create({report:e,slot:t,credentials:r})),Ms=ee.array(Ds),Ps=ee.object({requester:"number",blob:ee.fromString(P.parseBlob)},({requester:e,blob:t})=>ys.create({requester:e,blob:t})),Ls=ee.array(Ps),Hs=ee.object({attempt:Tt.ticketAttempt,signature:ee.fromString(e=>L.parseBytes(e,784).asOpaque())},e=>Rt.create({attempt:e.attempt,signature:e.signature})),Vs=ee.array(Hs),Ks=ee.fromString(e=>L.parseBytes(e,96).asOpaque()),Qs=ee.object({bandersnatch:Tt.bytes32(),ed25519:Tt.bytes32()},us.create),Fs=ee.object({entropy:Tt.bytes32(),tickets_entropy:Tt.bytes32(),validators:ee.array(Qs)},e=>hs.create({entropy:e.entropy,ticketsEntropy:e.tickets_entropy,validators:e.validators})),$s=ee.object({id:Tt.bytes32(),attempt:Tt.ticketAttempt},e=>Ot.create({id:e.id,attempt:e.attempt})),Gs=ee.object({parent:Tt.bytes32(),parent_state_root:Tt.bytes32(),extrinsic_hash:Tt.bytes32(),slot:"number",epoch_mark:ee.optional(Fs),tickets_mark:ee.optional(ee.array($s)),offenders_mark:ee.array(Tt.bytes32()),author_index:"number",entropy_source:Ks,seal:Ks},({parent:e,parent_state_root:t,extrinsic_hash:r,slot:s,epoch_mark:i,tickets_mark:n,offenders_mark:a,author_index:o,entropy_source:c,seal:l})=>{const d=ps.empty();return d.parentHeaderHash=e,d.priorStateRoot=t,d.extrinsicHash=r,d.timeSlotIndex=s,d.epochMarker=i??null,d.ticketsMarker=n??null,d.offendersMarker=a,d.bandersnatchBlockAuthorIndex=o,d.entropySource=c,d.seal=l,d}),js=t(import.meta.url)("node:timers/promises");var qs;function zs(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)}}function Ws(e){const t="debug"===e?"LOG":e.toUpperCase();if(void 0===qs[t])throw new Error(`Unknown logging level: "${e}". Use one of "trace", "debug", "log","info", "warn", "error"`);return qs[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"}(qs||(qs={}));class Js{options;static create(e,t){return e===qs.TRACE?new Ys(t):e===qs.LOG?new Xs(t):e===qs.INFO?new Zs(t):new Js(t)}constructor(e){this.options=e}trace(e,t,r){}log(e,t,r){}info(e,t,r){}warn(e,t,r){this.push(qs.WARN,e,t,r)}error(e,t,r){this.push(qs.ERROR,e,t,r)}push(e,t,r,s){const i=r.replace(this.options.workingDir,""),n=t.replace(this.options.workingDir,""),a=zs(this.options,t),o=qs[e].padEnd(5);if(e<a)return;const c=`${o} [${n}] ${s}\n\t@ ${i}`;e===qs.WARN?console.warn(c):e===qs.ERROR?console.error(c):console.info(c)}}class Ys extends Js{trace(e,t,r){this.push(qs.TRACE,e,t,r)}log(e,t,r){this.push(qs.LOG,e,t,r)}info(e,t,r){this.push(qs.INFO,e,t,r)}}class Xs extends Js{trace(e,t,r){}log(e,t,r){this.push(qs.LOG,e,t,r)}info(e,t,r){this.push(qs.INFO,e,t,r)}}class Zs extends Js{trace(e,t,r){}log(e,t,r){}info(e,t,r){this.push(qs.INFO,e,t,r)}}const ei={workingDir:"",defaultLevel:qs.LOG,modules:new Map},ti={options:ei,transport:Js.create(ei.defaultLevel,ei)};class ri{moduleName;fileName;config;static new(e,t){const r=e??"unknown";return new ri(t??r,r,ti)}static getLevel(e){return zs(ti.options,e)}static configureAllFromOptions(e){const t=Array.from(e.modules.values()).reduce((e,t)=>e<t?e:t,e.defaultLevel),r=Js.create(t,e);ti.options=e,ti.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(),Ws(r.trim()))}else n=Ws(t)}const a="".split("/");return a.pop(),a.pop(),{defaultLevel:n,modules:s,workingDir:r??a.join("/")}}(e,t,r);ri.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)}}var si;!function(e){e[e.NOTSET=0]="NOTSET",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=100]="SILENT"}(si||(si={}));const ii="captureStackTrace"in Error,ni="stackTraceLimit"in Error;function ai(e){switch(e){case si.NOTSET:return"NOTSET";case si.DEBUG:return"DEBUG";case si.INFO:return"INFO";case si.WARN:return"WARN";case si.ERROR:return"ERROR";case si.SILENT:return"SILENT"}}function oi(e,t){return"function"==typeof t?t():t}function ci(e){return JSON.stringify(e,oi)}const li=Symbol("level"),di=Symbol("key"),ui=Symbol("keys"),hi=Symbol("date"),fi=Symbol("msg"),gi=Symbol("stack"),pi=Symbol("data");function bi(e,...t){return r=>{let s=e[0];for(let i=0;i<t.length;i++){const n=t[i];if(n===di)s+=r.key;else if(n===ui)s+=r.keys;else if(n===hi)s+=r.date().toISOString();else if(n===fi)null!=r.msg&&(s+=r.msg);else if(n===li)s+=ai(r.level);else if(n===pi)s+=ci(r.data);else if(n===gi){const e=r.stack();""!==e&&(s+="\n"+e)}else s+=n.toString();s+=e[i+1]}return s}}const mi=bi`${li}:${di}:${fi}`,yi=class{formatter;constructor(e=mi){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)}},Ai=class extends yi{emit(e){console.error(e)}};class Ii{key;level;filter;keys;handlers;parent;_loggers=new Map;loggersRegistry;constructor(e="root",t=si.NOTSET,r=[new Ai],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 Ii(e,si.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!==si.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,{},si.DEBUG,t):this.log(e,t,si.DEBUG,r)}info(e,t,r){return null==t||"function"==typeof t?this.log(e,{},si.INFO,t):this.log(e,t,si.INFO,r)}warn(e,t,r){return null==t||"function"==typeof t?this.log(e,{},si.WARN,t):this.log(e,t,si.WARN,r)}error(e,t,r){return null==t||"function"==typeof t?this.log(e,{},si.ERROR,t):this.log(e,t,si.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(ii&&ni){Error.stackTraceLimit++;const t={};Error.captureStackTrace(t,Ii.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 vi=Ii,wi=t(import.meta.url)("node:process"),Si=class extends yi{emit(e){wi.stderr.write(e+"\n")}},Ei=t(import.meta.url)("dgram");class Ci 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 ki=Ci;class xi extends ki{constructor(e){super(xi.name,e,arguments)}}const Bi=xi;class _i extends ki{constructor(e){super(_i.name,e,arguments)}}const Ri=_i;class Oi extends ki{constructor(e){super(Oi.name,e,arguments)}}const Ui=Oi,Ti=Symbol("_eventTarget"),Ni=Symbol("eventTarget"),Di=Symbol("_eventHandlers"),Mi=Symbol("eventHandlers"),Pi=Symbol("_eventHandled"),Li=Symbol("eventHandled"),Hi=Symbol("_handleEventError"),Vi=Symbol("handleEventError");function Ki(e){return{capture:!1,once:!1,passive:!1,..."boolean"==typeof e?{capture:e}:"object"==typeof e?e:void 0}}function Qi(e,t){return e.capture===t.capture}function Fi(){return e=>{const t=class extends e{[Ti]=new EventTarget;[Di]=new Map;[Pi]=new WeakSet;[Hi]=e=>{throw e.detail};constructor(...e){super(...e),this[Ti].addEventListener(Ui.name,this[Hi])}get[Ni](){return this[Ti]}get[Mi](){return this[Di]}get[Li](){return this[Pi]}get[Vi](){return this[Hi]}addEventListener(e,t,r){r=Ki(r);const s=this;let i,n,a=!1;if("function"==typeof t||"function"==typeof t?.handleEvent){n=this[Di].get(e),void 0===n&&(n=new Set,this[Di].set(e,n));for(const e of n)if(e.callback===t&&(i=e.handler,Qi(e.options,r))){a=!0;break}}"function"==typeof t?null==i?(i=async function(e){let r;s[Pi].add(e);try{r=t.call(s,e)}catch(e){this.dispatchEvent(new Ui({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new Ui({detail:e}))}},n.add({callback:t,options:r,handler:i})):a||n.add({callback:t,options:r,handler:i}):"function"==typeof t?.handleEvent?null==i?(i=async function(e){let r;s[Pi].add(e);try{r=t.handleEvent(e)}catch(e){this.dispatchEvent(new Ui({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new Ui({detail:e}))}return r},n.add({callback:t,options:r,handler:i})):a||n.add({callback:t,options:r,handler:i}):i=t,this[Ti].addEventListener(e,i,r),e===Ui.name&&1===n?.size&&this[Ti].removeEventListener(Ui.name,this[Hi])}removeEventListener(e,t,r){let s,i,n;if(r=Ki(r),null!=t){if(i=this[Di].get(e),void 0===i)return;for(const e of i)if(e.callback===t&&Qi(e.options,r)){s=e.handler,n=e;break}if(null==s)return}else s=t;this[Ti].removeEventListener(e,s,r),null!=i&&null!=n&&(i.delete(n),e===Ui.name&&0===i.size&&this[Ti].addEventListener(Ui.name,this[Hi]))}dispatchEvent(e){if(Object.defineProperties(e,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),e instanceof Ui)return this[Ti].dispatchEvent(e);{let t=this[Ti].dispatchEvent(e);if(t&&!this[Pi].has(e)){const r=new Bi({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[Ti].dispatchEvent(r)}if(t){const r=new Ri({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[Ti].dispatchEvent(r)}return t}}};return Object.defineProperty(t,"name",Object.getOwnPropertyDescriptor(e,"name")),t}}async function $i(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*Gi(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 ji extends Promise{static get[Symbol.species](){return Promise}static resolve(e){return e instanceof ji?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 a=super.then(i,n),o=ji.from(a,r);return s=o.abortController.signal,o}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 qi=ji,zi=t(import.meta.url)("node:perf_hooks");var Wi,Ji=(Wi=function(e,t){return Wi=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])},Wi(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}Wi(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),Yi=function(e){function t(t){var r,s,i,n=this.constructor,a=e.call(this,t)||this;return Object.defineProperty(a,"name",{value:n.name,enumerable:!1,configurable:!0}),r=a,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)}(a),a}return Ji(t,e),t}(Error);const Xi=class extends Yi{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(zi.performance.timeOrigin+zi.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 Zi(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=Zi(s,t,r);if(e)return e}return Zi(e.cause,t,r)}return e instanceof Error&&Zi(e.cause,t,r)}class en extends Xi{static description="Timer error"}class tn extends en{static description="The timer has already ended"}class rn{_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 qi((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(zi.performance.timeOrigin+zi.performance.now()),this._scheduled=new Date(this.timestamp.getTime()+t)):(this.timeoutRef=setInterval(()=>{},2**31-1),this.timestamp=new Date(zi.performance.timeOrigin+zi.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()-(zi.performance.timeOrigin+zi.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 tn;return this.reset(this._delay)}reset(e){if(null!=this._status)throw new tn;clearTimeout(this.timeoutRef),this._delay=e,isFinite(e)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},e),this._scheduled=new Date(zi.performance.timeOrigin+zi.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 sn=rn;function nn(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function an(e,t,r,s,i,n){let a,o;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){a=new AbortController;const e=new s,t=new sn(()=>{a.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),a.abort(n.reason)};n.aborted?(t.cancel(),a.abort(n.reason)):n.addEventListener("abort",c),i.signal=a.signal,i.timer=t,o=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof sn&&void 0===i.signal){a=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||a.abort(e),r),()=>{}),i.signal=a.signal,o=()=>{t=!0}}else{a=new AbortController;const e=i.signal,t=()=>{a.abort(e.reason)};e.aborted?a.abort(e.reason):e.addEventListener("abort",t),i.signal=a.signal,o=()=>{e.removeEventListener("abort",t)}}else{a=new AbortController;const e=new s,t=new sn(()=>{a.abort(e)},i.timer??r);a.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=a.signal,i.timer=t,o=()=>{t.cancel()}}const c=e(i,...n);return new qi((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},a).finally(()=>{o()},a)}class on extends Xi{static description="Async locks error"}class cn extends on{static description="Async locks timeout"}const ln=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}:{},()=>an((e,t)=>{this._count++;const{p:r,resolveP:s,rejectP:i}=nn();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 a=!1;const o={task:()=>{this.currentWeight+=t,e.signal.removeEventListener("abort",n),s([async()=>{a||(a=!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,o),this.insertQueue(o),this.processQueue(),r},!0,1/0,cn,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}:{},an((e,t)=>{const{p:r,resolveP:s,rejectP:i}=nn();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)},a={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,a),this.insertQueue(a),this.processQueue(),r},!0,1/0,cn,r,[t])}withF(...e){const t=e.pop();return $i([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return Gi([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()}}},dn=class{semaphore=new ln(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 $i([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return Gi([this.lock(...e)],([e])=>t(e))}},un=class{readersLock=new dn;writersLock=new dn;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}:{},()=>an(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,cn,e,[])}write(e){return e=null!=e?{...e}:{},()=>an(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,cn,e,[])}waitForUnlock(e){const t=this.readersLock.waitForUnlock(e),r=this.writersLock.waitForUnlock(e);return qi.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 $i([this.read(...e)],([e])=>t(e))}withWriteF(...e){const t=e.pop();return $i([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 Gi([this.read(...e)],([e])=>t(e))}withWriteG(...e){const t=e.pop();return Gi([this.write(...e)],([e])=>t(e))}},hn=Symbol("_running"),fn=Symbol("running"),gn=Symbol("_destroyed"),pn=Symbol("destroyed"),bn=Symbol("_status"),mn=Symbol("status"),yn=Symbol("_statusP"),An=Symbol("statusP"),In=Symbol("resolveStatusP"),vn=Symbol("initLock"),wn=(async()=>{}).constructor,Sn=function*(){}.constructor,En=async function*(){}.constructor,Cn="captureStackTrace"in Error;function kn(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function xn(e,t){if(null!=e.stack){const r=e.stack.slice(0,e.stack.indexOf("\n")+1);Cn?Error.captureStackTrace(e,t):e.stack=(new Error).stack??"",e.stack=e.stack.replace(/[^\n]+\n/,r)}}class Bn extends ki{}class _n extends Bn{}class Rn extends Bn{}class On extends Bn{}class Un extends Bn{}class Tn extends Bn{}class Nn extends Bn{}class Dn extends Xi{static description="Async init error"}class Mn extends Dn{static description="Async init is not running"}class Pn extends Dn{static description="Async init is destroyed"}function Ln({eventDestroy:e=Tn,eventDestroyed:t=Nn}={}){return r=>{const{p:s,resolveP:i}=kn(),n=class extends(Fi()(r)){[gn]=!1;[bn]=null;[yn]=s;[In]=i;[vn]=new un;get[pn](){return this[gn]}get[mn](){return this[bn]}get[An](){return this[yn]}async destroy(...r){return this[vn].withWriteF(async()=>{if(this[gn])return;this[bn]="destroying",this[In]("destroying");const{p:s,resolveP:i}=kn();let n;return this[yn]=s,this[In]=i,this.dispatchEvent(new e),"function"==typeof super.destroy&&(n=await super.destroy(...r)),this[gn]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[bn]=null,this[In](null);const{p:e,resolveP:t}=kn();this[yn]=e,this[In]=t})}};return Object.defineProperty(n,"name",Object.getOwnPropertyDescriptor(r,"name")),n}}function Hn(e=new Pn,t=!1,r=[]){return(s,i,n)=>{let a;null!=n.value?a="value":null!=n.get?a="get":null!=n.set&&(a="set");const o=n[a];if("function"!=typeof o)throw new TypeError(`${i} is not a function`);return n[a]=o instanceof wn?async function(...s){if(this[vn].isLocked("write")&&null===this[bn]&&await this[yn],r.includes(this[bn]))return o.apply(this,s);if(t)return this[vn].withReadF(async()=>{if(this[gn])throw xn(e,n[a]),e;return o.apply(this,s)});if(this[vn].isLocked("write")||this[gn])throw xn(e,n[a]),e;return o.apply(this,s)}:o instanceof Sn?function*(...t){if(r.includes(this[bn]))return yield*o.apply(this,t);if(this[vn].isLocked("write")&&null!==this[mn]||this[gn])throw xn(e,n[a]),e;return yield*o.apply(this,t)}:o instanceof En?async function*(...s){if(this[vn].isLocked("write")&&null===this[bn]&&await this[yn],r.includes(this[bn]))return yield*o.apply(this,s);if(t)return yield*this[vn].withReadG(()=>{if(this[gn])throw xn(e,n[a]),e;return o.apply(this,s)});if(this[vn].isLocked("write")||this[gn])throw xn(e,n[a]),e;return yield*o.apply(this,s)}:function(...t){if(r.includes(this[bn]))return o.apply(this,t);if(this[vn].isLocked("write")&&null!==this[mn]||this[gn])throw xn(e,n[a]),e;return o.apply(this,t)},Object.defineProperty(n[a],"name",{value:i}),n}}function Vn({eventStart:e=_n,eventStarted:t=Rn,eventStop:r=On,eventStopped:s=Un}={}){return i=>{const{p:n,resolveP:a}=kn(),o=class extends(Fi()(i)){[hn]=!1;[bn]=null;[yn]=n;[In]=a;[vn]=new un;get[fn](){return this[hn]}get[mn](){return this[bn]}get[An](){return this[yn]}async start(...r){return this[vn].withWriteF(async()=>{if(this[hn])return;this[bn]="starting",this[In]("starting");const{p:s,resolveP:i}=kn();let n;return this[yn]=s,this[In]=i,this.dispatchEvent(new e),"function"==typeof super.start&&(n=await super.start(...r)),this[hn]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[bn]=null,this[In](null);const{p:e,resolveP:t}=kn();this[yn]=e,this[In]=t})}async stop(...e){return this[vn].withWriteF(async()=>{if(!this[hn])return;this[bn]="stopping",this[In]("stopping");const{p:t,resolveP:i}=kn();let n;return this[yn]=t,this[In]=i,this.dispatchEvent(new r),"function"==typeof super.stop&&(n=await super.stop(...e)),this[hn]=!1,this.dispatchEvent(new s),n}).finally(()=>{this[bn]=null,this[In](null);const{p:e,resolveP:t}=kn();this[yn]=e,this[In]=t})}};return Object.defineProperty(o,"name",Object.getOwnPropertyDescriptor(i,"name")),o}}function Kn(e=new Mn,t=!1,r=[]){return(s,i,n)=>{let a;null!=n.value?a="value":null!=n.get?a="get":null!=n.set&&(a="set");const o=n[a];if("function"!=typeof o)throw new TypeError(`${i} is not a function`);return n[a]=o instanceof wn?async function(...s){if(this[vn].isLocked("write")&&null===this[bn]&&await this[yn],r.includes(this[bn]))return o.apply(this,s);if(t)return this[vn].withReadF(async()=>{if(!this[hn])throw xn(e,n[a]),e;return o.apply(this,s)});if(this[vn].isLocked("write")||!this[hn])throw xn(e,n[a]),e;return o.apply(this,s)}:o instanceof Sn?function*(...t){if(r.includes(this[bn]))return yield*o.apply(this,t);if(this[vn].isLocked("write")&&null!==this[mn]||!this[hn])throw xn(e,n[a]),e;return yield*o.apply(this,t)}:o instanceof En?async function*(...s){if(this[vn].isLocked("write")&&null===this[bn]&&await this[yn],r.includes(this[bn]))return yield*o.apply(this,s);if(t)return yield*this[vn].withReadG(()=>{if(!this[hn])throw xn(e,n[a]),e;return o.apply(this,s)});if(this[vn].isLocked("write")||!this[hn])throw xn(e,n[a]),e;return yield*o.apply(this,s)}:function(...t){if(r.includes(this[bn]))return o.apply(this,t);if(this[vn].isLocked("write")&&null!==this[mn]||!this[hn])throw xn(e,n[a]),e;return o.apply(this,t)},Object.defineProperty(n[a],"name",{value:i}),n}}class Qn 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 Fn=Qn;class $n{[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,Fn.fromString(s),this)}),this._clientConnections.forEach((r,s)=>{e.bind(t)(r,Fn.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:[Fn.fromString(e),t]}}const s=t.next();if(!s.done){const[e,t]=s.value;return{done:!1,value:[Fn.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 Gn=$n,jn="data:application/javascript;base64,aW1wb3J0IHByb2Nlc3MgZnJvbSAncHJvY2Vzcyc7CmltcG9ydCBwYXRoIGZyb20gJ3BhdGgnOwppbXBvcnQgdXJsIGZyb20gJ3VybCc7CmltcG9ydCBNb2R1bGUgZnJvbSAnbm9kZTptb2R1bGUnOwpjb25zdCByZXF1aXJlID0gTW9kdWxlLmNyZWF0ZVJlcXVpcmUoaW1wb3J0Lm1ldGEudXJsKTsKY29uc3QgZGlybmFtZSA9IHVybC5maWxlVVJMVG9QYXRoKG5ldyBVUkwoJy4nLCBpbXBvcnQubWV0YS51cmwpKTsKY29uc3QgcHJvamVjdFJvb3QgPSBwYXRoLmpvaW4oZGlybmFtZSwgJy4uLy4uLycpOwpjb25zdCBwcmVidWlsZFBhdGggPSBwYXRoLmpvaW4ocHJvamVjdFJvb3QsICdwcmVidWlsZCcpOwovKioKICogVHJ5IHJlcXVpcmUgb24gYWxsIHByZWJ1aWxkIHRhcmdldHMgZmlyc3QsIHRoZW4KICogdHJ5IHJlcXVpcmUgb24gYWxsIG5wbSB0YXJnZXRzIHNlY29uZC4KICovCmZ1bmN0aW9uIHJlcXVpcmVCaW5kaW5nKHRhcmdldHMpIHsKICAgIGNvbnN0IHByZWJ1aWxkVGFyZ2V0cyA9IHRhcmdldHMubWFwKCh0YXJnZXQpID0+IHBhdGguam9pbihwcmVidWlsZFBhdGgsIGBxdWljLSR7dGFyZ2V0fS5ub2RlYCkpOwogICAgZm9yIChjb25zdCBwcmVidWlsZFRhcmdldCBvZiBwcmVidWlsZFRhcmdldHMpIHsKICAgICAgICB0cnkgewogICAgICAgICAgICByZXR1cm4gcmVxdWlyZShwcmVidWlsZFRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKHByZWJ1aWxkVGFyZ2V0KS5ocmVmKTsKICAgICAgICB9CiAgICAgICAgY2F0Y2ggKGUpIHsKICAgICAgICAgICAgaWYgKGUuY29kZSAhPT0gJ01PRFVMRV9OT1RfRk9VTkQnKQogICAgICAgICAgICAgICAgdGhyb3cgZTsKICAgICAgICB9CiAgICB9CiAgICBjb25zdCBucG1UYXJnZXRzID0gdGFyZ2V0cy5tYXAoKHRhcmdldCkgPT4gYEBtYXRyaXhhaS9xdWljLSR7dGFyZ2V0fWApOwogICAgZm9yIChjb25zdCBucG1UYXJnZXQgb2YgbnBtVGFyZ2V0cykgewogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKG5wbVRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKG5wbVRhcmdldCkuaHJlZik7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgfQogICAgdGhyb3cgbmV3IEVycm9yKGBGYWlsZWQgcmVxdWlyaW5nIHBvc3NpYmxlIG5hdGl2ZSBiaW5kaW5nczogJHtwcmVidWlsZFRhcmdldHMuY29uY2F0KG5wbVRhcmdldHMpfWApOwp9CmxldCBuYXRpdmVCaW5kaW5nOwovKioKICogRm9yIGRlc2t0b3Agd2Ugb25seSBzdXBwb3J0IHdpbjMyLCBkYXJ3aW4gYW5kIGxpbnV4LgogKiBNb2JpbGUgT1Mgc3VwcG9ydCBpcyBwZW5kaW5nLgogKi8Kc3dpdGNoIChwcm9jZXNzLnBsYXRmb3JtKSB7CiAgICBjYXNlICd3aW4zMic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLXg2NCddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlICdpYTMyJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLWlhMzInXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnd2luMzItYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgICAgIHRocm93IG5ldyBFcnJvcihgVW5zdXBwb3J0ZWQgYXJjaGl0ZWN0dXJlIG9uIFdpbmRvd3M6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGNhc2UgJ2Rhcndpbic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4teDY0K2FybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi11bml2ZXJzYWwnLAogICAgICAgICAgICAgICAgXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQrYXJtNjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4tdW5pdmVyc2FsJywKICAgICAgICAgICAgICAgIF0pOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoYFVuc3VwcG9ydGVkIGFyY2hpdGVjdHVyZSBvbiBtYWNPUzogJHtwcm9jZXNzLmFyY2h9YCk7CiAgICAgICAgfQogICAgICAgIGJyZWFrOwogICAgY2FzZSAnbGludXgnOgogICAgICAgIHN3aXRjaCAocHJvY2Vzcy5hcmNoKSB7CiAgICAgICAgICAgIGNhc2UgJ3g2NCc6CiAgICAgICAgICAgICAgICBuYXRpdmVCaW5kaW5nID0gcmVxdWlyZUJpbmRpbmcoWydsaW51eC14NjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnbGludXgtYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ2xpbnV4LWFybSddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBhcmNoaXRlY3R1cmUgb24gTGludXg6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGRlZmF1bHQ6CiAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBPUzogJHtwcm9jZXNzLnBsYXRmb3JtfSwgYXJjaGl0ZWN0dXJlOiAke3Byb2Nlc3MuYXJjaH1gKTsKfQpleHBvcnQgZGVmYXVsdCBuYXRpdmVCaW5kaW5nOwovLyMgc291cmNlTWFwcGluZ1VSTD1xdWljaGUuanMubWFw",qn=t(import.meta.url)("dns"),zn=t(import.meta.url)("node:events");var Wn=a.n(zn),Jn=a(618);class Yn extends Xi{static description="QUIC error"}class Xn extends Xi{static description="You should never see this error"}class Zn extends Xi{static description="Host provided was not valid"}class ea extends Xi{static description="Port provided was not valid"}class ta extends Yn{static description="QUIC config error"}class ra extends Yn{static description="QUIC Socket error"}class sa extends ra{static description="QUIC Socket is not running"}class ia extends ra{static description="QUIC Socket has active connections"}class na extends ra{static description="QUIC Socket cannot bind to the specified address"}class aa extends ra{static description="QUIC Socket cannot send to the specified address"}class oa extends ra{static description="QUIC Socket internal error"}class ca extends Yn{static description="QUIC Client error"}class la extends ca{static description="QUIC Client is destroyed"}class da extends ca{static description="QUIC Client cannot be created with an unstarted shared QUIC socket"}class ua extends ca{static description="QUIC Client had a failure relating to an invalid argument"}class ha extends ca{static description="QUIC Client cannot be created with the specified host"}class fa extends ca{static description="QUIC Client internal error"}class ga extends Yn{static description="QUIC Server error"}class pa extends ga{static description="QUIC Server is not running"}class ba extends ga{static description="QUIC Server cannot start with an unstarted shared QUIC socket"}class ma extends ga{static description="QUIC Server creating a new connection"}class ya extends ga{static description="QUIC Server internal error"}class Aa extends ga{static description="QUIC Server is stopping"}class Ia extends Yn{static description="QUIC Connection error"}class va extends Ia{static description="QUIC Connection is stopping"}class wa extends Ia{static description="QUIC Connection is not running"}class Sa extends Ia{static description="QUIC Connection cannot be restarted because it has already been closed"}class Ea extends Yn{static description="QUIC Connection start requires data when it is a server connection"}class Ca extends Ia{static description="QUIC connection invalid configuration"}class ka extends Ia{static description="QUIC Connection local error";constructor(e="",t){super(e,t)}}class xa extends ka{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class Ba extends Ia{static description="QUIC Connection peer error";constructor(e="",t){super(e,t)}}class _a extends ka{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class Ra extends Ia{static description="QUIC Connection max idle timeout exhausted"}class Oa extends Ia{static description="QUIC Connection internal error"}class Ua extends Yn{static description="QUIC Stream error"}class Ta extends Ua{static description="QUIC Stream is destroyed"}class Na extends Ua{static description="QUIC Stream locally closed readable side";constructor(e="",t){super(e,t)}}class Da extends Ua{static description="QUIC Stream locally closed writable side";constructor(e="",t){super(e,t)}}class Ma extends Ua{static description="QUIC Stream peer closed readable side";constructor(e="",t){super(e,t)}}class Pa extends Ua{static description="QUIC Stream peer closed writable side";constructor(e="",t){super(e,t)}}class La extends Ua{static description="QUIC Stream internal error"}class Ha extends Ua{static description="QUIC Stream limit has been reached"}const Va=new TextEncoder,Ka=new TextDecoder("utf-8");function Qa(e){throw new Xn(e)}function Fa(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 $a(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Ga(e){const[t]=Jn.Validator.isValidIPv4String(e);return t}function ja(e){const[t]=Jn.Validator.isValidIPv6String(e);return!!t||qa(e)}function qa(e){if(e.startsWith("::ffff:"))try{return Jn.IPv6.fromString(e),!0}catch{if(Ga(e.slice(7)))return!0}return!1}function za(e){if(!Ga(e))throw new TypeError("Invalid IPv4 address");return"::ffff:"+e}function Wa(e){const t=e.slice(7);if(Ga(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 Ja(e){const t=new Jn.IPv4("0.0.0.0"),r=new Jn.IPv6("::");if(qa(e)){const r=Wa(e);return new Jn.IPv4(r).isEquals(t)?za("127.0.0.1"):e}return Ga(e)&&new Jn.IPv4(e).isEquals(t)?"127.0.0.1":ja(e)&&new Jn.IPv6(e).isEquals(r)?"::1":e}async function Ya(e){return(await qn.promises.lookup(e,{family:0,all:!1,verbatim:!0})).address}async function Xa(e,t){if(Ga(e))return[e,"udp4"];if(ja(e))return[e,"udp6"];try{return Xa(e=await t(e),t)}catch{throw new Zn}}function Za(e){if(!function(e){return"number"==typeof e&&e>=0&&e<=65535}(e))throw new ea;return e}function eo(e,t=0){let r;return r=Ga(e)?`${e}:${t}`:ja(e)?`[${e}]:${t}`:`${e}:${t}`,r}function to(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 a=qa(e),o=qa(r);if("ipv4&ipv6"===t&&"udp4"===s)return za(r);if("ipv4"===t){if(a){if("udp4"===s)return za(r);if("udp6"===s&&!o)throw new i(`Invalid target host ${r} from an IPv4 socket`)}else if("udp6"===s){if(o)return Wa(r);throw new i(`Invalid target host ${r} from an IPv4 socket`)}return r}if("ipv6"===t){if("udp4"===s||o)throw new i(`Invalid target host ${r} from an IPv6 socket`);return r}return r}function ro(e){const t=[];if("string"==typeof e)t.push(e.trim()+"\n");else if(e instanceof Uint8Array)t.push(Ka.decode(e).trim()+"\n");else if(Array.isArray(e))for(const r of e)"string"==typeof r?t.push(r.trim()+"\n"):t.push(Ka.decode(r).trim()+"\n");return t}function so(e){const t=e.replace(/-----BEGIN .*-----/,"").replace(/-----END .*-----/,"").replace(/\s+/g,""),r=Buffer.from(t,"base64");return new Uint8Array(r)}function io(e){return`${e.name}${"description"in e?`: ${e.description}`:""}${void 0!==e.message?` - ${e.message}`:""}`}function no(e){let t;return null!=(t=e.message.match(/StreamStopped\((\d{1,16})\)/))&&parseInt(t[1])}function ao(e){let t;return null!=(t=e.message.match(/StreamReset\((\d{1,16})\)/))&&parseInt(t[1])}function oo(e,t=1e5){zn.setMaxListeners(t,e)}class co extends ki{}class lo extends co{}class uo extends lo{}class ho extends lo{}class fo extends lo{}class go extends co{}class po extends go{}class bo extends lo{}class mo extends go{}class yo extends co{}class Ao extends yo{}class Io extends yo{}class vo extends yo{}class wo extends co{}class So extends wo{}class Eo extends wo{}class Co extends wo{}class ko extends wo{}class xo extends wo{}class Bo extends co{}class _o extends Bo{}class Ro extends Bo{}class Oo extends Bo{}class Uo extends Bo{}class To extends Bo{}var No=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};let Do=class{connectionMap=new Gn;logger;server;resolveHostname;_host;_port;_type;_closed=!1;_closedP;resolveClosedP;socket;socketBind;socketClose;socketSend;handleEventQUICSocketError=e=>{const t=e.detail;this.logger.debug(io(t))};handleEventQUICSocketClose=async()=>{await this.socketClose(),this._closed=!0,this.resolveClosedP(),this[fn]&&await this.stop({force:!0})};handleSocketMessage=async(e,t)=>{let r;try{r=jn.Header.fromSlice(e,jn.MAX_CONN_ID_LEN)}catch(e){if("BufferTooShort"===e.message||"InvalidPacket"===e.message)return;throw e}const s=new Fn(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(Zi(e,e=>e instanceof ra)){const t=new oa("Failed to call accept connection due to socket send",{cause:e});return this.dispatchEvent(new ho({detail:t})),void this.dispatchEvent(new fo)}if(e instanceof ma)return;throw e}}};constructor({resolveHostname:e=Ya,logger:t}){this.logger=t??new vi(this.constructor.name),this.resolveHostname=e;const{p:r,resolveP:s}=$a();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}={}){oo(this[Ti]);let i=eo(e,t);this.logger.info(`Start ${this.constructor.name} on ${i}`);const[n,a]=await Xa(e,this.resolveHostname),o=Za(t);this.socket=Ei.createSocket({type:a,reuseAddr:r,ipv6Only:s}),this.socketBind=Fa(this.socket.bind).bind(this.socket),this.socketClose=Fa(this.socket.close).bind(this.socket),this.socketSend=Fa(this.socket.send).bind(this.socket);const{p:c,rejectP:l}=$a();c.catch(()=>{}),this.socket.once("error",l);const d=this.socketBind(o,n);try{await Promise.race([d,c])}catch(t){throw new na(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"===a||qa(n)?this._type="ipv4":"udp6"===a&&(this._type="ipv6"):this._type="ipv4&ipv6",this.socket.on("message",this.handleSocketMessage),this.addEventListener(ho.name,this.handleEventQUICSocketError),this.addEventListener(fo.name,this.handleEventQUICSocketClose,{once:!0}),this._closed=!1,i=eo(this._host,this._port),this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({force:e=!1}={}){const t=eo(this._host,this._port);if(this.logger.info(`Stop ${this.constructor.name} on ${t}`),!e&&this.connectionMap.size>0)throw new ia(`Cannot stop QUICSocket with ${this.connectionMap.size} active connection(s)`);this._closed||this.dispatchEvent(new fo),await this._closedP;const{p:r,resolveP:s}=$a();this._closedP=r,this.resolveClosedP=s,this.removeEventListener(ho.name,this.handleEventQUICSocketError),this.removeEventListener(fo.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 Xa(r,this.resolveHostname);return s=Ja(s),s=to(this._host,this._type,s,i,aa),e[t]=s,this.socketSend(...e)}async send_(...e){return this.socketSend(...e)}setServer(e){this.server=e}unsetServer(){delete this.server}};No([Kn(new sa)],Do.prototype,"host",null),No([Kn(new sa)],Do.prototype,"port",null),No([Kn(new sa)],Do.prototype,"type",null),No([Kn(new sa)],Do.prototype,"send",null),No([Kn(new sa)],Do.prototype,"send_",null),Do=No([Vn({eventStart:class extends lo{},eventStarted:class extends lo{},eventStop:class extends lo{},eventStopped:uo})],Do);const Mo=Do,Po=new WeakMap;const Lo=function(e,t,r){const s=e.name??e.constructor.name,i=e[t];if(Po.has(i))throw new TypeError(`\`${s}.${t.toString()}\` redeclares \`@context\` decorator`);Po.set(i,r)};class Ho extends Xi{static description="Contexts error"}class Vo extends Ho{static description="Aborted due to timer expiration"}const Ko=function(e=!1,t=1/0,r=Vo){return(s,i,n)=>{const a=s.name??s.constructor.name,o=n.value;if("function"!=typeof o)throw new TypeError(`\`${a}.${i.toString()}\` is not a function`);const c=function(e,t,r){const s=Po.get(e[t]);if(null==s)throw new TypeError(`\`${r}.${t.toString()}\` does not have a \`@context\` parameter decorator`);return s}(s,i,a);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 sn))throw new TypeError(`\`${r}.${t.toString()}\` decorated \`@context\` parameter's \`timer\` property is not a number nor an instance of \`Timer\``)}(n,i,a),function(e,t,r,s,i,n){let a,o;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){a=new AbortController;const e=new s,t=new sn(()=>{a.abort(e)},i.timer??r),n=i.signal,c=()=>{t.cancel(),a.abort(n.reason)};n.aborted?(t.cancel(),a.abort(n.reason)):n.addEventListener("abort",c),i.signal=a.signal,i.timer=t,o=()=>{n.removeEventListener("abort",c),t.cancel()}}else if(i.timer instanceof sn&&void 0===i.signal){a=new AbortController;const e=new s;let t=!1;i.timer.then((r,s)=>(t||s.aborted||a.abort(e),r),()=>{}),i.signal=a.signal,o=()=>{t=!0}}else{a=new AbortController;const e=i.signal,t=()=>{a.abort(e.reason)};e.aborted?a.abort(e.reason):e.addEventListener("abort",t),i.signal=a.signal,o=()=>{e.removeEventListener("abort",t)}}else{a=new AbortController;const e=new s,t=new sn(()=>{a.abort(e)},i.timer??r);a.signal.addEventListener("abort",()=>{t.cancel()}),i.signal=a.signal,i.timer=t,o=()=>{t.cancel()}}const c=e(i,...n);return new qi((e,r,s)=>{t||(s.aborted?r(s.reason):s.addEventListener("abort",()=>{r(s.reason)},{once:!0})),c.then(e,r)},a).finally(()=>{o()},a)}((e,...t)=>o.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}},Qo=["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(":"),Fo=1/0,$o={sigalgs:Qo,verifyPeer:!0,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:jn.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:jn.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:jn.MAX_CONNECTION_WINDOW,maxStreamWindow:jn.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},Go={sigalgs:Qo,verifyPeer:!1,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:jn.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:jn.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:jn.MAX_CONNECTION_WINDOW,maxStreamWindow:jn.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},jo=t(import.meta.url)("stream/web");var qo=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};const zo=Symbol("abort readableP reason");let Wo=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:a=new vi(`${this.name} ${t}`)}){a.info(`Create ${this.name}`);const o=new this({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:a});return"uni"===o.type&&("local"===e?(o.readableController.close(),o._readClosed=!0):"peer"===e&&(o.writable.close().catch(()=>{}),o._writeClosed=!0)),o.addEventListener(Ro.name,o.handleEventQUICStreamError),o.addEventListener(Oo.name,o.handleEventQUICStreamCloseRead,{once:!0}),o.addEventListener(Uo.name,o.handleEventQUICStreamCloseWrite,{once:!0}),a.info(`Created ${this.name}`),o}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 La)throw this.logger.debug(io(t)),t;t instanceof Na||t instanceof Ma?this.dispatchEvent(new Oo({detail:t})):(t instanceof Da||t instanceof Pa)&&this.dispatchEvent(new Uo({detail:t}))};handleEventQUICStreamCloseRead=async()=>{this._readClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[pn]||"destroying"===this[mn]||await this.destroy({force:!1}))};handleEventQUICStreamCloseWrite=async()=>{this._writeClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[pn]||"destroying"===this[mn]||await this.destroy({force:!1}))};constructor({initiated:e,streamId:t,connection:r,config:s,reasonToCode:i,codeToReason:n,logger:a}){!function(e){return!(2&e)}(t)?function(e){return!!(2&e)}(t)&&(this.type="uni"):this.type="bidi",this.logger=a,this.initiated=e,this.streamId=t,this.connection=r,this.reasonToCode=i,this.codeToReason=n;const{p:o,resolveP:c}=$a();if(this.closedP=o,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 jo.ReadableStream({start:this.readableStart.bind(this)}):this.readable=new jo.ReadableStream({start:this.readableStart.bind(this),pull:this.readablePull.bind(this),cancel:this.readableCancel.bind(this)},new jo.CountQueuingStrategy({highWaterMark:1})),"uni"===this.type&&"peer"===this.initiated)this.writable=new jo.WritableStream({start:this.writableStart.bind(this)});else{this.writable=new jo.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===no(e)){if("StreamLimit"===e.message){const t="bidi"===this.type?s.initialMaxStreamsBidi:s.initialMaxStreamsUni;throw new Ha(`Stream limit of ${t} has been reached`,{cause:e})}throw new La(`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(Ro.name,this.handleEventQUICStreamError),this.removeEventListener(Oo.name,this.handleEventQUICStreamCloseRead),this.removeEventListener(Uo.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=ao(e))){const e=this.codeToReason("read",t),r=new Ma("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),this.rejectReadableP?.(e),void this.dispatchEvent(new Ro({detail:r}))}{const t=new La("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.rejectReadableP?.(t),this.dispatchEvent(new Ro({detail:t})),t}}if(null===e){const e=new La("Failed `streamRecv` on the readable stream");throw this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new Ro({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 Oo),void this.rejectReadableP?.(zo)}this.resolveReadableP?.()}write(){try{this.connection.conn.streamCapacity(this.streamId)}catch(e){let t;if(!1!==(t=no(e))){this.connection.conn.streamShutdown(this.streamId,jn.Shutdown.Write,t);const e=this.codeToReason("write",t),r=new Pa("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),this.rejectWritableP?.(e),void this.dispatchEvent(new Ro({detail:r}))}{const t=new La("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.rejectWritableP?.(t),this.dispatchEvent(new Ro({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}=$a();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=ao(e))){const e=this.codeToReason("read",t),r=new Ma("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),void this.dispatchEvent(new Ro({detail:r}))}{const t=new La("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.dispatchEvent(new Ro({detail:t})),t}}if(null===e){const e=new La("Failed `streamRecv` on the readable stream because it is not readable");throw this.readableController.error(e),this.dispatchEvent(new Ro({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 Oo)),this.dispatchEvent(new To)}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=no(e))){const e=this.codeToReason("write",t),r=new Pa("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new Ro({detail:r}))}{const t=new La("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new Ro({detail:t})),t}}if(this.dispatchEvent(new To),t<e.byteLength){e=e.subarray(t,e.byteLength);const{p:r,resolveP:s,rejectP:i}=$a();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=no(e))){const e=this.codeToReason("write",t),r=new Pa("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new Ro({detail:r}))}{const t=new La("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new Ro({detail:t})),t}}this.dispatchEvent(new Uo),this.dispatchEvent(new To)}readableCancel(e){if(this._readClosed)return;const t=this.reasonToCode("read",e);try{this.connection.conn.streamShutdown(this.streamId,jn.Shutdown.Read,t)}catch(r){const e=new La("Local stream readable could not be shutdown",{cause:r});throw this.readableController.error(e),this.dispatchEvent(new Ro({detail:e})),e}const r=new Na("Closing readable stream locally",{data:{code:t},cause:e});this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new Ro({detail:r})),this.dispatchEvent(new To)}writableAbort(e){if(this._writeClosed)return;const t=this.reasonToCode("write",e);try{this.connection.conn.streamShutdown(this.streamId,jn.Shutdown.Write,t)}catch(r){const e=new La("Local stream writable could not be shutdown",{cause:r});throw this.writableController.error(e),this.dispatchEvent(new Ro({detail:e})),e}const r=new Da("Closing writable stream locally",{data:{code:t},cause:e});this.writableController.error(e),this.rejectWritableP?.(e),this.dispatchEvent(new Ro({detail:r})),this.dispatchEvent(new To)}};qo([Hn(new Ta)],Wo.prototype,"meta",null),qo([Hn(new Ta,!1,["destroying"])],Wo.prototype,"read",null),qo([Hn(new Ta,!1,["destroying"])],Wo.prototype,"write",null),Wo=qo([Ln({eventDestroy:class extends Bo{},eventDestroyed:_o})],Wo);const Jo=Wo;var Yo,Xo,Zo,ec,tc;!function(e){e[e.Reno=0]="Reno",e[e.CUBIC=1]="CUBIC",e[e.BBR=2]="BBR"}(Yo||(Yo={})),function(e){e[e.Read=0]="Read",e[e.Write=1]="Write"}(Xo||(Xo={})),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"}(Zo||(Zo={})),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"}(ec||(ec={})),function(e){e[e.CloseNotify=256]="CloseNotify",e[e.UnexpectedMessage=266]="UnexpectedMessage",e[e.BadRecordMac=276]="BadRecordMac",e[e.RecordOverflow=278]="RecordOverflow",e[e.HandshakeFailure=296]="HandshakeFailure",e[e.BadCertificate=298]="BadCertificate",e[e.UnsupportedCertificate=299]="UnsupportedCertificate",e[e.CertificateRevoked=300]="CertificateRevoked",e[e.CertificateExpired=301]="CertificateExpired",e[e.CertificateUnknown=302]="CertificateUnknown",e[e.IllegalParameter=303]="IllegalParameter",e[e.UnknownCA=304]="UnknownCA",e[e.AccessDenied=305]="AccessDenied",e[e.DecodeError=306]="DecodeError",e[e.DecryptError=307]="DecryptError",e[e.ProtocolVersion=326]="ProtocolVersion",e[e.InsufficientSecurity=327]="InsufficientSecurity",e[e.InternalError=336]="InternalError",e[e.InappropriateFallback=342]="InappropriateFallback",e[e.UserCanceled=346]="UserCanceled",e[e.MissingExtension=365]="MissingExtension",e[e.UnsupportedExtension=366]="UnsupportedExtension",e[e.UnrecognizedName=368]="UnrecognizedName",e[e.BadCertificateStatusResponse=369]="BadCertificateStatusResponse",e[e.UnknownPSKIdentity=371]="UnknownPSKIdentity",e[e.CertificateRequired=372]="CertificateRequired",e[e.NoApplicationProtocol=376]="NoApplicationProtocol"}(tc||(tc={}));var rc=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};let sc=class{type;closedP;conn;streamMap=new Map;sendId;logger;socket;config;reasonToCode;codeToReason;recvLock=new dn;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(io(t)),t instanceof Oa)throw t;this.dispatchEvent(new Co({detail:t}))};handleEventQUICConnectionClose=async e=>{const t=e.detail;this.secureEstablished||this.rejectSecureEstablishedP(t),t instanceof ka&&await this.send(),this[fn]&&"stopping"!==this[mn]&&await this.stop({force:!0})};handleEventQUICStream=e=>{e.detail instanceof ki&&!(e.detail instanceof To)&&this.dispatchEvent(e.detail.clone())};handleEventQUICStreamSend=async()=>{this[fn]&&await this.send()};handleEventQUICStreamDestroyed=e=>{const t=e.target;t.removeEventListener(To.name,this.handleEventQUICStreamSend),t.removeEventListener(Ri.name,this.handleEventQUICStream),this.streamMap.delete(t.streamId)};constructor({type:e,scid:t,dcid:r,serverName:s=null,remoteInfo:i,config:n,socket:a,reasonToCode:o=()=>0,codeToReason:c=(e,t)=>new Error(`${e} ${t}`),logger:l}){if(this.logger=l??new vi(`${this.constructor.name} ${t}`),this.sendId=t.toString(),null!=n.keepAliveIntervalTime&&0!==n.maxIdleTimeout&&n.keepAliveIntervalTime>=n.maxIdleTimeout)throw new Ca("`keepAliveIntervalTime` must be less than `maxIdleTimeout`");const d=function(e){if(null!=e.key&&null==e.cert)throw new ta("The cert option must be set when key is set");if(null==e.key&&null!=e.cert)throw new ta("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 ta("The number of keys must match the number of certs");let t,r,s,i;if(null!=e.ca){const r=ro(e.ca);t=Va.encode(r.join(""))}null!=e.key&&(r=ro(e.key).map(e=>Va.encode(e))),null!=e.cert&&(s=ro(e.cert).map(e=>Va.encode(e)));try{i=jn.Config.withBoringSslCtx(e.verifyPeer,null!=e.verifyCallback,t,r,s,e.sigalgs)}catch(e){throw new ta(`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=jn.Connection.connect(s,t,{host:a.host,port:a.port},{host:i.host,port:i.port},d)):"server"===e&&(this.logger.info(`Accept ${this.constructor.name}`),u=jn.Connection.accept(t,r,{host:a.host,port:a.port},{host:i.host,port:i.port},d)),null!=n.logKeys&&u.setKeylog(n.logKeys),this.type=e,this.conn=u,this.socket=a,this.config=n,null!=this.config.cert){const e=ro(this.config.cert);this.certDERs=e.map(so)}if(null!=this.config.ca){const e=ro(this.config.ca);this.caDERs=e.map(so)}this.reasonToCode=o,this.codeToReason=c,this._remoteHost=i.host,this._remotePort=i.port;const{p:h,resolveP:f,rejectP:g}=$a();h.catch(()=>{}),this.secureEstablishedP=h,this.resolveSecureEstablishedP=()=>{this.secureEstablished=!0,f()},this.rejectSecureEstablishedP=g;const{p,resolveP:b}=$a();this.closedP=p,this.resolveClosedP=b}get connectionId(){const e=this.conn.sourceId();return new Fn(e.buffer,e.byteOffset,e.byteLength)}get connectionIdPeer(){const e=this.conn.destinationId();return new Fn(e.buffer,e.byteOffset,e.byteLength)}get connectionIdShared(){const e=this.conn.sourceId(),t=this.conn.destinationId();return Buffer.compare(e,t)<=0?new Fn(Buffer.concat([e,t])):new Fn(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 Sa;r.signal.throwIfAborted();const{p:s,rejectP:i}=$a();s.catch(()=>{});const n=()=>{i(r.signal.reason)};if(r.signal.addEventListener("abort",n),this.addEventListener(Eo.name,this.handleEventQUICConnectionError),this.addEventListener(Co.name,this.handleEventQUICConnectionClose,{once:!0}),"client"===this.type)await this.send();else if("server"===this.type){if(null==e||null==t)throw new Ea("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,jn.Shutdown.Read,this.reasonToCode("read",e));for(const t of this.conn.writable())this.conn.streamShutdown(t,jn.Shutdown.Write,this.reasonToCode("write",e));this.conn.close(!1,ec.ApplicationError,Buffer.from(""));const t=this.conn.localError(),r=new ka("Failed to start QUIC connection due to start timeout",{data:t,cause:e});this.dispatchEvent(new Eo({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 ka(i,{data:s});this.dispatchEvent(new Eo({detail:n}))}await this.closedP,this.removeEventListener(Eo.name,this.handleEventQUICConnectionError),this.removeEventListener(Co.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 Oa("Failed connection recv due with unknown error",{cause:e});throw this.dispatchEvent(new Eo({detail:t})),t}{let r;return r="TlsFail"===e.message?new xa("Failed connection due to native TLS verification",{cause:e,data:t}):new ka("Failed connection due to local error",{cause:e,data:t}),void this.dispatchEvent(new Eo({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 Oa("Failed connection send with unknown internal error",{cause:e});throw this.dispatchEvent(new Eo({detail:t})),t}this.dispatchEvent(new xo({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 xa("Failed connection due to custom TLS verification",{data:e});return void this.dispatchEvent(new Eo({detail:r}))}this.resolveSecureEstablishedP(),this.processStreams()}if("stopping"!==this[mn]){const e=this.conn.peerError();if(null!=e){const t=`Peer closed with ${e.isApp?"application":"transport"} code ${e.errorCode}`;return void(e.errorCode>=jn.CRYPTO_ERROR_START&&e.errorCode<=jn.CRYPTO_ERROR_STOP?this.dispatchEvent(new Eo({detail:new _a(t,{data:e})})):this.dispatchEvent(new Eo({detail:new Ba(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:Qa("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[fn]||"stopping"===this[mn]){this.conn.streamShutdown(e,Xo.Write,this.reasonToCode("write",va)),this.conn.streamShutdown(e,Xo.Read,this.reasonToCode("read",va));continue}this.isStreamUsed(e)&&Qa("We should never repeat streamIds when creating streams"),t=Jo.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${Jo.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(To.name,this.handleEventQUICStreamSend),t.addEventListener(_o.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(Ri.name,this.handleEventQUICStream),this.dispatchEvent(new ko({detail:t}))}t.read()}for(const e of this.conn.writable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[fn]||"stopping"===this[mn]){this.conn.streamShutdown(e,Xo.Write,this.reasonToCode("write",va)),this.conn.streamShutdown(e,Xo.Read,this.reasonToCode("read",va));continue}if(this.isStreamUsed(e)){try{this.conn.streamSend(e,new Uint8Array,!1)}catch(e){if(!1!==no(e))continue;if("FinalSize"===e.message)continue;throw e}Qa("We never expect a duplicate stream to be readable")}t=Jo.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${Jo.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(To.name,this.handleEventQUICStreamSend),t.addEventListener(_o.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(Ri.name,this.handleEventQUICStream),this.dispatchEvent(new ko({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 Eo({detail:new Ra})));await this.send();const r=this.conn.timeout();null!=r&&(this.connTimeoutTimer=new sn({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 Eo({detail:new Ra}))));null==this.connTimeoutTimer||"settled"===this.connTimeoutTimer.status?this.connTimeoutTimer=new sn({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)&&Qa("We should never repeat streamIds when creating streams");const r=Jo.createQUICStream({initiated:"local",streamId:t,connection:this,config:this.config,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${Jo.name} ${t}`)});return this.streamMap.set(r.streamId,r),r.addEventListener(To.name,this.handleEventQUICStreamSend),r.addEventListener(_o.name,this.handleEventQUICStreamDestroyed,{once:!0}),r.addEventListener(Ri.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 sn({delay:e,handler:t,lazy:!0})))};this.keepAliveIntervalTimer=new sn({delay:e,handler:t,lazy:!0})}stopKeepAliveIntervalTimer(){this.keepAliveIntervalTimer?.cancel()}};var ic,nc;rc([Kn(new wa)],sc.prototype,"connectionIdPeer",null),rc([Kn(new wa)],sc.prototype,"connectionIdShared",null),rc([Ko(!0,Fo,class extends Ia{static description="QUIC Connection start timeout"}),(ic=1,nc=Lo,function(e,t){nc(e,t,ic)})],sc.prototype,"start",null),rc([Kn(new wa,!1,["starting","stopping"])],sc.prototype,"recv",null),rc([Kn(new wa,!1,["starting","stopping"])],sc.prototype,"send",null),rc([Kn(new wa)],sc.prototype,"newStream",null),sc=rc([Vn({eventStart:class extends wo{},eventStarted:class extends wo{},eventStop:class extends wo{},eventStopped:So})],sc);const ac=sc;var oc=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};let cc=class{isSocketShared;reasonToCode;codeToReason;minIdleTimeout;logger;socket;crypto;config;_closed=!1;_closedP;resolveClosedP;stopAbortController;handleEventQUICServerError=e=>{const t=e.detail;if(this.logger.info(io(t)),t instanceof ya)throw t;this.dispatchEvent(new vo({detail:t}))};handleEventQUICServerClose=async e=>{const t=e.detail;if(!(t instanceof ba||this.isSocketShared)){this.socket.removeEventListener(uo.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new ya("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new Io({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[fn]&&"stopping"!==this[mn]&&(void 0!==t?await this.stop({isApp:!1,errorCode:ec.InternalError,reason:Buffer.from(t.description),force:!0}):await this.stop({force:!0}))};handleEventQUICSocket=e=>{e.detail instanceof ki&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new ba;this.removeEventListener(Ri.name,this.handleEventQUICSocket),this.dispatchEvent(new Io({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof ki&&!(e.detail instanceof xo)&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionSend=async e=>{if(this.socket[fn]&&"stopping"!==this.socket[mn])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 bo(`${bo.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new Io({detail:new ya("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(xo.name,this.handleEventQUICConnectionSend),t.removeEventListener(Ri.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({crypto:e,config:t,socket:r,resolveHostname:s=Ya,reasonToCode:i,codeToReason:n,minIdleTimeout:a,logger:o}){this.logger=o??new vi(this.constructor.name),this.crypto=e,null==r?(this.socket=new Mo({resolveHostname:s,logger:this.logger.getChild(Mo.name)}),this.isSocketShared=!1):(this.socket=r,this.isSocketShared=!0),this.config={...Go,...t},this.reasonToCode=i,this.codeToReason=n,this.minIdleTimeout=a;const{p:c,resolveP:l}=$a();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,oo(this.stopAbortController.signal),this.isSocketShared){if(!this.socket[fn])throw new ba;i=eo(this.socket.host,this.socket.port),this.logger.info(`Start ${this.constructor.name} on ${i}`)}else i=eo(e,t),this.logger.info(`Start ${this.constructor.name} on ${i}`),await this.socket.start({host:e,port:t,reuseAddr:r,ipv6Only:s}),i=eo(this.socket.host,this.socket.port);this.socket.setServer(this),this.addEventListener(Io.name,this.handleEventQUICServerError),this.addEventListener(vo.name,this.handleEventQUICServerClose,{once:!0}),this.socket.addEventListener(uo.name,this.handleEventQUICSocketStopped,{once:!0}),this.isSocketShared||this.socket.addEventListener(Ri.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[fn]&&(i=eo(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 Aa),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 vo),await this._closedP;const{p:a,resolveP:o}=$a();this._closedP=a,this.resolveClosedP=o,this.removeEventListener(Io.name,this.handleEventQUICServerError),this.removeEventListener(vo.name,this.handleEventQUICServerClose),this.socket.removeEventListener(uo.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(Ri.name,this.handleEventQUICSocket),this.logger.info(`Stopped ${this.constructor.name}${null!=i?` on ${i}`:""}`)}async acceptConnection(e,t,r,s){if(t.ty!==jn.Type.Initial&&t.ty!==jn.Type.ZeroRTT)return;const i=new Fn(await this.crypto.ops.sign(this.crypto.key,r),0,jn.MAX_CONN_ID_LEN),n=eo(e.host,e.port);if(!jn.versionIsSupported(t.version)){const r=Buffer.allocUnsafe(jn.MAX_DATAGRAM_SIZE),s=jn.negotiateVersion(t.scid,t.dcid,r);try{await this.socket.send_(r,0,s,e.port,e.host)}catch(e){throw new ma(`Failed to send version datagram ${n}`,{cause:e})}return}const a=t.token;if(0===a.byteLength){const s=await this.mintToken(r,e.host),a=Buffer.allocUnsafe(jn.MAX_DATAGRAM_SIZE),o=jn.retry(t.scid,t.dcid,i,s,t.version,a);try{await this.socket.send_(a,0,o,e.port,e.host)}catch(e){throw new ma(`Failed to send stateless retry datagram to ${n}`,{cause:e})}return}const o=await this.validateToken(Buffer.from(a),e.host);if(null==o)return;if(i.byteLength!==t.dcid.byteLength)return;const c=new Fn(t.dcid),l=new ac({type:"server",scid:c,dcid:o,socket:this.socket,remoteInfo:e,config:{...this.config},reasonToCode:this.reasonToCode,codeToReason:this.codeToReason,logger:this.logger.getChild(`${ac.name} ${i.toString()}`)});this.socket.connectionMap.set(l.connectionId,l),l.addEventListener(xo.name,this.handleEventQUICConnectionSend),l.addEventListener(So.name,this.handleEventQUICConnectionStopped,{once:!0}),l.addEventListener(Ri.name,this.handleEventQUICConnection);try{await l.start({data:s,remoteInfo:e},{timer:this.minIdleTimeout,signal:this.stopAbortController?.signal})}catch(e){throw l.removeEventListener(xo.name,this.handleEventQUICConnectionSend),l.removeEventListener(So.name,this.handleEventQUICConnectionStopped),l.removeEventListener(Ri.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(l.connectionId),new ma("Failed to start accepted connection",{cause:e})}return this.dispatchEvent(new Ao({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),a=Buffer.from(await r.ops.sign(r.key,n)),o={msg:n.toString("base64url"),sig:a.toString("base64url")},c=JSON.stringify(o);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 a;try{a=JSON.parse(i.toString())}catch{return}return"object"==typeof a&&null!=a&&"string"==typeof a.dcid&&"string"==typeof a.host&&a.host===t?Fn.fromString(a.dcid):void 0}(e,t,this.crypto)}};oc([Kn(new pa)],cc.prototype,"host",null),oc([Kn(new pa)],cc.prototype,"port",null),oc([Kn(new pa)],cc.prototype,"acceptConnection",null),cc=oc([Vn({eventStart:class extends yo{},eventStarted:class extends yo{},eventStop:class extends yo{},eventStopped:class extends yo{}})],cc);const lc=cc;var dc=function(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a};let uc=class{static async createQUICClient({host:e,port:t,serverName:r,localHost:s="::",localPort:i=0,socket:n,crypto:a,config:o={},resolveHostname:c=Ya,reuseAddr:l,ipv6Only:d,reasonToCode:u,codeToReason:h,logger:f=new vi(`${this.name}`)},g){let p=eo(e,t);f.info(`Create ${this.name} to ${p}`);const b={...$o,...o},m=new ArrayBuffer(jn.MAX_CONN_ID_LEN);await a.ops.randomBytes(m);const y=new Fn(m);let[A,I]=await Xa(e,c);const v=Za(t);let w,S;if(A=Ja(A),null==n){const[e]=await Xa(s,c),t=Za(i);n=new Mo({resolveHostname:c,logger:f.getChild(Mo.name)}),w=!1,await n.start({host:e,port:t,reuseAddr:l,ipv6Only:d})}else if(w=!0,!n[fn])throw new ba;try{A=to(n.host,n.type,A,I,ha)}catch(e){throw w||await n.stop({force:!0}),e}try{S=new ac({type:"client",scid:y,serverName:r??e,socket:n,remoteInfo:{host:A,port:v},config:b,reasonToCode:u,codeToReason:h,logger:f.getChild(`${ac.name} ${y.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(Ri.name,E.handleEventQUICSocket),n.addEventListener(uo.name,E.handleEventQUICSocketStopped,{once:!0}),S.addEventListener(Ri.name,E.handleEventQUICConnection),S.addEventListener(Eo.name,E.handleEventQUICConnectionError),S.addEventListener(xo.name,E.handleEventQUICConnectionSend),S.addEventListener(So.name,E.handleEventQUICConnectionStopped,{once:!0}),E.addEventListener(po.name,E.handleEventQUICClientError),E.addEventListener(mo.name,E.handleEventQUICClientClose,{once:!0}),n.connectionMap.set(S.connectionId,S);const C=new AbortController,k=()=>{C.abort(g.signal.reason)};g.signal.aborted?C.abort(g.signal.reason):g.signal.addEventListener("abort",k);const x=e=>{switch(e.detail.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":C.abort(new ua(void 0,{cause:e.detail}))}};E.addEventListener(`${bo.name}-${S.sendId}`,x);try{await S.start(void 0,{timer:g.timer,signal:C.signal})}catch(e){throw n.connectionMap.delete(S.connectionId),n.removeEventListener(uo.name,E.handleEventQUICSocketStopped),w||(n.removeEventListener(Ri.name,E.handleEventQUICSocket),await n.stop({force:!0})),S.removeEventListener(Ri.name,E.handleEventQUICConnection),S.removeEventListener(Eo.name,E.handleEventQUICConnectionError),S.removeEventListener(xo.name,E.handleEventQUICConnectionSend),S.removeEventListener(So.name,E.handleEventQUICConnectionStopped),E.removeEventListener(po.name,E.handleEventQUICClientError),E.removeEventListener(mo.name,E.handleEventQUICClientClose),e}finally{g.signal.removeEventListener("abort",k),E.removeEventListener(`${bo.name}-${S.sendId}`,x)}return p=eo(A,t),f.info(`Created ${this.name} to ${p}`),E}isSocketShared;connection;closedP;logger;socket;config;_closed=!1;resolveClosedP;handleEventQUICClientError=e=>{const t=e.detail;if(this.logger.info(io(t)),t instanceof fa||t instanceof Oa)throw t;this.dispatchEvent(new mo({detail:t}))};handleEventQUICClientClose=async e=>{const t=e.detail;if(this.connection.removeEventListener(Eo.name,this.handleEventQUICConnectionError),await this.connection.stop({isApp:!1,errorCode:ec.InternalError,reason:Buffer.from(t.description),force:!0}),!(t instanceof da||this.isSocketShared)){this.socket.removeEventListener(uo.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new fa("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new po({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[pn]||"destroying"===this[mn]||await this.destroy({force:!0})};handleEventQUICSocket=e=>{e.detail instanceof ki&&!(e.detail instanceof xo)&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new da;this.removeEventListener(Ri.name,this.handleEventQUICSocket),this.dispatchEvent(new po({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof ki&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionError=e=>{const t=e.detail;this.dispatchEvent(new po({detail:t}))};handleEventQUICConnectionSend=async e=>{try{if(!this.socket[fn]||"stopping"===this.socket[mn])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 bo(`${bo.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new po({detail:new fa("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(Eo.name,this.handleEventQUICConnectionError),t.removeEventListener(xo.name,this.handleEventQUICConnectionSend),t.removeEventListener(Ri.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}=$a();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[fn]&&(i=eo(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(po.name,this.handleEventQUICClientError),this.removeEventListener(mo.name,this.handleEventQUICClientClose),this.socket.removeEventListener(uo.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(Ri.name,this.handleEventQUICSocket),this.logger.info(`Destroyed ${this.constructor.name}${null!=i?` to ${i}`:""}`)}};dc([Hn(new la)],uc.prototype,"host",null),dc([Hn(new la)],uc.prototype,"port",null),dc([Hn(new la)],uc.prototype,"localHost",null),dc([Hn(new la)],uc.prototype,"localPort",null),dc([Ko(!0,Fo,class extends ca{static description="QUIC Client create timeout"}),function(e,t){return function(r,s){t(r,s,e)}}(1,Lo)],uc,"createQUICClient",null),uc=dc([Ln({eventDestroy:class extends go{},eventDestroyed:class extends go{}})],uc);const hc=uc,fc=t(import.meta.url)("node:crypto");var gc=a.n(fc);class pc{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=pc.toUint8Array(e),s=pc.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 bc="string",mc=/^[0-9a-f\s]+$/i,yc=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ac=/^[a-zA-Z0-9-_]+$/;class Ic{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=pc.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return decodeURIComponent(escape(r))}}class vc{static toString(e,t=!1){const r=pc.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 wc{static isHex(e){return typeof e===bc&&mc.test(e)}static isBase64(e){return typeof e===bc&&yc.test(e)}static isBase64Url(e){return typeof e===bc&&Ac.test(e)}static ToString(e,t="utf8"){const r=pc.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 vc.toString(r,!0);case"utf16":case"utf16be":return vc.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 vc.fromString(e,!0);case"utf16":case"utf16be":return vc.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=pc.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(!wc.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(!wc.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=wc.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Ic.fromString(e);case"utf16":case"utf16be":return vc.fromString(e);case"utf16le":case"usc2":return vc.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=wc.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Ic.toString(e);case"utf16":case"utf16be":return vc.toString(e);case"utf16le":case"usc2":return vc.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=pc.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return r}static ToHex(e){const t=pc.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(!wc.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 vc.toString(e,t)}static FromUtf16String(e,t=!1){return vc.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 Sc(...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 Ec(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 Cc(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 kc(e,t,r=-1){const s=r;let i=e,n=0,a=Math.pow(2,t);for(let r=1;r<8;r++){if(e<a){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 a=new Uint8Array(e);for(let e=r-1;e>=0;e--){const r=Math.pow(2,e*t);a[n-e-1]=Math.floor(i/r),i-=a[n-e-1]*r}return e}a*=Math.pow(2,t)}return new ArrayBuffer(0)}function xc(...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 Bc(){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=Cc(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,Cc(n,8)-s}function _c(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 Rc(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Oc(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 Uc(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)}wc.DEFAULT_UTF8_ENCODING="utf8",Math.log(2);class Tc{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Oc(this.items)}}const Nc=[new Uint8Array([1])],Dc="0123456789",Mc="name",Pc="valueHexView",Lc="isHexOnly",Hc="idBlock",Vc="tagClass",Kc="tagNumber",Qc="isConstructed",Fc="fromBER",$c="toBER",Gc="local",jc="",qc=new ArrayBuffer(0),zc=new Uint8Array(0),Wc="EndOfContent",Jc="OCTET STRING",Yc="BIT STRING";function Xc(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?pc.toUint8Array(r.valueHex):zc}fromBER(e,t,r){const s=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!Uc(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",qc)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:wc.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class Zc{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=jc,warnings:r=[],valueBeforeDecode:s=zc}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=pc.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:wc.ToHex(this.valueBeforeDecodeView)}}}Zc.NAME="baseBlock";class el extends Zc{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'")}}el.NAME="valueBlock";class tl extends(Xc(Zc)){constructor({idBlock:e={}}={}){var t,r,s,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?pc.toUint8Array(e.valueHex):zc,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",qc}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=kc(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=pc.toUint8Array(e);if(!Uc(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=Cc(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}}}tl.NAME="identificationBlock";class rl extends Zc{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=pc.toUint8Array(e);if(!Uc(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 a=t+1,o=s.subarray(a,a+n);return 0===o[n-1]&&this.warnings.push("Needlessly long encoded length"),this.length=Cc(o,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=kc(this.length,8);if(s.byteLength>127)return this.error="Too big length",qc;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}}}rl.NAME="lengthBlock";const sl={};class il extends Zc{constructor({name:e=jc,optional:t=!1,primitiveSchema:r,...s}={},i){super(s),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new tl(s),this.lenBlock=new rl(s),this.valueBlock=i?new i(s):new el(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 Tc;t||nl(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?qc: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():wc.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${wc.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 nl(e){var t;if(e instanceof sl.Constructed)for(const t of e.valueBlock.value)nl(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}il.NAME="BaseBlock";class al extends il{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=jc,...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}'`}}al.NAME="BaseStringBlock";class ol extends(Xc(el)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var cl,ll,dl,ul,hl,fl,gl,pl,bl,ml,yl,Al,Il,vl,wl,Sl,El,Cl,kl,xl,Bl,_l,Rl,Ol,Ul,Tl,Nl,Dl,Ml,Pl,Ll,Hl,Vl,Kl,Ql,Fl;ol.NAME="PrimitiveValueBlock";class $l extends il{constructor(e={}){super(e,ol),this.idBlock.isConstructed=!1}}function Gl(e,t=0,r=e.length){const s=t;let i=new il({},el);const n=new Zc;if(!Uc(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 a=i.idBlock.fromBER(e,t,r);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),-1===a)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=a,r-=i.idBlock.blockLength,a=i.lenBlock.fromBER(e,t,r),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),-1===a)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=a,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 o=il;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};o=sl.EndOfContent;break;case 1:o=sl.Boolean;break;case 2:o=sl.Integer;break;case 3:o=sl.BitString;break;case 4:o=sl.OctetString;break;case 5:o=sl.Null;break;case 6:o=sl.ObjectIdentifier;break;case 10:o=sl.Enumerated;break;case 12:o=sl.Utf8String;break;case 13:o=sl.RelativeObjectIdentifier;break;case 14:o=sl.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:o=sl.Sequence;break;case 17:o=sl.Set;break;case 18:o=sl.NumericString;break;case 19:o=sl.PrintableString;break;case 20:o=sl.TeletexString;break;case 21:o=sl.VideotexString;break;case 22:o=sl.IA5String;break;case 23:o=sl.UTCTime;break;case 24:o=sl.GeneralizedTime;break;case 25:o=sl.GraphicString;break;case 26:o=sl.VisibleString;break;case 27:o=sl.GeneralString;break;case 28:o=sl.UniversalString;break;case 29:o=sl.CharacterString;break;case 30:o=sl.BmpString;break;case 31:o=sl.DATE;break;case 32:o=sl.TimeOfDay;break;case 33:o=sl.DateTime;break;case 34:o=sl.Duration;break;default:{const e=i.idBlock.isConstructed?new sl.Constructed:new sl.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else o=i.idBlock.isConstructed?sl.Constructed:sl.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,o),a=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?r:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(s,s+i.blockLength),{offset:a,result:i}}function jl(e){if(!e.byteLength){const e=new il({},el);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Gl(pc.toUint8Array(e).slice(),0,e.byteLength)}function ql(e,t){return e?1:t}cl=$l,sl.Primitive=cl,$l.NAME="PRIMITIVE";class zl extends el{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const s=pc.toUint8Array(e);if(!Uc(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(;ql(this.isIndefiniteForm,r)>0;){const e=Gl(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===Wc)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Wc?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){const r=t||new Tc;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?qc:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}zl.NAME="ConstructedValueBlock";class Wl extends il{constructor(e={}){super(e,zl),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} :`}}ll=Wl,sl.Constructed=ll,Wl.NAME="CONSTRUCTED";class Jl extends el{fromBER(e,t,r){return t}toBER(e){return qc}}Jl.override="EndOfContentValueBlock";class Yl extends il{constructor(e={}){super(e,Jl),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}dl=Yl,sl.EndOfContent=dl,Yl.NAME=Wc;class Xl extends il{constructor(e={}){super(e,el),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}`}}ul=Xl,sl.Null=ul,Xl.NAME="NULL";class Zl extends(Xc(el)){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=pc.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,r){const s=pc.toUint8Array(e);return Uc(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,Bc.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}Zl.NAME="BooleanValueBlock";class ed extends il{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,Zl),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}hl=ed,sl.Boolean=hl,ed.NAME="BOOLEAN";class td extends(Xc(zl)){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=zl.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===Wc){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==Jc)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?zl.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}td.NAME="OctetStringValueBlock";class rd extends il{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},td),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=Gl(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?Wl.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${wc.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 fl&&e.push(t.valueBlock.valueHexView);return pc.concat(e)}}fl=rd,sl.OctetString=fl,rd.NAME=Jc;class sd extends(Xc(zl)){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=zl.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(const e of this.value){const t=e.constructor.NAME;if(t===Wc){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==Yc)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=pc.toUint8Array(e);if(!Uc(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=Gl(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 zl.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return qc;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}}}sd.NAME="BitStringValueBlock";class id extends il{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},sd),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 Wl.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 nd(e,t){const r=new Uint8Array([0]),s=new Uint8Array(e),i=new Uint8Array(t);let n=s.slice(0);const a=n.length-1,o=i.slice(0),c=o.length-1;let l=0,d=0;for(let e=c<a?a:c;e>=0;e--,d++)l=1==d<o.length?n[a-d]+o[c-d]+r[0]:n[a-d]+r[0],r[0]=l/10,1==d>=n.length?n=xc(new Uint8Array([l%10]),n):n[a-d]=l%10;return r[0]>0&&(n=xc(r,n)),n}function ad(e){if(e>=Nc.length)for(let t=Nc.length;t<=e;t++){const e=new Uint8Array([0]);let r=Nc[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=xc(e,r)),Nc.push(r)}return Nc[e]}function od(e,t){let r=0;const s=new Uint8Array(e),i=new Uint8Array(t),n=s.slice(0),a=n.length-1,o=i.slice(0),c=o.length-1;let l,d=0;for(let e=c;e>=0;e--,d++)l=n[a-d]-o[c-d]-r,1==l<0?(r=1,n[a-d]=l+10):(r=0,n[a-d]=l);if(r>0)for(let e=a-c+1;e>=0;e--,d++){if(l=n[a-d]-r,!(l<0)){r=0,n[a-d]=l;break}r=1,n[a-d]=l+10}return n.slice()}gl=id,sl.BitString=gl,id.NAME=Yc;class cd extends(Xc(el)){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=Bc.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=kc(r-t,8,s);return new Uint8Array(e)[0]|=128,e}let i=kc(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="",a=!1;for(let a=i.byteLength-1;a>=0;a--){t=i[a];for(let i=0;i<8;i++)1&~t||(s===e?(r=od(ad(s),r),n="-"):r=nd(r,ad(s))),s++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(a=!0),a&&(n+=Dc.charAt(r[e]));return!1===a&&(n+=Dc.charAt(0)),n}}pl=cd,cd.NAME="IntegerValueBlock",Object.defineProperty(pl.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class ld extends il{constructor(e={}){super(e,cd),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Rc(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Rc();const t=BigInt(e),r=new Tc,s=t.toString(16).replace(/^-/,""),i=new Uint8Array(wc.FromHex(s));if(t<0){const e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;const s=BigInt(`0x${wc.ToHex(e)}`)+t,n=pc.toUint8Array(wc.FromHex(s.toString(16)));n[0]|=128,r.write(n)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);return new bl({valueHex:r.final()})}convertToDER(){const e=new bl({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new bl({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}bl=ld,sl.Integer=bl,ld.NAME="INTEGER";class dd extends ld{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}ml=dd,sl.Enumerated=ml,dd.NAME="ENUMERATED";class ud extends(Xc(el)){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=pc.toUint8Array(e);if(!Uc(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=Cc(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Rc();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=kc(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",qc;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=wc.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}}}ud.NAME="sidBlock";class hd extends el{constructor({value:e=jc,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new ud;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,qc;t.push(s)}return Oc(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 ud;if(s>Number.MAX_SAFE_INTEGER){Rc();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}}hd.NAME="ObjectIdentifierValueBlock";class fd extends il{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,hd),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}yl=fd,sl.ObjectIdentifier=yl,fd.NAME="OBJECT IDENTIFIER";class gd extends(Xc(Zc)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const s=pc.toUint8Array(e);if(!Uc(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=Cc(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=kc(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",qc;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?wc.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}gd.NAME="relativeSidBlock";class pd extends el{constructor({value:e=jc,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new gd;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,qc;r.push(s)}return Oc(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 gd;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}}pd.NAME="RelativeObjectIdentifierValueBlock";class bd extends il{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,pd),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Al=bd,sl.RelativeObjectIdentifier=Al,bd.NAME="RelativeObjectIdentifier";class md extends Wl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}Il=md,sl.Sequence=Il,md.NAME="SEQUENCE";class yd extends Wl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}vl=yd,sl.Set=vl,yd.NAME="SET";class Ad extends(Xc(el)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=jc}toJSON(){return{...super.toJSON(),value:this.value}}}Ad.NAME="StringValueBlock";class Id extends Ad{}Id.NAME="SimpleStringValueBlock";class vd extends al{constructor({...e}={}){super(e,Id)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,pc.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}}vd.NAME="SIMPLE STRING";class wd extends vd{fromBuffer(e){this.valueBlock.valueHexView=pc.toUint8Array(e);try{this.valueBlock.value=wc.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=wc.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(wc.FromUtf8String(e)),this.valueBlock.value=e}}wd.NAME="Utf8StringValueBlock";class Sd extends wd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}wl=Sd,sl.Utf8String=wl,Sd.NAME="UTF8String";class Ed extends vd{fromBuffer(e){this.valueBlock.value=wc.ToUtf16String(e),this.valueBlock.valueHexView=pc.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(wc.FromUtf16String(e))}}Ed.NAME="BmpStringValueBlock";class Cd extends Ed{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}Sl=Cd,sl.BmpString=Sl,Cd.NAME="BMPString";class kd extends vd{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=kc(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}}kd.NAME="UniversalStringValueBlock";class xd extends kd{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}El=xd,sl.UniversalString=El,xd.NAME="UniversalString";class Bd extends vd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}Cl=Bd,sl.NumericString=Cl,Bd.NAME="NumericString";class _d extends vd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}kl=_d,sl.PrintableString=kl,_d.NAME="PrintableString";class Rd extends vd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}xl=Rd,sl.TeletexString=xl,Rd.NAME="TeletexString";class Od extends vd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Bl=Od,sl.VideotexString=Bl,Od.NAME="VideotexString";class Ud extends vd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}_l=Ud,sl.IA5String=_l,Ud.NAME="IA5String";class Td extends vd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}Rl=Td,sl.GraphicString=Rl,Td.NAME="GraphicString";class Nd extends vd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}Ol=Nd,sl.VisibleString=Ol,Nd.NAME="VisibleString";class Dd extends vd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}Ul=Dd,sl.GeneralString=Ul,Dd.NAME="GeneralString";class Md extends vd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}Tl=Md,sl.CharacterString=Tl,Md.NAME="CharacterString";class Pd extends Nd{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,pc.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]=_c(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=_c(this.month,2),e[2]=_c(this.day,2),e[3]=_c(this.hour,2),e[4]=_c(this.minute,2),e[5]=_c(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}}}Nl=Pd,sl.UTCTime=Nl,Pd.NAME="UTCTime";class Ld extends Pd{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,a=0,o=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(a=e*i,4===r.length){if(i=parseInt(r.substring(2,4),10),isNaN(i.valueOf()))throw new Error("Wrong input string for conversion");o=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)+a;break;case 5:this.minute=parseInt(l[e],10)+o;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(_c(this.year,4)),e.push(_c(this.month,2)),e.push(_c(this.day,2)),e.push(_c(this.hour,2)),e.push(_c(this.minute,2)),e.push(_c(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(_c(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}Dl=Ld,sl.GeneralizedTime=Dl,Ld.NAME="GeneralizedTime";class Hd extends Sd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}Ml=Hd,sl.DATE=Ml,Hd.NAME="DATE";class Vd extends Sd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}Pl=Vd,sl.TimeOfDay=Pl,Vd.NAME="TimeOfDay";class Kd extends Sd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}Ll=Kd,sl.DateTime=Ll,Kd.NAME="DateTime";class Qd extends Sd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}Hl=Qd,sl.Duration=Hl,Qd.NAME="Duration";class Fd extends Sd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}Vl=Fd,sl.TIME=Vl,Fd.NAME="TIME";class $d{constructor({name:e=jc,optional:t=!1}={}){this.name=e,this.optional=t}}class Gd extends $d{constructor({value:e=[],...t}={}){super(t),this.value=e}}class jd extends $d{constructor({value:e=new $d,local:t=!1,...r}={}){super(r),this.value=e,this.local=t}}class qd{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=pc.toUint8Array(e)}constructor({data:e=zc}={}){this.dataView=pc.toUint8Array(e)}fromBER(e,t,r){const s=t+r;return this.dataView=pc.toUint8Array(e).subarray(t,s),s}toBER(e){return this.dataView.slice().buffer}}function zd(e,t,r){if(r instanceof Gd){for(const s of r.value)if(zd(e,t,s).verified)return{verified:!0,result:e};{const e={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(Mc)&&(e.name=r.name),e}}if(r instanceof $d)return r.hasOwnProperty(Mc)&&(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(Hc in r==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(Fc in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if($c 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(Vc))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(Kc))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(Qc))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(Lc 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(Pc 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,jc),r.name&&(e[r.name]=t)),r instanceof sl.Constructed){let s=0,i={verified:!1,result:{error:"Unknown error"}},n=r.valueBlock.value.length;if(n>0&&r.valueBlock.value[0]instanceof jd&&(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,jc),r.name&&delete e[r.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(let a=0;a<n;a++)if(a-s>=t.valueBlock.value.length){if(!1===r.valueBlock.value[a].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,jc),r.name&&(delete e[r.name],t.name=r.name)),t}}else if(r.valueBlock.value[0]instanceof jd){if(i=zd(e,t.valueBlock.value[a],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,jc),r.name&&delete e[r.name]),i;s++}if(Mc in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let s={};s=Gc 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[a])}}else if(i=zd(e,t.valueBlock.value[a-s],r.valueBlock.value[a]),!1===i.verified){if(!r.valueBlock.value[a].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,jc),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,jc),r.name&&(delete e[r.name],t.name=r.name)),t}return{verified:!0,result:e}}if(r.primitiveSchema&&Pc in t.valueBlock){const s=Gl(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,jc),r.name&&(delete e[r.name],t.name=r.name)),t}return zd(e,s.result,r.primitiveSchema)}return{verified:!0,result:e}}function Wd(e,t){if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=Gl(pc.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:zd(r.result,r.result,t)}(Fl=Kl||(Kl={}))[Fl.Sequence=0]="Sequence",Fl[Fl.Set=1]="Set",Fl[Fl.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"}(Ql||(Ql={}));class Jd{constructor(e,t=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if("number"==typeof e)this.fromNumber(e);else{if(!pc.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=pc.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof id))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 id({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new id({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 Yd{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):pc.isBufferSource(e)?this.buffer=pc.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof rd))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new rd({valueHex:this.buffer})}toSchema(e){return new rd({name:e})}}const Xd={fromASN:e=>e instanceof Xl?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new Xl;const t=jl(e);if(t.result.error)throw new Error(t.result.error);return t.result}},Zd={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new ld({value:+e})},eu={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new dd({value:e})},tu={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new ld({valueHex:e})},ru={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new id({valueHex:e})},su={fromASN:e=>e.valueBlock.toString(),toASN:e=>new fd({value:e})},iu={fromASN:e=>e.valueBlock.value,toASN:e=>new ed({value:e})},nu={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new rd({valueHex:e})},au={fromASN:e=>new Yd(e.getValue()),toASN:e=>e.toASN()};function ou(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}const cu=ou(Sd),lu=ou(Cd),du=ou(xd),uu=ou(Bd),hu=ou(_d),fu=ou(Rd),gu=ou(Od),pu=ou(Ud),bu=ou(Td),mu=ou(Nd),yu=ou(Dd),Au=ou(Md),Iu={fromASN:e=>e.toDate(),toASN:e=>new Pd({valueDate:e})},vu={fromASN:e=>e.toDate(),toASN:e=>new Ld({valueDate:e})},wu={fromASN:()=>null,toASN:()=>new Xl};function Su(e){switch(e){case Ql.Any:return Xd;case Ql.BitString:return ru;case Ql.BmpString:return lu;case Ql.Boolean:return iu;case Ql.CharacterString:return Au;case Ql.Enumerated:return eu;case Ql.GeneralString:return yu;case Ql.GeneralizedTime:return vu;case Ql.GraphicString:return bu;case Ql.IA5String:return pu;case Ql.Integer:return Zd;case Ql.Null:return wu;case Ql.NumericString:return uu;case Ql.ObjectIdentifier:return su;case Ql.OctetString:return nu;case Ql.PrintableString:return hu;case Ql.TeletexString:return fu;case Ql.UTCTime:return Iu;case Ql.UniversalString:return du;case Ql.Utf8String:return cu;case Ql.VideotexString:return gu;case Ql.VisibleString:return mu;default:return null}}function Eu(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||Eu(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function Cu(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||Cu(r)}return!1}function ku(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 xu=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:Kl.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 a;if("number"==typeof i.type){const e=Ql[i.type],t=o[e];if(!t)throw new Error(`Cannot get ASN1 class by name '${e}'`);a=new t({name:n})}else Eu(i.type)?a=(new i.type).toSchema(n):i.optional?this.get(i.type).type===Kl.Choice?a=new $d({name:n}):(a=this.create(i.type,!1),a.name=n):a=new $d({name:n});const c=!!i.optional||void 0!==i.defaultValue;if(i.repeated&&(a.name="",a=new("set"===i.repeated?yd:md)({name:"",value:[new jd({name:n,value:a})]})),null!==i.context&&void 0!==i.context)if(i.implicit)if("number"==typeof i.type||Eu(i.type)){const e=i.repeated?Wl:$l;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?a:this.get(i.type,!0).schema;t="valueBlock"in t?t.valueBlock.value:t.value,s.push(new Wl({name:e?"":n,optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}else s.push(new Wl({optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:[a]}));else a.optional=c,s.push(a)}switch(r.type){case Kl.Sequence:return new md({value:s,name:""});case Kl.Set:return new yd({value:s,name:""});case Kl.Choice:return new Gd({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}},Bu=e=>t=>{let r;xu.has(t)?r=xu.get(t):(r=xu.createDefault(t),xu.set(t,r)),Object.assign(r,e)},_u=e=>(t,r)=>{let s;xu.has(t.constructor)?s=xu.get(t.constructor):(s=xu.createDefault(t.constructor),xu.set(t.constructor,s));const i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){const s=Su(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 Ru extends Error{constructor(){super(...arguments),this.schemas=[]}}class Ou{static parse(e,t){const r=jl(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(Eu(t))return(new t).fromASN(e);const s=xu.get(t);xu.cache(t);let i=s.schema;if(e.constructor===Wl&&s.type!==Kl.Choice){i=new Wl({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:s.schema.valueBlock.value});for(const t in s.items)delete e[t]}const n=zd({},e,i);if(!n.verified)throw new Ru(`Data does not match to ${t.name} ASN1 schema. ${n.result.error}`);const a=new t;if(Cu(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=Su(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||Eu(c)){const s=null!==(r=i.converter)&&void 0!==r?r:Eu(c)?new c:null;if(!s)throw new Error("Converter is empty");if(i.repeated)if(i.implicit){const r=new("sequence"===i.repeated?md:yd);r.valueBlock=t.valueBlock;const n=jl(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 o=n.result.valueBlock.value;a[e]=Array.from(o,e=>s.fromASN(e))}else a[e]=Array.from(t,e=>s.fromASN(e));else{let r=t;if(i.implicit){let e;if(Eu(c))e=(new c).toSchema("");else{const t=Ql[c],r=o[t];if(!r)throw new Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=r.valueBlock,r=jl(e.toBER(!1)).result}a[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.");a[e]=Array.from(t,e=>this.fromASN(e,c))}else a[e]=this.fromASN(t,c)}return a}catch(e){throw e instanceof Ru&&e.schemas.push(t.name),e}}}class Uu{static serialize(e){return e instanceof il?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&"object"==typeof e&&Eu(e))return e.toASN();if(!e||"object"!=typeof e)throw new TypeError("Parameter 1 should be type of Object.");const t=e.constructor,r=xu.get(t);xu.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=Su(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],a=e[s];if(void 0===a||n.defaultValue===a||"object"==typeof n.defaultValue&&"object"==typeof a&&ku(this.serialize(n.defaultValue),this.serialize(a)))continue;const o=Uu.toAsnItem(n,s,t,a);if("number"==typeof n.context)if(n.implicit)if(n.repeated||"number"!=typeof n.type&&!Eu(n.type))i.push(new Wl({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:o.valueBlock.value}));else{const e={};e.valueHex=o instanceof Xl?o.valueBeforeDecodeView:o.valueBlock.toBER(),i.push(new $l({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},...e}))}else i.push(new Wl({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:[o]}));else n.repeated?i=i.concat(o):i.push(o)}switch(r.type){case Kl.Sequence:s=new md({value:i});break;case Kl.Set:s=new yd({value:i});break;case Kl.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 ${Ql[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?md:yd)({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?md:yd)({value:t})}else i=this.toASN(s);return i}}class Tu extends Array{constructor(e=[]){if("number"==typeof e)super(e);else{super();for(const t of e)this.push(t)}}}class Nu{static serialize(e){return Uu.serialize(e)}static parse(e,t){return Ou.parse(e,t)}static toString(e){const t=jl(pc.isBufferSource(e)?pc.toArrayBuffer(e):Nu.serialize(e));if(-1===t.offset)throw new Error(`Cannot decode ASN.1 data. ${t.result.error}`);return t.result.toString()}}function Du(e,t,r,s){var i,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,s);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;class Mu extends Error{constructor(e,t){super(t?`${e}. See the inner exception for more details.`:e),this.message=e,this.innerError=t}}class Pu extends Mu{constructor(e,t,r){super(t,r),this.schema=e}}class Lu extends Pu{constructor(e,t,r){super(e,`JSON doesn't match to '${e.target.name}' schema. ${t}`,r)}}class Hu extends Mu{}class Vu extends Mu{constructor(e,t,r){super(`Cannot serialize by '${e}' schema. ${t}`,r),this.schemaName=e}}class Ku extends Lu{constructor(e,t,r={}){super(e,"Some keys doesn't match to schema"),this.keys=t,this.errors=r}}var Qu;function Fu(e,t){if(!function(e,t){switch(t){case Qu.Boolean:return"boolean"==typeof e;case Qu.Number:return"number"==typeof e;case Qu.String:return"string"==typeof e}return!0}(e,t))throw new TypeError(`Value must be ${Qu[t]}`)}function $u(e){return e&&e.prototype?!(!e.prototype.toJSON||!e.prototype.fromJSON)||$u(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"}(Qu||(Qu={}));const Gu="default",ju=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 qu{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 Hu("Incoming value must be string");if(!t.exec(e))throw new Hu(`Value doesn't match to pattern '${t.toString()}'`)}}class zu{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(Fu(e,Qu.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 Hu(`Value doesn't match to diapason [${e},${t}]`)}}}class Wu{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(Fu(e,Qu.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 Hu(`Value doesn't match to diapason (${e},${t})`)}}}class Ju{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 Hu(`Value length must be more than ${this.minLength}.`);if(void 0!==this.maxLength&&e.length>this.maxLength)throw new Hu(`Value length must be less than ${this.maxLength}.`)}else if(e.length!==this.length)throw new Hu(`Value length must be exactly ${this.length}.`)}}class Yu{constructor(e){this.enumeration=e}validate(e){if(Fu(e,Qu.String),!this.enumeration.includes(e))throw new Hu(`Value must be one of ${this.enumeration.map(e=>`'${e}'`).join(", ")}`)}}class Xu{static checkValues(e,t){const r=Array.isArray(e)?e:[e];for(const s of r)for(const r of t.validations)r instanceof Ju&&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)Fu(e,t.type)}}static getSchemaByName(e,t=Gu){return{...e.names[Gu],...e.names[t]}}}class Zu extends Xu{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||Gu;if($u(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&&!ju.has(s))throw new Mu("Cannot get schema for `targetSchema` param");if(s=s||e.constructor,ju.has(s)){const t=ju.get(s);r={};const n=this.getSchemaByName(t,i);for(const a in n)try{const t=n[a],o=e[a];let c;if(t.optional&&void 0===o||void 0!==t.defaultValue&&o===t.defaultValue)continue;if(!t.optional&&void 0===o)throw new Vu(s.name,`Property '${a}' is required.`);c="number"==typeof t.type?t.converter?t.repeated?o.map(r=>t.converter.toJSON(r,e)):t.converter.toJSON(o,e):o:t.repeated?o.map(e=>this.toJSON(e,{schemaName:i})):this.toJSON(o,{schemaName:i}),this.checkTypes(c,t),this.checkValues(c,t),r[t.name||a]=c}catch(e){throw e instanceof Vu?e:new Vu(t.target.name,`Property '${a}' 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 eh extends Xu{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||Gu,i=new r;if($u(i))return i.fromJSON(e);const n=ju.get(r),a=this.getSchemaByName(n,s),o={};t.strictProperty&&!Array.isArray(e)&&eh.checkStrictProperty(e,a,n);for(const r in a)try{const o=a[r],c=o.name||r,l=e[c];if(void 0===l&&(o.optional||void 0!==o.defaultValue))continue;if(!o.optional&&void 0===l)throw new Lu(n,`Property '${c}' is required.`);if(this.checkTypes(l,o),this.checkValues(l,o),"number"==typeof o.type)o.converter?o.repeated?i[r]=l.map(e=>o.converter.fromJSON(e,i)):i[r]=o.converter.fromJSON(l,i):i[r]=l;else{const e={...t,targetSchema:o.type,schemaName:s};o.repeated?i[r]=l.map(t=>this.fromJSON(t,e)):i[r]=this.fromJSON(l,e)}}catch(e){if(e instanceof Lu||(e=new Lu(n,`Property '${r}' is wrong. ${e.message}`,e)),!t.strictAllKeys)throw e;o[r]=e}const c=Object.keys(o);if(c.length)throw new Ku(n,c,o);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 Ku(r,n)}}const th=(e={})=>(t,r)=>{const s=`Cannot set type for ${r} property of ${t.constructor.name} schema`;let i;ju.has(t.constructor)?(i=ju.get(t.constructor),i.target!==t.constructor&&(i=ju.create(t.constructor),ju.set(t.constructor,i))):(i=ju.create(t.constructor),ju.set(t.constructor,i));const n={type:Qu.Any,validations:[]},a=Object.assign(n,e);if(a.validations=function(e){const t=[];return e.pattern&&t.push(new qu(e.pattern)),e.type!==Qu.Number&&e.type!==Qu.Any||(void 0===e.minInclusive&&void 0===e.maxInclusive||t.push(new zu(e.minInclusive,e.maxInclusive)),void 0===e.minExclusive&&void 0===e.maxExclusive||t.push(new Wu(e.minExclusive,e.maxExclusive)),void 0!==e.enumeration&&t.push(new Yu(e.enumeration))),(e.type===Qu.String||e.repeated||e.type===Qu.Any)&&(void 0===e.length&&void 0===e.minLength&&void 0===e.maxLength||t.push(new Ju(e.length,e.minLength,e.maxLength))),t}(a),"number"!=typeof a.type&&!ju.has(a.type)&&!$u(a.type))throw new Error(`${s}. Assigning type doesn't have schema.`);let o;o=Array.isArray(e.schema)?e.schema:[e.schema||Gu];for(const e of o)i.names[e]||(i.names[e]={}),i.names[e][r]=a};class rh extends Error{}class sh extends rh{}class ih extends rh{constructor(e){super("Unsupported operation: "+(e?`${e}`:""))}}class nh extends rh{}class ah extends rh{constructor(e){super(`${e}: Missing required property`)}}class oh{static toArrayBuffer(e){const t=e.replace(/-{5}(BEGIN|END) .*-{5}/g,"").replace("\r","").replace("\n","");return wc.FromBase64(t)}static toUint8Array(e){const t=this.toArrayBuffer(e);return new Uint8Array(t)}static fromBufferSource(e,t){const r=wc.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 a=t.toUpperCase();return`-----BEGIN ${a}-----\n${n.join("\n")}\n-----END ${a}-----`}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 ch{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 ih("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 ih("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 ih("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 ih("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 ih("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 ih("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 nh("length: Is not multiple of 8")}async onDeriveBits(e,t,r,...s){throw new ih("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 rh("key: Is not extractable")}async onExportKey(e,t,...r){throw new ih("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 ih("importKey")}checkAlgorithmName(e){if(e.name.toLowerCase()!==this.name.toLowerCase())throw new sh("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 rh("key does not match that of operation")}checkRequiredProperty(e,t){if(!(t in e))throw new ah(t)}checkHashAlgorithm(e,t){for(const r of t)if(r.toLowerCase()===e.name.toLowerCase())return;throw new nh(`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(!pc.isBufferSource(t))throw new TypeError("keyData: Is not ArrayBufferView or ArrayBuffer");var r}prepareData(e){return pc.toArrayBuffer(e)}}class lh extends ch{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 dh extends lh{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 uh extends lh{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 nh("length: Must be more than 0")}}class hh extends lh{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 nh("length: Must be more than 0")}}class fh extends lh{constructor(){super(...arguments),this.name="AES-ECB",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}}class gh extends lh{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 nh("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 nh("tagLength: Must be one of 32, 64, 96, 104, 112, 120 or 128")}}}class ph extends lh{constructor(){super(...arguments),this.name="AES-KW",this.usages=["wrapKey","unwrapKey"]}}class bh extends ch{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 nh(`algorithm.length: Must be ${this.keySizeBits}`)}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class mh extends ch{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=wc.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 yh extends mh{constructor(){super(...arguments),this.name="RSASSA-PKCS1-v1_5",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class Ah extends mh{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 Ih extends mh{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 vh extends ch{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 nh(`namedCurve: Must be one of ${this.namedCurves.join(", ")}`)}}class wh extends vh{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 Sh=["secret","private","public"];class Eh{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!==Sh.indexOf(e)}get[Symbol.toStringTag](){return"CryptoKey"}}class Ch extends vh{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 Eh))throw new TypeError("public: Is not a CryptoKey");if("public"!==e.public.type)throw new nh("public: Is not a public key");if(e.public.algorithm.name!==this.name)throw new nh(`public: Is not ${this.name} key`)}}class kh extends Ch{constructor(){super(...arguments),this.name="ECDH-ES",this.namedCurves=["X25519","X448"]}}class xh extends vh{constructor(){super(...arguments),this.name="EdDSA",this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["Ed25519","Ed448"]}}let Bh=class{constructor(e){e&&(this.value=e)}};Du([_u({type:Ql.ObjectIdentifier})],Bh.prototype,"value",void 0),Bh=Du([Bu({type:Kl.Choice})],Bh);class _h{constructor(e){Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],_h.prototype,"algorithm",void 0),Du([_u({type:Ql.Any,optional:!0})],_h.prototype,"parameters",void 0);class Rh{constructor(){this.version=0,this.privateKeyAlgorithm=new _h,this.privateKey=new ArrayBuffer(0)}}Du([_u({type:Ql.Integer})],Rh.prototype,"version",void 0),Du([_u({type:_h})],Rh.prototype,"privateKeyAlgorithm",void 0),Du([_u({type:Ql.OctetString})],Rh.prototype,"privateKey",void 0),Du([_u({type:Ql.Any,optional:!0})],Rh.prototype,"attributes",void 0);class Oh{constructor(){this.publicKeyAlgorithm=new _h,this.publicKey=new ArrayBuffer(0)}}Du([_u({type:_h})],Oh.prototype,"publicKeyAlgorithm",void 0),Du([_u({type:Ql.BitString})],Oh.prototype,"publicKey",void 0);const Uh={fromJSON:e=>wc.FromBase64Url(e),toJSON:e=>wc.ToBase64Url(new Uint8Array(e))},Th={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?Sc(new Uint8Array([0]).buffer,e):e;return new ld({valueHex:t})}};class Nh{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)}}Du([_u({type:Ql.Integer,converter:Zd})],Nh.prototype,"version",void 0),Du([_u({type:Ql.Integer,converter:Th}),th({name:"n",converter:Uh})],Nh.prototype,"modulus",void 0),Du([_u({type:Ql.Integer,converter:Th}),th({name:"e",converter:Uh})],Nh.prototype,"publicExponent",void 0),Du([_u({type:Ql.Integer,converter:Th}),th({name:"d",converter:Uh})],Nh.prototype,"privateExponent",void 0),Du([_u({type:Ql.Integer,converter:Th}),th({name:"p",converter:Uh})],Nh.prototype,"prime1",void 0),Du([_u({type:Ql.Integer,converter:Th}),th({name:"q",converter:Uh})],Nh.prototype,"prime2",void 0),Du([_u({type:Ql.Integer,converter:Th}),th({name:"dp",converter:Uh})],Nh.prototype,"exponent1",void 0),Du([_u({type:Ql.Integer,converter:Th}),th({name:"dq",converter:Uh})],Nh.prototype,"exponent2",void 0),Du([_u({type:Ql.Integer,converter:Th}),th({name:"qi",converter:Uh})],Nh.prototype,"coefficient",void 0),Du([_u({type:Ql.Any,optional:!0})],Nh.prototype,"otherPrimeInfos",void 0);class Dh{constructor(){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0)}}Du([_u({type:Ql.Integer,converter:Th}),th({name:"n",converter:Uh})],Dh.prototype,"modulus",void 0),Du([_u({type:Ql.Integer,converter:Th}),th({name:"e",converter:Uh})],Dh.prototype,"publicExponent",void 0);let Mh=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 rh("Wrong ECPoint. Current version supports only Uncompressed (0x04) point");e=new Uint8Array(this.value.slice(1));const t=e.length/2;return{x:wc.ToBase64Url(e.buffer.slice(0,0+t)),y:wc.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=wc.FromBase64Url(e.x),r=wc.FromBase64Url(e.y),s=Sc(new Uint8Array([4]).buffer,t,r);return this.value=new Uint8Array(s).buffer,this}};Du([_u({type:Ql.OctetString})],Mh.prototype,"value",void 0),Mh=Du([Bu({type:Kl.Choice})],Mh);class Ph{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=wc.FromBase64Url(e.d),"x"in e){const t=new Mh;t.fromJSON(e);const r=Uu.toASN(t);"valueHex"in r.valueBlock&&(this.publicKey=r.valueBlock.valueHex)}return this}toJSON(){const e={};return e.d=wc.ToBase64Url(this.privateKey),this.publicKey&&Object.assign(e,new Mh(this.publicKey).toJSON()),e}}Du([_u({type:Ql.Integer,converter:Zd})],Ph.prototype,"version",void 0),Du([_u({type:Ql.OctetString})],Ph.prototype,"privateKey",void 0),Du([_u({context:0,type:Ql.Any,optional:!0})],Ph.prototype,"parameters",void 0),Du([_u({context:1,type:Ql.BitString,optional:!0})],Ph.prototype,"publicKey",void 0);const Lh={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 ld({valueHex:e.buffer})}return new ld({valueHex:e})}};var Hh=Object.freeze({__proto__:null,AsnIntegerWithoutPaddingConverter:Lh});class Vh{static decodePoint(e,t){const r=pc.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=pc.toUint8Array(e.x),i=pc.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=pc.toUint8Array(e.r),i=pc.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=pc.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 Kh{constructor(){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0)}static fromWebCryptoSignature(e){const t=e.byteLength/2,r=Vh.decodeSignature(e,8*t),s=new Kh;return s.r=pc.toArrayBuffer(r.r),s.s=pc.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 Vh.encodeSignature(this,e).buffer}}Du([_u({type:Ql.Integer,converter:Lh})],Kh.prototype,"r",void 0),Du([_u({type:Ql.Integer,converter:Lh})],Kh.prototype,"s",void 0);class Qh extends Rh{}Du([_u({context:1,implicit:!0,type:Ql.BitString,optional:!0})],Qh.prototype,"publicKey",void 0);let Fh=class{constructor(){this.value=new ArrayBuffer(0)}fromJSON(e){if(!e.d)throw new Error("d: Missing required property");return this.value=wc.FromBase64Url(e.d),this}toJSON(){return{d:wc.ToBase64Url(this.value)}}};Du([_u({type:Ql.OctetString})],Fh.prototype,"value",void 0),Fh=Du([Bu({type:Kl.Choice})],Fh);let $h=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){return{x:wc.ToBase64Url(this.value)}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");return this.value=wc.FromBase64Url(e.x),this}};Du([_u({type:Ql.BitString})],$h.prototype,"value",void 0),$h=Du([Bu({type:Kl.Choice})],$h);let Gh=class{};Du([_u({type:Ql.OctetString}),th({type:Qu.String,converter:Uh})],Gh.prototype,"d",void 0),Gh=Du([Bu({type:Kl.Choice})],Gh);const jh="1.2.840.10045.3.1.7",qh="1.3.132.0",zh=`${qh}.34`,Wh=`${qh}.35`,Jh=`${qh}.10`,Yh="1.3.36.3.3.2.8.1.1",Xh=`${Yh}.1`,Zh=`${Yh}.2`,ef=`${Yh}.3`,tf=`${Yh}.4`,rf=`${Yh}.5`,sf=`${Yh}.6`,nf=`${Yh}.7`,af=`${Yh}.8`,of=`${Yh}.9`,cf=`${Yh}.10`,lf=`${Yh}.11`,df=`${Yh}.12`,uf=`${Yh}.13`,hf=`${Yh}.14`;var ff=Object.freeze({__proto__:null,AlgorithmIdentifier:_h,get CurvePrivateKey(){return Gh},EcDsaSignature:Kh,EcPrivateKey:Ph,get EcPublicKey(){return Mh},get EdPrivateKey(){return Fh},get EdPublicKey(){return $h},get ObjectIdentifier(){return Bh},OneAsymmetricKey:Qh,PrivateKeyInfo:Rh,PublicKeyInfo:Oh,RsaPrivateKey:Nh,RsaPublicKey:Dh,converters:Hh,idBrainpoolP160r1:Xh,idBrainpoolP160t1:Zh,idBrainpoolP192r1:ef,idBrainpoolP192t1:tf,idBrainpoolP224r1:rf,idBrainpoolP224t1:sf,idBrainpoolP256r1:nf,idBrainpoolP256t1:af,idBrainpoolP320r1:of,idBrainpoolP320t1:cf,idBrainpoolP384r1:lf,idBrainpoolP384t1:df,idBrainpoolP512r1:uf,idBrainpoolP512t1:hf,idEd25519:"1.3.101.112",idEd448:"1.3.101.113",idEllipticCurve:qh,idSecp256k1:Jh,idSecp256r1:jh,idSecp384r1:zh,idSecp521r1:Wh,idVersionOne:Yh,idX25519:"1.3.101.110",idX448:"1.3.101.111"});class gf{constructor(){}static register(e){const t=new Bh;t.value=e.id;const r=Nu.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}}gf.items=[],gf.names=[],gf.register({name:"P-256",id:jh,size:256}),gf.register({name:"P-384",id:zh,size:384}),gf.register({name:"P-521",id:Wh,size:521}),gf.register({name:"K-256",id:Jh,size:256}),gf.register({name:"brainpoolP160r1",id:Xh,size:160}),gf.register({name:"brainpoolP160t1",id:Zh,size:160}),gf.register({name:"brainpoolP192r1",id:ef,size:192}),gf.register({name:"brainpoolP192t1",id:tf,size:192}),gf.register({name:"brainpoolP224r1",id:rf,size:224}),gf.register({name:"brainpoolP224t1",id:sf,size:224}),gf.register({name:"brainpoolP256r1",id:nf,size:256}),gf.register({name:"brainpoolP256t1",id:af,size:256}),gf.register({name:"brainpoolP320r1",id:of,size:320}),gf.register({name:"brainpoolP320t1",id:cf,size:320}),gf.register({name:"brainpoolP384r1",id:lf,size:384}),gf.register({name:"brainpoolP384t1",id:df,size:384}),gf.register({name:"brainpoolP512r1",id:uf,size:512}),gf.register({name:"brainpoolP512t1",id:hf,size:512});class pf extends ch{constructor(){super(...arguments),this.name="X25519",this.usages={privateKey:["deriveKey","deriveBits"],publicKey:[]}}checkAlgorithmParams(e){this.checkRequiredProperty(e,"public")}}class bf extends ch{constructor(){super(...arguments),this.name="Ed25519",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class mf extends ch{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 yf extends ch{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 Af extends ch{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"),!pc.isBufferSource(e.salt))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"info"),!pc.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 If extends ch{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 vf extends If{constructor(){super(...arguments),this.name="shake128",this.defaultLength=16}}class wf extends If{constructor(){super(...arguments),this.name="shake256",this.defaultLength=32}}class Sf{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=wc.ToHex(e).toLowerCase();return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}}class Ef{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 Cf={jwk:["private","public","secret"],pkcs8:["private"],spki:["public"],raw:["secret","public"]},kf=["pkcs8","spki","raw"];class xf{constructor(){this.providers=new Ef}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=pc.toArrayBuffer(r),a=this.getProvider(i.name);return await a.digest(i,n,...s)}async generateKey(...e){this.checkRequiredArguments(e,3,"generateKey");const[t,r,s,...i]=e,n=this.prepareAlgorithm(t),a=this.getProvider(n.name);return await a.generateKey({...n,name:a.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),a=pc.toArrayBuffer(s),o=this.getProvider(n.name);return await o.sign({...n,name:o.name},r,a,...i)}async verify(...e){this.checkRequiredArguments(e,4,"verify");const[t,r,s,i,...n]=e;this.checkCryptoKey(r);const a=this.prepareAlgorithm(t),o=pc.toArrayBuffer(i),c=pc.toArrayBuffer(s),l=this.getProvider(a.name);return await l.verify({...a,name:l.name},r,c,o,...n)}async encrypt(...e){this.checkRequiredArguments(e,3,"encrypt");const[t,r,s,...i]=e;this.checkCryptoKey(r);const n=this.prepareAlgorithm(t),a=pc.toArrayBuffer(s),o=this.getProvider(n.name);return await o.encrypt({...n,name:o.name},r,a,{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),a=pc.toArrayBuffer(s),o=this.getProvider(n.name);return await o.decrypt({...n,name:o.name},r,a,{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),a=this.getProvider(n.name);return await a.deriveBits({...n,name:a.name},r,s,{keyUsage:!0},...i)}async deriveKey(...e){this.checkRequiredArguments(e,5,"deriveKey");const[t,r,s,i,n,...a]=e,o=this.prepareAlgorithm(s);this.getProvider(o.name).checkDerivedKeyParams(o);const c=this.prepareAlgorithm(t),l=this.getProvider(c.name);l.checkCryptoKey(r,"deriveKey");const d=await l.deriveBits({...c,name:l.name},r,s.length||512,{keyUsage:!1},...a);return this.importKey("raw",d,s,i,n,...a)}async exportKey(...e){this.checkRequiredArguments(e,2,"exportKey");const[t,r,...s]=e;if(this.checkCryptoKey(r),!Cf[t])throw new TypeError("Invalid keyFormat argument");if(!Cf[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,...a]=e,o=this.prepareAlgorithm(s),c=this.getProvider(o.name);if("jwk"===t){if("object"!=typeof r||!r.kty)throw new TypeError("Key data must be an object for JWK import")}else{if(!kf.includes(t))throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView or JsonWebKey)'");if(!pc.isBufferSource(r))throw new TypeError("Key data must be a BufferSource for non-JWK formats")}return c.importKey(t,r,{...o,name:c.name},i,n,...a)}async wrapKey(e,t,r,s,...i){let n=await this.exportKey(e,t,...i);if("jwk"===e){const e=JSON.stringify(n);n=wc.FromUtf8String(e)}const a=this.prepareAlgorithm(s),o=pc.toArrayBuffer(n),c=this.getProvider(a.name);return c.encrypt({...a,name:c.name},r,o,{keyUsage:!1},...i)}async unwrapKey(e,t,r,s,i,n,a,...o){const c=this.prepareAlgorithm(s),l=pc.toArrayBuffer(t),d=this.getProvider(c.name);let u=await d.decrypt({...c,name:d.name},r,l,{keyUsage:!1},...o);if("jwk"===e)try{u=JSON.parse(wc.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,a,...o)}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(xf.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 sh("Unrecognized name");return t}checkCryptoKey(e){if(!(e instanceof Eh))throw new TypeError("Key is not of type 'CryptoKey'")}}const Bf=t(import.meta.url)("buffer"),_f=t(import.meta.url)("crypto");var Rf=a.n(_f);const Of=t(import.meta.url)("process"),Uf={fromJSON:e=>Bf.Buffer.from(wc.FromBase64Url(e)),toJSON:e=>wc.ToBase64Url(e)};class Tf extends Eh{constructor(){super(...arguments),this.data=Bf.Buffer.alloc(0),this.algorithm={name:""},this.extractable=!1,this.type="secret",this.usages=[],this.kty="oct",this.alg=""}}Du([th({name:"ext",type:Qu.Boolean,optional:!0})],Tf.prototype,"extractable",void 0),Du([th({name:"key_ops",type:Qu.String,repeated:!0,optional:!0})],Tf.prototype,"usages",void 0),Du([th({type:Qu.String})],Tf.prototype,"kty",void 0),Du([th({type:Qu.String,optional:!0})],Tf.prototype,"alg",void 0);class Nf extends Tf{constructor(){super(...arguments),this.kty="oct",this.type="secret"}}class Df extends Tf{}class Mf extends Nf{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 sh("Unsupported algorithm name")}}set alg(e){}}Du([th({name:"k",converter:Uf})],Mf.prototype,"data",void 0);class Pf{static async generateKey(e,t,r){const s=new Mf;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=Rf().randomBytes(e.length>>3),s}static async exportKey(e,t){if(!(t instanceof Mf))throw new Error("key: Is not AesCryptoKey");switch(e.toLowerCase()){case"jwk":return Zu.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new nh("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=eh.fromJSON(t,{targetSchema:Mf});break;case"raw":n=new Mf,n.data=Bf.Buffer.from(t);break;default:throw new nh("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 nh("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,Bf.Buffer.from(r));case"AES-CTR":return this.encryptAesCTR(e,t,Bf.Buffer.from(r));case"AES-GCM":return this.encryptAesGCM(e,t,Bf.Buffer.from(r));case"AES-KW":return this.encryptAesKW(e,t,Bf.Buffer.from(r));case"AES-ECB":return this.encryptAesECB(e,t,Bf.Buffer.from(r));default:throw new nh("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof Mf))throw new Error("key: Is not AesCryptoKey");switch(e.name.toUpperCase()){case"AES-CBC":return this.decryptAesCBC(e,t,Bf.Buffer.from(r));case"AES-CTR":return this.decryptAesCTR(e,t,Bf.Buffer.from(r));case"AES-GCM":return this.decryptAesGCM(e,t,Bf.Buffer.from(r));case"AES-KW":return this.decryptAesKW(e,t,Bf.Buffer.from(r));case"AES-ECB":return this.decryptAesECB(e,t,Bf.Buffer.from(r));default:throw new nh("algorithm: Is not recognized")}}static async encryptAesCBC(e,t,r){const s=Rf().createCipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Bf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCBC(e,t,r){const s=Rf().createDecipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Bf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesCTR(e,t,r){const s=Rf().createCipheriv(`aes-${t.algorithm.length}-ctr`,t.data,Bf.Buffer.from(e.counter));let i=s.update(r);return i=Bf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCTR(e,t,r){const s=Rf().createDecipheriv(`aes-${t.algorithm.length}-ctr`,t.data,new Uint8Array(e.counter));let i=s.update(r);return i=Bf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesGCM(e,t,r){const s=Rf().createCipheriv(`aes-${t.algorithm.length}-gcm`,t.data,Bf.Buffer.from(e.iv),{authTagLength:(e.tagLength||128)>>3});e.additionalData&&s.setAAD(Bf.Buffer.from(e.additionalData));let i=s.update(r);return i=Bf.Buffer.concat([i,s.final(),s.getAuthTag()]),new Uint8Array(i).buffer}static async decryptAesGCM(e,t,r){const s=(e.tagLength||128)>>3,i=Rf().createDecipheriv(`aes-${t.algorithm.length}-gcm`,t.data,new Uint8Array(e.iv),{authTagLength:s}),n=r.slice(0,r.length-s),a=r.slice(r.length-s);e.additionalData&&i.setAAD(Bf.Buffer.from(e.additionalData)),i.setAuthTag(a);let o=i.update(n);return o=Bf.Buffer.concat([o,i.final()]),new Uint8Array(o).buffer}static async encryptAesKW(e,t,r){const s=Rf().createCipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=Bf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesKW(e,t,r){const s=Rf().createDecipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=Bf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesECB(e,t,r){const s=Rf().createCipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=Bf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesECB(e,t,r){const s=Rf().createDecipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=Bf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}Pf.AES_KW_IV=Bf.Buffer.from("A6A6A6A6A6A6A6A6","hex");const Lf=new WeakMap;function Hf(e){const t=Lf.get(e);if(!t)throw new nh("Cannot get CryptoKey from secure storage");return t}function Vf(e){const t=Eh.create(e.algorithm,e.type,e.extractable,e.usages);return Object.freeze(t),Lf.set(t,e),t}class Kf extends dh{async onGenerateKey(e,t,r){return Vf(await Pf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Pf.encrypt(e,Hf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Pf.decrypt(e,Hf(t),new Uint8Array(r))}async onExportKey(e,t){return Pf.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await Pf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Hf(e)instanceof Mf))throw new TypeError("key: Is not a AesCryptoKey")}}const Qf=Bf.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Ff=Bf.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,135]),$f=16;function Gf(e){const t=Bf.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 jf(e,t){const r=Math.min(e.length,t.length),s=Bf.Buffer.alloc(r);for(let i=0;i<r;i++)s[i]=e[i]^t[i];return s}function qf(e,t){const r=Rf().createCipheriv("aes"+(e.length<<3),e,Qf),s=r.update(t);return r.final(),s}function zf(e,t){const r=Bf.Buffer.alloc($f),s=t*$f,i=s+$f;return e.copy(r,0,s,i),r}class Wf extends uh{async onGenerateKey(e,t,r){return Vf(await Pf.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=qf(e,Qf);let r=Gf(t);128&t[0]&&(r=jf(r,Ff));let s=Gf(r);return 128&r[0]&&(s=jf(s,Ff)),{subkey1:r,subkey2:s}}(e);let s,i,n=Math.ceil(t.length/$f);0===n?(n=1,s=!1):s=t.length%$f===0;const a=n-1;i=s?jf(zf(t,a),r.subkey1):jf(function(e,t){const r=Bf.Buffer.alloc($f),s=t*$f,i=e.length;return r.fill(0),e.copy(r,0,s,i),r[i-s]=128,r}(t,a),r.subkey2);let o,c=Qf;for(let r=0;r<a;r++)o=jf(c,zf(t,r)),c=qf(e,o);return o=jf(i,c),qf(e,o)}(Hf(t).data,Bf.Buffer.from(r));return new Uint8Array(s).buffer}async onVerify(e,t,r,s){const i=await this.sign(e,t,s);return 0===Bf.Buffer.from(r).compare(Bf.Buffer.from(i))}async onExportKey(e,t){return Pf.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await Pf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Hf(e)instanceof Mf))throw new TypeError("key: Is not a AesCryptoKey")}}class Jf extends hh{async onGenerateKey(e,t,r){return Vf(await Pf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Pf.encrypt(e,Hf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Pf.decrypt(e,Hf(t),new Uint8Array(r))}async onExportKey(e,t){return Pf.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await Pf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Hf(e)instanceof Mf))throw new TypeError("key: Is not a AesCryptoKey")}}class Yf extends gh{async onGenerateKey(e,t,r){return Vf(await Pf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Pf.encrypt(e,Hf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Pf.decrypt(e,Hf(t),new Uint8Array(r))}async onExportKey(e,t){return Pf.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await Pf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Hf(e)instanceof Mf))throw new TypeError("key: Is not a AesCryptoKey")}}class Xf extends ph{async onGenerateKey(e,t,r){return Vf(await Pf.generateKey({name:this.name,length:e.length},t,r))}async onExportKey(e,t){return Pf.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await Pf.importKey(e,t,{name:r.name},s,i))}async onEncrypt(e,t,r){return Pf.encrypt(e,Hf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Pf.decrypt(e,Hf(t),new Uint8Array(r))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Hf(e)instanceof Mf))throw new TypeError("key: Is not a AesCryptoKey")}}class Zf extends fh{async onGenerateKey(e,t,r){return Vf(await Pf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Pf.encrypt(e,Hf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Pf.decrypt(e,Hf(t),new Uint8Array(r))}async onExportKey(e,t){return Pf.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await Pf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Hf(e)instanceof Mf))throw new TypeError("key: Is not a AesCryptoKey")}}class eg extends Nf{get alg(){switch(this.algorithm.name.toUpperCase()){case"DES-CBC":return"DES-CBC";case"DES-EDE3-CBC":return"3DES-CBC";default:throw new sh("Unsupported algorithm name")}}set alg(e){}}Du([th({name:"k",converter:Uf})],eg.prototype,"data",void 0);class tg{static async generateKey(e,t,r){const s=new eg;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=Rf().randomBytes(e.length>>3),s}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Zu.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new nh("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=eh.fromJSON(t,{targetSchema:eg});break;case"raw":n=new eg,n.data=Bf.Buffer.from(t);break;default:throw new nh("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,Bf.Buffer.from(r));case"DES-EDE3-CBC":return this.encryptDesEDE3CBC(e,t,Bf.Buffer.from(r));default:throw new nh("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof eg))throw new Error("key: Is not DesCryptoKey");switch(e.name.toUpperCase()){case"DES-CBC":return this.decryptDesCBC(e,t,Bf.Buffer.from(r));case"DES-EDE3-CBC":return this.decryptDesEDE3CBC(e,t,Bf.Buffer.from(r));default:throw new nh("algorithm: Is not recognized")}}static async encryptDesCBC(e,t,r){const s=Rf().createCipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Bf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesCBC(e,t,r){const s=Rf().createDecipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Bf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptDesEDE3CBC(e,t,r){const s=Rf().createCipheriv("des-ede3-cbc",t.data,Bf.Buffer.from(e.iv));let i=s.update(r);return i=Bf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesEDE3CBC(e,t,r){const s=Rf().createDecipheriv("des-ede3-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=Bf.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}class rg extends bh{constructor(){super(...arguments),this.keySizeBits=64,this.ivSize=8,this.name="DES-CBC"}async onGenerateKey(e,t,r){return Vf(await tg.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return tg.encrypt(e,Hf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return tg.decrypt(e,Hf(t),new Uint8Array(r))}async onExportKey(e,t){return tg.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){const n=await tg.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new nh("keyData: Wrong key size");return Vf(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Hf(e)instanceof eg))throw new TypeError("key: Is not a DesCryptoKey")}}class sg extends bh{constructor(){super(...arguments),this.keySizeBits=192,this.ivSize=8,this.name="DES-EDE3-CBC"}async onGenerateKey(e,t,r){return Vf(await tg.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return tg.encrypt(e,Hf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return tg.decrypt(e,Hf(t),new Uint8Array(r))}async onExportKey(e,t){return tg.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){const n=await tg.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new nh("keyData: Wrong key size");return Vf(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Hf(e)instanceof eg))throw new TypeError("key: Is not a DesCryptoKey")}}function ig(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 nh("algorithm: Is not recognized")}}class ng extends Df{constructor(){super(...arguments),this.type="private"}getKey(){const e=Ou.parse(this.data,ff.PrivateKeyInfo);return Ou.parse(e.privateKey,ff.RsaPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:ig(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,Zu.toJSON(e))}fromJSON(e){const t=eh.fromJSON(e,{targetSchema:ff.RsaPrivateKey}),r=new ff.PrivateKeyInfo;r.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.privateKeyAlgorithm.parameters=null,r.privateKey=Uu.serialize(t),this.data=Bf.Buffer.from(Uu.serialize(r))}}class ag extends Df{constructor(){super(...arguments),this.type="public"}getKey(){const e=Ou.parse(this.data,ff.PublicKeyInfo);return Ou.parse(e.publicKey,ff.RsaPublicKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:ig(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,Zu.toJSON(e))}fromJSON(e){const t=eh.fromJSON(e,{targetSchema:ff.RsaPublicKey}),r=new ff.PublicKeyInfo;r.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.publicKeyAlgorithm.parameters=null,r.publicKey=Uu.serialize(t),this.data=Bf.Buffer.from(Uu.serialize(r))}}class og{static async generateKey(e,t,r){const s=new ng;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new ag;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=Bf.Buffer.concat([Bf.Buffer.alloc(4-e.publicExponent.byteLength,0),Bf.Buffer.from(e.publicExponent)]).readInt32BE(0),a=Rf().generateKeyPairSync("rsa",{modulusLength:e.modulusLength,publicExponent:n,publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=a.privateKey,i.data=a.publicKey,{privateKey:s,publicKey:i}}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Zu.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;default:throw new nh("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=eh.fromJSON(t,{targetSchema:ff.RsaPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=eh.fromJSON(t,{targetSchema:ff.RsaPublicKey});return this.importPublicKey(e,r,s,i)}case"spki":{const e=Ou.parse(new Uint8Array(t),ff.PublicKeyInfo),n=Ou.parse(e.publicKey,ff.RsaPublicKey);return this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=Ou.parse(new Uint8Array(t),ff.PrivateKeyInfo),n=Ou.parse(e.privateKey,ff.RsaPrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new nh("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 nh("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 nh("algorithm: Is not recognized")}}static async encrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.encryptOAEP(e,t,r);throw new nh("algorithm: Is not recognized")}static async decrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.decryptOAEP(e,t,r);throw new nh("algorithm: Is not recognized")}static importPrivateKey(e,t,r,s){const i=new ff.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.privateKeyAlgorithm.parameters=null,i.privateKey=Uu.serialize(e);const n=new ng;return n.data=Bf.Buffer.from(Uu.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 ff.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.publicKeyAlgorithm.parameters=null,i.publicKey=Uu.serialize(e);const n=new ag;return n.data=Bf.Buffer.from(Uu.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 nh("algorithm.hash: Is not recognized")}}static signRsa(e,t,r){const s=this.getCryptoAlgorithm(t.algorithm),i=Rf().createSign(s);i.update(Bf.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=Rf().constants.RSA_PKCS1_PSS_PADDING,n.saltLength=e.saltLength);const a=i.sign(n);return new Uint8Array(a).buffer}static verifySSA(e,t,r,s){const i=this.getCryptoAlgorithm(t.algorithm),n=Rf().createVerify(i);n.update(Bf.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const a={key:t.pem};return"RSA-PSS"===e.name.toUpperCase()&&(a.padding=Rf().constants.RSA_PKCS1_PSS_PADDING,a.saltLength=e.saltLength),n.verify(a,s)}static encryptOAEP(e,t,r){const s={key:`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`,padding:Rf().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(Rf().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:Rf().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(Rf().privateDecrypt(s,r)).buffer}}og.publicKeyUsages=["verify","encrypt","wrapKey"],og.privateKeyUsages=["sign","decrypt","unwrapKey"];class cg extends yh{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 og.generateKey({...e,name:this.name},t,r);return{privateKey:Vf(s.privateKey),publicKey:Vf(s.publicKey)}}async onSign(e,t,r){return og.sign(e,Hf(t),new Uint8Array(r))}async onVerify(e,t,r,s){return og.verify(e,Hf(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return og.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await og.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Hf(e);if(!(r instanceof ng||r instanceof ag))throw new TypeError("key: Is not RSA CryptoKey")}}class lg extends Ah{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 og.generateKey({...e,name:this.name},t,r);return{privateKey:Vf(s.privateKey),publicKey:Vf(s.publicKey)}}async onSign(e,t,r){return og.sign(e,Hf(t),new Uint8Array(r))}async onVerify(e,t,r,s){return og.verify(e,Hf(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return og.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await og.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Hf(e);if(!(r instanceof ng||r instanceof ag))throw new TypeError("key: Is not RSA CryptoKey")}}class dg{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=Rf().createHash(r).update(Bf.Buffer.from(t)).digest();return new Uint8Array(s).buffer}}class ug extends Ih{async onGenerateKey(e,t,r){const s=await og.generateKey({...e,name:this.name},t,r);return{privateKey:Vf(s.privateKey),publicKey:Vf(s.publicKey)}}async onEncrypt(e,t,r){const s=Hf(t),i=new Uint8Array(r),n=Math.ceil(s.algorithm.modulusLength>>3),a=dg.size(s.algorithm.hash)>>3,o=i.byteLength,c=n-o-2*a-2;if(o>n-2*a-2)throw new Error("Data too large");const l=new Uint8Array(n),d=l.subarray(1,a+1),u=l.subarray(a+1);u.set(i,a+c+1);const h=Rf().createHash(s.algorithm.hash.name.replace("-","")).update(pc.toUint8Array(e.label||new Uint8Array(0))).digest();u.set(h,0),u[a+c]=1,Rf().randomFillSync(d);const f=this.mgf1(s.algorithm.hash,d,u.length);for(let e=0;e<u.length;e++)u[e]^=f[e];const g=this.mgf1(s.algorithm.hash,u,d.length);for(let e=0;e<d.length;e++)d[e]^=g[e];s.pem||(s.pem=`-----BEGIN PUBLIC KEY-----\n${s.data.toString("base64")}\n-----END PUBLIC KEY-----`);const p=Rf().publicEncrypt({key:s.pem,padding:Rf().constants.RSA_NO_PADDING},Bf.Buffer.from(l));return new Uint8Array(p).buffer}async onDecrypt(e,t,r){const s=Hf(t),i=Math.ceil(s.algorithm.modulusLength>>3),n=dg.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 a=Rf().privateDecrypt({key:s.pem,padding:Rf().constants.RSA_NO_PADDING},Bf.Buffer.from(r));const o=a[0],c=a.subarray(1,n+1),l=a.subarray(n+1);if(0!==o)throw new Error("Decryption failed");const d=this.mgf1(s.algorithm.hash,l,c.length);for(let e=0;e<c.length;e++)c[e]^=d[e];const u=this.mgf1(s.algorithm.hash,c,l.length);for(let e=0;e<l.length;e++)l[e]^=u[e];const h=Rf().createHash(s.algorithm.hash.name.replace("-","")).update(pc.toUint8Array(e.label||new Uint8Array(0))).digest();for(let e=0;e<n;e++)if(h[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 a=l.subarray(f+1),new Uint8Array(a).buffer}async onExportKey(e,t){return og.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await og.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Hf(e);if(!(r instanceof ng||r instanceof ag))throw new TypeError("key: Is not RSA CryptoKey")}mgf1(e,t,r=0){const s=dg.size(e)>>3,i=new Uint8Array(r),n=new Uint8Array(4),a=Math.ceil(r/s);for(let r=0;r<a;r++){n[0]=r>>>24,n[1]=r>>>16&255,n[2]=r>>>8&255,n[3]=255&r;const a=i.subarray(r*s);let o=Rf().createHash(e.name.replace("-","")).update(t).update(n).digest();o.length>a.length&&(o=o.subarray(0,a.length)),a.set(o)}return i}}class hg extends ch{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 og.generateKey({...e,name:this.name},t,r);return{privateKey:Vf(s.privateKey),publicKey:Vf(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=wc.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=Rf().publicEncrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onDecrypt(e,t,r){const s=this.toCryptoOptions(t),i=Rf().privateDecrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onExportKey(e,t){return og.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await og.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Hf(e);if(!(r instanceof ng||r instanceof ag))throw new TypeError("key: Is not RSA CryptoKey")}toCryptoOptions(e){const t=e.type.toUpperCase();return{key:`-----BEGIN ${t} KEY-----\n${Hf(e).data.toString("base64")}\n-----END ${t} KEY-----`,padding:Rf().constants.RSA_PKCS1_PADDING}}}const fg={"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 gg(e){const t=fg[e];if(!t)throw new nh(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class pg extends Df{constructor(){super(...arguments),this.type="private"}getKey(){const e=Ou.parse(this.data,ff.PrivateKeyInfo);return Ou.parse(e.privateKey,ff.EcPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,Zu.toJSON(e))}fromJSON(e){if(!e.crv)throw new nh("Cannot get named curve from JWK. Property 'crv' is required");const t=new ff.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",t.privateKeyAlgorithm.parameters=Uu.serialize(new ff.ObjectIdentifier(gg(e.crv)));const r=eh.fromJSON(e,{targetSchema:ff.EcPrivateKey});return t.privateKey=Uu.serialize(r),this.data=Bf.Buffer.from(Uu.serialize(t)),this}}class bg extends Df{constructor(){super(...arguments),this.type="public"}getKey(){const e=Ou.parse(this.data,ff.PublicKeyInfo);return new ff.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,Zu.toJSON(e))}fromJSON(e){if(!e.crv)throw new nh("Cannot get named curve from JWK. Property 'crv' is required");const t=eh.fromJSON(e,{targetSchema:ff.EcPublicKey}),r=new ff.PublicKeyInfo;return r.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1",r.publicKeyAlgorithm.parameters=Uu.serialize(new ff.ObjectIdentifier(gg(e.crv))),r.publicKey=Uu.toASN(t).valueHex,this.data=Bf.Buffer.from(Uu.serialize(r)),this}}class mg extends ch{constructor(){super(...arguments),this.name="SHA-1",this.usages=[]}async onDigest(e,t){return dg.digest(e,t)}}class yg extends ch{constructor(){super(...arguments),this.name="SHA-256",this.usages=[]}async onDigest(e,t){return dg.digest(e,t)}}class Ag extends ch{constructor(){super(...arguments),this.name="SHA-384",this.usages=[]}async onDigest(e,t){return dg.digest(e,t)}}class Ig extends ch{constructor(){super(...arguments),this.name="SHA-512",this.usages=[]}async onDigest(e,t){return dg.digest(e,t)}}class vg extends ch{constructor(){super(...arguments),this.name="SHA3-256",this.usages=[]}async onDigest(e,t){return dg.digest(e,t)}}class wg extends ch{constructor(){super(...arguments),this.name="SHA3-384",this.usages=[]}async onDigest(e,t){return dg.digest(e,t)}}class Sg extends ch{constructor(){super(...arguments),this.name="SHA3-512",this.usages=[]}async onDigest(e,t){return dg.digest(e,t)}}class Eg{static async generateKey(e,t,r){const s=new pg;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new bg;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=Rf().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=dg.getAlgorithmName(e.hash),i=Rf().createSign(s);i.update(Bf.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem},a=i.sign(n),o=Ou.parse(a,ff.EcDsaSignature);return Vh.encodeSignature(o,gf.get(t.algorithm.namedCurve).size).buffer}static async verify(e,t,r,s){const i=dg.getAlgorithmName(e.hash),n=Rf().createVerify(i);n.update(Bf.Buffer.from(s)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const a={key:t.pem},o=new ff.EcDsaSignature,c=gf.get(t.algorithm.namedCurve),l=Vh.decodeSignature(r,c.size);o.r=pc.toArrayBuffer(l.r),o.s=pc.toArrayBuffer(l.s);const d=Bf.Buffer.from(Uu.serialize(o));return n.verify(a,d)}static async deriveBits(e,t,r){const s=this.getOpenSSLNamedCurve(t.algorithm.namedCurve),i=Rf().createECDH(s),n=Ou.parse(t.data,ff.PrivateKeyInfo),a=Ou.parse(n.privateKey,ff.EcPrivateKey);i.setPrivateKey(Bf.Buffer.from(a.privateKey));const o=Ou.parse(e.public.data,ff.PublicKeyInfo),c=i.computeSecret(Bf.Buffer.from(o.publicKey));return null===r?c:new Uint8Array(c).buffer.slice(0,r>>3)}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return Zu.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return Ou.parse(t.data,ff.PublicKeyInfo).publicKey;default:throw new nh("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=eh.fromJSON(t,{targetSchema:ff.EcPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=eh.fromJSON(t,{targetSchema:ff.EcPublicKey});return this.importPublicKey(e,r,s,i)}case"raw":{const e=new ff.EcPublicKey(t);return this.importPublicKey(e,r,s,i)}case"spki":{const e=Ou.parse(new Uint8Array(t),ff.PublicKeyInfo),n=new ff.EcPublicKey(e.publicKey);return this.assertKeyParameters(e.publicKeyAlgorithm.parameters,r.namedCurve),this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=Ou.parse(new Uint8Array(t),ff.PrivateKeyInfo),n=Ou.parse(e.privateKey,ff.EcPrivateKey);return this.assertKeyParameters(e.privateKeyAlgorithm.parameters,r.namedCurve),this.importPrivateKey(n,r,s,i)}default:throw new nh("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static assertKeyParameters(e,t){if(!e)throw new rh("Key info doesn't have required parameters");let r="";try{r=Ou.parse(e,ff.ObjectIdentifier).value}catch(e){throw new rh("Cannot read key info parameters")}if(gg(t)!==r)throw new rh("Key info parameter doesn't match to named curve")}static async importPrivateKey(e,t,r,s){const i=new ff.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",i.privateKeyAlgorithm.parameters=Uu.serialize(new ff.ObjectIdentifier(gg(t.namedCurve))),i.privateKey=Uu.serialize(e);const n=new pg;return n.data=Bf.Buffer.from(Uu.serialize(i)),n.algorithm=Object.assign({},t),n.extractable=r,n.usages=s,n}static async importPublicKey(e,t,r,s){const i=new ff.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1";const n=gg(t.namedCurve);i.publicKeyAlgorithm.parameters=Uu.serialize(new ff.ObjectIdentifier(n)),i.publicKey=e.value;const a=new bg;return a.data=Bf.Buffer.from(Uu.serialize(i)),a.algorithm=Object.assign({},t),a.extractable=r,a.usages=s,a}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}}}Eg.publicKeyUsages=["verify"],Eg.privateKeyUsages=["sign","deriveKey","deriveBits"];class Cg extends wh{constructor(){super(...arguments),this.namedCurves=gf.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 Eg.generateKey({...e,name:this.name},t,r);return{privateKey:Vf(s.privateKey),publicKey:Vf(s.publicKey)}}async onSign(e,t,r){return Eg.sign(e,Hf(t),new Uint8Array(r))}async onVerify(e,t,r,s){return Eg.verify(e,Hf(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return Eg.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await Eg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Hf(e);if(!(r instanceof pg||r instanceof bg))throw new TypeError("key: Is not EC CryptoKey")}}class kg extends Ch{constructor(){super(...arguments),this.namedCurves=gf.names}async onGenerateKey(e,t,r){const s=await Eg.generateKey({...e,name:this.name},t,r);return{privateKey:Vf(s.privateKey),publicKey:Vf(s.publicKey)}}async onExportKey(e,t){return Eg.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await Eg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Hf(e);if(!(r instanceof pg||r instanceof bg))throw new TypeError("key: Is not EC CryptoKey")}async onDeriveBits(e,t,r){return await Eg.deriveBits({...e,public:Hf(e.public)},Hf(t),r)}}const xg={[ff.idEd448]:"Ed448",ed448:ff.idEd448,[ff.idX448]:"X448",x448:ff.idX448,[ff.idEd25519]:"Ed25519",ed25519:ff.idEd25519,[ff.idX25519]:"X25519",x25519:ff.idX25519};function Bg(e){const t=xg[e.toLowerCase()];if(!t)throw new nh(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class _g extends Df{constructor(){super(...arguments),this.type="private"}getKey(){const e=Ou.parse(this.data,ff.PrivateKeyInfo);return Ou.parse(e.privateKey,ff.CurvePrivateKey)}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,Zu.toJSON(e))}fromJSON(e){if(!e.crv)throw new nh("Cannot get named curve from JWK. Property 'crv' is required");const t=new ff.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm=Bg(e.crv);const r=eh.fromJSON(e,{targetSchema:ff.CurvePrivateKey});return t.privateKey=Uu.serialize(r),this.data=Bf.Buffer.from(Uu.serialize(t)),this}}class Rg extends Df{constructor(){super(...arguments),this.type="public"}getKey(){return Ou.parse(this.data,ff.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:wc.ToBase64Url(e)})}fromJSON(e){if(!e.crv)throw new nh("Cannot get named curve from JWK. Property 'crv' is required");if(!e.x)throw new nh("Cannot get property from JWK. Property 'x' is required");const t=new ff.PublicKeyInfo;return t.publicKeyAlgorithm.algorithm=Bg(e.crv),t.publicKey=wc.FromBase64Url(e.x),this.data=Bf.Buffer.from(Uu.serialize(t)),this}}class Og{static async generateKey(e,t,r){const s=new _g;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new Rg;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=e.namedCurve.toLowerCase(),a=Rf().generateKeyPairSync(n,{publicKeyEncoding:{format:"der",type:"spki"},privateKeyEncoding:{format:"der",type:"pkcs8"}});return s.data=a.privateKey,i.data=a.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=Rf().sign(null,Bf.Buffer.from(r),s);return pc.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 Rf().verify(null,Bf.Buffer.from(s),i,Bf.Buffer.from(r))}static async deriveBits(e,t,r){const s=Rf().createPublicKey({key:e.public.data,format:"der",type:"spki"}),i=Rf().createPrivateKey({key:t.data,format:"der",type:"pkcs8"}),n=Rf().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 Zu.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return Ou.parse(t.data,ff.PublicKeyInfo).publicKey;default:throw new nh("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=eh.fromJSON(t,{targetSchema:ff.CurvePrivateKey});return this.importPrivateKey(e,r,s,i)}if(!e.x)throw new TypeError("keyData: Cannot get required 'x' filed");return this.importPublicKey(wc.FromBase64Url(e.x),r,s,i)}case"raw":return this.importPublicKey(t,r,s,i);case"spki":{const e=Ou.parse(new Uint8Array(t),ff.PublicKeyInfo);return this.importPublicKey(e.publicKey,r,s,i)}case"pkcs8":{const e=Ou.parse(new Uint8Array(t),ff.PrivateKeyInfo),n=Ou.parse(e.privateKey,ff.CurvePrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new nh("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static importPrivateKey(e,t,r,s){const i=new _g;return i.fromJSON({crv:t.namedCurve,d:wc.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 Rg;return i.fromJSON({crv:t.namedCurve,x:wc.ToBase64Url(e)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}}Og.publicKeyUsages=["verify"],Og.privateKeyUsages=["sign","deriveKey","deriveBits"];class Ug extends xh{async onGenerateKey(e,t,r){const s=await Og.generateKey({name:this.name,namedCurve:e.namedCurve.replace(/^ed/i,"Ed")},t,r);return{privateKey:Vf(s.privateKey),publicKey:Vf(s.publicKey)}}async onSign(e,t,r){return Og.sign(e,Hf(t),new Uint8Array(r))}async onVerify(e,t,r,s){return Og.verify(e,Hf(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return Og.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await Og.importKey(e,t,{...r,name:this.name},s,i))}}class Tg extends kh{async onGenerateKey(e,t,r){const s=await Og.generateKey({name:this.name,namedCurve:e.namedCurve.toUpperCase()},t,r);return{privateKey:Vf(s.privateKey),publicKey:Vf(s.publicKey)}}async onDeriveBits(e,t,r){return await Og.deriveBits({...e,public:Hf(e.public)},Hf(t),r)}async onExportKey(e,t){return Og.exportKey(e,Hf(t))}async onImportKey(e,t,r,s,i){return Vf(await Og.importKey(e,t,{...r,name:this.name},s,i))}}class Ng extends Tf{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 Dg extends Ng{constructor(){super(...arguments),this.type="private"}toJWK(){const e=Rf().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"}),t=oh.toUint8Array(this.data.toString()),r=Nu.parse(t,ff.PrivateKeyInfo),s=Nu.parse(r.privateKey,ff.EdPrivateKey).value;return{...super.toJWK(),...e,d:Buffer.from(new Uint8Array(s)).toString("base64url")}}}class Mg extends Ng{constructor(){super(...arguments),this.type="public"}toJWK(){const e=Rf().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"});return{...super.toJWK(),...e}}}class Pg{static async generateKey(e,t,r){const s=e.name.toLowerCase(),i=Rf().generateKeyPairSync(s,{publicKeyEncoding:{format:"pem",type:"spki"},privateKeyEncoding:{format:"pem",type:"pkcs8"}}),n={name:"ed25519"===s?"Ed25519":"X25519"},a=r.filter(e=>this.privateKeyUsages.includes(e)),o=r.filter(e=>this.publicKeyUsages.includes(e));return{privateKey:new Dg(n,t,a,i.privateKey),publicKey:new Mg(n,!0,o,i.publicKey)}}static async sign(e,t,r){const s=Rf().sign(null,Buffer.from(r),t.data);return pc.toArrayBuffer(s)}static async verify(e,t,r,s){return Rf().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 oh.toArrayBuffer(t.data.toString());case"raw":{const e=t.toJWK();return wc.FromBase64Url(e.x)}default:return Promise.reject(new nh("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 ff.EdPrivateKey;t.value=pc.toArrayBuffer(Buffer.from(e.d,"base64url"));const n=new ff.PrivateKeyInfo;n.privateKeyAlgorithm.algorithm="ed25519"===r.name.toLowerCase()?ff.idEd25519:ff.idX25519,n.privateKey=Nu.serialize(t);const a=Nu.serialize(n),o=oh.fromBufferSource(a,"PRIVATE KEY");return new Dg(r,s,i,o)}if(e.x){const t=Rf().createPublicKey({format:"jwk",key:e}).export({format:"pem",type:"spki"});return new Mg(r,s,i,t)}throw new nh("keyData: Cannot import JWK. 'd' or 'x' must be presented")}case"pkcs8":{const e=oh.fromBufferSource(t,"PRIVATE KEY");return new Dg(r,s,i,e)}case"spki":{const e=oh.fromBufferSource(t,"PUBLIC KEY");return new Mg(r,s,i,e)}case"raw":{const e=t,n=Rf().createPublicKey({format:"jwk",key:{kty:"OKP",crv:"ed25519"===r.name.toLowerCase()?"Ed25519":"X25519",x:wc.ToBase64Url(e)}}).export({format:"pem",type:"spki"});return new Mg(r,s,i,n)}default:return Promise.reject(new nh("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}}Pg.privateKeyUsages=["sign","deriveBits","deriveKey"],Pg.publicKeyUsages=["verify"];class Lg extends bf{async onGenerateKey(e,t,r){const s=await Pg.generateKey(e,t,r);return{privateKey:Vf(s.privateKey),publicKey:Vf(s.publicKey)}}async onSign(e,t,r){const s=Hf(t);return Pg.sign(e,s,new Uint8Array(r))}onVerify(e,t,r,s){const i=Hf(t);return Pg.verify(e,i,new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){const r=Hf(t);return Pg.exportKey(e,r)}async onImportKey(e,t,r,s,i){return Vf(await Pg.importKey(e,t,r,s,i))}}class Hg extends pf{async onGenerateKey(e,t,r){const s=await Pg.generateKey(e,t,r);return{privateKey:Vf(s.privateKey),publicKey:Vf(s.publicKey)}}async onDeriveBits(e,t,r){const s=Hf(t),i=Hf(e.public),n=Rf().createPublicKey({key:i.data.toString(),format:"pem",type:"spki"}),a=Rf().createPrivateKey({key:s.data.toString(),format:"pem",type:"pkcs8"}),o=Rf().diffieHellman({publicKey:n,privateKey:a});return new Uint8Array(o).buffer.slice(0,r>>3)}async onExportKey(e,t){const r=Hf(t);return Pg.exportKey(e,r)}async onImportKey(e,t,r,s,i){return Vf(await Pg.importKey(e,t,r,s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Hf(e)instanceof Ng))throw new TypeError("key: Is not a Ed25519CryptoKey")}}class Vg extends Tf{}class Kg extends yf{async onDeriveBits(e,t,r){return new Promise((s,i)=>{const n=pc.toArrayBuffer(e.salt),a=e.hash.name.replace("-","");Rf().pbkdf2(Hf(t).data,Bf.Buffer.from(n),e.iterations,r>>3,a,(e,t)=>{e?i(e):s(new Uint8Array(t).buffer)})})}async onImportKey(e,t,r,s,i){if("raw"===e){const e=new Vg;return e.data=Bf.Buffer.from(t),e.algorithm={name:this.name},e.extractable=!1,e.usages=i,Vf(e)}throw new nh("format: Must be 'raw'")}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Hf(e)instanceof Vg))throw new TypeError("key: Is not PBKDF CryptoKey")}}class Qg extends Tf{get alg(){return`HS${this.algorithm.hash.name.toUpperCase().replace("SHA-","")}`}set alg(e){}}Du([th({name:"k",converter:Uf})],Qg.prototype,"data",void 0);class Fg extends mf{async onGenerateKey(e,t,r){const s=(e.length||this.getDefaultLength(e.hash.name))>>3<<3,i=new Qg;return i.algorithm={...e,length:s,name:this.name},i.extractable=t,i.usages=r,i.data=Rf().randomBytes(s>>3),Vf(i)}async onSign(e,t,r){const s=dg.getAlgorithmName(t.algorithm.hash),i=Rf().createHmac(s,Hf(t).data).update(Bf.Buffer.from(r)).digest();return new Uint8Array(i).buffer}async onVerify(e,t,r,s){const i=dg.getAlgorithmName(t.algorithm.hash);return 0===Rf().createHmac(i,Hf(t).data).update(Bf.Buffer.from(s)).digest().compare(Bf.Buffer.from(r))}async onImportKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=eh.fromJSON(t,{targetSchema:Qg});break;case"raw":n=new Qg,n.data=Bf.Buffer.from(t);break;default:throw new nh("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,Vf(n)}async onExportKey(e,t){switch(e.toLowerCase()){case"jwk":return Zu.toJSON(Hf(t));case"raw":return new Uint8Array(Hf(t).data).buffer;default:throw new nh("format: Must be 'jwk' or 'raw'")}}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Hf(e)instanceof Qg))throw new TypeError("key: Is not HMAC CryptoKey")}}class $g extends Tf{}class Gg extends Af{async onImportKey(e,t,r,s,i){if("raw"!==e.toLowerCase())throw new nh("Operation not supported");const n=new $g;return n.data=Bf.Buffer.from(t),n.algorithm={name:this.name},n.extractable=s,n.usages=i,Vf(n)}async onDeriveBits(e,t,r){const s=e.hash.name.replace("-",""),i=Rf().createHash(s).digest().length,n=r/8,a=pc.toUint8Array(e.info),o=Rf().createHmac(s,pc.toUint8Array(e.salt)).update(pc.toUint8Array(Hf(t).data)).digest(),c=[Bf.Buffer.alloc(0)],l=Math.ceil(n/i)+1;for(let e=1;e<l;++e)c.push(Rf().createHmac(s,o).update(Bf.Buffer.concat([c[e-1],a,Bf.Buffer.from([e])])).digest());return Bf.Buffer.concat(c).slice(0,n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Hf(e)instanceof $g))throw new TypeError("key: Is not HKDF CryptoKey")}}class jg{static digest(e,t){const r=Rf().createHash(e.name.toLowerCase(),{outputLength:e.length}).update(Bf.Buffer.from(t)).digest();return new Uint8Array(r).buffer}}class qg extends vf{async onDigest(e,t){return jg.digest(e,t)}}class zg extends wf{async onDigest(e,t){return jg.digest(e,t)}}class Wg extends xf{constructor(){var e;super(),this.providers.set(new Kf),this.providers.set(new Jf),this.providers.set(new Yf),this.providers.set(new Wf),this.providers.set(new Xf),this.providers.set(new Zf),Rf().getCiphers().includes("des-cbc")&&this.providers.set(new rg),this.providers.set(new sg),this.providers.set(new cg),this.providers.set(new lg),this.providers.set(new ug),this.providers.set(new hg),this.providers.set(new Cg),this.providers.set(new kg),this.providers.set(new mg),this.providers.set(new yg),this.providers.set(new Ag),this.providers.set(new Ig),this.providers.set(new Kg),this.providers.set(new Fg),this.providers.set(new Gg);const t=null===(e=/^v(\d+)/.exec(Of.version))||void 0===e?void 0:e[1];t&&parseInt(t,10)>=12&&(this.providers.set(new qg),this.providers.set(new zg));const r=Rf().getHashes();r.includes("sha3-256")&&this.providers.set(new vg),r.includes("sha3-384")&&this.providers.set(new wg),r.includes("sha3-512")&&this.providers.set(new Sg),t&&parseInt(t,10)>=14&&(this.providers.set(new Ug),this.providers.set(new Tg),this.providers.set(new Lg),this.providers.set(new Hg))}}var Jg,Yg,Xg;a(909);class Zg{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(wc.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 ep=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};Du([_u({type:Ql.TeletexString})],ep.prototype,"teletexString",void 0),Du([_u({type:Ql.PrintableString})],ep.prototype,"printableString",void 0),Du([_u({type:Ql.UniversalString})],ep.prototype,"universalString",void 0),Du([_u({type:Ql.Utf8String})],ep.prototype,"utf8String",void 0),Du([_u({type:Ql.BmpString})],ep.prototype,"bmpString",void 0),ep=Du([Bu({type:Kl.Choice})],ep);let tp=class extends ep{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?wc.ToHex(this.anyValue):super.toString())}};Du([_u({type:Ql.IA5String})],tp.prototype,"ia5String",void 0),Du([_u({type:Ql.Any})],tp.prototype,"anyValue",void 0),tp=Du([Bu({type:Kl.Choice})],tp);class rp{constructor(e={}){this.type="",this.value=new tp,Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],rp.prototype,"type",void 0),Du([_u({type:tp})],rp.prototype,"value",void 0);let sp=Jg=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,Jg.prototype)}};sp=Jg=Du([Bu({type:Kl.Set,itemType:rp})],sp);let ip=Yg=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,Yg.prototype)}};ip=Yg=Du([Bu({type:Kl.Sequence,itemType:sp})],ip);let np=Xg=class extends ip{constructor(e){super(e),Object.setPrototypeOf(this,Xg.prototype)}};np=Xg=Du([Bu({type:Kl.Sequence})],np);const ap={fromASN:e=>Zg.toString(nu.fromASN(e)),toASN:e=>nu.toASN(Zg.fromString(e))};class op{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],op.prototype,"typeId",void 0),Du([_u({type:Ql.Any,context:0})],op.prototype,"value",void 0);class cp{constructor(e={}){this.partyName=new ep,Object.assign(this,e)}}Du([_u({type:ep,optional:!0,context:0,implicit:!0})],cp.prototype,"nameAssigner",void 0),Du([_u({type:ep,context:1,implicit:!0})],cp.prototype,"partyName",void 0);let lp=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:op,context:0,implicit:!0})],lp.prototype,"otherName",void 0),Du([_u({type:Ql.IA5String,context:1,implicit:!0})],lp.prototype,"rfc822Name",void 0),Du([_u({type:Ql.IA5String,context:2,implicit:!0})],lp.prototype,"dNSName",void 0),Du([_u({type:Ql.Any,context:3,implicit:!0})],lp.prototype,"x400Address",void 0),Du([_u({type:np,context:4,implicit:!1})],lp.prototype,"directoryName",void 0),Du([_u({type:cp,context:5})],lp.prototype,"ediPartyName",void 0),Du([_u({type:Ql.IA5String,context:6,implicit:!0})],lp.prototype,"uniformResourceIdentifier",void 0),Du([_u({type:Ql.OctetString,context:7,implicit:!0,converter:ap})],lp.prototype,"iPAddress",void 0),Du([_u({type:Ql.ObjectIdentifier,context:8,implicit:!0})],lp.prototype,"registeredID",void 0),lp=Du([Bu({type:Kl.Choice})],lp);const dp="1.3.6.1.5.5.7",up=`${dp}.3`,hp=`${dp}.48`,fp=`${hp}.1`,gp=`${hp}.2`,pp=`${hp}.3`,bp=`${hp}.5`,mp="2.5.29";var yp;const Ap=`${dp}.1.1`;class Ip{constructor(e={}){this.accessMethod="",this.accessLocation=new lp,Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],Ip.prototype,"accessMethod",void 0),Du([_u({type:lp})],Ip.prototype,"accessLocation",void 0);let vp=yp=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,yp.prototype)}};vp=yp=Du([Bu({type:Kl.Sequence,itemType:Ip})],vp);const wp=`${mp}.35`;class Sp extends Yd{}class Ep{constructor(e={}){e&&Object.assign(this,e)}}Du([_u({type:Sp,context:0,optional:!0,implicit:!0})],Ep.prototype,"keyIdentifier",void 0),Du([_u({type:lp,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Ep.prototype,"authorityCertIssuer",void 0),Du([_u({type:Ql.Integer,context:2,optional:!0,implicit:!0,converter:tu})],Ep.prototype,"authorityCertSerialNumber",void 0);const Cp=`${mp}.19`;class kp{constructor(e={}){this.cA=!1,Object.assign(this,e)}}var xp;Du([_u({type:Ql.Boolean,defaultValue:!1})],kp.prototype,"cA",void 0),Du([_u({type:Ql.Integer,optional:!0})],kp.prototype,"pathLenConstraint",void 0);let Bp=xp=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,xp.prototype)}};var _p;Bp=xp=Du([Bu({type:Kl.Sequence,itemType:lp})],Bp);let Rp=_p=class extends Bp{constructor(e){super(e),Object.setPrototypeOf(this,_p.prototype)}};var Op;Rp=_p=Du([Bu({type:Kl.Sequence})],Rp);const Up=`${mp}.32`;let Tp=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};Du([_u({type:Ql.IA5String})],Tp.prototype,"ia5String",void 0),Du([_u({type:Ql.VisibleString})],Tp.prototype,"visibleString",void 0),Du([_u({type:Ql.BmpString})],Tp.prototype,"bmpString",void 0),Du([_u({type:Ql.Utf8String})],Tp.prototype,"utf8String",void 0),Tp=Du([Bu({type:Kl.Choice})],Tp);class Np{constructor(e={}){this.organization=new Tp,this.noticeNumbers=[],Object.assign(this,e)}}Du([_u({type:Tp})],Np.prototype,"organization",void 0),Du([_u({type:Ql.Integer,repeated:"sequence"})],Np.prototype,"noticeNumbers",void 0);class Dp{constructor(e={}){Object.assign(this,e)}}Du([_u({type:Np,optional:!0})],Dp.prototype,"noticeRef",void 0),Du([_u({type:Tp,optional:!0})],Dp.prototype,"explicitText",void 0);let Mp=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:Ql.IA5String})],Mp.prototype,"cPSuri",void 0),Du([_u({type:Dp})],Mp.prototype,"userNotice",void 0),Mp=Du([Bu({type:Kl.Choice})],Mp);class Pp{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],Pp.prototype,"policyQualifierId",void 0),Du([_u({type:Ql.Any})],Pp.prototype,"qualifier",void 0);class Lp{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],Lp.prototype,"policyIdentifier",void 0),Du([_u({type:Pp,repeated:"sequence",optional:!0})],Lp.prototype,"policyQualifiers",void 0);let Hp=Op=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,Op.prototype)}};Hp=Op=Du([Bu({type:Kl.Sequence,itemType:Lp})],Hp);let Vp=class{constructor(e=0){this.value=e}};Du([_u({type:Ql.Integer})],Vp.prototype,"value",void 0),Vp=Du([Bu({type:Kl.Choice})],Vp);let Kp=class extends Vp{};var Qp;Kp=Du([Bu({type:Kl.Choice})],Kp);const Fp=`${mp}.31`;var $p;!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"}($p||($p={}));class Gp extends Jd{toJSON(){const e=[],t=this.toNumber();return t&$p.aACompromise&&e.push("aACompromise"),t&$p.affiliationChanged&&e.push("affiliationChanged"),t&$p.cACompromise&&e.push("cACompromise"),t&$p.certificateHold&&e.push("certificateHold"),t&$p.cessationOfOperation&&e.push("cessationOfOperation"),t&$p.keyCompromise&&e.push("keyCompromise"),t&$p.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&$p.superseded&&e.push("superseded"),t&$p.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let jp=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:lp,context:0,repeated:"sequence",implicit:!0})],jp.prototype,"fullName",void 0),Du([_u({type:sp,context:1,implicit:!0})],jp.prototype,"nameRelativeToCRLIssuer",void 0),jp=Du([Bu({type:Kl.Choice})],jp);class qp{constructor(e={}){Object.assign(this,e)}}Du([_u({type:jp,context:0,optional:!0})],qp.prototype,"distributionPoint",void 0),Du([_u({type:Gp,context:1,optional:!0,implicit:!0})],qp.prototype,"reasons",void 0),Du([_u({type:lp,context:2,optional:!0,repeated:"sequence",implicit:!0})],qp.prototype,"cRLIssuer",void 0);let zp=Qp=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,Qp.prototype)}};var Wp;zp=Qp=Du([Bu({type:Kl.Sequence,itemType:qp})],zp);let Jp=Wp=class extends zp{constructor(e){super(e),Object.setPrototypeOf(this,Wp.prototype)}};Jp=Wp=Du([Bu({type:Kl.Sequence,itemType:qp})],Jp);class Yp{constructor(e={}){this.onlyContainsUserCerts=Yp.ONLY,this.onlyContainsCACerts=Yp.ONLY,this.indirectCRL=Yp.ONLY,this.onlyContainsAttributeCerts=Yp.ONLY,Object.assign(this,e)}}var Xp;Yp.ONLY=!1,Du([_u({type:jp,context:0,optional:!0})],Yp.prototype,"distributionPoint",void 0),Du([_u({type:Ql.Boolean,context:1,defaultValue:Yp.ONLY,implicit:!0})],Yp.prototype,"onlyContainsUserCerts",void 0),Du([_u({type:Ql.Boolean,context:2,defaultValue:Yp.ONLY,implicit:!0})],Yp.prototype,"onlyContainsCACerts",void 0),Du([_u({type:Gp,context:3,optional:!0,implicit:!0})],Yp.prototype,"onlySomeReasons",void 0),Du([_u({type:Ql.Boolean,context:4,defaultValue:Yp.ONLY,implicit:!0})],Yp.prototype,"indirectCRL",void 0),Du([_u({type:Ql.Boolean,context:5,defaultValue:Yp.ONLY,implicit:!0})],Yp.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"}(Xp||(Xp={}));let Zp=class{constructor(e=Xp.unspecified){this.reason=Xp.unspecified,this.reason=e}toJSON(){return Xp[this.reason]}toString(){return this.toJSON()}};var eb;Du([_u({type:Ql.Enumerated})],Zp.prototype,"reason",void 0),Zp=Du([Bu({type:Kl.Choice})],Zp);const tb=`${mp}.37`;let rb=eb=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,eb.prototype)}};rb=eb=Du([Bu({type:Kl.Sequence,itemType:Ql.ObjectIdentifier})],rb);const sb=`${up}.1`,ib=`${up}.2`,nb=`${up}.3`,ab=`${up}.4`,ob=`${up}.8`,cb=`${up}.9`;let lb=class{constructor(e=new ArrayBuffer(0)){this.value=e}};Du([_u({type:Ql.Integer,converter:tu})],lb.prototype,"value",void 0),lb=Du([Bu({type:Kl.Choice})],lb);let db=class{constructor(e){this.value=new Date,e&&(this.value=e)}};var ub;Du([_u({type:Ql.GeneralizedTime})],db.prototype,"value",void 0),db=Du([Bu({type:Kl.Choice})],db);let hb=ub=class extends Bp{constructor(e){super(e),Object.setPrototypeOf(this,ub.prototype)}};hb=ub=Du([Bu({type:Kl.Sequence})],hb);const fb=`${mp}.15`;var gb,pb;!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"}(gb||(gb={}));class bb extends Jd{toJSON(){const e=this.toNumber(),t=[];return e&gb.cRLSign&&t.push("crlSign"),e&gb.dataEncipherment&&t.push("dataEncipherment"),e&gb.decipherOnly&&t.push("decipherOnly"),e&gb.digitalSignature&&t.push("digitalSignature"),e&gb.encipherOnly&&t.push("encipherOnly"),e&gb.keyAgreement&&t.push("keyAgreement"),e&gb.keyCertSign&&t.push("keyCertSign"),e&gb.keyEncipherment&&t.push("keyEncipherment"),e&gb.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}}class mb{constructor(e={}){this.base=new lp,this.minimum=0,Object.assign(this,e)}}Du([_u({type:lp})],mb.prototype,"base",void 0),Du([_u({type:Ql.Integer,context:0,defaultValue:0,implicit:!0})],mb.prototype,"minimum",void 0),Du([_u({type:Ql.Integer,context:1,optional:!0,implicit:!0})],mb.prototype,"maximum",void 0);let yb=pb=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,pb.prototype)}};yb=pb=Du([Bu({type:Kl.Sequence,itemType:mb})],yb);class Ab{constructor(e={}){Object.assign(this,e)}}Du([_u({type:yb,context:0,optional:!0,implicit:!0})],Ab.prototype,"permittedSubtrees",void 0),Du([_u({type:yb,context:1,optional:!0,implicit:!0})],Ab.prototype,"excludedSubtrees",void 0);class Ib{constructor(e={}){Object.assign(this,e)}}var vb;Du([_u({type:Ql.Integer,context:0,implicit:!0,optional:!0,converter:tu})],Ib.prototype,"requireExplicitPolicy",void 0),Du([_u({type:Ql.Integer,context:1,implicit:!0,optional:!0,converter:tu})],Ib.prototype,"inhibitPolicyMapping",void 0);class wb{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],wb.prototype,"issuerDomainPolicy",void 0),Du([_u({type:Ql.ObjectIdentifier})],wb.prototype,"subjectDomainPolicy",void 0);let Sb=vb=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,vb.prototype)}};var Eb;Sb=vb=Du([Bu({type:Kl.Sequence,itemType:wb})],Sb);const Cb=`${mp}.17`;let kb=Eb=class extends Bp{constructor(e){super(e),Object.setPrototypeOf(this,Eb.prototype)}};kb=Eb=Du([Bu({type:Kl.Sequence})],kb);class xb{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}}var Bb;Du([_u({type:Ql.ObjectIdentifier})],xb.prototype,"type",void 0),Du([_u({type:Ql.Any,repeated:"set"})],xb.prototype,"values",void 0);let _b=Bb=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,Bb.prototype)}};_b=Bb=Du([Bu({type:Kl.Sequence,itemType:xb})],_b);const Rb=`${mp}.14`;class Ob extends Sp{}class Ub{constructor(e={}){Object.assign(this,e)}}var Tb,Nb;Du([_u({type:Ql.GeneralizedTime,context:0,implicit:!0,optional:!0})],Ub.prototype,"notBefore",void 0),Du([_u({type:Ql.GeneralizedTime,context:1,implicit:!0,optional:!0})],Ub.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(Tb||(Tb={}));class Db extends Jd{toJSON(){const e=[],t=this.toNumber();return t&Tb.pKIXCertificate&&e.push("pKIXCertificate"),t&Tb.newExtensions&&e.push("newExtensions"),t&Tb.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class Mb{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new Db,Object.assign(this,e)}}Du([_u({type:Ql.GeneralString})],Mb.prototype,"entrustVers",void 0),Du([_u({type:Db})],Mb.prototype,"entrustInfoFlags",void 0);let Pb=Nb=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,Nb.prototype)}};Pb=Nb=Du([Bu({type:Kl.Sequence,itemType:Ip})],Pb);class Lb{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof Lb&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Ec(e.parameters,this.parameters)||e.parameters===this.parameters)}}Du([_u({type:Ql.ObjectIdentifier})],Lb.prototype,"algorithm",void 0),Du([_u({type:Ql.Any,optional:!0})],Lb.prototype,"parameters",void 0);class Hb{constructor(e={}){this.algorithm=new Lb,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Lb})],Hb.prototype,"algorithm",void 0),Du([_u({type:Ql.BitString})],Hb.prototype,"subjectPublicKey",void 0);let Vb=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}};Du([_u({type:Ql.UTCTime})],Vb.prototype,"utcTime",void 0),Du([_u({type:Ql.GeneralizedTime})],Vb.prototype,"generalTime",void 0),Vb=Du([Bu({type:Kl.Choice})],Vb);class Kb{constructor(e){this.notBefore=new Vb(new Date),this.notAfter=new Vb(new Date),e&&(this.notBefore=new Vb(e.notBefore),this.notAfter=new Vb(e.notAfter))}}var Qb;Du([_u({type:Vb})],Kb.prototype,"notBefore",void 0),Du([_u({type:Vb})],Kb.prototype,"notAfter",void 0);class Fb{constructor(e={}){this.extnID="",this.critical=Fb.CRITICAL,this.extnValue=new Yd,Object.assign(this,e)}}Fb.CRITICAL=!1,Du([_u({type:Ql.ObjectIdentifier})],Fb.prototype,"extnID",void 0),Du([_u({type:Ql.Boolean,defaultValue:Fb.CRITICAL})],Fb.prototype,"critical",void 0),Du([_u({type:Yd})],Fb.prototype,"extnValue",void 0);let $b=Qb=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,Qb.prototype)}};var Gb;$b=Qb=Du([Bu({type:Kl.Sequence,itemType:Fb})],$b),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(Gb||(Gb={}));class jb{constructor(e={}){this.version=Gb.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new Lb,this.issuer=new np,this.validity=new Kb,this.subject=new np,this.subjectPublicKeyInfo=new Hb,Object.assign(this,e)}}Du([_u({type:Ql.Integer,context:0,defaultValue:Gb.v1})],jb.prototype,"version",void 0),Du([_u({type:Ql.Integer,converter:tu})],jb.prototype,"serialNumber",void 0),Du([_u({type:Lb})],jb.prototype,"signature",void 0),Du([_u({type:np})],jb.prototype,"issuer",void 0),Du([_u({type:Kb})],jb.prototype,"validity",void 0),Du([_u({type:np})],jb.prototype,"subject",void 0),Du([_u({type:Hb})],jb.prototype,"subjectPublicKeyInfo",void 0),Du([_u({type:Ql.BitString,context:1,implicit:!0,optional:!0})],jb.prototype,"issuerUniqueID",void 0),Du([_u({type:Ql.BitString,context:2,implicit:!0,optional:!0})],jb.prototype,"subjectUniqueID",void 0),Du([_u({type:$b,context:3,optional:!0})],jb.prototype,"extensions",void 0);class qb{constructor(e={}){this.tbsCertificate=new jb,this.signatureAlgorithm=new Lb,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:jb})],qb.prototype,"tbsCertificate",void 0),Du([_u({type:Lb})],qb.prototype,"signatureAlgorithm",void 0),Du([_u({type:Ql.BitString})],qb.prototype,"signatureValue",void 0);class zb{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new Vb,Object.assign(this,e)}}Du([_u({type:Ql.Integer,converter:tu})],zb.prototype,"userCertificate",void 0),Du([_u({type:Vb})],zb.prototype,"revocationDate",void 0),Du([_u({type:Fb,optional:!0,repeated:"sequence"})],zb.prototype,"crlEntryExtensions",void 0);class Wb{constructor(e={}){this.signature=new Lb,this.issuer=new np,this.thisUpdate=new Vb,Object.assign(this,e)}}Du([_u({type:Ql.Integer,optional:!0})],Wb.prototype,"version",void 0),Du([_u({type:Lb})],Wb.prototype,"signature",void 0),Du([_u({type:np})],Wb.prototype,"issuer",void 0),Du([_u({type:Vb})],Wb.prototype,"thisUpdate",void 0),Du([_u({type:Vb,optional:!0})],Wb.prototype,"nextUpdate",void 0),Du([_u({type:zb,repeated:"sequence",optional:!0})],Wb.prototype,"revokedCertificates",void 0),Du([_u({type:Fb,optional:!0,context:0,repeated:"sequence"})],Wb.prototype,"crlExtensions",void 0);class Jb{constructor(e={}){this.tbsCertList=new Wb,this.signatureAlgorithm=new Lb,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Wb})],Jb.prototype,"tbsCertList",void 0),Du([_u({type:Lb})],Jb.prototype,"signatureAlgorithm",void 0),Du([_u({type:Ql.BitString})],Jb.prototype,"signature",void 0);class Yb{constructor(e={}){this.issuer=new np,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:np})],Yb.prototype,"issuer",void 0),Du([_u({type:Ql.Integer,converter:tu})],Yb.prototype,"serialNumber",void 0);let Xb=class{constructor(e={}){Object.assign(this,e)}};var Zb;Du([_u({type:Ob,context:0,implicit:!0})],Xb.prototype,"subjectKeyIdentifier",void 0),Du([_u({type:Yb})],Xb.prototype,"issuerAndSerialNumber",void 0),Xb=Du([Bu({type:Kl.Choice})],Xb),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"}(Zb||(Zb={}));let em=class extends Lb{};em=Du([Bu({type:Kl.Sequence})],em);let tm=class extends Lb{};tm=Du([Bu({type:Kl.Sequence})],tm);let rm=class extends Lb{};rm=Du([Bu({type:Kl.Sequence})],rm);let sm=class extends Lb{};sm=Du([Bu({type:Kl.Sequence})],sm);let im=class extends Lb{};im=Du([Bu({type:Kl.Sequence})],im);let nm=class extends Lb{};nm=Du([Bu({type:Kl.Sequence})],nm);class am{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}}var om;Du([_u({type:Ql.ObjectIdentifier})],am.prototype,"attrType",void 0),Du([_u({type:Ql.Any,repeated:"set"})],am.prototype,"attrValues",void 0);class cm{constructor(e={}){this.version=Zb.v0,this.sid=new Xb,this.digestAlgorithm=new em,this.signatureAlgorithm=new tm,this.signature=new Yd,Object.assign(this,e)}}Du([_u({type:Ql.Integer})],cm.prototype,"version",void 0),Du([_u({type:Xb})],cm.prototype,"sid",void 0),Du([_u({type:em})],cm.prototype,"digestAlgorithm",void 0),Du([_u({type:am,repeated:"set",context:0,implicit:!0,optional:!0})],cm.prototype,"signedAttrs",void 0),Du([_u({type:tm})],cm.prototype,"signatureAlgorithm",void 0),Du([_u({type:Yd})],cm.prototype,"signature",void 0),Du([_u({type:am,repeated:"set",context:1,implicit:!0,optional:!0})],cm.prototype,"unsignedAttrs",void 0);let lm=om=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,om.prototype)}};lm=om=Du([Bu({type:Kl.Set,itemType:cm})],lm);let dm=class extends Vb{};dm=Du([Bu({type:Kl.Choice})],dm);let um=class extends cm{};um=Du([Bu({type:Kl.Sequence})],um);class hm{constructor(e={}){this.acIssuer=new lp,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}var fm;Du([_u({type:lp})],hm.prototype,"acIssuer",void 0),Du([_u({type:Ql.Integer})],hm.prototype,"acSerial",void 0),Du([_u({type:xb,repeated:"sequence"})],hm.prototype,"attrs",void 0);let gm=fm=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,fm.prototype)}};gm=fm=Du([Bu({type:Kl.Sequence,itemType:Ql.ObjectIdentifier})],gm);class pm{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}}Du([_u({type:Ql.Integer,optional:!0})],pm.prototype,"pathLenConstraint",void 0),Du([_u({type:gm,implicit:!0,context:0,optional:!0})],pm.prototype,"permittedAttrs",void 0),Du([_u({type:gm,implicit:!0,context:1,optional:!0})],pm.prototype,"excludedAttrs",void 0),Du([_u({type:Ql.Boolean,defaultValue:!0})],pm.prototype,"permitUnSpecified",void 0);class bm{constructor(e={}){this.issuer=new Bp,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}var mm;Du([_u({type:Bp})],bm.prototype,"issuer",void 0),Du([_u({type:Ql.Integer,converter:tu})],bm.prototype,"serial",void 0),Du([_u({type:Ql.BitString,optional:!0})],bm.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}(mm||(mm={}));class ym{constructor(e={}){this.digestedObjectType=mm.publicKey,this.digestAlgorithm=new Lb,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.Enumerated})],ym.prototype,"digestedObjectType",void 0),Du([_u({type:Ql.ObjectIdentifier,optional:!0})],ym.prototype,"otherObjectTypeID",void 0),Du([_u({type:Lb})],ym.prototype,"digestAlgorithm",void 0),Du([_u({type:Ql.BitString})],ym.prototype,"objectDigest",void 0);class Am{constructor(e={}){Object.assign(this,e)}}Du([_u({type:Bp,optional:!0})],Am.prototype,"issuerName",void 0),Du([_u({type:bm,context:0,implicit:!0,optional:!0})],Am.prototype,"baseCertificateID",void 0),Du([_u({type:ym,context:1,implicit:!0,optional:!0})],Am.prototype,"objectDigestInfo",void 0);let Im=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:lp,repeated:"sequence"})],Im.prototype,"v1Form",void 0),Du([_u({type:Am,context:0,implicit:!0})],Im.prototype,"v2Form",void 0),Im=Du([Bu({type:Kl.Choice})],Im);class vm{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}Du([_u({type:Ql.GeneralizedTime})],vm.prototype,"notBeforeTime",void 0),Du([_u({type:Ql.GeneralizedTime})],vm.prototype,"notAfterTime",void 0);class wm{constructor(e={}){Object.assign(this,e)}}var Sm,Em,Cm;Du([_u({type:bm,implicit:!0,context:0,optional:!0})],wm.prototype,"baseCertificateID",void 0),Du([_u({type:Bp,implicit:!0,context:1,optional:!0})],wm.prototype,"entityName",void 0),Du([_u({type:ym,implicit:!0,context:2,optional:!0})],wm.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(Sm||(Sm={}));class km{constructor(e={}){this.version=Sm.v2,this.holder=new wm,this.issuer=new Im,this.signature=new Lb,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new vm,this.attributes=[],Object.assign(this,e)}}Du([_u({type:Ql.Integer})],km.prototype,"version",void 0),Du([_u({type:wm})],km.prototype,"holder",void 0),Du([_u({type:Im})],km.prototype,"issuer",void 0),Du([_u({type:Lb})],km.prototype,"signature",void 0),Du([_u({type:Ql.Integer,converter:tu})],km.prototype,"serialNumber",void 0),Du([_u({type:vm})],km.prototype,"attrCertValidityPeriod",void 0),Du([_u({type:xb,repeated:"sequence"})],km.prototype,"attributes",void 0),Du([_u({type:Ql.BitString,optional:!0})],km.prototype,"issuerUniqueID",void 0),Du([_u({type:$b,optional:!0})],km.prototype,"extensions",void 0);class xm{constructor(e={}){this.acinfo=new km,this.signatureAlgorithm=new Lb,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:km})],xm.prototype,"acinfo",void 0),Du([_u({type:Lb})],xm.prototype,"signatureAlgorithm",void 0),Du([_u({type:Ql.BitString})],xm.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"}(Em||(Em={}));class Bm extends Jd{}class _m{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier,implicit:!0,context:0})],_m.prototype,"type",void 0),Du([_u({type:Ql.Any,implicit:!0,context:1})],_m.prototype,"value",void 0);class Rm{constructor(e={}){this.policyId="",this.classList=new Bm(Em.unclassified),Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],Rm.prototype,"policyId",void 0),Du([_u({type:Bm,defaultValue:new Bm(Em.unclassified)})],Rm.prototype,"classList",void 0),Du([_u({type:_m,repeated:"set"})],Rm.prototype,"securityCategories",void 0);class Om{constructor(e={}){Object.assign(this,e)}}Du([_u({type:Yd})],Om.prototype,"cotets",void 0),Du([_u({type:Ql.ObjectIdentifier})],Om.prototype,"oid",void 0),Du([_u({type:Ql.Utf8String})],Om.prototype,"string",void 0);class Um{constructor(e={}){this.values=[],Object.assign(this,e)}}Du([_u({type:Bp,implicit:!0,context:0,optional:!0})],Um.prototype,"policyAuthority",void 0),Du([_u({type:Om,repeated:"sequence"})],Um.prototype,"values",void 0);class Tm{constructor(e={}){this.targetCertificate=new bm,Object.assign(this,e)}}Du([_u({type:bm})],Tm.prototype,"targetCertificate",void 0),Du([_u({type:lp,optional:!0})],Tm.prototype,"targetName",void 0),Du([_u({type:ym,optional:!0})],Tm.prototype,"certDigestInfo",void 0);let Nm=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:lp,context:0,implicit:!0})],Nm.prototype,"targetName",void 0),Du([_u({type:lp,context:1,implicit:!0})],Nm.prototype,"targetGroup",void 0),Du([_u({type:Tm,context:2,implicit:!0})],Nm.prototype,"targetCert",void 0),Nm=Du([Bu({type:Kl.Choice})],Nm);let Dm=Cm=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,Cm.prototype)}};var Mm;Dm=Cm=Du([Bu({type:Kl.Sequence,itemType:Nm})],Dm);let Pm=Mm=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,Mm.prototype)}};Pm=Mm=Du([Bu({type:Kl.Sequence,itemType:Dm})],Pm);class Lm{constructor(e={}){Object.assign(this,e)}}Du([_u({type:Bp,implicit:!0,context:0,optional:!0})],Lm.prototype,"roleAuthority",void 0),Du([_u({type:lp,implicit:!0,context:1})],Lm.prototype,"roleName",void 0);class Hm{constructor(e={}){this.service=new lp,this.ident=new lp,Object.assign(this,e)}}var Vm;Du([_u({type:lp})],Hm.prototype,"service",void 0),Du([_u({type:lp})],Hm.prototype,"ident",void 0),Du([_u({type:Yd,optional:!0})],Hm.prototype,"authInfo",void 0);class Km{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],Km.prototype,"otherCertFormat",void 0),Du([_u({type:Ql.Any})],Km.prototype,"otherCert",void 0);let Qm=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:qb})],Qm.prototype,"certificate",void 0),Du([_u({type:xm,context:2,implicit:!0})],Qm.prototype,"v2AttrCert",void 0),Du([_u({type:Km,context:3,implicit:!0})],Qm.prototype,"other",void 0),Qm=Du([Bu({type:Kl.Choice})],Qm);let Fm=Vm=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,Vm.prototype)}};Fm=Vm=Du([Bu({type:Kl.Set,itemType:Qm})],Fm);class $m{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],$m.prototype,"contentType",void 0),Du([_u({type:Ql.Any,context:0})],$m.prototype,"content",void 0);let Gm=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:Yd})],Gm.prototype,"single",void 0),Du([_u({type:Ql.Any})],Gm.prototype,"any",void 0),Gm=Du([Bu({type:Kl.Choice})],Gm);class jm{constructor(e={}){this.eContentType="",Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],jm.prototype,"eContentType",void 0),Du([_u({type:Gm,context:0,optional:!0})],jm.prototype,"eContent",void 0);let qm=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:Yd,context:0,implicit:!0,optional:!0})],qm.prototype,"value",void 0),Du([_u({type:Yd,converter:au,context:0,implicit:!0,optional:!0,repeated:"sequence"})],qm.prototype,"constructedValue",void 0),qm=Du([Bu({type:Kl.Choice})],qm);class zm{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new sm,Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],zm.prototype,"contentType",void 0),Du([_u({type:sm})],zm.prototype,"contentEncryptionAlgorithm",void 0),Du([_u({type:qm,optional:!0})],zm.prototype,"encryptedContent",void 0);class Wm{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}}var Jm;Du([_u({type:Ql.ObjectIdentifier})],Wm.prototype,"keyAttrId",void 0),Du([_u({type:Ql.Any,optional:!0})],Wm.prototype,"keyAttr",void 0);class Ym{constructor(e={}){this.subjectKeyIdentifier=new Ob,Object.assign(this,e)}}Du([_u({type:Ob})],Ym.prototype,"subjectKeyIdentifier",void 0),Du([_u({type:Ql.GeneralizedTime,optional:!0})],Ym.prototype,"date",void 0),Du([_u({type:Wm,optional:!0})],Ym.prototype,"other",void 0);let Xm=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:Ym,context:0,implicit:!0,optional:!0})],Xm.prototype,"rKeyId",void 0),Du([_u({type:Yb,optional:!0})],Xm.prototype,"issuerAndSerialNumber",void 0),Xm=Du([Bu({type:Kl.Choice})],Xm);class Zm{constructor(e={}){this.rid=new Xm,this.encryptedKey=new Yd,Object.assign(this,e)}}Du([_u({type:Xm})],Zm.prototype,"rid",void 0),Du([_u({type:Yd})],Zm.prototype,"encryptedKey",void 0);let ey=Jm=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,Jm.prototype)}};ey=Jm=Du([Bu({type:Kl.Sequence,itemType:Zm})],ey);class ty{constructor(e={}){this.algorithm=new Lb,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Lb})],ty.prototype,"algorithm",void 0),Du([_u({type:Ql.BitString})],ty.prototype,"publicKey",void 0);let ry=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:Ob,context:0,implicit:!0,optional:!0})],ry.prototype,"subjectKeyIdentifier",void 0),Du([_u({type:ty,context:1,implicit:!0,optional:!0})],ry.prototype,"originatorKey",void 0),Du([_u({type:Yb,optional:!0})],ry.prototype,"issuerAndSerialNumber",void 0),ry=Du([Bu({type:Kl.Choice})],ry);class sy{constructor(e={}){this.version=Zb.v3,this.originator=new ry,this.keyEncryptionAlgorithm=new rm,this.recipientEncryptedKeys=new ey,Object.assign(this,e)}}Du([_u({type:Ql.Integer})],sy.prototype,"version",void 0),Du([_u({type:ry,context:0})],sy.prototype,"originator",void 0),Du([_u({type:Yd,context:1,optional:!0})],sy.prototype,"ukm",void 0),Du([_u({type:rm})],sy.prototype,"keyEncryptionAlgorithm",void 0),Du([_u({type:ey})],sy.prototype,"recipientEncryptedKeys",void 0);let iy=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:Ob,context:0,implicit:!0})],iy.prototype,"subjectKeyIdentifier",void 0),Du([_u({type:Yb})],iy.prototype,"issuerAndSerialNumber",void 0),iy=Du([Bu({type:Kl.Choice})],iy);class ny{constructor(e={}){this.version=Zb.v0,this.rid=new iy,this.keyEncryptionAlgorithm=new rm,this.encryptedKey=new Yd,Object.assign(this,e)}}Du([_u({type:Ql.Integer})],ny.prototype,"version",void 0),Du([_u({type:iy})],ny.prototype,"rid",void 0),Du([_u({type:rm})],ny.prototype,"keyEncryptionAlgorithm",void 0),Du([_u({type:Yd})],ny.prototype,"encryptedKey",void 0);class ay{constructor(e={}){this.keyIdentifier=new Yd,Object.assign(this,e)}}Du([_u({type:Yd})],ay.prototype,"keyIdentifier",void 0),Du([_u({type:Ql.GeneralizedTime,optional:!0})],ay.prototype,"date",void 0),Du([_u({type:Wm,optional:!0})],ay.prototype,"other",void 0);class oy{constructor(e={}){this.version=Zb.v4,this.kekid=new ay,this.keyEncryptionAlgorithm=new rm,this.encryptedKey=new Yd,Object.assign(this,e)}}Du([_u({type:Ql.Integer})],oy.prototype,"version",void 0),Du([_u({type:ay})],oy.prototype,"kekid",void 0),Du([_u({type:rm})],oy.prototype,"keyEncryptionAlgorithm",void 0),Du([_u({type:Yd})],oy.prototype,"encryptedKey",void 0);class cy{constructor(e={}){this.version=Zb.v0,this.keyEncryptionAlgorithm=new rm,this.encryptedKey=new Yd,Object.assign(this,e)}}Du([_u({type:Ql.Integer})],cy.prototype,"version",void 0),Du([_u({type:nm,context:0,optional:!0})],cy.prototype,"keyDerivationAlgorithm",void 0),Du([_u({type:rm})],cy.prototype,"keyEncryptionAlgorithm",void 0),Du([_u({type:Yd})],cy.prototype,"encryptedKey",void 0);class ly{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],ly.prototype,"oriType",void 0),Du([_u({type:Ql.Any})],ly.prototype,"oriValue",void 0);let dy=class{constructor(e={}){Object.assign(this,e)}};var uy;Du([_u({type:ny,optional:!0})],dy.prototype,"ktri",void 0),Du([_u({type:sy,context:1,implicit:!0,optional:!0})],dy.prototype,"kari",void 0),Du([_u({type:oy,context:2,implicit:!0,optional:!0})],dy.prototype,"kekri",void 0),Du([_u({type:cy,context:3,implicit:!0,optional:!0})],dy.prototype,"pwri",void 0),Du([_u({type:ly,context:4,implicit:!0,optional:!0})],dy.prototype,"ori",void 0),dy=Du([Bu({type:Kl.Choice})],dy);let hy=uy=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,uy.prototype)}};var fy;hy=uy=Du([Bu({type:Kl.Set,itemType:dy})],hy);class gy{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],gy.prototype,"otherRevInfoFormat",void 0),Du([_u({type:Ql.Any})],gy.prototype,"otherRevInfo",void 0);let py=class{constructor(e={}){this.other=new gy,Object.assign(this,e)}};Du([_u({type:gy,context:1,implicit:!0})],py.prototype,"other",void 0),py=Du([Bu({type:Kl.Choice})],py);let by=fy=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,fy.prototype)}};by=fy=Du([Bu({type:Kl.Set,itemType:py})],by);class my{constructor(e={}){Object.assign(this,e)}}var yy;Du([_u({type:Fm,context:0,implicit:!0,optional:!0})],my.prototype,"certs",void 0),Du([_u({type:by,context:1,implicit:!0,optional:!0})],my.prototype,"crls",void 0);let Ay=yy=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,yy.prototype)}};Ay=yy=Du([Bu({type:Kl.Set,itemType:am})],Ay);class Iy{constructor(e={}){this.version=Zb.v0,this.recipientInfos=new hy,this.encryptedContentInfo=new zm,Object.assign(this,e)}}Du([_u({type:Ql.Integer})],Iy.prototype,"version",void 0),Du([_u({type:my,context:0,implicit:!0,optional:!0})],Iy.prototype,"originatorInfo",void 0),Du([_u({type:hy})],Iy.prototype,"recipientInfos",void 0),Du([_u({type:zm})],Iy.prototype,"encryptedContentInfo",void 0),Du([_u({type:Ay,context:1,implicit:!0,optional:!0})],Iy.prototype,"unprotectedAttrs",void 0);const vy="1.2.840.113549.1.7.2";var wy;let Sy=wy=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,wy.prototype)}};Sy=wy=Du([Bu({type:Kl.Set,itemType:em})],Sy);class Ey{constructor(e={}){this.version=Zb.v0,this.digestAlgorithms=new Sy,this.encapContentInfo=new jm,this.signerInfos=new lm,Object.assign(this,e)}}Du([_u({type:Ql.Integer})],Ey.prototype,"version",void 0),Du([_u({type:Sy})],Ey.prototype,"digestAlgorithms",void 0),Du([_u({type:jm})],Ey.prototype,"encapContentInfo",void 0),Du([_u({type:Fm,context:0,implicit:!0,optional:!0})],Ey.prototype,"certificates",void 0),Du([_u({type:by,context:1,implicit:!0,optional:!0})],Ey.prototype,"crls",void 0),Du([_u({type:lm})],Ey.prototype,"signerInfos",void 0);const Cy="1.2.840.10045.2.1",ky="1.2.840.10045.4.1",xy="1.2.840.10045.4.3.1",By="1.2.840.10045.4.3.2",_y="1.2.840.10045.4.3.3",Ry="1.2.840.10045.4.3.4",Oy="1.2.840.10045.3.1.7",Uy="1.3.132.0.34",Ty="1.3.132.0.35";function Ny(e){return new Lb({algorithm:e})}const Dy=Ny(ky),My=(Ny(xy),Ny(By)),Py=Ny(_y),Ly=Ny(Ry);let Hy=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:Ql.ObjectIdentifier})],Hy.prototype,"fieldType",void 0),Du([_u({type:Ql.Any})],Hy.prototype,"parameters",void 0),Hy=Du([Bu({type:Kl.Sequence})],Hy);let Vy=class{constructor(e={}){Object.assign(this,e)}};var Ky;Du([_u({type:Ql.OctetString})],Vy.prototype,"a",void 0),Du([_u({type:Ql.OctetString})],Vy.prototype,"b",void 0),Du([_u({type:Ql.BitString,optional:!0})],Vy.prototype,"seed",void 0),Vy=Du([Bu({type:Kl.Sequence})],Vy),function(e){e[e.ecpVer1=1]="ecpVer1"}(Ky||(Ky={}));let Qy=class{constructor(e={}){this.version=Ky.ecpVer1,Object.assign(this,e)}};Du([_u({type:Ql.Integer})],Qy.prototype,"version",void 0),Du([_u({type:Hy})],Qy.prototype,"fieldID",void 0),Du([_u({type:Vy})],Qy.prototype,"curve",void 0),Du([_u({type:class extends Yd{}})],Qy.prototype,"base",void 0),Du([_u({type:Ql.Integer,converter:tu})],Qy.prototype,"order",void 0),Du([_u({type:Ql.Integer,optional:!0})],Qy.prototype,"cofactor",void 0),Qy=Du([Bu({type:Kl.Sequence})],Qy);let Fy=class{constructor(e={}){Object.assign(this,e)}};Du([_u({type:Ql.ObjectIdentifier})],Fy.prototype,"namedCurve",void 0),Du([_u({type:Ql.Null})],Fy.prototype,"implicitCurve",void 0),Du([_u({type:Qy})],Fy.prototype,"specifiedCurve",void 0),Fy=Du([Bu({type:Kl.Choice})],Fy);class $y{constructor(e={}){this.version=1,this.privateKey=new Yd,Object.assign(this,e)}}Du([_u({type:Ql.Integer})],$y.prototype,"version",void 0),Du([_u({type:Yd})],$y.prototype,"privateKey",void 0),Du([_u({type:Fy,context:0,optional:!0})],$y.prototype,"parameters",void 0),Du([_u({type:Ql.BitString,context:1,optional:!0})],$y.prototype,"publicKey",void 0);class Gy{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.Integer,converter:tu})],Gy.prototype,"r",void 0),Du([_u({type:Ql.Integer,converter:tu})],Gy.prototype,"s",void 0);const jy="1.2.840.113549.1.1",qy=`${jy}.1`,zy=`${jy}.7`,Wy=`${jy}.9`,Jy=`${jy}.10`,Yy=`${jy}.2`,Xy=`${jy}.4`,Zy=`${jy}.5`,eA=`${jy}.14`,tA=`${jy}.11`,rA=`${jy}.12`,sA=`${jy}.13`,iA=`${jy}.15`,nA=`${jy}.16`,aA="1.3.14.3.2.26",oA="2.16.840.1.101.3.4.2.4",cA="2.16.840.1.101.3.4.2.1",lA="2.16.840.1.101.3.4.2.2",dA="2.16.840.1.101.3.4.2.3",uA=`${jy}.8`;function hA(e){return new Lb({algorithm:e,parameters:null})}hA("1.2.840.113549.2.2"),hA("1.2.840.113549.2.5");const fA=hA(aA),gA=(hA(oA),hA(cA),hA(lA),hA(dA),hA("2.16.840.1.101.3.4.2.5"),hA("2.16.840.1.101.3.4.2.6"),new Lb({algorithm:uA,parameters:Nu.serialize(fA)})),pA=new Lb({algorithm:Wy,parameters:Nu.serialize(nu.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});hA(qy),hA(Yy),hA(Xy),hA(Zy),hA(iA),hA(nA),hA(rA),hA(sA),hA(iA),hA(nA);class bA{constructor(e={}){this.hashAlgorithm=new Lb(fA),this.maskGenAlgorithm=new Lb({algorithm:uA,parameters:Nu.serialize(fA)}),this.pSourceAlgorithm=new Lb(pA),Object.assign(this,e)}}Du([_u({type:Lb,context:0,defaultValue:fA})],bA.prototype,"hashAlgorithm",void 0),Du([_u({type:Lb,context:1,defaultValue:gA})],bA.prototype,"maskGenAlgorithm",void 0),Du([_u({type:Lb,context:2,defaultValue:pA})],bA.prototype,"pSourceAlgorithm",void 0),new Lb({algorithm:zy,parameters:Nu.serialize(new bA)});class mA{constructor(e={}){this.hashAlgorithm=new Lb(fA),this.maskGenAlgorithm=new Lb({algorithm:uA,parameters:Nu.serialize(fA)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}Du([_u({type:Lb,context:0,defaultValue:fA})],mA.prototype,"hashAlgorithm",void 0),Du([_u({type:Lb,context:1,defaultValue:gA})],mA.prototype,"maskGenAlgorithm",void 0),Du([_u({type:Ql.Integer,context:2,defaultValue:20})],mA.prototype,"saltLength",void 0),Du([_u({type:Ql.Integer,context:3,defaultValue:1})],mA.prototype,"trailerField",void 0),new Lb({algorithm:Jy,parameters:Nu.serialize(new mA)});class yA{constructor(e={}){this.digestAlgorithm=new Lb,this.digest=new Yd,Object.assign(this,e)}}var AA;Du([_u({type:Lb})],yA.prototype,"digestAlgorithm",void 0),Du([_u({type:Yd})],yA.prototype,"digest",void 0);class IA{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.Integer,converter:tu})],IA.prototype,"prime",void 0),Du([_u({type:Ql.Integer,converter:tu})],IA.prototype,"exponent",void 0),Du([_u({type:Ql.Integer,converter:tu})],IA.prototype,"coefficient",void 0);let vA=AA=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,AA.prototype)}};vA=AA=Du([Bu({type:Kl.Sequence,itemType:IA})],vA);class wA{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)}}Du([_u({type:Ql.Integer})],wA.prototype,"version",void 0),Du([_u({type:Ql.Integer,converter:tu})],wA.prototype,"modulus",void 0),Du([_u({type:Ql.Integer,converter:tu})],wA.prototype,"publicExponent",void 0),Du([_u({type:Ql.Integer,converter:tu})],wA.prototype,"privateExponent",void 0),Du([_u({type:Ql.Integer,converter:tu})],wA.prototype,"prime1",void 0),Du([_u({type:Ql.Integer,converter:tu})],wA.prototype,"prime2",void 0),Du([_u({type:Ql.Integer,converter:tu})],wA.prototype,"exponent1",void 0),Du([_u({type:Ql.Integer,converter:tu})],wA.prototype,"exponent2",void 0),Du([_u({type:Ql.Integer,converter:tu})],wA.prototype,"coefficient",void 0),Du([_u({type:vA,optional:!0})],wA.prototype,"otherPrimeInfos",void 0);class SA{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}var EA;Du([_u({type:Ql.Integer,converter:tu})],SA.prototype,"modulus",void 0),Du([_u({type:Ql.Integer,converter:tu})],SA.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"}(EA||(EA={}));const CA=EA;var kA=function(e,t){return kA=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])},kA(e,t)};function xA(e,t){function r(){this.constructor=e}kA(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function BA(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 _A(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var s,i,n=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)a.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 a}function RA(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(_A(arguments[t]));return e}function OA(e){return!!e.useClass}function UA(e){return!!e.useFactory}var TA=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,RA(t))}}),t},e}();function NA(e){return"string"==typeof e||"symbol"==typeof e}function DA(e){return"object"==typeof e&&"token"in e&&"transform"in e}function MA(e){return!!e.useToken}function PA(e){return null!=e.useValue}var LA=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 HA=LA,VA=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return xA(t,e),t}(HA),KA=function(){this.scopedResolutions=new Map};var QA=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return xA(t,e),t}(HA),FA=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return xA(t,e),t}(HA);const $A=function(){this.preResolution=new QA,this.postResolution=new FA};var GA=new Map,jA=function(){function e(e){this.parent=e,this._registry=new VA,this.interceptors=new $A,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var s;if(void 0===r&&(r={lifecycle:CA.Transient}),this.ensureNotDisposed(),s=function(e){return OA(e)||PA(e)||MA(e)||UA(e)}(t)?t:{useClass:t},MA(s))for(var i=[e],n=s;null!=n;){var a=n.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+RA(i,[a]).join(" -> "));i.push(a);var o=this._registry.get(a);n=o&&MA(o.provider)?o.provider:null}if((r.lifecycle===CA.Singleton||r.lifecycle==CA.ContainerScoped||r.lifecycle==CA.ResolutionScoped)&&(PA(s)||UA(s)))throw new Error('Cannot use lifecycle "'+CA[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(),NA(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(),NA(e)){if(NA(t))return this.register(e,{useToken:t},{lifecycle:CA.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:CA.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!NA(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:CA.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new KA),void 0===r&&(r=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&NA(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 TA}(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=BA(this.interceptors.preResolution.getAll(e)),a=n.next();!a.done;a=n.next()){var o=a.value;"Once"!=o.options.frequency&&i.push(o),o.callback(e,t)}}catch(e){r={error:e}}finally{try{a&&!a.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 a=BA(this.interceptors.postResolution.getAll(e)),o=a.next();!o.done;o=a.next()){var c=o.value;"Once"!=c.options.frequency&&n.push(c),c.callback(e,t,r)}}catch(e){s={error:e}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(s)throw s.error}}this.interceptors.postResolution.setAll(e,n)}},e.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===CA.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,s=e.options.lifecycle===CA.Singleton,i=e.options.lifecycle===CA.ContainerScoped,n=s||i;return r=PA(e.provider)?e.provider.useValue:MA(e.provider)?n?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):OA(e.provider)?n?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):UA(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===CA.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var s=this;void 0===t&&(t=new KA),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&NA(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 a=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,a,"All"),a},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=BA(this._registry.entries()),s=r.next();!s.done;s=r.next()){var i=_A(s.value,2),n=i[0],a=i[1];this._registry.setAll(n,a.filter(function(e){return!PA(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=BA(this._registry.entries()),n=i.next();!n.done;n=i.next()){var a=_A(n.value,2),o=a[0],c=a[1];c.some(function(e){return e.options.lifecycle===CA.ContainerScoped})&&s._registry.setAll(o,c.map(function(e){return e.options.lifecycle===CA.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 a(e){try{c(s.next(e))}catch(e){n(e)}}function o(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(a,o)}c((s=s.apply(e,t||[])).next())})}(this,void 0,void 0,function(){var e;return function(e,t){var r,s,i,n,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return n={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function o(n){return function(o){return function(n){if(r)throw new TypeError("Generator is already executing.");for(;a;)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 a.label++,{value:n[1],done:!1};case 5:a.label++,s=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==n[0]&&2!==n[0])){a=0;continue}if(3===n[0]&&(!i||n[1]>i[0]&&n[1]<i[3])){a.label=n[1];break}if(6===n[0]&&a.label<i[1]){a.label=i[1],i=n;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(n);break}i[2]&&a.ops.pop(),a.trys.pop();continue}n=t.call(e,a)}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,o])}}}(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 TA)return e.createProxy(function(e){return r.resolve(e,t)});var s,i=function(){var s=GA.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,RA([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,a,o,c;try{return"object"==typeof(c=s)&&"token"in c&&"multiple"in c?DA(s)?s.multiple?(n=r.resolve(s.transform)).transform.apply(n,RA([r.resolveAll(s.token,new KA,s.isOptional)],s.transformArgs)):(a=r.resolve(s.transform)).transform.apply(a,RA([r.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?r.resolveAll(s.token,new KA,s.isOptional):r.resolve(s.token,e,s.isOptional):DA(s)?(o=r.resolve(s.transform,e)).transform.apply(o,RA([r.resolve(s.token,e)],s.transformArgs)):r.resolve(s,e)}catch(e){throw new Error(function(e,t,r){var s,i,n=_A(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return function(e,t,r){return void 0===r&&(r=" "),RA([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}(),qA=new jA;const zA=function(e){return function(t){GA.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){qA.register(e,t)}):qA.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 WA;class JA{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}}Du([_u({type:Ql.ObjectIdentifier})],JA.prototype,"attrId",void 0),Du([_u({type:Ql.Any,repeated:"set"})],JA.prototype,"attrValues",void 0);let YA=WA=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,WA.prototype)}};var XA;YA=WA=Du([Bu({type:Kl.Sequence,itemType:JA})],YA);let ZA=XA=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,XA.prototype)}};ZA=XA=Du([Bu({type:Kl.Sequence,itemType:$m})],ZA);class eI{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],eI.prototype,"certId",void 0),Du([_u({type:Ql.Any,context:0})],eI.prototype,"certValue",void 0);class tI{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],tI.prototype,"crlId",void 0),Du([_u({type:Ql.Any,context:0})],tI.prototype,"crltValue",void 0);class rI extends Yd{}class sI{constructor(e={}){this.encryptionAlgorithm=new Lb,this.encryptedData=new rI,Object.assign(this,e)}}var iI,nI;Du([_u({type:Lb})],sI.prototype,"encryptionAlgorithm",void 0),Du([_u({type:rI})],sI.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(nI||(nI={}));class aI extends Yd{}let oI=iI=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,iI.prototype)}};oI=iI=Du([Bu({type:Kl.Sequence,itemType:xb})],oI);class cI{constructor(e={}){this.version=nI.v1,this.privateKeyAlgorithm=new Lb,this.privateKey=new aI,Object.assign(this,e)}}Du([_u({type:Ql.Integer})],cI.prototype,"version",void 0),Du([_u({type:Lb})],cI.prototype,"privateKeyAlgorithm",void 0),Du([_u({type:aI})],cI.prototype,"privateKey",void 0),Du([_u({type:oI,implicit:!0,context:0,optional:!0})],cI.prototype,"attributes",void 0);let lI=class extends cI{};lI=Du([Bu({type:Kl.Sequence})],lI);let dI=class extends sI{};dI=Du([Bu({type:Kl.Sequence})],dI);class uI{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],uI.prototype,"secretTypeId",void 0),Du([_u({type:Ql.Any,context:0})],uI.prototype,"secretValue",void 0);class hI{constructor(e={}){this.mac=new yA,this.macSalt=new Yd,this.iterations=1,Object.assign(this,e)}}Du([_u({type:yA})],hI.prototype,"mac",void 0),Du([_u({type:Yd})],hI.prototype,"macSalt",void 0),Du([_u({type:Ql.Integer,defaultValue:1})],hI.prototype,"iterations",void 0);class fI{constructor(e={}){this.version=3,this.authSafe=new $m,this.macData=new hI,Object.assign(this,e)}}var gI;Du([_u({type:Ql.Integer})],fI.prototype,"version",void 0),Du([_u({type:$m})],fI.prototype,"authSafe",void 0),Du([_u({type:hI,optional:!0})],fI.prototype,"macData",void 0);class pI{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:Ql.ObjectIdentifier})],pI.prototype,"bagId",void 0),Du([_u({type:Ql.Any,context:0})],pI.prototype,"bagValue",void 0),Du([_u({type:JA,repeated:"set",optional:!0})],pI.prototype,"bagAttributes",void 0);let bI=gI=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,gI.prototype)}};var mI,yI,AI;bI=gI=Du([Bu({type:Kl.Sequence,itemType:pI})],bI);const II="1.2.840.113549.1.9",vI=`${II}.7`,wI=`${II}.14`;let SI=class extends ep{constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};Du([_u({type:Ql.IA5String})],SI.prototype,"ia5String",void 0),SI=Du([Bu({type:Kl.Choice})],SI);let EI=class extends $m{};EI=Du([Bu({type:Kl.Sequence})],EI);let CI=class extends fI{};CI=Du([Bu({type:Kl.Sequence})],CI);let kI=class extends sI{};kI=Du([Bu({type:Kl.Sequence})],kI);let xI=class{constructor(e=""){this.value=e}toString(){return this.value}};Du([_u({type:Ql.IA5String})],xI.prototype,"value",void 0),xI=Du([Bu({type:Kl.Choice})],xI);let BI=class extends SI{};BI=Du([Bu({type:Kl.Choice})],BI);let _I=class extends ep{};_I=Du([Bu({type:Kl.Choice})],_I);let RI=class{constructor(e=new Date){this.value=e}};Du([_u({type:Ql.GeneralizedTime})],RI.prototype,"value",void 0),RI=Du([Bu({type:Kl.Choice})],RI);let OI=class extends ep{};OI=Du([Bu({type:Kl.Choice})],OI);let UI=class{constructor(e="M"){this.value=e}toString(){return this.value}};Du([_u({type:Ql.PrintableString})],UI.prototype,"value",void 0),UI=Du([Bu({type:Kl.Choice})],UI);let TI=class{constructor(e=""){this.value=e}toString(){return this.value}};Du([_u({type:Ql.PrintableString})],TI.prototype,"value",void 0),TI=Du([Bu({type:Kl.Choice})],TI);let NI=class extends TI{};NI=Du([Bu({type:Kl.Choice})],NI);let DI=class extends ep{};DI=Du([Bu({type:Kl.Choice})],DI);let MI=class{constructor(e=""){this.value=e}toString(){return this.value}};Du([_u({type:Ql.ObjectIdentifier})],MI.prototype,"value",void 0),MI=Du([Bu({type:Kl.Choice})],MI);let PI=class extends Vb{};PI=Du([Bu({type:Kl.Choice})],PI);let LI=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};Du([_u({type:Ql.Integer})],LI.prototype,"value",void 0),LI=Du([Bu({type:Kl.Choice})],LI);let HI=class extends cm{};HI=Du([Bu({type:Kl.Sequence})],HI);let VI=class extends ep{};VI=Du([Bu({type:Kl.Choice})],VI);let KI=mI=class extends $b{constructor(e){super(e),Object.setPrototypeOf(this,mI.prototype)}};KI=mI=Du([Bu({type:Kl.Sequence})],KI);let QI=yI=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,yI.prototype)}};QI=yI=Du([Bu({type:Kl.Set,itemType:am})],QI);let FI=class{constructor(e=""){this.value=e}toString(){return this.value}};Du([_u({type:Ql.BmpString})],FI.prototype,"value",void 0),FI=Du([Bu({type:Kl.Choice})],FI);let $I=class extends Lb{};$I=Du([Bu({type:Kl.Sequence})],$I);let GI=AI=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,AI.prototype)}};var jI;GI=AI=Du([Bu({type:Kl.Sequence,itemType:$I})],GI);let qI=jI=class extends Tu{constructor(e){super(e),Object.setPrototypeOf(this,jI.prototype)}};qI=jI=Du([Bu({type:Kl.Sequence,itemType:xb})],qI);class zI{constructor(e={}){this.version=0,this.subject=new np,this.subjectPKInfo=new Hb,this.attributes=new qI,Object.assign(this,e)}}Du([_u({type:Ql.Integer})],zI.prototype,"version",void 0),Du([_u({type:np})],zI.prototype,"subject",void 0),Du([_u({type:Hb})],zI.prototype,"subjectPKInfo",void 0),Du([_u({type:qI,implicit:!0,context:0})],zI.prototype,"attributes",void 0);class WI{constructor(e={}){this.certificationRequestInfo=new zI,this.signatureAlgorithm=new Lb,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Du([_u({type:zI})],WI.prototype,"certificationRequestInfo",void 0),Du([_u({type:Lb})],WI.prototype,"signatureAlgorithm",void 0),Du([_u({type:Ql.BitString})],WI.prototype,"signature",void 0);const JI="crypto.algorithm",YI="crypto.algorithmProvider";var XI;qA.registerSingleton(YI,class{getAlgorithms(){return qA.resolveAll(JI)}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 Lb({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 ZI="1.3.36.3.3.2.8.1.1",ev=`${ZI}.1`,tv=`${ZI}.2`,rv=`${ZI}.3`,sv=`${ZI}.4`,iv=`${ZI}.5`,nv=`${ZI}.6`,av=`${ZI}.7`,ov=`${ZI}.8`,cv=`${ZI}.9`,lv=`${ZI}.10`,dv=`${ZI}.11`,uv=`${ZI}.12`,hv=`${ZI}.13`,fv=`${ZI}.14`,gv="brainpoolP160r1",pv="brainpoolP160t1",bv="brainpoolP192r1",mv="brainpoolP192t1",yv="brainpoolP224r1",Av="brainpoolP224t1",Iv="brainpoolP256r1",vv="brainpoolP256t1",wv="brainpoolP320r1",Sv="brainpoolP320t1",Ev="brainpoolP384r1",Cv="brainpoolP384t1",kv="brainpoolP512r1",xv="brainpoolP512t1",Bv="ECDSA";let _v=XI=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===Bv.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return Dy;case"sha-256":return My;case"sha-384":return Py;case"sha-512":return Ly}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=Oy;break;case"K-256":t=XI.SECP256K1;break;case"P-384":t=Uy;break;case"P-521":t=Ty;break;case gv:t=ev;break;case pv:t=tv;break;case bv:t=rv;break;case mv:t=sv;break;case yv:t=iv;break;case Av:t=nv;break;case Iv:t=av;break;case vv:t=ov;break;case wv:t=cv;break;case Sv:t=lv;break;case Ev:t=dv;break;case Cv:t=uv;break;case kv:t=hv;break;case xv:t=fv}if(t)return new Lb({algorithm:Cy,parameters:Nu.serialize(new Fy({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case ky:return{name:Bv,hash:{name:"SHA-1"}};case By:return{name:Bv,hash:{name:"SHA-256"}};case _y:return{name:Bv,hash:{name:"SHA-384"}};case Ry:return{name:Bv,hash:{name:"SHA-512"}};case Cy:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Nu.parse(e.parameters,Fy).namedCurve){case Oy:return{name:Bv,namedCurve:"P-256"};case XI.SECP256K1:return{name:Bv,namedCurve:"K-256"};case Uy:return{name:Bv,namedCurve:"P-384"};case Ty:return{name:Bv,namedCurve:"P-521"};case ev:return{name:Bv,namedCurve:gv};case tv:return{name:Bv,namedCurve:pv};case rv:return{name:Bv,namedCurve:bv};case sv:return{name:Bv,namedCurve:mv};case iv:return{name:Bv,namedCurve:yv};case nv:return{name:Bv,namedCurve:Av};case av:return{name:Bv,namedCurve:Iv};case ov:return{name:Bv,namedCurve:vv};case cv:return{name:Bv,namedCurve:wv};case lv:return{name:Bv,namedCurve:Sv};case dv:return{name:Bv,namedCurve:Ev};case uv:return{name:Bv,namedCurve:Cv};case hv:return{name:Bv,namedCurve:kv};case fv:return{name:Bv,namedCurve:xv}}}return null}};_v.SECP256K1="1.3.132.0.10",_v=XI=Du([zA()],_v),qA.registerSingleton(JI,_v);const Rv=Symbol("name"),Ov=Symbol("value");class Uv{constructor(e,t={},r=""){this[Rv]=e,this[Ov]=r;for(const e in t)this[e]=t[e]}}Uv.NAME=Rv,Uv.VALUE=Ov;class Tv{static toString(e){return this.items[e]||e}}Tv.items={[aA]:"sha1",[oA]:"sha224",[cA]:"sha256",[lA]:"sha384",[dA]:"sha512",[qy]:"rsaEncryption",[Zy]:"sha1WithRSAEncryption",[eA]:"sha224WithRSAEncryption",[tA]:"sha256WithRSAEncryption",[rA]:"sha384WithRSAEncryption",[sA]:"sha512WithRSAEncryption",[Cy]:"ecPublicKey",[ky]:"ecdsaWithSHA1",[xy]:"ecdsaWithSHA224",[By]:"ecdsaWithSHA256",[_y]:"ecdsaWithSHA384",[Ry]:"ecdsaWithSHA512",[sb]:"TLS WWW server authentication",[ib]:"TLS WWW client authentication",[nb]:"Code Signing",[ab]:"E-mail Protection",[ob]:"Time Stamping",[cb]:"OCSP Signing",[vy]:"Signed Data"};class Nv{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[Uv.VALUE];n&&(i=` ${n}`),r.push(`${s}${e[Uv.NAME]}:${i}`),s=this.pad(t);for(const i in e){if("symbol"==typeof i)continue;const n=e[i],a=i?`${i}: `:"";if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)r.push(`${s}${a}${n}`);else if(n instanceof Date)r.push(`${s}${a}${n.toUTCString()}`);else if(Array.isArray(n))for(const e of n)e[Uv.NAME]=i,r.push(...this.serializeObj(e,t));else if(n instanceof Uv)n[Uv.NAME]=i,r.push(...this.serializeObj(n,t));else if(pc.isBufferSource(n))i?(r.push(`${s}${a}`),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[Uv.NAME]=i,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),s=pc.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)}}Nv.oidSerializer=Tv,Nv.algorithmSerializer=class{static toTextObject(e){const t=new Uv("Algorithm Identifier",{},Tv.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case Cy:{const r=(new _v).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class Dv{constructor(...e){if(1===e.length){const t=e[0];this.rawData=Nu.serialize(t),this.onInit(t)}else{const t=Nu.parse(e[0],e[1]);this.rawData=pc.toArrayBuffer(e[0]),this.onInit(t)}}equal(e){return e instanceof Dv&&Ec(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return Nu.toString(this.rawData);case"text":return Nv.serialize(this.toTextObject());case"hex":return wc.ToHex(this.rawData);case"base64":return wc.ToBase64(this.rawData);case"base64url":return wc.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 Uv(this.getTextName(),{},e)}}Dv.NAME="ASN";class Mv extends Dv{constructor(...e){let t;t=pc.isBufferSource(e[0])?pc.toArrayBuffer(e[0]):Nu.serialize(new Fb({extnID:e[0],critical:e[1],extnValue:new Yd(pc.toArrayBuffer(e[2]))})),super(t,Fb)}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[Uv.NAME]===Mv.NAME&&(e[Uv.NAME]=Tv.toString(this.type)),e}}var Pv;class Lv{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[Pv]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(Lv.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(Lv.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=Lv.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(Lv.DEFAULT,e);return this}}Pv=Symbol.toStringTag,Lv.DEFAULT="default";const Hv=new Lv,Vv=/^[0-2](?:\.[1-9][0-9]*)+$/;class Kv{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(Vv).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const Qv=new Kv;function Fv(e,t){return`\\${wc.ToHex(wc.FromUtf8String(t)).toUpperCase()}`}Qv.register("CN","2.5.4.3"),Qv.register("L","2.5.4.7"),Qv.register("ST","2.5.4.8"),Qv.register("O","2.5.4.10"),Qv.register("OU","2.5.4.11"),Qv.register("C","2.5.4.6"),Qv.register("DC","0.9.2342.19200300.100.1.25"),Qv.register("E","1.2.840.113549.1.9.1"),Qv.register("G","2.5.4.42"),Qv.register("I","2.5.4.43"),Qv.register("SN","2.5.4.4"),Qv.register("T","2.5.4.12");class $v{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 Kv,this.asn=new np;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 np?this.asn=e:pc.isBufferSource(e)?this.asn=Nu.parse(e,np):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||Qv.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)||Qv.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${wc.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,Fv)}`).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?`#${wc.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(s)}return t}fromString(e){const t=new np,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 a=s[3];e=this.getTypeOid(e);const o=this.createAttribute(e,r);"+"===i?t[t.length-1].push(o):t.push(new sp([o])),i=a}return t}fromJSON(e){const t=new np;for(const r of e){const e=new sp;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 rp({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=wc.FromHex(t.slice(1));else{const s=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=s:$v.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 Nu.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]||Hv.get()):r=e[0]||Hv.get(),await r.subtle.digest(s,this.toArrayBuffer())}}const Gv="Cannot initialize GeneralName from ASN.1 data.",jv=`${Gv} Unsupported string format in use.`,qv=`${Gv} Value doesn't match to GUID regular expression.`,zv=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Wv="1.3.6.1.4.1.311.25.1",Jv="1.3.6.1.4.1.311.20.2.3",Yv="dns",Xv="dn",Zv="email",ew="ip",tw="url",rw="guid",sw="upn",iw="id";class nw extends Dv{constructor(...e){let t;if(2===e.length)switch(e[0]){case Xv:{const r=new $v(e[1]).toArrayBuffer(),s=Nu.parse(r,np);t=new lp({directoryName:s});break}case Yv:t=new lp({dNSName:e[1]});break;case Zv:t=new lp({rfc822Name:e[1]});break;case rw:{const r=new RegExp(zv,"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?wc.ToHex(new Uint8Array(wc.FromHex(e)).reverse()):e).join("");t=new lp({otherName:new op({typeId:Wv,value:Nu.serialize(new Yd(wc.FromHex(s)))})});break}case ew:t=new lp({iPAddress:e[1]});break;case iw:t=new lp({registeredID:e[1]});break;case sw:t=new lp({otherName:new op({typeId:Jv,value:Nu.serialize(cu.toASN(e[1]))})});break;case tw:t=new lp({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=pc.isBufferSource(e[0])?Nu.parse(e[0],lp):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=Yv,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=Zv,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=ew,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=tw,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=iw,this.value=e.registeredID;else if(null!=e.directoryName)this.type=Xv,this.value=new $v(e.directoryName).toString();else{if(null==e.otherName)throw new Error(jv);if(e.otherName.typeId===Wv){this.type=rw;const t=Nu.parse(e.otherName.value,Yd),r=new RegExp(zv,"i").exec(wc.ToHex(t));if(!r)throw new Error(qv);this.value=r.slice(1).map((e,t)=>t<3?wc.ToHex(new Uint8Array(wc.FromHex(e)).reverse()):e).join("-")}else{if(e.otherName.typeId!==Jv)throw new Error(jv);this.type=sw,this.value=Nu.parse(e.otherName.value,ep).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case Xv:case Yv:case rw:case ew:case iw:case sw:case tw:e=this.type.toUpperCase();break;case Zv:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===iw&&(t=Tv.toString(t)),new Uv(e,void 0,t)}}class aw extends Dv{constructor(e){let t;if(e instanceof Bp)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof lp)r.push(t);else{const e=Nu.parse(new nw(t.type,t.value).rawData,lp);r.push(e)}t=new Bp(r)}else{if(!pc.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=Nu.parse(e,Bp)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new nw(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[Uv.NAME]];Array.isArray(s)||(s=[],e[r[Uv.NAME]]=s),s.push(r)}return e}}aw.NAME="GeneralNames";const ow="-{5}",cw="\\n",lw="\\n",dw=`${ow}BEGIN ([^${cw}]+(?=${ow}))${ow}${lw}(?:((?:[^:${cw}]+: (?:[^${cw}]+${lw}(?: +[^${cw}]+${lw})*))+))?${lw}?((?:[a-zA-Z0-9=+/]+${lw})+)${ow}END \\1${ow}`;class uw{static isPem(e){return"string"==typeof e&&new RegExp(dw,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(dw,"g"),r=[];let s=null;for(;s=t.exec(e);){const e=s[3].replace(new RegExp(`[${cw}]+`,"g"),""),t={type:s[1],headers:[],rawData:wc.FromBase64(e)},i=s[2];if(i){const e=i.split(new RegExp(lw,"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(!pc.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:pc.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:pc.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=wc.ToBase64(e.rawData);let n,a=0;const o=Array();for(;a<i.length&&(i.length-a<64?n=i.substring(a):(n=i.substring(a,a+64),a+=64),0!==n.length)&&(o.push(n),!(n.length<64)););return s.push(...o),s.push(`-----END ${r}-----`),s.join("\n")}}uw.CertificateTag="CERTIFICATE",uw.CrlTag="CRL",uw.CertificateRequestTag="CERTIFICATE REQUEST",uw.PublicKeyTag="PUBLIC KEY",uw.PrivateKeyTag="PRIVATE KEY";class hw extends Dv{static isAsnEncoded(e){return pc.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(uw.isPem(e))return uw.decode(e)[0];if(wc.isHex(e))return wc.FromHex(e);if(wc.isBase64(e))return wc.FromBase64(e);if(wc.isBase64Url(e))return wc.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=wc.ToBinary(e);return uw.isPem(t)?uw.decode(t)[0]:wc.isHex(t)?wc.FromHex(t):wc.isBase64(t)?wc.FromBase64(t):wc.isBase64Url(t)?wc.FromBase64Url(t):pc.toArrayBuffer(e)}}constructor(...e){hw.isAsnEncoded(e[0])?super(hw.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?uw.encode(this.rawData,this.tag):super.toString(e)}}class fw extends hw{static async create(e,t=Hv.get()){if(e instanceof fw)return e;if(Lv.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new fw(r)}if(e.publicKey)return e.publicKey;if(pc.isBufferSource(e))return new fw(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){hw.isAsnEncoded(e)?super(e,Hb):super(e),this.tag=uw.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]||Hv.get()):t=e[0]||Hv.get();let i=this.rawData;const n=Nu.parse(this.rawData,Hb);return n.algorithm.algorithm===Jy&&(i=function(e){return e.algorithm=new Lb({algorithm:qy,parameters:null}),Nu.serialize(e)}(n)),t.subtle.importKey("spki",i,s,!0,r)}onInit(e){const t=qA.resolve(YI),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case qy:{const t=Nu.parse(e.subjectPublicKey,SA),s=pc.toUint8Array(t.modulus);r.publicExponent=pc.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]||Hv.get()):r=e[0]||Hv.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=Hv.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=Hv.get();const s=Nu.parse(this.rawData,Hb);return await t.subtle.digest(r,s.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=Nu.parse(this.rawData,Hb);return e.Algorithm=Nv.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===Cy?e["EC Point"]=t.subjectPublicKey:e["Raw Data"]=t.subjectPublicKey,e}}class gw extends Mv{static async create(e,t=!1,r=Hv.get()){if("name"in e&&"serialNumber"in e)return new gw(e,t);const s=await fw.create(e,r),i=await s.getKeyIdentifier(r);return new gw(wc.ToHex(i),t)}constructor(...e){if(pc.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new Ep({keyIdentifier:new Sp(wc.FromHex(e[0]))});super(wp,e[1],Nu.serialize(t))}else{const t=e[0],r=t.name instanceof aw?Nu.parse(t.name.rawData,Bp):t.name,s=new Ep({authorityCertIssuer:r,authorityCertSerialNumber:wc.FromHex(t.serialNumber)});super(wp,e[1],Nu.serialize(s))}}onInit(e){super.onInit(e);const t=Nu.parse(e.extnValue,Ep);t.keyIdentifier&&(this.keyId=wc.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?wc.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Nu.parse(this.value,Ep);return t.authorityCertIssuer&&(e["Authority Issuer"]=new aw(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}gw.NAME="Authority Key Identifier";class pw extends Mv{constructor(...e){if(pc.isBufferSource(e[0])){super(e[0]);const t=Nu.parse(this.value,kp);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new kp({cA:e[0],pathLenConstraint:e[1]});super(Cp,e[2],Nu.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 bw,mw;pw.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"}(bw||(bw={}));class yw extends Mv{constructor(...e){if(pc.isBufferSource(e[0])){super(e[0]);const t=Nu.parse(this.value,rb);this.usages=t.map(e=>e)}else{const t=new rb(e[0]);super(tb,e[1],Nu.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(e=>Tv.toString(e)).join(", "),e}}yw.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"}(mw||(mw={}));class Aw extends Mv{constructor(...e){if(pc.isBufferSource(e[0])){super(e[0]);const t=Nu.parse(this.value,bb);this.usages=t.toNumber()}else{const t=new bb(e[0]);super(fb,e[1],Nu.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Nu.parse(this.value,bb);return e[""]=t.toJSON().join(", "),e}}Aw.NAME="Key Usages";class Iw extends Mv{static async create(e,t=!1,r=Hv.get()){const s=await fw.create(e,r),i=await s.getKeyIdentifier(r);return new Iw(wc.ToHex(i),t)}constructor(...e){if(pc.isBufferSource(e[0])){super(e[0]);const t=Nu.parse(this.value,Ob);this.keyId=wc.ToHex(t)}else{const t="string"==typeof e[0]?wc.FromHex(e[0]):e[0],r=new Ob(t);super(Rb,e[1],Nu.serialize(r)),this.keyId=wc.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Nu.parse(this.value,Ob);return e[""]=t,e}}Iw.NAME="Subject Key Identifier";class vw extends Mv{constructor(...e){pc.isBufferSource(e[0])?super(e[0]):super(Cb,e[1],new aw(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Nu.parse(e.extnValue,kb);this.names=new aw(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}vw.NAME="Subject Alternative Name";class ww{static register(e,t){this.items.set(e,t)}static create(e){const t=new Mv(e),r=this.items.get(t.type);return r?new r(e):t}}ww.items=new Map;class Sw extends Mv{constructor(...e){var t;if(pc.isBufferSource(e[0])){super(e[0]);const t=Nu.parse(this.value,Hp);this.policies=t.map(e=>e.policyIdentifier)}else{const r=e[0],s=null!==(t=e[1])&&void 0!==t&&t,i=new Hp(r.map(e=>new Lp({policyIdentifier:e})));super(Up,s,Nu.serialize(i)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new Uv("",{},Tv.toString(e))),e}}Sw.NAME="Certificate Policies",ww.register(Up,Sw);class Ew extends Mv{constructor(...e){var t;if(pc.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map(e=>new qp({distributionPoint:new jp({fullName:[new lp({uniformResourceIdentifier:e})]})})),r=new zp(t);super(Fp,e[1],Nu.serialize(r))}else{const t=new zp(e[0]);super(Fp,e[1],Nu.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=Nu.parse(e.extnValue,zp);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 nw(e).toString()).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map(e=>e.toString()).join(", ")),r}),e}}Ew.NAME="CRL Distribution Points";class Cw extends Mv{constructor(...e){var t,r,s,i;if(pc.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof vp){const t=new vp(e[0]);super(Ap,e[1],Nu.serialize(t))}else{const t=e[0],r=new vp;xw(r,t,fp,"ocsp"),xw(r,t,gp,"caIssuers"),xw(r,t,pp,"timeStamping"),xw(r,t,bp,"caRepository"),super(Ap,e[1],Nu.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=[],Nu.parse(e.extnValue,vp).forEach(e=>{switch(e.accessMethod){case fp:this.ocsp.push(new nw(e.accessLocation));break;case gp:this.caIssuers.push(new nw(e.accessLocation));break;case pp:this.timeStamping.push(new nw(e.accessLocation));break;case bp:this.caRepository.push(new nw(e.accessLocation))}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&kw(e,"OCSP",this.ocsp),this.caIssuers.length&&kw(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&kw(e,"Time Stamping",this.timeStamping),this.caRepository.length&&kw(e,"CA Repository",this.caRepository),e}}function kw(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const s=new Uv("");r.forEach((e,t)=>{const r=e.toTextObject(),i=`${r[Uv.NAME]} ${t+1}`;let n=s[i];Array.isArray(n)||(n=[],s[i]=n),n.push(r)}),e[t]=s}}function xw(e,t,r,s){const i=t[s];i&&(Array.isArray(i)?i:[i]).forEach(t=>{"string"==typeof t&&(t=new nw("url",t)),e.push(new Ip({accessMethod:r,accessLocation:Nu.parse(t.rawData,lp)}))})}Cw.NAME="Authority Info Access";class Bw extends Dv{constructor(...e){let t;if(pc.isBufferSource(e[0]))t=pc.toArrayBuffer(e[0]);else{const r=e[0],s=Array.isArray(e[1])?e[1].map(e=>pc.toArrayBuffer(e)):[];t=Nu.serialize(new xb({type:r,values:s}))}super(t,xb)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new Uv("",{"":e})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[Uv.NAME]===Bw.NAME&&(e[Uv.NAME]=Tv.toString(this.type)),e}}Bw.NAME="Attribute";class _w extends Bw{constructor(...e){var t;if(pc.isBufferSource(e[0]))super(e[0]);else{const t=new VI({printableString:e[0]});super(vI,[Nu.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=Nu.parse(this.values[0],VI);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[Uv.VALUE]=this.password,e}}_w.NAME="Challenge Password";class Rw extends Bw{constructor(...e){var t;if(pc.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new $b;for(const e of t)r.push(Nu.parse(e.rawData,Fb));super(wI,[Nu.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=Nu.parse(this.values[0],$b);this.items=e.map(e=>ww.create(Nu.serialize(e)))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(const r of t)e[r[Uv.NAME]]=r;return e}}Rw.NAME="Extensions";class Ow{static register(e,t){this.items.set(e,t)}static create(e){const t=new Bw(e),r=this.items.get(t.type);return r?new r(e):t}}Ow.items=new Map;const Uw="crypto.signatureFormatter";var Tw;let Nw=Tw=class{static createPssParams(e,t){const r=Tw.getHashAlgorithm(e);return r?new mA({hashAlgorithm:r,maskGenAlgorithm:new Lb({algorithm:uA,parameters:Nu.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=qA.resolve(YI);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 Lb({algorithm:qy,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 Lb({algorithm:Zy,parameters:null});case"sha-256":return new Lb({algorithm:tA,parameters:null});case"sha-384":return new Lb({algorithm:rA,parameters:null});case"sha-512":return new Lb({algorithm:sA,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=Tw.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new Lb({algorithm:Jy,parameters:Nu.serialize(t)})}return new Lb({algorithm:Jy,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case qy:return{name:"RSASSA-PKCS1-v1_5"};case Zy:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case tA:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case rA:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case sA:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case Jy:if(e.parameters){const t=Nu.parse(e.parameters,mA);return{name:"RSA-PSS",hash:qA.resolve(YI).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};Nw=Tw=Du([zA()],Nw),qA.registerSingleton(JI,Nw);let Dw=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new Lb({algorithm:aA});case"sha-256":return new Lb({algorithm:cA});case"sha-384":return new Lb({algorithm:lA});case"sha-512":return new Lb({algorithm:dA})}return null}toWebAlgorithm(e){switch(e.algorithm){case aA:return{name:"SHA-1"};case cA:return{name:"SHA-256"};case lA:return{name:"SHA-384"};case dA:return{name:"SHA-512"}}return null}};Dw=Du([zA()],Dw),qA.registerSingleton(JI,Dw);class Mw{addPadding(e,t){const r=pc.toUint8Array(t),s=new Uint8Array(e);return s.set(r,e-r.length),s}removePadding(e,t=!1){let r=pc.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=Mw.namedCurveSize.get(r)||Mw.defaultNamedCurveSize,i=new Gy,n=pc.toUint8Array(t);return i.r=this.removePadding(n.slice(0,s),!0),i.s=this.removePadding(n.slice(s,s+s),!0),Nu.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=Nu.parse(t,Gy),s=e.namedCurve,i=Mw.namedCurveSize.get(s)||Mw.defaultNamedCurveSize;return Sc(this.addPadding(i,this.removePadding(r.r)),this.addPadding(i,this.removePadding(r.s)))}return null}}Mw.namedCurveSize=new Map,Mw.defaultNamedCurveSize=32;const Pw="1.3.101.110",Lw="1.3.101.111",Hw="1.3.101.112",Vw="1.3.101.113";let Kw=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=Hw;break;case"x25519":t=Pw;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=Hw;break;case"ed448":t=Vw}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=Pw;break;case"x448":t=Lw}}return t?new Lb({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case Hw:return{name:"Ed25519"};case Vw:return{name:"EdDSA",namedCurve:"Ed448"};case Pw:return{name:"X25519"};case Lw:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};Kw=Du([zA()],Kw),qA.registerSingleton(JI,Kw);(class extends hw{constructor(e){hw.isAsnEncoded(e)?super(e,WI):super(e),this.tag=uw.CertificateRequestTag}onInit(e){this.tbs=Nu.serialize(e.certificationRequestInfo),this.publicKey=new fw(e.certificationRequestInfo.subjectPKInfo);const t=qA.resolve(YI);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>Ow.create(Nu.serialize(e)));const r=this.getAttribute(wI);this.extensions=[],r instanceof Rw&&(this.extensions=r.items),this.subjectName=new $v(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=Hv.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),s=qA.resolveAll(Uw).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=Nu.parse(this.rawData,WI),r=t.certificationRequestInfo,s=new Uv("",{Version:`${Gb[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new Uv("");for(const t of this.attributes){const r=t.toTextObject();e[r[Uv.NAME]]=r}s.Attributes=e}return e.Data=s,e.Signature=new Uv("",{Algorithm:Nv.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";class Qw extends hw{constructor(e){hw.isAsnEncoded(e)?super(e,qb):super(e),this.tag=uw.CertificateTag}onInit(e){const t=e.tbsCertificate;this.tbs=Nu.serialize(t),this.serialNumber=wc.ToHex(t.serialNumber),this.subjectName=new $v(t.subject),this.subject=new $v(t.subject).toString(),this.issuerName=new $v(t.issuer),this.issuer=this.issuerName.toString();const r=qA.resolve(YI);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=>ww.create(Nu.serialize(e)))),this.publicKey=new fw(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=Hv.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 fw)r={...i.algorithm,...this.signatureAlgorithm},s=await i.export(r,["verify"],t);else if(pc.isBufferSource(i)){const e=new fw(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=qA.resolveAll(Uw).reverse();let a=null;for(const e of n)if(a=e.toWebSignature(r,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const o=await t.subtle.verify(this.signatureAlgorithm,s,a,this.tbs);if(e.signatureOnly)return o;{const t=(e.date||new Date).getTime();return o&&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=Hv.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=Hv.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=Nu.parse(this.rawData,qb),r=t.tbsCertificate,s=new Uv("",{Version:`${Gb[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":Nv.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new Uv("",{"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 Uv("");for(const t of this.extensions){const r=t.toTextObject();e[r[Uv.NAME]]=r}s.Extensions=e}return e.Data=s,e.Signature=new Uv("",{Algorithm:Nv.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}Qw.NAME="Certificate";class Fw{static async createSelfSigned(e,t=Hv.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},t)}static async create(e,t=Hv.get()){var r;let s;s=e.publicKey instanceof fw?e.publicKey.rawData:"publicKey"in e.publicKey?e.publicKey.publicKey.rawData:pc.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey("spki",e.publicKey);const i=e.serialNumber?pc.toUint8Array(wc.FromHex(e.serialNumber)):t.getRandomValues(new Uint8Array(16));i[0]>127&&(i[0]&=127),i.length>1&&0===i[0]&&(i[1]|=128);const n=e.notBefore||new Date,a=e.notAfter||new Date(n.getTime()+31536e6),o=new qb({tbsCertificate:new jb({version:Gb.v3,serialNumber:i,validity:new Kb({notBefore:n,notAfter:a}),extensions:new $b((null===(r=e.extensions)||void 0===r?void 0:r.map(e=>Nu.parse(e.rawData,Fb)))||[]),subjectPublicKeyInfo:Nu.parse(s,Hb)})});if(e.subject){const t=e.subject instanceof $v?e.subject:new $v(e.subject);o.tbsCertificate.subject=Nu.parse(t.toArrayBuffer(),np)}if(e.issuer){const t=e.issuer instanceof $v?e.issuer:new $v(e.issuer);o.tbsCertificate.issuer=Nu.parse(t.toArrayBuffer(),np)}const c={hash:"SHA-256"},l="signingKey"in e?{...c,...e.signingAlgorithm,...e.signingKey.algorithm}:{...c,...e.signingAlgorithm},d=qA.resolve(YI);o.tbsCertificate.signature=o.signatureAlgorithm=d.toAsnAlgorithm(l);const u=Nu.serialize(o.tbsCertificate),h="signingKey"in e?await t.subtle.sign(l,e.signingKey,u):e.signature,f=qA.resolveAll(Uw).reverse();let g=null;for(const e of f)if(g=e.toAsnSignature(l,h),g)break;if(!g)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return o.signatureValue=g,new Qw(Nu.serialize(o))}}var $w;!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"}($w||($w={})),ww.register(Cp,pw),ww.register(tb,yw),ww.register(fb,Aw),ww.register(Rb,Iw),ww.register(wp,gw),ww.register(Cb,vw),ww.register(Fp,Ew),ww.register(Ap,Cw),Ow.register(vI,_w),Ow.register(wI,Rw),qA.registerSingleton(Uw,class{toAsnSignature(e,t){return pc.toArrayBuffer(t)}toWebSignature(e,t){return pc.toArrayBuffer(t)}}),qA.registerSingleton(Uw,Mw),Mw.namedCurveSize.set("P-256",32),Mw.namedCurveSize.set("K-256",32),Mw.namedCurveSize.set("P-384",48),Mw.namedCurveSize.set("P-521",66);const Gw=ri.new(void 0,"net"),jw=new class extends Sf{constructor(){super(...arguments),this.subtle=new Wg}getRandomValues(e){if(!ArrayBuffer.isView(e))throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'");const t=Bf.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return Rf().randomFillSync(t),e}};Hv.set(jw);const qw="Ed25519",zw="OKP";var Ww,Jw,Yw;function Xw(e){return`e${function(e){function t(t){const r=t>>3,s=t%8;return(e.at(r)??0)>>s&1}const r=[];for(let s=0;s<8*e.length;s+=5){let e=0;for(let r=s+4;r>=s;r--)e<<=1,e|=t(r);r.push("abcdefghijklmnopqrstuvwxyz234567"[e])}return r.join("")}(e.raw)}`}function Zw(e){const t=new Uint8Array(Buffer.from(e.x??"","base64url"));return Xw(P.blobFrom(t))}async function eS(e,t){if(e.kty!==zw)throw new Error(`Unsupported key type ${e.kty}`);const r={name:"EdDSA",namedCurve:qw};return await jw.subtle.importKey("jwk",e,r,!0,[t===Jw.Public?"verify":"sign"])}function tS(e){return`${e.toString("pem")}\n`}function rS(e){return{key:sS(e._privKey.raw),ops:{async sign(e,t){const r=await Ir(L.fromBlob(new Uint8Array(e),mr).asOpaque());return sS((await vr(r,P.blobFrom(new Uint8Array(t)))).raw)},async verify(e,t,r){const s=await Ir(L.fromBlob(new Uint8Array(e),mr).asOpaque());return(await wr([{signature:L.fromBlob(new Uint8Array(r),yr).asOpaque(),key:s.pubKey,message:P.blobFrom(new Uint8Array(t))}]))[0]}}}}function sS(e){if(e.buffer instanceof ArrayBuffer)return e.buffer;const t=new ArrayBuffer(e.length);return new Uint8Array(t).set(e,0),t}function iS(){const e={info:null,verifyCallback:async(t,r)=>{const s=await async function(e){if(Gw.log("Incoming peer. Verifying certificate"),1!==e.length)return Gw.log("Rejecting peer with no certificates."),D.error(Ww.NoCertificate);const t=new(gc().X509Certificate)(e[0]);if(t.publicKey.asymmetricKeyType!==qw.toLowerCase())return Gw.log(`Rejecting peer using non-ed25519 certificate: ${t.publicKey.asymmetricKeyType}`),D.error(Ww.NotEd25519);const r=t.publicKey.export({format:"jwk"});if(r.kty!==zw||r.crv!==qw)return Gw.log(`Public key type mismatch: ${r.kty}, ${r.crv}`),D.error(Ww.PublicKeyTypeMismatch);const s=Zw(r),i=(t.subjectAltName??"").match(/DNS:([^,]+)/);if(null===i||i[1]!==s)return Gw.log(`AltName mismatch. Expected: '${s}', got: '${i?.[1]}'`),D.error(Ww.AltNameMismatch);const n=Buffer.from(r.x??"","base64url");if(!t.verify(t.publicKey))return D.error(Ww.IncorrectSignature);const a=L.fromBlob(new Uint8Array(n),mr);return D.ok({id:s,key:a.asOpaque()})}(t);if(s.isError)return function(e){if(void 0===e)return e;switch(e){case Ww.AltNameMismatch:return tc.IllegalParameter;case Ww.NotEd25519:return tc.InsufficientSecurity;case Ww.PublicKeyTypeMismatch:return tc.BadCertificate;case Ww.NoCertificate:return tc.CertificateRequired;case Ww.IncorrectSignature:return tc.BadCertificate;default:throw new Error(`Unexpected VerifyCertError: ${e}`)}}(s.error);e.info=s.ok}};return e}!function(e){e[e.NoCertificate=0]="NoCertificate",e[e.NotEd25519=1]="NotEd25519",e[e.PublicKeyTypeMismatch=2]="PublicKeyTypeMismatch",e[e.AltNameMismatch=3]="AltNameMismatch",e[e.IncorrectSignature=4]="IncorrectSignature"}(Ww||(Ww={})),function(e){e[e.Public=0]="Public",e[e.Private=1]="Private"}(Jw||(Jw={})),function(e){e[e.LocalClose=0]="LocalClose",e[e.RemoteClose=1]="RemoteClose",e[e.Exception=2]="Exception"}(Yw||(Yw={}));const nS=ri.new(void 0,"peers");function aS(e){return`${e.id}@${e.address.host}:${e.address.port}`}class oS{_onPeerConnected=[];_onPeerDisconnected=[];peers=new Map;peerConnected(e){nS.info(`💡 Peer ${aS(e)} connected.`),void 0!==this.peers.get(e.id)&&nS.warn("Replacing older connection."),this.peers.set(e.id,e);for(const t of this._onPeerConnected)t(e)}peerDisconnected(e){nS.info(`⚡︎Peer ${aS(e)} disconnected.`),this.peers.delete(e.id);for(const t of this._onPeerDisconnected)t(e)}isConnected(e){return this.peers.has(e)}noOfConnectedPeers(){return this.peers.size}onPeerConnected(e){return this._onPeerConnected.push(e),()=>{const t=this._onPeerConnected.indexOf(e);-1!==t&&this._onPeerConnected.splice(t,1)}}onPeerDisconnected(e){return this._onPeerDisconnected.push(e),()=>{const t=this._onPeerDisconnected.indexOf(e);-1!==t&&this._onPeerDisconnected.splice(t,1)}}}const cS=ri.new(void 0,"net");class lS{socket;server;_dial;_peers;listen;started=!1;constructor(e,t,r,s,i){this.socket=e,this.server=t,this._dial=r,this._peers=s,this.listen=i}get isRunning(){return this.started}async start(){if(this.started)throw new Error("Network already started!");this.started=!0,await this.socket.start({host:this.listen.host,port:this.listen.port}),cS.info(`🛜 QUIC socket on ${this.socket.host}:${this.socket.port}`),await this.server.start(),cS.log("🛜 QUIC server listening")}async stop(){if(!this.started)throw new Error("Network not started yet!");cS.info("Stopping the networking."),await this.server.stop(),await this.socket.stop(),this.started=!1,cS.info("Networking stopped.")}get peers(){return this._peers}async dial(e,t={}){return this._dial(e,t)}}const dS=ri.new(void 0,"net");function uS(e,t,r){e.addEventListener(t.name,async e=>{try{await r(e)}catch(e){dS.error(`Unhandled exception in ${t.name} event handler: ${e}`)}})}class hS{stream;constructor(e){this.stream=e}get streamId(){return this.stream.streamId}get readable(){return this.stream.readable}get writable(){return this.stream.writable}addOnError(e){uS(this.stream,Ro,t=>{const r=t.detail instanceof Na||t.detail instanceof Da||t.detail instanceof ka,s=t.detail instanceof Ba,i=r?Yw.LocalClose:s?Yw.RemoteClose:Yw.Exception;e(t.detail,i)})}destroy(){return this.stream.destroy()}}const fS=ri.new(void 0,"peers");class gS{conn;connectionId;address;id;key;streamEvents=new(Wn());constructor(e,t){this.conn=e,fS.log(`👥 [${t.id}] peer connected ${e.remoteHost}:${e.remotePort}`),this.connectionId=e.connectionIdShared.toString(),this.address={host:e.remoteHost,port:e.remotePort},this.id=t.id,this.key=t.key,uS(e,ko,e=>{const t=e.detail;fS.log(`🚰 [${this.id}] new stream: [${t.streamId}]`),this.streamEvents.emit("stream",new hS(t))}),uS(e,Eo,e=>{fS.error(`❌ [${this.id}] connection failed: ${e.detail}`)})}addOnIncomingStream(e){this.streamEvents.on("stream",e)}openStream(){const e=this.conn.newStream("bidi");return fS.log(`🚰 [${this.id}] opening stream: [${e.streamId}]`),new hS(e)}async disconnect(){fS.log(`👋 [${this.id}] disconnecting`),await this.conn.stop({isApp:!0})}}const pS=ri.new(void 0,"net");class bS{static async setup({host:e,port:t,protocols:r,key:s}){const i=ri.getLevel("net")>qs.TRACE?si.WARN:si.DEBUG,n=new vi("quic",i,[new Si(bi`${li}:${ui}:${fi}`)]),a=function(e){const t={kty:zw,crv:qw,x:Buffer.from(e.pubKey.raw).toString("base64url"),d:Buffer.from(e._privKey.raw).toString("base64url")};return{publicKey:{...t,d:void 0},privateKey:{...t,x:void 0}}}(s),o=await async function(e){const t=await eS(e.privateKey,Jw.Private),r=await jw.subtle.exportKey("pkcs8",t);return["-----BEGIN PRIVATE KEY-----",...Buffer.from(r).toString("base64").match(/.{1,64}/g)??[],"-----END PRIVATE KEY-----",""].join("\n")}(a),c=await async function({certId:e,subjectKeyPair:t,issuerKeyPair:r,subjectAttrsExtra:s=[],issuerAttrsExtra:i=[],now:n=new Date}){const a=await eS(t.publicKey,Jw.Public),o=await eS(t.privateKey,Jw.Private),c=await eS(r.privateKey,Jw.Private),l=await eS(r.publicKey,Jw.Public),d=new Date(n.getTime()-n.getTime()%1e3),u=new Date(n.getTime()-n.getTime()%1e3+2e3),h=await jw.subtle.digest("SHA-256",await jw.subtle.exportKey("spki",a)),f=await jw.subtle.digest("SHA-256",await jw.subtle.exportKey("spki",l)),g=e.toString().substring(2),p=Buffer.from(h).toString("hex"),b=Buffer.from(f).toString("hex"),m={serialNumber:g,notBefore:d,notAfter:u,subject:[{CN:[p]},...s.filter(e=>!("CN"in e))],issuer:[{CN:[b]},...i.filter(e=>!("CN"in e))],signingAlgorithm:c.algorithm,publicKey:a,signingKey:o,extensions:[new pw(!0),new Aw(mw.keyCertSign|mw.cRLSign|mw.digitalSignature|mw.nonRepudiation|mw.keyAgreement|mw.keyEncipherment|mw.dataEncipherment),new yw([]),new vw([{type:"dns",value:Zw(t.publicKey)}]),await Iw.create(a)]};return m.signingKey=c,await Fw.create(m)}({certId:P.blobFromString("QUIC Networking"),subjectKeyPair:a,issuerKeyPair:a}),l=iS(),d={keepAliveIntervalTime:3e3,maxIdleTimeout:6e3,applicationProtos:r,cert:tS(c),key:o,verifyPeer:!0,verifyCallback:l.verifyCallback};pS.info(`🆔 Peer id: ** ${Xw(s.pubKey)}@${e}:${t} ** (pubkey: ${s.pubKey})`);const u=new Mo({logger:n.getChild("socket")}),h=new lc({socket:u,config:d,crypto:rS(s),logger:n.getChild("server")}),f=new oS;function g(e,t){const r=new gS(e,t);return uS(r.conn,Co,()=>f.peerDisconnected(r)),f.peerConnected(r),r}return uS(h,Io,e=>pS.error(`🛜 Server error: ${e}`)),uS(h,vo,e=>pS.error(`🛜 Server stopped: ${e}`)),uS(h,Ao,async e=>{const t=e.detail;if(null!==l.info){if(l.info.key.isEqualTo(s.pubKey))return pS.log(`🛜 Rejecting connection from ourself from ${t.remoteHost}:${t.remotePort}`),void await t.stop();if(f.isConnected(l.info.id))return pS.log(`🛜 Rejecting duplicate connection with peer ${l.info.id} from ${t.remoteHost}:${t.remotePort}`),void await t.stop();pS.log(`🛜 Server handshake with ${t.remoteHost}:${t.remotePort}`),g(t,l.info),l.info=null,await t.start()}else await t.stop()}),new lS(u,h,async function(e,t){const r=iS(),s=hc.createQUICClient({socket:u,host:e.host,port:e.port,crypto:{ops:{async randomBytes(e){fc.webcrypto.getRandomValues(new Uint8Array(e))}}},config:{...d,verifyCallback:r.verifyCallback},logger:n.getChild("client")},{signal:t.signal}),i=await s;if(uS(i,mo,()=>{pS.log("⚰️ Client connection closed.")}),uS(i,po,e=>{pS.error(`🔴 Client error: ${e.detail}`)}),null===r.info)throw new Error("Client connected, but there is no peer details!");if(void 0!==t.verifyName&&t.verifyName!==r.info.id)throw new Error(`Client connected, but the id didn't match. Expected: ${t.verifyName}, got: ${r.info.id}`);return pS.log(`🤝 Client handshake with: ${e.host}:${e.port}`),g(i.connection,r.info)},f,{host:e,port:t})}}const mS=t(import.meta.url)("node:buffer");function yS(e){return de(ne(e.length))}function AS(e,t){let r=mS.Buffer.alloc(0),s=-1;return i=>{r=mS.Buffer.concat([r,i]);do{if(-1===s){if(r.length<4)break;s=r.readUint32LE(),r=r.subarray(4)}if(r.length<s)break;if(r.length>16777216){t();break}const i=r.subarray(0,s);r=r.subarray(s),s=-1,e(new Uint8Array(i))}while(r.length>0)}}class IS{id;ip;port;constructor(e,t,r){this.id=e,this.ip=t,this.port=r}get host(){return this.ip}toString(){return`${this.id}@${this.ip}:${this.port}`}}const vS=ri.new(void 0,"net:conn");class wS{network;peerInfo=new Map;constructor(e){this.network=e,e.peers.onPeerConnected(e=>(this.updatePeer(e),O)),e.peers.onPeerDisconnected(e=>(this.scheduleReconnect(e.id),O))}setAuxData(e,t,r){this.peerInfo.get(e)?.aux.set(t.id,r)}getAuxData(e,t){return this.peerInfo.get(e)?.aux.get(t.id)}withAuxData(e,t,r){const s=r(this.getAuxData(e,t));this.setAuxData(e,t,s)}getPeerCount(){return this.network.peers.noOfConnectedPeers()}*getConnectedPeers(){for(const e of this.peerInfo.values())null!==e.peerRef&&(yield e)}updatePeer(e){const t=this.peerInfo.get(e.id);void 0!==t?(t.peerRef=e,t.lastConnected=Date.now(),t.currentRetry=Math.floor(t.currentRetry/2),t.address=e.address):this.peerInfo.set(e.id,{peerId:e.id,address:e.address,peerRef:e,lastConnected:Date.now(),maxRetries:5,currentRetry:0,backgroundTask:new AbortController,aux:new Map})}async scheduleReconnect(e){const t=this.peerInfo.get(e);if(void 0===t)return;t.peerRef=null,t.backgroundTask=new AbortController;const r=t.backgroundTask.signal;for(;;){if(t.currentRetry+=1,t.currentRetry>=t.maxRetries)return this.peerInfo.delete(e),void vS.log(`[${e}] max retries reached. Removing peer.`);const s=Math.min(3*t.currentRetry*t.currentRetry,3600);try{await(0,js.setTimeout)(1e3*s,void 0,{signal:r})}catch{return}if(null!==t.peerRef)return;try{return vS.trace(`[${e}] Attempting to connect to peer at ${t.address.host}:${t.address.port}.`),void await this.network.dial(t.address,{signal:r,verifyName:t.peerId})}catch{if(r.aborted)return;vS.trace(`[${e}] attempt failed. Will retry (${t.currentRetry}/${t.maxRetries})`)}}}addPersistentRetry(e){for(const t of e)this.peerInfo.set(t.id,{peerId:t.id,address:{host:t.host,port:t.port},maxRetries:2**32,currentRetry:0,peerRef:null,lastConnected:0,backgroundTask:new AbortController,aux:new Map}),this.scheduleReconnect(t.id)}}function SS(e){return te(e)}function ES(e,t){return e().catch(t)}const CS=ri.new(void 0,"stream");class kS{incomingHandlers=new Map;outgoingHandlers=new Map;streams=new Map;backgroundTasks=new Map;registerIncomingHandlers(...e){for(const t of e)this.incomingHandlers.set(t.kind,t)}registerOutgoingHandlers(...e){for(const t of e)this.outgoingHandlers.set(t.kind,t)}getPeer(e){return this.streams.get(e)?.peer??null}async waitForFinish(){for(const e of this.backgroundTasks.values())await e}withStreamOfKind(e,t,r){for(const s of this.streams.values())if(s.handler.kind===t&&s.peer.id===e)return void r(s.handler,s.streamSender)}withNewStream(e,t,r){const s=this.outgoingHandlers.get(t);if(void 0===s)throw new Error(`Unsupported outgoing stream kind: ${t}`);const i=e.openStream(),n=this.registerStream(e,s,i,P.empty());n.bufferAndSend(P.blobFromNumbers([t]),!1),r(s,n)}async onIncomingStream(e,t){const{readable:r,streamId:s}=t,i=r.getReader();let n=P.empty();try{const t=await i.read();n=P.blobFrom(void 0!==t.value?t.value:new Uint8Array),CS.trace(`🚰 --\x3e [${e.id}:${s}] Initial data: ${n}`)}finally{i.releaseLock()}if(n.raw.length<1)throw new Error(`Expected 1-byte stream identifier, got: ${n}`);const a=SS(n.raw[0]),o=this.incomingHandlers.get(a);if(void 0===o)throw new Error(`Unsupported stream kind: ${a}`);CS.log(`🚰 --\x3e [${e.id}:${t.streamId}] Stream identified as: ${a}`),this.registerStream(e,o,t,P.blobFrom(n.raw.subarray(1)))}registerStream(e,t,r,s){const i=(n=r.streamId,ne(n));var n;const a=(r,s)=>{this.streams.delete(i),this.backgroundTasks.delete(i),s===Yw.Exception&&CS.error(`🚰 --- [${e.id}:${i}] Stream error: ${r}. Disconnecting peer.`),s!==Yw.LocalClose&&(t.onClose(i,!0),e.disconnect())};r.addOnError(a);const o=new xS(i,r,a);this.streams.set(i,{handler:t,streamSender:o,peer:e});const c=ES(()=>async function(e,t,r,s,i){let n=s,a=!1;const o=AS(s=>{const i=P.blobFrom(new Uint8Array(s));CS.trace(`🚰 --\x3e [${e.id}:${r.streamId}] ${i}`),t.onStreamMessage(r,i)},()=>{CS.error(`🚰 --\x3e [${e.id}:${r.streamId}] got too much data. Disconnecting.`),e.disconnect()});for(;;){if(o(n.raw),a)return void CS.log(`🚰 --\x3e [${e.id}:${r.streamId}] remote finished.`);const t=await i.read();a=t.done,n=P.blobFrom(void 0!==t.value?t.value:new Uint8Array)}}(e,t,o,s,r.readable.getReader()),e=>a(e,Yw.Exception));return this.streams.has(i)&&this.backgroundTasks.set(i,c),o}}class xS{streamId;internal;onError;bufferedLength=0;bufferedData=[];currentWriterPromise=null;constructor(e,t,r){this.streamId=e,this.internal=t,this.onError=r}bufferAndSend(e,t=!0){return!(this.bufferedLength>16384||(this.bufferedData.push({data:e,addPrefix:t}),this.bufferedLength+=e.length,null!==this.currentWriterPromise||(this.currentWriterPromise=ES(async()=>{const e=this.internal.writable.getWriter();try{for(;;){const t=this.bufferedData.shift();if(void 0===t)return;const{data:r,addPrefix:s}=t;CS.trace(`🚰 <-- [${this.streamId}] write: ${r}`),s&&await e.write(yS(r.raw)),await e.write(r.raw),this.bufferedLength-=r.length}}finally{e.releaseLock(),this.currentWriterPromise=null}},e=>this.onError(e,Yw.Exception))),0))}close(){ES(async()=>{CS.trace(`🚰 <-- [${this.streamId}] closing`),null!==this.currentWriterPromise&&await this.currentWriterPromise,await this.internal.writable.close()},e=>this.onError(e,Yw.Exception))}flush(){return this.currentWriterPromise??Promise.resolve()}}const BS=SS(128);var _S;!function(e){e[e.AscExcl=0]="AscExcl",e[e.DescIncl=1]="DescIncl"}(_S||(_S={}));class RS extends B{headerHash;direction;maxBlocks;static Codec=Be.Class(RS,{headerHash:Be.bytes(Pe).asOpaque(),direction:Be.u8.convert(e=>te(e),e=>{switch(e){case _S.AscExcl:return _S.AscExcl;case _S.DescIncl:return _S.DescIncl;default:throw new Error(`Invalid 'Direction' value: ${e}`)}}),maxBlocks:Be.u32});static create({headerHash:e,direction:t,maxBlocks:r}){return new RS(e,t,r)}constructor(e,t,r){super(),this.headerHash=e,this.direction=t,this.maxBlocks=r}}const OS=ri.new(void 0,"protocol/ce-128");class US{chainSpec;getBlockSequence;kind=BS;constructor(e,t){this.chainSpec=e,this.getBlockSequence=t}onStreamMessage(e,t){const r=fe.decodeObject(RS.Codec,t);OS.log(`[${e.streamId}] Client has requested: ${r}`);const s=this.getBlockSequence(e.streamId,r.headerHash,r.direction,r.maxBlocks);e.bufferAndSend(Ae.encodeObject(Be.sequenceFixLen(vs.Codec.View,s.length),s,this.chainSpec)),e.close()}onClose(){}}class TS{chainSpec;kind=BS;promiseResolvers=new Map;promiseRejectors=new Map;constructor(e){this.chainSpec=e}onStreamMessage(e,t){if(!this.promiseResolvers.has(e.streamId))throw new Error("Received an unexpected message from the server.");const r=fe.decodeSequence(vs.Codec.View,t,this.chainSpec);OS.log(`[${e.streamId}] Server returned ${r.length} blocks in ${t.length} bytes of data.`),this.promiseResolvers.get(e.streamId)?.(r),this.promiseResolvers.delete(e.streamId)}onClose(e){this.promiseRejectors.get(e)?.("Stream closed."),this.promiseResolvers.delete(e),this.promiseRejectors.delete(e)}async requestBlockSequence(e,t,r,s){if(this.promiseResolvers.has(e.streamId))throw new Error("It is disallowed to use the same stream for multiple requests.");return new Promise((i,n)=>{this.promiseResolvers.set(e.streamId,i),this.promiseRejectors.set(e.streamId,n),e.bufferAndSend(Ae.encodeObject(RS.Codec,RS.create({headerHash:t,direction:r,maxBlocks:s}))),e.close()})}}var NS;!function(e){e[e.NoStartBlock=0]="NoStartBlock",e[e.BlockOnFork=1]="BlockOnFork"}(NS||(NS={}));const DS=SS(0);class MS extends B{hash;slot;static Codec=Be.Class(MS,{hash:Be.bytes(Pe).asOpaque(),slot:Be.u32.asOpaque()});static create({hash:e,slot:t}){return new MS(e,t)}constructor(e,t){super(),this.hash=e,this.slot=t}}class PS{final;leafs;static Codec=Be.Class(PS,{final:MS.Codec,leafs:Be.sequenceVarLen(MS.Codec)});static create({final:e,leafs:t}){return new PS(e,t)}constructor(e,t){this.final=e,this.leafs=t}}class LS extends B{header;final;static Codec=Be.Class(LS,{header:ps.Codec,final:MS.Codec});static create({header:e,final:t}){return new LS(e,t)}constructor(e,t){super(),this.header=e,this.final=t}}const HS=ri.new(void 0,"protocol/up-0");class VS{spec;getHandshake;onAnnouncement;onHandshake;kind=DS;handshakes=new Map;pendingHandshakes=new Map;constructor(e,t,r,s){this.spec=e,this.getHandshake=t,this.onAnnouncement=r,this.onHandshake=s}onStreamMessage(e,t){const{streamId:r}=e;if(!this.handshakes.has(r)){const s=fe.decodeObject(PS.Codec,t);return this.handshakes.set(r,s),this.pendingHandshakes.delete(r)||(HS.log(`[${r}] <-- responding with a handshake.`),e.bufferAndSend(Ae.encodeObject(PS.Codec,this.getHandshake()))),void this.onHandshake(r,s)}const s=fe.decodeObject(LS.Codec,t,this.spec);HS.log(`[${r}] --\x3e got blocks announcement: ${s.final}`),this.onAnnouncement(r,s)}onClose(e){this.handshakes.delete(e),this.pendingHandshakes.delete(e)}sendHandshake(e){const{streamId:t}=e;if(this.handshakes.has(t)||this.pendingHandshakes.has(t))return;const r=this.getHandshake();HS.trace(`[${t}] <-- sending handshake`),this.pendingHandshakes.set(e.streamId,!0),e.bufferAndSend(Ae.encodeObject(PS.Codec,r))}sendAnnouncement(e,t){const{streamId:r}=e;this.handshakes.has(r)?(HS.trace(`[${r}] <-- sending block announcement: ${t.final}`),e.bufferAndSend(Ae.encodeObject(LS.Codec,t,this.spec))):HS.warn(`[${r}] <-- no handshake yet, skipping announcement.`)}}const KS=31;var QS;!function(e){e[e.Branch=0]="Branch",e[e.Leaf=1]="Leaf",e[e.EmbedLeaf=2]="EmbedLeaf"}(QS||(QS={}));class FS{raw;constructor(e=new Uint8Array(64)){this.raw=e}getNodeType(){return 128&this.raw[0]?192&~this.raw[0]?QS.EmbedLeaf:QS.Leaf:QS.Branch}asBranchNode(){return w(this.getNodeType()===QS.Branch),new $S(this)}asLeafNode(){return w(this.getNodeType()!==QS.Branch),new GS(this)}toString(){return P.blobFrom(this.raw).toString()}}class $S{node;constructor(e){this.node=e}static fromSubNodes(e,t){const r=new FS;return r.raw.set(e.raw,0),r.raw.set(t.raw,Pe),r.raw[0]&=127,new $S(r)}getLeft(){return L.fromBlob(this.node.raw.subarray(0,Pe),Pe).asOpaque()}getRight(){return L.fromBlob(this.node.raw.subarray(Pe),Pe).asOpaque()}}class GS{node;constructor(e){this.node=e}static fromValue(e,t,r){const s=new FS;return t.length<=Pe?(s.raw[0]=128|t.length,s.raw.set(e.raw.subarray(0,KS),1),s.raw.set(t.raw,32)):(s.raw[0]=192,s.raw.set(e.raw.subarray(0,KS),1),s.raw.set(r().raw,32)),new GS(s)}getKey(){return L.fromBlob(this.node.raw.subarray(1,32),KS).asOpaque()}hasEmbeddedValue(){return this.node.getNodeType()===QS.EmbedLeaf}getValueLength(){return 63&this.node.raw[0]}getValue(){const e=this.getValueLength();return P.blobFrom(this.node.raw.subarray(Pe,Pe+e))}getValueHash(){return L.fromBlob(this.node.raw.subarray(Pe),Pe).asOpaque()}toString(){return`LeafNode {\n key: ${this.getKey()},\n valueHash: ${this.getValueHash()}\n}`}}const jS=SS(129),qS=Be.bytes(64).convert(e=>L.fromBlob(e.raw,64),e=>new FS(e.raw));class zS extends B{key;value;static Codec=Be.Class(zS,{key:Be.bytes(KS),value:Be.blob});static create({key:e,value:t}){return new zS(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}class WS extends B{keyValuePairs;static Codec=Be.Class(WS,{keyValuePairs:Be.sequenceVarLen(zS.Codec)});static create({keyValuePairs:e}){return new WS(e)}constructor(e){super(),this.keyValuePairs=e}}class JS extends B{headerHash;startKey;endKey;maximumSize;static Codec=Be.Class(JS,{headerHash:Be.bytes(Pe).asOpaque(),startKey:Be.bytes(KS),endKey:Be.bytes(KS),maximumSize:Be.u32});static create({headerHash:e,startKey:t,endKey:r,maximumSize:s}){return new JS(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.startKey=t,this.endKey=r,this.maximumSize=s}}const YS=ri.new(void 0,"protocol/ce-129");class XS{isServer;getBoundaryNodes;getKeyValuePairs;kind=jS;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(YS.info(`[${e.streamId}][server]: Received request.`),void 0===this.getBoundaryNodes||void 0===this.getKeyValuePairs)return;const r=fe.decodeObject(JS.Codec,t),s=this.getBoundaryNodes(r.headerHash,r.startKey,r.endKey),i=this.getKeyValuePairs(r.headerHash,r.startKey,r.endKey);return YS.info(`[${e.streamId}][server]: <-- responding with boundary nodes and key value pairs.`),e.bufferAndSend(Ae.encodeObject(Be.sequenceVarLen(qS),s)),e.bufferAndSend(Ae.encodeObject(WS.Codec,WS.create({keyValuePairs:i}))),void e.close()}if(!this.boundaryNodes.has(e.streamId))return this.boundaryNodes.set(e.streamId,fe.decodeObject(Be.sequenceVarLen(qS),t)),void YS.info(`[${e.streamId}][client]: Received boundary nodes.`);this.onResponse.get(e.streamId)?.(fe.decodeObject(WS.Codec,t)),YS.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(Ae.encodeObject(JS.Codec,JS.create({headerHash:t,startKey:r,endKey:r,maximumSize:ne(4096)}))),e.close()}}SS(131),SS(132);class ZS extends B{epochIndex;ticket;static Codec=Be.Class(ZS,{epochIndex:Be.u32.asOpaque(),ticket:Rt.Codec});static create({epochIndex:e,ticket:t}){return new ZS(e,t)}constructor(e,t){super(),this.epochIndex=e,this.ticket=t}}ri.new(void 0,"protocol/ce-131-ce-132"),SS(133);class eE extends B{coreIndex;workPackage;static Codec=Be.Class(eE,{coreIndex:Be.u16.asOpaque(),workPackage:Jr.Codec});static create({coreIndex:e,workPackage:t}){return new eE(e,t)}constructor(e,t){super(),this.coreIndex=e,this.workPackage=t}}ri.new(void 0,"protocol/ce-133"),Be.blob,SS(134);class tE extends B{coreIndex;segmentsRootMappings;static Codec=Be.Class(tE,{coreIndex:Be.u16.asOpaque(),segmentsRootMappings:Be.sequenceVarLen(ss.Codec)});static create({coreIndex:e,segmentsRootMappings:t}){return new tE(e,t)}constructor(e,t){super(),this.coreIndex=e,this.segmentsRootMappings=t}}class rE extends B{workReportHash;signature;static Codec=Be.Class(rE,{workReportHash:Be.bytes(Pe).asOpaque(),signature:Be.bytes(yr).asOpaque()});static create({workReportHash:e,signature:t}){return new rE(e,t)}constructor(e,t){super(),this.workReportHash=e,this.signature=t}}ri.new(void 0,"protocol/ce-134"),SS(135);class sE extends B{report;slot;signatures;static Codec=Be.Class(sE,{report:is.Codec,slot:Be.u32.asOpaque(),signatures:kt(e=>xt(cs.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2}))});static create({report:e,slot:t,signatures:r}){return new sE(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.signatures=r}}ri.new(void 0,"protocol/ce-135");const iE={id:Symbol("sync")},nE=ri.new(void 0,"net:sync");class aE{spec;streamManager;connections;blocks;onNewBlocks;static start(e,t,r,s,i){const n=new aE(e,t,r,s,i),a=e=>t.getPeer(e),o=new VS(e,()=>n.getUp0Handshake(),(e,t)=>{const r=a(e);null!==r&&n.onUp0Annoucement(r,t)},(e,t)=>{const r=a(e);null!==r&&n.onUp0Handshake(r,t)});return t.registerIncomingHandlers(o),t.registerIncomingHandlers(new US(e,(e,t,r,s)=>{const i=a(e);return null!==i?n.handleGetBlockSequence(i,t,r,s):[]})),t.registerOutgoingHandlers(o),t.registerOutgoingHandlers(new TS(e)),n}othersBest;constructor(e,t,r,s,i){this.spec=e,this.streamManager=t,this.connections=r,this.blocks=s,this.onNewBlocks=i;const n=s.getBestHeaderHash(),a=s.getHeader(n);if(null===a)throw new Error(`Best header ${n} missing in the database?`);this.othersBest=MS.create({hash:n,slot:a.timeSlotIndex.materialize()})}onUp0Handshake(e,t){const{hash:r,slot:s}=t.final;this.connections.withAuxData(e.id,iE,e=>void 0===e?{finalBlockHash:r,finalBlockSlot:s,bestHeader:null}:(e.finalBlockHash=r,e.finalBlockSlot=s,e.bestHeader=null,e)),this.othersBest.slot<s&&(this.othersBest=t.final)}onUp0Annoucement(e,t){const{hash:r,slot:s}=t.final,i=function(e,t){const r=Ae.encodeObject(ps.Codec,e,t);return new He(qe(r).asOpaque(),e)}(t.header,this.spec);nE.info(`[${e.id}] --\x3e Received new header #${t.header.timeSlotIndex}: ${i.hash}`),this.connections.withAuxData(e.id,iE,e=>void 0===e?{finalBlockHash:r,finalBlockSlot:s,bestHeader:i}:(e.finalBlockHash=r,e.finalBlockSlot=s,e.bestHeader=i,e)),this.othersBest.slot<i.data.timeSlotIndex&&(this.othersBest=MS.create({hash:i.hash,slot:i.data.timeSlotIndex}))}getUp0Handshake(){const e=this.blocks.getBestHeaderHash(),t=this.blocks.getHeader(e),r=t?.timeSlotIndex.materialize(),s=MS.create({hash:e,slot:r??Ur(0)});return PS.create({final:s,leafs:[]})}openUp0(e){this.streamManager.withNewStream(e,DS,(e,t)=>(e.sendHandshake(t),O))}broadcastHeader(e){const t=e.data.timeSlotIndex.materialize(),r=LS.create({header:e.data.materialize(),final:MS.create({hash:e.hash,slot:t})}),s=this.connections.getConnectedPeers();for(const i of s)this.streamManager.withStreamOfKind(i.peerId,DS,(s,n)=>(nE.log(`[${i.peerId}] <-- Broadcasting new header #${t}: ${e.hash}`),s.sendAnnouncement(n,r),O))}handleGetBlockSequence(e,t,r,s){const i=ne(Math.min(s,128)),n=function(e,t,r,s,i){const n=r=>{const s=t.getHeader(r),i=t.getExtrinsic(r);if(null===s||null===i)return null;const n=P.blobFromParts(s.encoded().raw,i.encoded().raw);return fe.decodeObject(vs.Codec.View,n,e)},a=n(r);if(null===a)return D.error(NS.NoStartBlock);if(s===_S.AscExcl){const e=[],s=a.header.view().timeSlotIndex.materialize();let o=t.getBestHeaderHash();for(;;){const a=t.getHeader(o);if(null===a||a.timeSlotIndex.materialize()<s)return D.error(NS.BlockOnFork);if(r.isEqualTo(o))return D.ok(e.reverse().slice(0,i).flatMap(e=>{const t=n(e);return null===t?[]:[t]}));e.push(o),o=a.parentHeaderHash.materialize()}}const o=[a];let c=a;for(let e=0;e<i;e++){const e=n(c.header.view().parentHeaderHash.materialize());if(null===e)break;o.push(e),c=e}return D.ok(o)}(this.spec,this.blocks,t,r,i);return n.isOk?n.ok:n.error===NS.BlockOnFork?(nE.warn(`[${e.id}] <-- Invalid block sequence request: ${t} is on a fork.`),[]):n.error===NS.NoStartBlock?(nE.warn(`[${e.id}] <-- Invalid block sequence request: ${t} missing header or extrinsic.`),[]):void E(n.error)}maintainSync(){const e=this.blocks.getBestHeaderHash(),t=this.blocks.getHeader(e),r=this.connections.getPeerCount();if(null===t)return{kind:oE.OurBestHeaderMissing};const s=t.timeSlotIndex.materialize(),i=this.othersBest,n=i.slot-s;if(nE.trace(`Our best. ${s}. Best seen: ${i.slot}`),n<1)return this.connections.getPeerCount(),nE.trace(`No new blocks. ${r} peers.`),{kind:oE.NoNewBlocks,ours:s,theirs:i.slot};const a=[];nE.log(`Sync ${n} blocks from ${r} peers.`);for(const e of this.connections.getConnectedPeers()){const t=this.connections.getAuxData(e.peerId,iE);if(void 0===t||null===e.peerRef)continue;const r=null!==t.bestHeader?t.bestHeader.data.timeSlotIndex:t.finalBlockSlot,i=null!==t.bestHeader?t.bestHeader.hash:t.finalBlockHash;r<=s||(a.push({peerId:e.peerId,theirs:r,count:r-s}),this.streamManager.withNewStream(e.peerRef,BS,(t,n)=>(ES(async()=>{nE.log(`Fetching blocks from ${e.peerId}.`);const a=await t.requestBlockSequence(n,i,_S.DescIncl,ne(r-s));a.reverse(),this.onNewBlocks(a,e.peerId)},t=>{nE.warn(`[${e.peerId}] --\x3e requesting blocks to import: ${t}`)}),O)))}return{kind:oE.BlocksRequested,ours:s,requested:a}}}var oE;!function(e){e[e.OurBestHeaderMissing=1]="OurBestHeaderMissing",e[e.NoNewBlocks=2]="NoNewBlocks",e[e.BlocksRequested=3]="BlocksRequested"}(oE||(oE={}));const cE=ri.new(void 0,"jamnps");function lE(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(!ie(n))throw new Error(`Invalid port number: "${i}"`);return new IS(t,s,n)}class dE extends B{bootnodes;id;genesisHeader;genesisState;static fromJson=ee.object({bootnodes:ee.optional(ee.array(ee.fromString(lE))),id:"string",genesis_header:Tt.bytesBlobNoPrefix,genesis_state:ee.map(Tt.bytesNNoPrefix(31),Tt.bytesBlobNoPrefix)},e=>dE.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=P.empty(),genesisState:s=new Map}){return new dE({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}}const uE=t(import.meta.url)("node:fs");var hE=a.n(uE);const fE=t(import.meta.url)("node:os");var gE=a.n(fE);const pE=JSON.parse('{"$schema":"https://fluffylabs.dev/typeberry/schemas/config-v1.schema.json","version":1,"flavor":"tiny","authorship":{"omit_seal_verification":false},"chain_spec":{"id":"typeberry-default","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"}'),bE=JSON.parse('{"$schema":"https://fluffylabs.dev/typeberry/schemas/config-v1.schema.json","version":1,"flavor":"tiny","authorship":{"omit_seal_verification":true},"chain_spec":{"id":"typeberry-dev","bootnodes":["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"}');class mE{omitSealVerification;static fromJson=ee.object({omit_seal_verification:"boolean"},mE.new);static new({omit_seal_verification:e}){return new mE(e)}constructor(e){this.omitSealVerification=e}}const yE="dev",AE="default",IE={name:gE().hostname(),config:AE};var vE;!function(e){e.Tiny="tiny",e.Full="full"}(vE||(vE={}));const wE=ee.fromString((e,t)=>{switch(e){case vE.Tiny:return vE.Tiny;case vE.Full:return vE.Full;default:throw Error(`unknown network flavor: ${e} at ${t}`)}});class SE{$schema;version;flavor;chainSpec;databaseBasePath;authorship;static fromJson=ee.object({$schema:"string",version:"number",flavor:wE,chain_spec:dE.fromJson,database_base_path:"string",authorship:mE.fromJson},SE.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 SE(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 EE=t(import.meta.url)("node:worker_threads"),CE="best hash and posterior state root";class kE{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:L.fromBlob(t,Pe).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(CE,e.raw)}getBestHeaderHash(){const e=this.root.db.get(CE);return void 0===e?L.zero(Pe).asOpaque():L.fromBlob(e,Pe).asOpaque()}getHeader(e){const t=this.headers.get(e.raw);return void 0===t?null:fe.decodeObject(ps.Codec.View,t,this.chainSpec)}getExtrinsic(e){const t=this.extrinsics.get(e.raw);return void 0===t?null:fe.decodeObject(Is.Codec.View,t,this.chainSpec)}}const xE=(BE={open:()=>r.open},_E={},a.d(_E,BE),_E);var BE,_E;class RE{db;constructor(e,t=!1){this.db=xE.open(e,{compression:!0,keyEncoding:"binary",encoding:"binary",readOnly:t})}subDb(e){return this.db.openDB({name:e})}}class OE{serviceId;output;static Codec=Be.Class(OE,{serviceId:Be.u32.asOpaque(),output:Be.bytes(Pe)});static create(e){return new OE(e.serviceId,e.output)}constructor(e,t){this.serviceId=e,this.output=t}}const UE=e=>Ce.withView(e.name,e.sizeHint,(t,r)=>e.encode(t,r.data),t=>{const r=t.clone(),s=qe(e.skipEncoded(r));return new He(s.asOpaque(),e.decode(t))},e.skip,e.View);class TE extends B{workReport;timeout;static Codec=Be.Class(TE,{workReport:UE(is.Codec),timeout:Be.u32.asOpaque()});static create({workReport:e,timeout:t}){return new TE(e,t)}constructor(e,t){super(),this.workReport=e,this.timeout=t}}function NE(e,t){return w(e.length===t.coresCount,`Invalid per-core array length. Expected ${t.coresCount}, got: ${e.length}`),e}const DE=e=>kt(t=>xt(e,{fixedLength:t.coresCount})),ME=()=>ke(Be.sequenceVarLen(Be.bytes(Pe))).convert(e=>e.array,e=>{const t=e.map(e=>e.asOpaque());return It.fromSortedArray(HE,t)}),PE=ME();class LE{goodSet;badSet;wonkySet;punishSet;static Codec=Be.Class(LE,{goodSet:PE,badSet:PE,wonkySet:PE,punishSet:ME()});static create({goodSet:e,badSet:t,wonkySet:r,punishSet:s}){return new LE(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 LE(It.fromSortedArray(HE,e),It.fromSortedArray(HE,t),It.fromSortedArray(HE,r),It.fromSortedArray(HE,s))}}function HE(e,t){return e.compare(t)}class VE{service;gasLimit;static Codec=Be.Class(VE,{service:Be.u32.asOpaque(),gasLimit:Be.u64.asOpaque()});static create({service:e,gasLimit:t}){return new VE(e,t)}constructor(e,t){this.service=e,this.gasLimit=t}}class KE{manager;authManager;validatorsManager;autoAccumulateServices;static Codec=Be.Class(KE,{manager:Be.u32.asOpaque(),authManager:v.isGreaterOrEqual(h.V0_6_7)?DE(Be.u32.asOpaque()):kt(e=>Be.u32.asOpaque().convert(e=>e[0],t=>NE(new Array(e.coresCount).fill(t),e))),validatorsManager:Be.u32.asOpaque(),autoAccumulateServices:ke(Be.sequenceVarLen(VE.Codec))});static create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s}){return new KE(e,t,r,s)}constructor(e,t,r,s){this.manager=e,this.authManager=t,this.validatorsManager=r,this.autoAccumulateServices=s}}const QE=P.blobFromString("peak");class FE{hasher;mountains;static empty(e){return new FE(e)}static fromPeaks(e,t){return new FE(e,t.peaks.reduce((e,t,r)=>(null!==t&&e.push($E.fromPeak(t,2**r)),e),[]).reverse())}constructor(e,t=[]){this.hasher=e,this.mountains=t}append(e){let t=$E.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 L.zero(Pe).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(QE,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 $E{peak;size;constructor(e,t){this.peak=e,this.size=t}static fromPeak(e,t){return new $E(e,t)}static fromChildren(e,t){const[r,s]=t,i=e.hashConcat(r.peak,s.peak),n=r.size+s.size;return new $E(i,n)}mergeWith(e,t){return $E.fromChildren(e,[this,t])}toString(){return`${this.size} @ ${this.peak}`}}class GE extends B{headerHash;mmr;postStateRoot;reported;static Codec=Be.Class(GE,{headerHash:Be.bytes(Pe).asOpaque(),mmr:Be.object({peaks:ke(Be.sequenceVarLen(Be.optional(Be.bytes(Pe))))}),postStateRoot:Be.bytes(Pe).asOpaque(),reported:_t(ss.Codec,e=>e.workPackageHash)});static create({headerHash:e,mmr:t,postStateRoot:r,reported:s}){return new GE(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.mmr=t,this.postStateRoot=r,this.reported=s}}class jE extends B{blocks;static Codec=Be.Class(jE,{blocks:xt(GE.Codec,{minLength:0,maxLength:8,typicalLength:8})});static create(e){return new jE(e.blocks)}constructor(e){super(),this.blocks=e}}class qE extends B{headerHash;accumulationResult;postStateRoot;reported;static Codec=Be.Class(qE,{headerHash:Be.bytes(Pe).asOpaque(),accumulationResult:Be.bytes(Pe),postStateRoot:Be.bytes(Pe).asOpaque(),reported:_t(ss.Codec,e=>e.workPackageHash)});static create({headerHash:e,accumulationResult:t,postStateRoot:r,reported:s}){return new qE(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.accumulationResult=t,this.postStateRoot=r,this.reported=s}}class zE extends B{blocks;accumulationLog;static Codec=Be.Class(zE,{blocks:xt(qE.Codec,{minLength:0,maxLength:8,typicalLength:8}),accumulationLog:Be.object({peaks:ke(Be.sequenceVarLen(Be.optional(Be.bytes(Pe))))})});static create(e){return new zE(e.blocks,e.accumulationLog)}constructor(e,t){super(),this.blocks=e,this.accumulationLog=t}}class WE extends B{current;legacy;static Codec=Ce.new("RecentBlocksHistory",v.isGreaterOrEqual(h.V0_6_7)?zE.Codec.sizeHint:jE.Codec.sizeHint,(e,t)=>v.isGreaterOrEqual(h.V0_6_7)?zE.Codec.encode(e,t.asCurrent()):jE.Codec.encode(e,t.asLegacy()),e=>{if(v.isGreaterOrEqual(h.V0_6_7)){const t=zE.Codec.decode(e);return WE.create(t)}const t=jE.Codec.decode(e);return WE.legacyCreate(t)},e=>v.isGreaterOrEqual(h.V0_6_7)?zE.Codec.sizeHint:jE.Codec.sizeHint);static create(e){return new WE(e,null)}static legacyCreate(e){return new WE(null,e)}static empty(){return v.isGreaterOrEqual(h.V0_6_7)?WE.create(zE.create({blocks:[],accumulationLog:{peaks:[]}})):WE.legacyCreate(jE.create({blocks:[]}))}static accumulationResult(e,{hasher:t}){return v.isGreaterOrEqual(h.V0_6_7)?e.accumulationResult:FE.fromPeaks(t,e.mmr).getSuperPeakHash()}constructor(e,t){super(),this.current=e,this.legacy=t}get blocks(){if(v.isGreaterOrEqual(h.V0_6_7)&&null!==this.current)return this.current.blocks;if(null!==this.legacy)return this.legacy.blocks;throw new Error("RecentBlocksHistory is in invalid state")}asCurrent(){if(null===this.current)throw new Error("Cannot access current RecentBlocks format");return this.current}asLegacy(){if(null===this.legacy)throw new Error("Cannot access legacy RecentBlocks format");return this.legacy}updateBlocks(e){if(v.isGreaterOrEqual(h.V0_6_7)&&null!==this.current)return WE.create(zE.create({...this.current,blocks:e}));if(null!==this.legacy)return WE.legacyCreate(jE.create({blocks:e}));throw new Error("RecentBlocksHistory is in invalid state. Cannot be updated!")}}const JE=128;class YE extends B{bandersnatch;ed25519;bls;metadata;static Codec=Be.Class(YE,{bandersnatch:Be.bytes(Te).asOpaque(),ed25519:Be.bytes(mr).asOpaque(),bls:Be.bytes(Me).asOpaque(),metadata:Be.bytes(JE)});static create({ed25519:e,bandersnatch:t,bls:r,metadata:s}){return new YE(t,e,r,s)}constructor(e,t,r,s){super(),this.bandersnatch=e,this.ed25519=t,this.bls=r,this.metadata=s}}var XE;!function(e){e[e.Tickets=0]="Tickets",e[e.Keys=1]="Keys"}(XE||(XE={}));const ZE=Be.bytes(Te).asOpaque();class eC extends B{kind;keys;tickets;static Codec=kt(e=>Be.custom({name:"SafroleSealingKeys",sizeHint:{bytes:1+Pe*e.epochLength,isExact:!1}},(e,t)=>{e.varU32(ne(t.kind)),t.kind===XE.Keys?e.sequenceFixLen(ZE,t.keys):e.sequenceFixLen(Ot.Codec,t.tickets)},t=>{const r=e.epochLength,s=t.varU32();if(s===XE.Keys){const s=t.sequenceFixLen(ZE,r);return eC.keys(Vr(s,e))}if(s===XE.Tickets){const s=t.sequenceFixLen(Ot.Codec,r);return eC.tickets(Vr(s,e))}throw new Error(`Unexpected safrole sealing keys kind: ${s}`)},t=>{const r=t.decoder.varU32();if(r!==XE.Keys){if(r!==XE.Tickets)throw new Error(`Unexpected safrole sealing keys kind: ${r}`);t.sequenceFixLen(Ot.Codec,e.epochLength)}else t.sequenceFixLen(ZE,e.epochLength)}));static keys(e){return new eC(XE.Keys,e,void 0)}static tickets(e){return new eC(XE.Tickets,void 0,e)}constructor(e,t,r){super(),this.kind=e,this.keys=t,this.tickets=r}}class tC{nextValidatorData;epochRoot;sealingKeySeries;ticketsAccumulator;static Codec=Be.Class(tC,{nextValidatorData:Hr(YE.Codec),epochRoot:Be.bytes(De).asOpaque(),sealingKeySeries:eC.Codec,ticketsAccumulator:ke(Be.sequenceVarLen(Ot.Codec)).convert(R,mt)});static create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s}){return new tC(e,t,r,s)}constructor(e,t,r,s){this.nextValidatorData=e,this.epochRoot=t,this.sealingKeySeries=r,this.ticketsAccumulator=s}}const rC={bytes:0,isExact:!0},sC=e=>Ce.new("ignoreValue",rC,(e,t)=>{},t=>e,e=>{});class iC extends B{codeHash;balance;accumulateMinGas;onTransferMinGas;storageUtilisationBytes;gratisStorage;storageUtilisationCount;created;lastAccumulation;parentService;static Codec=v.isGreaterOrEqual(h.V0_6_7)?Be.Class(iC,{codeHash:Be.bytes(Pe).asOpaque(),balance:Be.u64,accumulateMinGas:Be.u64.convert(e=>e,Dr),onTransferMinGas:Be.u64.convert(e=>e,Dr),storageUtilisationBytes:Be.u64,gratisStorage:Be.u64,storageUtilisationCount:Be.u32,created:Be.u32.convert(e=>e,Ur),lastAccumulation:Be.u32.convert(e=>e,Ur),parentService:Be.u32.convert(e=>e,Nr)}):Be.Class(iC,{codeHash:Be.bytes(Pe).asOpaque(),balance:Be.u64,accumulateMinGas:Be.u64.convert(e=>e,Dr),onTransferMinGas:Be.u64.convert(e=>e,Dr),storageUtilisationBytes:Be.u64,storageUtilisationCount:Be.u32,gratisStorage:sC(oe(0)),created:sC(Ur(0)),lastAccumulation:sC(Ur(0)),parentService:sC(Nr(0))});static create(e){return new iC(e.codeHash,e.balance,e.accumulateMinGas,e.onTransferMinGas,e.storageUtilisationBytes,e.gratisStorage,e.storageUtilisationCount,e.created,e.lastAccumulation,e.parentService)}static calculateThresholdBalance(e,t,r){w(r===oe(0)||v.isGreaterOrEqual(h.V0_6_7),"Gratis storage cannot be non-zero before 0.6.7");const s=100n+10n*BigInt(e)+1n*t-r;return oe(s<0n?0:s>=2n**64n?2n**64n-1n:s)}constructor(e,t,r,s,i,n,a,o,c,l){super(),this.codeHash=e,this.balance=t,this.accumulateMinGas=r,this.onTransferMinGas=s,this.storageUtilisationBytes=i,this.gratisStorage=n,this.storageUtilisationCount=a,this.created=o,this.lastAccumulation=c,this.parentService=l}}class nC extends B{hash;blob;static Codec=Be.Class(nC,{hash:Be.bytes(Pe).asOpaque(),blob:Be.blob});static create({hash:e,blob:t}){return new nC(e,t)}constructor(e,t){super(),this.hash=e,this.blob=t}}class aC extends B{key;value;static Codec=Be.Class(aC,{key:Be.blob.convert(e=>e,e=>e),value:Be.blob});static create({key:e,value:t}){return new aC(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}function oC(e){const t=e;if(t.length>3)throw new Error("Lookup history items must contain 0-3 timeslots.");return t}class cC{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 lC,dC,uC;!function(e){e[e.Provide=0]="Provide",e[e.Remove=1]="Remove",e[e.UpdateOrAdd=2]="UpdateOrAdd"}(lC||(lC={}));class hC{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static provide({serviceId:e,preimage:t,slot:r}){return new hC(e,{kind:lC.Provide,preimage:t,slot:r})}static remove({serviceId:e,hash:t,length:r}){return new hC(e,{kind:lC.Remove,hash:t,length:r})}static updateOrAdd({serviceId:e,lookupHistory:t}){return new hC(e,{kind:lC.UpdateOrAdd,item:t})}get hash(){switch(this.action.kind){case lC.Provide:return this.action.preimage.hash;case lC.Remove:return this.action.hash;case lC.UpdateOrAdd:return this.action.item.hash}throw E(this.action)}get length(){switch(this.action.kind){case lC.Provide:return ne(this.action.preimage.blob.length);case lC.Remove:return this.action.length;case lC.UpdateOrAdd:return this.action.item.length}throw E(this.action)}}!function(e){e[e.Update=0]="Update",e[e.Create=1]="Create"}(dC||(dC={}));class fC{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static update({serviceId:e,serviceInfo:t}){return new fC(e,{kind:dC.Update,account:t})}static create({serviceId:e,serviceInfo:t,lookupHistory:r}){return new fC(e,{kind:dC.Create,account:t,lookupHistory:r})}}!function(e){e[e.Set=0]="Set",e[e.Remove=1]="Remove"}(uC||(uC={}));class gC{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static set({serviceId:e,storage:t}){return new gC(e,{kind:uC.Set,storage:t})}static remove({serviceId:e,key:t}){return new gC(e,{kind:uC.Remove,key:t})}get key(){return this.action.kind===uC.Remove?this.action.key:this.action.storage.key}get value(){return this.action.kind===uC.Remove?null:this.action.storage.value}}const pC=v.isSuite(f.W3F_DAVXY)||v.isSuite(f.JAMDUNA,h.V0_6_5)||v.isSuite(f.JAMDUNA,h.V0_6_7)?Be.u32.asOpaque():Be.varU32.convert(e=>ne(e),e=>Nr(e));class bC{blocks;tickets;preImages;preImagesSize;guarantees;assurances;static Codec=Be.Class(bC,{blocks:Be.u32,tickets:Be.u32,preImages:Be.u32,preImagesSize:Be.u32,guarantees:Be.u32,assurances:Be.u32});static create({blocks:e,tickets:t,preImages:r,preImagesSize:s,guarantees:i,assurances:n}){return new bC(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=ne(0);return new bC(e,e,e,e,e,e)}}const mC=Be.varU32.convert(e=>ne(e),e=>se(e)),yC=Be.varU64.convert(e=>oe(e),e=>Dr(e));class AC{dataAvailabilityLoad;popularity;imports;exports;extrinsicSize;extrinsicCount;bundleSize;gasUsed;static Codec=Be.Class(AC,{dataAvailabilityLoad:Be.varU32,popularity:mC,imports:mC,exports:mC,extrinsicSize:Be.varU32,extrinsicCount:mC,bundleSize:Be.varU32,gasUsed:yC});static create(e){return new AC(e.dataAvailabilityLoad,e.popularity,e.imports,e.exports,e.extrinsicSize,e.extrinsicCount,e.bundleSize,e.gasUsed)}constructor(e,t,r,s,i,n,a,o){this.dataAvailabilityLoad=e,this.popularity=t,this.imports=r,this.exports=s,this.extrinsicSize=i,this.extrinsicCount=n,this.bundleSize=a,this.gasUsed=o}static empty(){const e=ne(0),t=se(0),r=Dr(0);return new AC(e,t,t,t,e,t,e,r)}}class IC{providedCount;providedSize;refinementCount;refinementGasUsed;imports;exports;extrinsicSize;extrinsicCount;accumulateCount;accumulateGasUsed;onTransfersCount;onTransfersGasUsed;static Codec=Be.Class(IC,{providedCount:mC,providedSize:Be.varU32,refinementCount:Be.varU32,refinementGasUsed:yC,imports:mC,exports:mC,extrinsicSize:Be.varU32,extrinsicCount:mC,accumulateCount:Be.varU32,accumulateGasUsed:yC,onTransfersCount:Be.varU32,onTransfersGasUsed:yC});static create(e){return new IC(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,a,o,c,l,d,u){this.providedCount=e,this.providedSize=t,this.refinementCount=r,this.refinementGasUsed=s,this.imports=i,this.exports=n,this.extrinsicSize=a,this.extrinsicCount=o,this.accumulateCount=c,this.accumulateGasUsed=l,this.onTransfersCount=d,this.onTransfersGasUsed=u}static empty(){const e=ne(0),t=se(0),r=Dr(0);return new IC(t,e,e,r,t,t,e,t,e,r,e,r)}}class vC{current;previous;cores;services;static Codec=Be.Class(vC,{current:Hr(bC.Codec),previous:Hr(bC.Codec),cores:DE(AC.Codec),services:Be.dictionary(pC,IC.Codec,{sortKeys:(e,t)=>e-t})});static create(e){return new vC(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 wC,SC;(SC=wC||(wC={}))[SC.DuplicateService=0]="DuplicateService",SC[SC.NoService=1]="NoService",SC[SC.PreimageExists=2]="PreimageExists";class EC extends B{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.toString())?.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.values()).map(e=>e.key),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=pt.new(),i=new Map,n=pt.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,nC.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 cC(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.toString(),aC.create({key:r,value:t}))}return new EC(e.serviceId,{info:r,preimages:s,storage:i,lookupHistory:n})}}class CC extends B{static create(e){return new CC(e)}static partial(e,t){const r=CC.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=EC.copyFrom(t,i);r.set(s,n)}return CC.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,accumulationOutputLog:e.accumulationOutputLog,services:r})}intoServicesData(){const e=new Map;for(const[t,{data:r}]of this.services)e.set(t,{storageKeys:Array.from(r.storage.values()).map(e=>e.key),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 a;return Object.assign(this,n),a=this.updateServices(r),a.isError?a:(a=this.updatePreimages(s),a.isError?a:(a=this.updateStorage(i),a.isError?a:(this.removeServices(t),D.ok(O))))}removeServices(e){for(const t of e??[])w(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 D.error(wC.NoService,`Attempting to update storage of non-existing service: ${t}`);if(e===uC.Set){const{key:e,value:t}=r.storage;s.data.storage.set(e.toString(),aC.create({key:e,value:t}))}else if(e===uC.Remove){const{key:e}=r;w(s.data.storage.has(e.toString()),`Attempting to remove non-existing storage item at ${t}: ${r.key}`),s.data.storage.delete(e.toString())}else E(e)}return D.ok(O)}updatePreimages(e){for(const{serviceId:t,action:r}of e??[]){const e=this.services.get(t);if(void 0===e)return D.error(wC.NoService,`Attempting to update preimage of non-existing service: ${t}`);const{kind:s}=r;if(s===lC.Provide){const{preimage:s,slot:i}=r;if(e.data.preimages.has(s.hash))return D.error(wC.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=ne(s.blob.length),n=new cC(s.hash,r,oC([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===lC.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===lC.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 E(s)}return D.ok(O)}updateServices(e){for(const{serviceId:t,action:r}of e??[]){const{kind:e,account:s}=r;if(e===dC.Create){const{lookupHistory:e}=r;if(this.services.has(t))return D.error(wC.DuplicateService,`${t} already exists!`);this.services.set(t,new EC(t,{info:s,preimages:pt.new(),storage:new Map,lookupHistory:pt.fromEntries(null===e?[]:[[e.hash,[e]]])}))}else if(e===dC.Update){const e=this.services.get(t);if(void 0===e)return D.error(wC.NoService,`Cannot update ${t} because it does not exist.`);e.data.info=s}else E(e)}return D.ok(O)}availabilityAssignment;designatedValidatorData;nextValidatorData;currentValidatorData;previousValidatorData;disputesRecords;timeslot;entropy;authPools;authQueues;recentBlocks;statistics;accumulationQueue;recentlyAccumulated;ticketsAccumulator;sealingKeySeries;epochRoot;privilegedServices;accumulationOutputLog;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.accumulationOutputLog=e.accumulationOutputLog,this.services=e.services}static empty(e){return new CC({availabilityAssignment:NE(Array.from({length:e.coresCount},()=>null),e),designatedValidatorData:Lr(Array.from({length:e.validatorsCount},()=>YE.create({bandersnatch:L.zero(Te).asOpaque(),bls:L.zero(Me).asOpaque(),ed25519:L.zero(mr).asOpaque(),metadata:L.zero(JE).asOpaque()})),e),nextValidatorData:Lr(Array.from({length:e.validatorsCount},()=>YE.create({bandersnatch:L.zero(Te).asOpaque(),bls:L.zero(Me).asOpaque(),ed25519:L.zero(mr).asOpaque(),metadata:L.zero(JE).asOpaque()})),e),currentValidatorData:Lr(Array.from({length:e.validatorsCount},()=>YE.create({bandersnatch:L.zero(Te).asOpaque(),bls:L.zero(Me).asOpaque(),ed25519:L.zero(mr).asOpaque(),metadata:L.zero(JE).asOpaque()})),e),previousValidatorData:Lr(Array.from({length:e.validatorsCount},()=>YE.create({bandersnatch:L.zero(Te).asOpaque(),bls:L.zero(Me).asOpaque(),ed25519:L.zero(mr).asOpaque(),metadata:L.zero(JE).asOpaque()})),e),disputesRecords:LE.create({goodSet:It.fromSortedArray(HE,[]),badSet:It.fromSortedArray(HE,[]),wonkySet:It.fromSortedArray(HE,[]),punishSet:It.fromSortedArray(HE,[])}),timeslot:Ur(0),entropy:yt.fill(()=>L.zero(Pe).asOpaque(),4),authPools:NE(Array.from({length:e.coresCount},()=>[]),e),authQueues:NE(Array.from({length:e.coresCount},()=>yt.fill(()=>L.zero(Pe).asOpaque(),80)),e),recentBlocks:WE.empty(),statistics:vC.create({current:Lr(Array.from({length:e.validatorsCount},()=>bC.empty()),e),previous:Lr(Array.from({length:e.validatorsCount},()=>bC.empty()),e),cores:NE(Array.from({length:e.coresCount},()=>AC.empty()),e),services:new Map}),accumulationQueue:Vr(Array.from({length:e.epochLength},()=>[]),e),recentlyAccumulated:Vr(Array.from({length:e.epochLength},()=>bt.new()),e),ticketsAccumulator:[],sealingKeySeries:eC.keys(Vr(Array.from({length:e.epochLength},()=>L.zero(Te).asOpaque()),e)),epochRoot:L.zero(De).asOpaque(),privilegedServices:KE.create({manager:Nr(0),authManager:NE(new Array(e.coresCount).fill(Nr(0)),e),validatorsManager:Nr(0),autoAccumulateServices:[]}),accumulationOutputLog:[],services:new Map})}}const kC=Be.object({storageKeys:Be.sequenceVarLen(Be.blob.convert(e=>e,e=>e)),preimages:Be.sequenceVarLen(Be.bytes(Pe).asOpaque()),lookupHistory:Be.sequenceVarLen(Be.object({hash:Be.bytes(Pe).asOpaque(),length:Be.u32}))});Be.dictionary(Be.u32.asOpaque(),kC,{sortKeys:(e,t)=>e-t});class xC extends B{report;dependencies;static Codec=Be.Class(xC,{report:is.Codec,dependencies:xt(Be.bytes(Pe).asOpaque(),{typicalLength:4,maxLength:8,minLength:0})});static create({report:e,dependencies:t}){return new xC(e,t)}constructor(e,t){super(),this.report=e,this.dependencies=t}}var BC,_C,RC;function OC(e,t){const r=L.zero(Pe);let s=0;for(const i of de(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,Pe-i),s),r.asOpaque()}!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.Omega=14]="Omega",e[e.Xi=15]="Xi",e[e.Theta=16]="Theta",e[e.Delta=255]="Delta"}(BC||(BC={})),function(e){function t(e,t,r){const s=qe(P.blobFromParts(de(t),r.raw)).raw.subarray(0,28),i=L.zero(Pe);let n=0;for(const t of de(e))i.raw[n]=t,i.raw[n+1]=s[n/2],n+=2;const a=n/2;return i.raw.set(s.subarray(a),n),i.asOpaque()}e.index=function(e){const t=L.zero(Pe);return t.raw[0]=e,t.asOpaque()},e.serviceInfo=function(e){const t=L.zero(Pe);t.raw[0]=BC.Delta;let r=1;for(const s of de(e))t.raw[r]=s,r+=2;return t.asOpaque()},e.serviceStorage=function(e,r){if(v.isLessThan(h.V0_6_7)){const t=L.zero(Pe);return t.raw.set(de(ne(2**32-1)),0),t.raw.set(r.raw.subarray(0,28),4),OC(e,t)}return t(e,ne(2**32-1),r)},e.servicePreimage=function(e,r){if(v.isLessThan(h.V0_6_7)){const t=L.zero(Pe);return t.raw.set(de(ne(2**32-2)),0),t.raw.set(r.raw.subarray(1,29),4),OC(e,t)}return t(e,ne(2**32-2),r)},e.serviceLookupHistory=function(e,r,s){if(v.isLessThan(h.V0_6_7)){const t=qe(r),i=L.zero(Pe);return i.raw.set(de(s),0),i.raw.set(t.raw.subarray(2,30),4),OC(e,i)}return t(e,s,r)},e.serviceNested=t}(_C||(_C={})),function(e){e.authPools={key:_C.index(BC.Alpha),Codec:DE(xt(Be.bytes(Pe).asOpaque(),{minLength:0,maxLength:8,typicalLength:8})),extract:e=>e.authPools},e.authQueues={key:_C.index(BC.Phi),Codec:DE(Bt(Be.bytes(Pe).asOpaque(),80)),extract:e=>e.authQueues},e.recentBlocks={key:_C.index(BC.Beta),Codec:WE.Codec,extract:e=>e.recentBlocks},e.safrole={key:_C.index(BC.Gamma),Codec:tC.Codec,extract:e=>tC.create({nextValidatorData:e.nextValidatorData,epochRoot:e.epochRoot,sealingKeySeries:e.sealingKeySeries,ticketsAccumulator:e.ticketsAccumulator})},e.disputesRecords={key:_C.index(BC.Psi),Codec:LE.Codec,extract:e=>e.disputesRecords},e.entropy={key:_C.index(BC.Eta),Codec:Bt(Be.bytes(Pe).asOpaque(),4),extract:e=>e.entropy},e.designatedValidators={key:_C.index(BC.Iota),Codec:Hr(YE.Codec),extract:e=>e.designatedValidatorData},e.currentValidators={key:_C.index(BC.Kappa),Codec:Hr(YE.Codec),extract:e=>e.currentValidatorData},e.previousValidators={key:_C.index(BC.Lambda),Codec:Hr(YE.Codec),extract:e=>e.previousValidatorData},e.availabilityAssignment={key:_C.index(BC.Rho),Codec:DE(Be.optional(TE.Codec)),extract:e=>e.availabilityAssignment},e.timeslot={key:_C.index(BC.Tau),Codec:Be.u32.asOpaque(),extract:e=>e.timeslot},e.privilegedServices={key:_C.index(BC.Chi),Codec:KE.Codec,extract:e=>e.privilegedServices},e.statistics={key:_C.index(BC.Pi),Codec:vC.Codec,extract:e=>e.statistics},e.accumulationQueue={key:_C.index(BC.Omega),Codec:Kr(ke(Be.sequenceVarLen(xC.Codec))),extract:e=>e.accumulationQueue},e.recentlyAccumulated={key:_C.index(BC.Xi),Codec:Kr(Be.sequenceVarLen(Be.bytes(Pe).asOpaque()).convert(e=>Array.from(e),e=>bt.from(e))),extract:e=>e.recentlyAccumulated},e.accumulationOutputLog={key:_C.index(BC.Theta),Codec:Be.sequenceVarLen(OE.Codec),extract:e=>e.accumulationOutputLog},e.serviceData=e=>({key:_C.serviceInfo(e),Codec:iC.Codec}),e.serviceStorage=(e,t)=>({key:_C.serviceStorage(e,t),Codec:UC}),e.servicePreimages=(e,t)=>({key:_C.servicePreimage(e,t),Codec:UC}),e.serviceLookupHistory=(e,t,r)=>({key:_C.serviceLookupHistory(e,t,r),Codec:ke(Be.sequenceVarLen(Be.u32))})}(RC||(RC={}));const UC=Ce.new("Dump",{bytes:64,isExact:!1},(e,t)=>e.bytes(L.fromBlob(t.raw,t.raw.length)),e=>P.blobFrom(e.bytes(e.source.length-e.bytesRead()).raw),e=>e.bytes(e.decoder.source.length-e.decoder.bytesRead()));var TC;!function(e){e[e.Insert=0]="Insert",e[e.Remove=1]="Remove"}(TC||(TC={}));const NC=P.empty();function DC(e,t){const r=new Uint8Array(4+t.length);return r.set(de(e)),r.set(t.raw,4),P.blobFrom(qe(r).raw)}class MC{spec;backend;_recentServiceIds;static fromStateEntries(e,t,r=[]){return new MC(e,t,r)}static new(e,t,r=[]){return new MC(e,t,r)}constructor(e,t,r){this.spec=e,this.backend=t,this._recentServiceIds=r}[M](){return this.backend}updateBackend(e){this.backend=e}recentServiceIds(){return this._recentServiceIds}getService(e){const t=this.retrieveOptional(RC.serviceData(e));return void 0===t?null:(this._recentServiceIds.includes(e)||this._recentServiceIds.push(e),new PC(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 fe.decodeObject(t,s,this.spec)}retrieveOptional({key:e,Codec:t}){const r=this.backend.get(e);if(null!==r)return fe.decodeObject(t,r,this.spec)}get availabilityAssignment(){return this.retrieve(RC.availabilityAssignment,"availabilityAssignment")}get designatedValidatorData(){return this.retrieve(RC.designatedValidators,"designatedValidatorData")}get nextValidatorData(){return this.retrieve(RC.safrole,"safroleData.nextValidatorData").nextValidatorData}get currentValidatorData(){return this.retrieve(RC.currentValidators,"currentValidators")}get previousValidatorData(){return this.retrieve(RC.previousValidators,"previousValidators")}get disputesRecords(){return this.retrieve(RC.disputesRecords,"disputesRecords")}get timeslot(){return this.retrieve(RC.timeslot,"timeslot")}get entropy(){return this.retrieve(RC.entropy,"entropy")}get authPools(){return this.retrieve(RC.authPools,"authPools")}get authQueues(){return this.retrieve(RC.authQueues,"authQueues")}get recentBlocks(){return this.retrieve(RC.recentBlocks,"recentBlocks")}get statistics(){return this.retrieve(RC.statistics,"statistics")}get accumulationQueue(){return this.retrieve(RC.accumulationQueue,"accumulationQueue")}get recentlyAccumulated(){return this.retrieve(RC.recentlyAccumulated,"recentlyAccumulated")}get ticketsAccumulator(){return this.retrieve(RC.safrole,"safroleData.ticketsAccumulator").ticketsAccumulator}get sealingKeySeries(){return this.retrieve(RC.safrole,"safrole.sealingKeySeries").sealingKeySeries}get epochRoot(){return this.retrieve(RC.safrole,"safrole.epochRoot").epochRoot}get privilegedServices(){return this.retrieve(RC.privilegedServices,"privilegedServices")}get accumulationOutputLog(){return v.isGreaterOrEqual(h.V0_6_7)?this.retrieve(RC.accumulationOutputLog,"accumulationOutputLog"):[]}}class PC{serviceId;accountInfo;retrieveOptional;constructor(e,t,r){this.serviceId=e,this.accountInfo=t,this.retrieveOptional=r}getInfo(){return this.accountInfo}getStorage(e){if(v.isLessThan(h.V0_6_7)){const t=4,r=new Uint8Array(t+e.length);r.set(de(this.serviceId)),r.set(e.raw,t);const s=P.blobFrom(qe(r).raw);return this.retrieveOptional(RC.serviceStorage(this.serviceId,s))??null}return this.retrieveOptional(RC.serviceStorage(this.serviceId,e))??null}hasPreimage(e){return void 0!==this.retrieveOptional(RC.servicePreimages(this.serviceId,e))}getPreimage(e){return this.retrieveOptional(RC.servicePreimages(this.serviceId,e))??null}getLookupHistory(e,t){const r=this.retrieveOptional(RC.serviceLookupHistory(this.serviceId,e,t));return void 0===r?null:oC(r.map(Ur))}}class LC{hasher;nodes=pt.new();constructor(e){this.hasher=e}get(e){return LC.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()!==QS.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 HC extends LC{remove(e){return LC.withHashCompat(e,e=>{this.nodes.delete(e)})}insert(e,t){const r=t??this.hashNode(e);return LC.withHashCompat(r,t=>{this.nodes.set(t,e)}),r}}const VC=(e,t)=>t.getKey().compare(e.getKey());class KC{nodes;root;static empty(e){return new KC(new HC(e))}static computeStateRoot(e,t){return KC.fromLeaves(e,t).getRootHash()}static fromLeaves(e,t){let r=null;const s=new HC(e);for(const e of t)r=QC(r,s,e);return new KC(s,r)}static constructLeaf(e,t,r,s){return GS.fromValue(t,r,()=>s??e.hashConcat(r.raw).asOpaque())}constructor(e,t=null){this.nodes=e,this.root=t}set(e,t,r){const s=KC.constructLeaf(this.nodes.hasher,e,t,r);return this.root=QC(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?L.zero(Pe).asOpaque():this.nodes.hashNode(this.root)}toString(){return GC(this.root,this.nodes)}}function QC(e,t,r){if(null===e)return t.insert(r.node),r.node;const s=function(e,t,r){const s=new FC;let i=e,n=t.hashNode(e);for(;;){if(i.getNodeType()!==QS.Branch){const e=i.asLeafNode();return s.leafToReplace=[e,n],s}const e=i.asBranchNode(),a=$C(r,s.bitIndex),o=a?e.getRight():e.getLeft();s.branchingHistory.push([e,n,a]);const c=t.get(o);if(null===c){if(o.isEqualTo(L.zero(Pe)))return s;throw new Error(`Missing trie node '${o}' with key prefix: ${r}[0..${s.bitIndex}]`)}i=c,n=o,s.bitIndex+=1}}(e,t,r.getKey()),i=void 0!==s.leafToReplace?function(e,t,r,s){const i=s.getKey();let[n,a]=r;const o=n.getKey(),c=t.insert(s.node);if(o.isEqualTo(i))return n.getValueHash().isEqualTo(s.getValueHash())||t.remove(a),[s.node,c];const l=[];let d=$C(i,e.bitIndex);for(;e.bitIndex<248;){d=$C(i,e.bitIndex);const t=$C(o,e.bitIndex);if(d!==t)break;l.push(t),e.bitIndex+=1}const u=L.zero(Pe).asOpaque();(()=>{const t=e.branchingHistory.length;return t>0&&!1===e.branchingHistory[t-1][2]})()&&!d&&(a=t.hashNode(n.node));let h=d?$S.fromSubNodes(a,c):$S.fromSubNodes(c,a),f=t.insert(h.node),g=l.pop();for(;void 0!==g;)h=g?$S.fromSubNodes(u,f):$S.fromSubNodes(f,u),f=t.insert(h.node),g=l.pop();return[h.node,f]}(s,t,s.leafToReplace,r):[r.node,t.insert(r.node)];let n=s.branchingHistory.pop(),[a,o]=i;for(;void 0!==n;){const[e,r,i]=n;t.remove(r);const c=i?$S.fromSubNodes(e.getLeft(),o):$S.fromSubNodes(o,e.getRight());o=t.insert(c.node),a=c.node,n=s.branchingHistory.pop()}return a}class FC{branchingHistory=[];bitIndex=0;leafToReplace}function $C(e,t){w(t<248);const r=t>>>3,s=128>>>t-(r<<3);return 0!==(e.raw[r]&s)}function GC(e,t){if(null===e)return"<empty tree>";if(e.getNodeType()===QS.Branch){const r=e.asBranchNode(),s=r.getLeft(),i=r.getRight(),n=e=>e.split("\n").map(e=>`\t\t${e}`).join("\n"),a=GC(t.get(s),t),o=GC(t.get(i),t);return`<branch>\n\t-- ${s}: ${n(a)}\n\t-- ${i}: ${n(o)}\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 jC={hashConcat:(e,t=[])=>je([e,...t])};class qC{entries;static serializeInMemory(e,t){return new qC(function(e,t){const r=vt.fromEntries([]);function s(s){r.set(s.key,Ae.encodeObject(s.Codec,s.extract(t),e))}s(RC.authPools),s(RC.authQueues),s(RC.recentBlocks),s(RC.safrole),s(RC.disputesRecords),s(RC.entropy),s(RC.designatedValidators),s(RC.currentValidators),s(RC.previousValidators),s(RC.availabilityAssignment),s(RC.timeslot),s(RC.privilegedServices),s(RC.statistics),s(RC.accumulationQueue),s(RC.recentlyAccumulated),v.isGreaterOrEqual(h.V0_6_7)&&s(RC.accumulationOutputLog);for(const[e,s]of t.services.entries()){const{key:t,Codec:i}=RC.serviceData(e);r.set(t,Ae.encodeObject(i,s.getInfo()));for(const t of s.data.preimages.values()){const{key:s,Codec:i}=RC.servicePreimages(e,t.hash);r.set(s,Ae.encodeObject(i,t.blob))}for(const t of s.data.storage.values()){const{key:s,Codec:i}=RC.serviceStorage(e,t.key);r.set(s,Ae.encodeObject(i,t.value))}for(const t of s.data.lookupHistory.values())for(const s of t){const{key:t,Codec:i}=RC.serviceLookupHistory(e,s.hash,s.length);r.set(t,Ae.encodeObject(i,s.slots.slice()))}}return r}(e,t))}static fromDictionaryUnsafe(e){return new qC(e)}static fromEntriesUnsafe(e){return new qC(vt.fromEntries(e))}trieCache=null;constructor(e){this.entries=e}[M](){return this.entries}[Symbol.iterator](){return this.entries[Symbol.iterator]()}getTrie(){if(null===this.trieCache){const e=KC.empty(jC);for(const[t,r]of this.entries)e.set(t.asOpaque(),r);this.trieCache=e}return this.trieCache}get(e){return this.entries.get(e)??null}applyUpdate(e){this.trieCache=null;for(const[t,r,s]of e)t===TC.Insert?this.entries.set(r,s):t===TC.Remove?this.entries.delete(r):E(t)}getRootHash(){return this.getTrie().getRootHash().asOpaque()}}const zC=(e,t,{typicalLength:r=32,compare:s=(e,r)=>{const s=t(e),i=t(r);return s<i?g.Less:s>i?g.Greater:g.Equal}}={})=>Ce.new(`Map<${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(ne(i.length));for(const r of i)e.encode(t,r)},r=>{const i=new Map,n=r.varU32();let a=null;for(let o=0;o<n;o+=1){const n=e.decode(r),o=t(n);if(i.has(o))throw new Error(`Duplicate item in the dictionary encoding: "${o}"!`);if(null!==a&&s(a,n).isGreaterOrEqual())throw new Error(`The keys in dictionary encoding are not sorted "${t(a)}" >= "${t(n)}"!`);i.set(o,n),a=n}return i},t=>{const r=t.decoder.varU32();t.sequenceFixLen(e,r)}),WC=Be.object({hash:Be.bytes(Pe).asOpaque(),length:Be.u32,slots:ke(Be.sequenceVarLen(Be.u32.asOpaque())).convert(R,oC)},"LookupHistoryItem",({hash:e,length:t,slots:r})=>new cC(e,t,r)),JC=Be.object({key:Be.bytes(Pe).asOpaque(),data:Be.sequenceVarLen(WC)}),YC=Be.sequenceVarLen(JC).convert(e=>{const t=[];for(const[r,s]of e)t.push({key:r,data:s});return t},e=>{const t=pt.new();for(const{key:r,data:s}of e){const e=t.get(r)??[];e.push(...s),t.set(r,e)}return t});class XC extends EC{static Codec=Be.Class(XC,{serviceId:Be.u32.asOpaque(),data:Be.object({info:iC.Codec,preimages:_t(nC.Codec,e=>e.hash),lookupHistory:YC,storage:zC(aC.Codec,e=>e.key.toString())})});constructor(e,t){super(e,t)}static create({serviceId:e,data:t}){return new XC(e,t)}}var ZC,ek,tk;Be.Class(CC,{authPools:RC.authPools.Codec,authQueues:RC.authQueues.Codec,recentBlocks:RC.recentBlocks.Codec,nextValidatorData:Hr(YE.Codec),epochRoot:Be.bytes(De).asOpaque(),sealingKeySeries:eC.Codec,ticketsAccumulator:ke(Be.sequenceVarLen(Ot.Codec)).convert(e=>e,mt),disputesRecords:RC.disputesRecords.Codec,entropy:RC.entropy.Codec,designatedValidatorData:RC.designatedValidators.Codec,currentValidatorData:RC.currentValidators.Codec,previousValidatorData:RC.previousValidators.Codec,availabilityAssignment:RC.availabilityAssignment.Codec,timeslot:RC.timeslot.Codec,privilegedServices:RC.privilegedServices.Codec,statistics:RC.statistics.Codec,accumulationQueue:RC.accumulationQueue.Codec,recentlyAccumulated:RC.recentlyAccumulated.Codec,accumulationOutputLog:RC.accumulationOutputLog.Codec,services:Be.dictionary(Be.u32.asOpaque(),XC.Codec,{sortKeys:(e,t)=>e-t})}),function(e){e[e.Conflict=0]="Conflict",e[e.Commit=1]="Commit"}(ZC||(ZC={})),function(e){e[e.InvalidLeafData=0]="InvalidLeafData"}(ek||(ek={}));class rk{leaves;db;static fromLeavesBlob(e,t){if(e.length%64!=0)return D.error(ek.InvalidLeafData,`${e.length} is not a multiply of 64: ${e}`);const r=[];for(const t of e.chunks(64)){const e=new FS(t.raw);if(e.getNodeType()===QS.Branch)return D.error(ek.InvalidLeafData,`Branch node detected: ${t}`);r.push(e.asLeafNode())}return D.ok(new rk(r,t))}lookup;constructor(e,t){this.leaves=e,this.db=t,this.lookup=vt.fromEntries(e.map(e=>[e.getKey().asOpaque(),e.hasEmbeddedValue()?{kind:tk.EmbeddedValue,value:e.getValue()}:{kind:tk.DbKey,key:e.getValueHash().raw}]))}get(e){const t=this.lookup.get(e);return void 0===t?null:t.kind===tk.EmbeddedValue?t.value:t.kind===tk.DbKey?P.blobFrom(this.db.get(t.key)):void E(t)}getStateRoot(){return KC.computeStateRoot(jC,this.leaves).asOpaque()}}!function(e){e[e.EmbeddedValue=0]="EmbeddedValue",e[e.DbKey=1]="DbKey"}(tk||(tk={}));class sk{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){return await this.updateAndCommit(e,It.fromArray(VC,[]),Array.from(t,e=>[TC.Insert,e[0],e[1]]))}async updateAndCommit(e,t,r){const s=[];for(const[e,i,n]of r)if(e===TC.Insert){const e=KC.constructLeaf(jC,i.asOpaque(),n);t.replace(e),e.hasEmbeddedValue()||s.push([e.getValueHash(),n])}else if(e===TC.Remove){const e=KC.constructLeaf(jC,i.asOpaque(),P.empty());t.removeOne(e)}else E(e);const i=P.blobFromParts(t.array.map(e=>e.node.raw)),n=this.states.put(e.raw,i.raw),a=this.values.transaction(()=>{for(const[e,t]of s)this.values.put(e.raw,t.raw)});try{await Promise.all([a,n])}catch(e){return console.error(e),D.error(ZC.Commit)}return D.ok(O)}async updateAndSetState(e,t,r){const s=It.fromSortedArray(VC,t.backend.leaves),i=function*(e,t){yield*function*(e,t){function r(t,r){return[TC.Insert,r.key,Ae.encodeObject(r.Codec,t,e)]}void 0!==t.authPools&&(yield r(t.authPools,RC.authPools)),void 0!==t.authQueues&&(yield r(t.authQueues,RC.authQueues)),void 0!==t.recentBlocks&&(yield r(t.recentBlocks,RC.recentBlocks));const s=function(e,t,r,s){if(void 0!==e&&void 0!==t&&void 0!==r&&void 0!==s)return tC.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,RC.safrole)),void 0!==t.disputesRecords&&(yield r(t.disputesRecords,RC.disputesRecords)),void 0!==t.entropy&&(yield r(t.entropy,RC.entropy)),void 0!==t.designatedValidatorData&&(yield r(t.designatedValidatorData,RC.designatedValidators)),void 0!==t.currentValidatorData&&(yield r(t.currentValidatorData,RC.currentValidators)),void 0!==t.previousValidatorData&&(yield r(t.previousValidatorData,RC.previousValidators)),void 0!==t.availabilityAssignment&&(yield r(t.availabilityAssignment,RC.availabilityAssignment)),void 0!==t.timeslot&&(yield r(t.timeslot,RC.timeslot)),void 0!==t.privilegedServices&&(yield r(t.privilegedServices,RC.privilegedServices)),void 0!==t.statistics&&(yield r(t.statistics,RC.statistics)),void 0!==t.accumulationQueue&&(yield r(t.accumulationQueue,RC.accumulationQueue)),void 0!==t.recentlyAccumulated&&(yield r(t.recentlyAccumulated,RC.recentlyAccumulated))}(e,t);const r=(t,r)=>Ae.encodeObject(t,r,e);yield*function*(e,t){for(const{action:r,serviceId:s}of e??[]){const e=RC.serviceData(s);if(yield[TC.Insert,e.key,t(e.Codec,r.account)],r.kind===dC.Create&&null!==r.lookupHistory){const{lookupHistory:e}=r,i=RC.serviceLookupHistory(s,e.hash,e.length);yield[TC.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 lC.Provide:{const{hash:e,blob:i}=r.preimage,n=RC.servicePreimages(s,e);if(yield[TC.Insert,n.key,i],null!==r.slot){const n=RC.serviceLookupHistory(s,e,ne(i.length));yield[TC.Insert,n.key,t(n.Codec,oC([r.slot]))]}break}case lC.UpdateOrAdd:{const{hash:e,length:i,slots:n}=r.item,a=RC.serviceLookupHistory(s,e,i);yield[TC.Insert,a.key,t(a.Codec,n)];break}case lC.Remove:{const{hash:e,length:t}=r,i=RC.servicePreimages(s,e);yield[TC.Remove,i.key,NC];const n=RC.serviceLookupHistory(s,e,t);yield[TC.Remove,n.key,NC];break}default:E(r)}}(t.preimages,r),yield*function*(e){for(const{action:t,serviceId:r}of e??[])switch(t.kind){case uC.Set:{const e=v.isGreaterOrEqual(h.V0_6_7)?t.storage.key:DC(r,t.storage.key),s=RC.serviceStorage(r,e);yield[TC.Insert,s.key,t.storage.value];break}case uC.Remove:{const e=v.isGreaterOrEqual(h.V0_6_7)?t.key:DC(r,t.key),s=RC.serviceStorage(r,e);yield[TC.Remove,s.key,NC];break}default:E(t)}}(t.storage),yield*function*(e){for(const t of e??[]){const e=RC.serviceData(t);yield[TC.Remove,e.key,NC]}}(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=rk.fromLeavesBlob(P.blobFrom(t),{get(e){const t=r.get(e);if(void 0===t)throw new Error(`Missing required value: ${P.blobFrom(e)} in the DB`);return t}});if(s.isError)throw new Error(`Inconsistent DB. Invalid leaf nodes for ${e}: ${N(s)}`);return MC.new(this.spec,s.ok)}}const ik=2**32,nk=ri.new(void 0,"state-machine/port");class ak{port;listeners=new zn.EventEmitter;responseListeners=new zn.EventEmitter;messageId=0;constructor(e){this.port=e,e.on("message",e=>{try{this.dispatchPortMessage(e)}catch(t){throw nk.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)%ik,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(ok(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){w("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 nk.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":w(-1!==this.responseListeners.eventNames().indexOf(ok(e.id))),this.responseListeners.emit(ok(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 ok(e){return`req:${e}`}const ck=ri.new(void 0,"state-machine"),lk="channel";class dk{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 ck.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 ck.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),a=this.currentState()!==s;if(void 0!==n.transitionTo&&this.machine.transition(n.transitionTo.state,n.transitionTo.data),!a)return this.port.respond(s.stateName,r,n.response);ck.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 ck.trace(`[${this.machine.name}] transitioned to ${this.currentState()}`),this}static async createAndTransferChannel(e,t){const r=new EE.MessageChannel,s=new ak(r.port2),i=e.currentState().stateName,[n,a]=s.prepareRequest(i,lk,r.port1);t.postMessage(n,[r.port1]);try{await a}catch(e){ck.error(JSON.stringify(e))}return new dk(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{w("request"===t.kind,"The initial message should be a request with channel."),w(t.name===lk),w(t.data instanceof EE.MessagePort);const s=new ak(t.data);s.respond(e.currentState().stateName,t,"OK"),r(s)}catch(e){s(e)}})}),s=await r;return new dk(e,s)}}const uk=Symbol(),hk=Symbol();class fk{emitter=new zn.EventEmitter;emit(e){this.emitter.emit(uk,e)}on(e){return this.emitter.on(uk,e),this}off(e){return this.emitter.off(uk,e),this}once(e){return this.emitter.once(uk,e),this}onceDone(e){return this.emitter.once(hk,e),this}markDone(){this.emitter.emit(hk),this.emitter.removeAllListeners(uk),this.emitter.removeAllListeners(hk)}}class gk{name;state;allStates;stateListeners=new zn.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 w(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 pk=ri.new(void 0,"state-machine/state");class bk{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){pk.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 mk extends bk{constructor(){super({name:"finished"})}close(e){e.close()}async waitForWorkerToFinish(){return this.data}}class yk extends bk{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 Ak extends bk{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 Ik(e,t,r,s){const i=new EE.Worker(e),n=function(e,t,r){const s=new yk(t),i=new mk;return new gk(e,s,[s,r,i])}(`main->${r}`,r,s),a=await dk.createAndTransferChannel(n,i);return t.trace(`[${n.name}] Worker spawned ${a.currentState()}`),a}const vk=4294967295,wk=4294967296,Sk=4096,Ek=(w(!0,"incorrect minimal allocation shift"),7),Ck=Sk>>Ek,kk=1048575,xk=1048576,Bk=e=>S(e,e>=0&&e<=vk,`Incorrect memory index: ${e}!`),_k=e=>S(e,e>=0&&e<=4294967296,`Incorrect sbrk index: ${e}!`);var Rk,Ok;(Ok=Rk||(Rk={}))[Ok.OK=255]="OK",Ok[Ok.HALT=0]="HALT",Ok[Ok.PANIC=1]="PANIC",Ok[Ok.FAULT=2]="FAULT",Ok[Ok.HOST=3]="HOST",Ok[Ok.OOG=4]="OOG";const Uk=e=>S(e,e>=0&&e<=13,`Incorrect register index: ${e}!`);class Tk{bytes;asSigned;asUnsigned;constructor(e=new Uint8Array(104)){this.bytes=e,w(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 w(104===e.length,"Invalid size of registers array."),new Tk(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]=Nk(t)}setI32(e,t){this.asSigned[e]=Nk(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 Nk(e){const t="number"==typeof e?BigInt(e):e,r=BigInt(4294967295),s=t&r;return(s&BigInt(2147483648))!==BigInt(0)?s|~r:s}const Dk=e=>ne(e);var Mk,Pk;function Lk(...e){return e.map(Uk)}!function(e){e[e.Halt=0]="Halt",e[e.Panic=1]="Panic"}(Mk||(Mk={}));class Hk{lookupTableForward;constructor(e){this.lookupTableForward=this.buildLookupTableForward(e)}isInstruction(e){return 0===this.lookupTableForward[e]}getNoOfBytesToNextInstruction(e){return w(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 Hk(J.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"}(Pk||(Pk={}));class Vk{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 Kk{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 Qk{nibblesDecoder=new Kk;offsetDecoder=new Vk;code=new Uint8Array;mask=Hk.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 Pk.NO_ARGUMENTS:break;case Pk.ONE_IMMEDIATE:{const s=Math.min(4,r-1),i=e+1;t.immediateDecoder.setBytes(this.code.subarray(i,i+s));break}case Pk.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 Pk.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 Pk.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,a=n+i;t.immediateDecoder.setBytes(this.code.subarray(n,a));const o=e+2+i,c=o+Math.min(4,Math.max(0,r-2-i));this.offsetDecoder.setBytes(this.code.subarray(o,c)),t.nextPc=e+this.offsetDecoder.getSigned();break}case Pk.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 Pk.TWO_REGISTERS:{const r=this.code[e+1];this.nibblesDecoder.setByte(r),t.firstRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();break}case Pk.ONE_OFFSET:{const s=e+1,i=s+Math.min(4,r-1),n=this.code.subarray(s,i);this.offsetDecoder.setBytes(n);const a=this.offsetDecoder.getSigned();t.nextPc=e+a;break}case Pk.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)),a=this.code.subarray(i,n);t.immediateDecoder.setBytes(a);break}case Pk.TWO_IMMEDIATES:{const s=this.code[e+1];this.nibblesDecoder.setByte(s);const i=this.nibblesDecoder.getLowNibbleAsLength(),n=e+2,a=n+i,o=this.code.subarray(n,a);t.firstImmediateDecoder.setBytes(o);const c=a,l=c+Math.min(4,Math.max(0,r-2-i)),d=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(d);break}case Pk.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,a=n+i,o=this.code.subarray(n,a);t.firstImmediateDecoder.setBytes(o);const c=a,l=c+Math.min(4,Math.max(0,r-2-i)),d=this.code.subarray(c,l);t.secondImmediateDecoder.setBytes(d);break}case Pk.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(),a=e+3,o=a+n,c=this.code.subarray(a,o);t.firstImmediateDecoder.setBytes(c);const l=o,d=l+Math.min(4,Math.max(0,r-3-n)),u=this.code.subarray(l,d);t.secondImmediateDecoder.setBytes(u);break}case Pk.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 Fk{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 $k=Object.keys(Pk).length/2;var Gk;!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"}(Gk||(Gk={}));const jk=Gk.MIN_U,qk=(()=>{const e=new Array(jk+1);return e[Gk.TRAP]=Pk.NO_ARGUMENTS,e[Gk.FALLTHROUGH]=Pk.NO_ARGUMENTS,e[Gk.ECALLI]=Pk.ONE_IMMEDIATE,e[Gk.LOAD_IMM_64]=Pk.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,e[Gk.STORE_IMM_U8]=Pk.TWO_IMMEDIATES,e[Gk.STORE_IMM_U16]=Pk.TWO_IMMEDIATES,e[Gk.STORE_IMM_U32]=Pk.TWO_IMMEDIATES,e[Gk.STORE_IMM_U64]=Pk.TWO_IMMEDIATES,e[Gk.JUMP]=Pk.ONE_OFFSET,e[Gk.JUMP_IND]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.LOAD_IMM]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.LOAD_U8]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.LOAD_I8]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.LOAD_U16]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.LOAD_I16]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.LOAD_U32]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.LOAD_I32]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.LOAD_U64]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.STORE_U8]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.STORE_U16]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.STORE_U32]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.STORE_U64]=Pk.ONE_REGISTER_ONE_IMMEDIATE,e[Gk.STORE_IMM_IND_U8]=Pk.ONE_REGISTER_TWO_IMMEDIATES,e[Gk.STORE_IMM_IND_U16]=Pk.ONE_REGISTER_TWO_IMMEDIATES,e[Gk.STORE_IMM_IND_U32]=Pk.ONE_REGISTER_TWO_IMMEDIATES,e[Gk.STORE_IMM_IND_U64]=Pk.ONE_REGISTER_TWO_IMMEDIATES,e[Gk.LOAD_IMM_JUMP]=Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Gk.BRANCH_EQ_IMM]=Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Gk.BRANCH_NE_IMM]=Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Gk.BRANCH_LT_U_IMM]=Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Gk.BRANCH_LE_U_IMM]=Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Gk.BRANCH_GE_U_IMM]=Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Gk.BRANCH_GT_U_IMM]=Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Gk.BRANCH_LT_S_IMM]=Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Gk.BRANCH_LE_S_IMM]=Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Gk.BRANCH_GE_S_IMM]=Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Gk.BRANCH_GT_S_IMM]=Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[Gk.MOVE_REG]=Pk.TWO_REGISTERS,e[Gk.SBRK]=Pk.TWO_REGISTERS,e[Gk.COUNT_SET_BITS_64]=Pk.TWO_REGISTERS,e[Gk.COUNT_SET_BITS_32]=Pk.TWO_REGISTERS,e[Gk.LEADING_ZERO_BITS_64]=Pk.TWO_REGISTERS,e[Gk.LEADING_ZERO_BITS_32]=Pk.TWO_REGISTERS,e[Gk.TRAILING_ZERO_BITS_64]=Pk.TWO_REGISTERS,e[Gk.TRAILING_ZERO_BITS_32]=Pk.TWO_REGISTERS,e[Gk.SIGN_EXTEND_8]=Pk.TWO_REGISTERS,e[Gk.SIGN_EXTEND_16]=Pk.TWO_REGISTERS,e[Gk.ZERO_EXTEND_16]=Pk.TWO_REGISTERS,e[Gk.REVERSE_BYTES]=Pk.TWO_REGISTERS,e[Gk.STORE_IND_U8]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.STORE_IND_U16]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.STORE_IND_U32]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.STORE_IND_U64]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.LOAD_IND_U8]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.LOAD_IND_I8]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.LOAD_IND_U16]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.LOAD_IND_I16]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.LOAD_IND_U32]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.LOAD_IND_I32]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.LOAD_IND_U64]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.ADD_IMM_32]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.ADD_IMM_64]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.AND_IMM]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.XOR_IMM]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.OR_IMM]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.MUL_IMM_32]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.MUL_IMM_64]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SET_LT_U_IMM]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SET_LT_S_IMM]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SHLO_L_IMM_32]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SHLO_R_IMM_32]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SHAR_R_IMM_32]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.NEG_ADD_IMM_32]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SHLO_L_IMM_64]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SHLO_R_IMM_64]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SHAR_R_IMM_64]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.NEG_ADD_IMM_64]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SET_GT_U_IMM]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SET_GT_S_IMM]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SHLO_L_IMM_ALT_32]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SHLO_R_IMM_ALT_32]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SHAR_R_IMM_ALT_32]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SHLO_L_IMM_ALT_64]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SHLO_R_IMM_ALT_64]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.SHAR_R_IMM_ALT_64]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.CMOV_IZ_IMM]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.CMOV_NZ_IMM]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.ROT_R_64_IMM]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.ROT_R_64_IMM_ALT]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.ROT_R_32_IMM]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.ROT_R_32_IMM_ALT]=Pk.TWO_REGISTERS_ONE_IMMEDIATE,e[Gk.BRANCH_EQ]=Pk.TWO_REGISTERS_ONE_OFFSET,e[Gk.BRANCH_NE]=Pk.TWO_REGISTERS_ONE_OFFSET,e[Gk.BRANCH_LT_U]=Pk.TWO_REGISTERS_ONE_OFFSET,e[Gk.BRANCH_LT_S]=Pk.TWO_REGISTERS_ONE_OFFSET,e[Gk.BRANCH_GE_U]=Pk.TWO_REGISTERS_ONE_OFFSET,e[Gk.BRANCH_GE_S]=Pk.TWO_REGISTERS_ONE_OFFSET,e[Gk.LOAD_IMM_JUMP_IND]=Pk.TWO_REGISTERS_TWO_IMMEDIATES,e[Gk.ADD_32]=Pk.THREE_REGISTERS,e[Gk.ADD_64]=Pk.THREE_REGISTERS,e[Gk.SUB_32]=Pk.THREE_REGISTERS,e[Gk.SUB_64]=Pk.THREE_REGISTERS,e[Gk.AND]=Pk.THREE_REGISTERS,e[Gk.XOR]=Pk.THREE_REGISTERS,e[Gk.OR]=Pk.THREE_REGISTERS,e[Gk.MUL_32]=Pk.THREE_REGISTERS,e[Gk.MUL_64]=Pk.THREE_REGISTERS,e[Gk.MUL_UPPER_S_S]=Pk.THREE_REGISTERS,e[Gk.MUL_UPPER_U_U]=Pk.THREE_REGISTERS,e[Gk.MUL_UPPER_S_U]=Pk.THREE_REGISTERS,e[Gk.DIV_U_32]=Pk.THREE_REGISTERS,e[Gk.DIV_S_32]=Pk.THREE_REGISTERS,e[Gk.REM_U_32]=Pk.THREE_REGISTERS,e[Gk.REM_S_32]=Pk.THREE_REGISTERS,e[Gk.DIV_U_64]=Pk.THREE_REGISTERS,e[Gk.DIV_S_64]=Pk.THREE_REGISTERS,e[Gk.REM_U_64]=Pk.THREE_REGISTERS,e[Gk.REM_S_64]=Pk.THREE_REGISTERS,e[Gk.SET_LT_U]=Pk.THREE_REGISTERS,e[Gk.SET_LT_S]=Pk.THREE_REGISTERS,e[Gk.SHLO_L_32]=Pk.THREE_REGISTERS,e[Gk.SHLO_R_32]=Pk.THREE_REGISTERS,e[Gk.SHAR_R_32]=Pk.THREE_REGISTERS,e[Gk.SHLO_L_64]=Pk.THREE_REGISTERS,e[Gk.SHLO_R_64]=Pk.THREE_REGISTERS,e[Gk.SHAR_R_64]=Pk.THREE_REGISTERS,e[Gk.CMOV_IZ]=Pk.THREE_REGISTERS,e[Gk.CMOV_NZ]=Pk.THREE_REGISTERS,e[Gk.ROT_L_64]=Pk.THREE_REGISTERS,e[Gk.ROT_L_32]=Pk.THREE_REGISTERS,e[Gk.ROT_R_64]=Pk.THREE_REGISTERS,e[Gk.ROT_R_32]=Pk.THREE_REGISTERS,e[Gk.AND_INV]=Pk.THREE_REGISTERS,e[Gk.OR_INV]=Pk.THREE_REGISTERS,e[Gk.XNOR]=Pk.THREE_REGISTERS,e[Gk.MAX]=Pk.THREE_REGISTERS,e[Gk.MAX_U]=Pk.THREE_REGISTERS,e[Gk.MIN]=Pk.THREE_REGISTERS,e[Gk.MIN_U]=Pk.THREE_REGISTERS,e})(),zk=e=>ne(e),Wk=e=>oe(e),Jk=e=>"number"==typeof e&&e<2**32?zk(e):Wk(e);function Yk(e){return new Xk(oe(e))}class Xk{gas;constructor(e){this.gas=e}set(e){this.gas=oe(e)}get(){return Jk(this.gas)}sub(e){const t=this.gas-oe(e);return t>=0n?(this.gas=oe(t),!1):(this.gas=oe(0n),!0)}}const Zk=[[Gk.TRAP,1],[Gk.FALLTHROUGH,1],[Gk.ECALLI,v.isSuite(f.JAMDUNA,h.V0_6_5)?0:1],[Gk.LOAD_IMM_64,1],[Gk.STORE_IMM_U8,1],[Gk.STORE_IMM_U16,1],[Gk.STORE_IMM_U32,1],[Gk.STORE_IMM_U64,1],[Gk.JUMP,1],[Gk.JUMP_IND,1],[Gk.LOAD_IMM,1],[Gk.LOAD_U8,1],[Gk.LOAD_I8,1],[Gk.LOAD_U16,1],[Gk.LOAD_I16,1],[Gk.LOAD_U32,1],[Gk.LOAD_I32,1],[Gk.LOAD_U64,1],[Gk.STORE_U8,1],[Gk.STORE_U16,1],[Gk.STORE_U32,1],[Gk.STORE_U64,1],[Gk.STORE_IMM_IND_U8,1],[Gk.STORE_IMM_IND_U16,1],[Gk.STORE_IMM_IND_U32,1],[Gk.STORE_IMM_IND_U64,1],[Gk.LOAD_IMM_JUMP,1],[Gk.BRANCH_EQ_IMM,1],[Gk.BRANCH_NE_IMM,1],[Gk.BRANCH_LT_U_IMM,1],[Gk.BRANCH_LE_U_IMM,1],[Gk.BRANCH_GE_U_IMM,1],[Gk.BRANCH_GT_U_IMM,1],[Gk.BRANCH_LT_S_IMM,1],[Gk.BRANCH_LE_S_IMM,1],[Gk.BRANCH_GE_S_IMM,1],[Gk.BRANCH_GT_S_IMM,1],[Gk.MOVE_REG,1],[Gk.SBRK,1],[Gk.COUNT_SET_BITS_64,1],[Gk.COUNT_SET_BITS_32,1],[Gk.LEADING_ZERO_BITS_64,1],[Gk.LEADING_ZERO_BITS_32,1],[Gk.TRAILING_ZERO_BITS_64,1],[Gk.TRAILING_ZERO_BITS_32,1],[Gk.SIGN_EXTEND_8,1],[Gk.SIGN_EXTEND_16,1],[Gk.ZERO_EXTEND_16,1],[Gk.REVERSE_BYTES,1],[Gk.STORE_IND_U8,1],[Gk.STORE_IND_U16,1],[Gk.STORE_IND_U32,1],[Gk.STORE_IND_U64,1],[Gk.LOAD_IND_U8,1],[Gk.LOAD_IND_I8,1],[Gk.LOAD_IND_U16,1],[Gk.LOAD_IND_I16,1],[Gk.LOAD_IND_U32,1],[Gk.LOAD_IND_I32,1],[Gk.LOAD_IND_U64,1],[Gk.ADD_IMM_32,1],[Gk.AND_IMM,1],[Gk.XOR_IMM,1],[Gk.OR_IMM,1],[Gk.MUL_IMM_32,1],[Gk.SET_LT_U_IMM,1],[Gk.SET_LT_S_IMM,1],[Gk.SHLO_L_IMM_32,1],[Gk.SHLO_R_IMM_32,1],[Gk.SHAR_R_IMM_32,1],[Gk.NEG_ADD_IMM_32,1],[Gk.SET_GT_U_IMM,1],[Gk.SET_GT_S_IMM,1],[Gk.SHLO_L_IMM_ALT_32,1],[Gk.SHLO_R_IMM_ALT_32,1],[Gk.SHAR_R_IMM_ALT_32,1],[Gk.CMOV_IZ_IMM,1],[Gk.CMOV_NZ_IMM,1],[Gk.ADD_IMM_64,1],[Gk.MUL_IMM_64,1],[Gk.SHLO_L_IMM_64,1],[Gk.SHLO_R_IMM_64,1],[Gk.SHAR_R_IMM_64,1],[Gk.NEG_ADD_IMM_64,1],[Gk.SHLO_L_IMM_ALT_64,1],[Gk.SHLO_R_IMM_ALT_64,1],[Gk.SHAR_R_IMM_ALT_64,1],[Gk.ROT_R_64_IMM,1],[Gk.ROT_R_64_IMM_ALT,1],[Gk.ROT_R_32_IMM,1],[Gk.ROT_R_32_IMM_ALT,1],[Gk.BRANCH_EQ,1],[Gk.BRANCH_NE,1],[Gk.BRANCH_LT_U,1],[Gk.BRANCH_LT_S,1],[Gk.BRANCH_GE_U,1],[Gk.BRANCH_GE_S,1],[Gk.LOAD_IMM_JUMP_IND,1],[Gk.ADD_32,1],[Gk.SUB_32,1],[Gk.MUL_32,1],[Gk.DIV_U_32,1],[Gk.DIV_S_32,1],[Gk.REM_U_32,1],[Gk.REM_S_32,1],[Gk.SHLO_L_32,1],[Gk.SHLO_R_32,1],[Gk.SHAR_R_32,1],[Gk.ADD_64,1],[Gk.SUB_64,1],[Gk.MUL_64,1],[Gk.DIV_U_64,1],[Gk.DIV_S_64,1],[Gk.REM_U_64,1],[Gk.REM_S_64,1],[Gk.SHLO_L_64,1],[Gk.SHLO_R_64,1],[Gk.SHAR_R_64,1],[Gk.AND,1],[Gk.XOR,1],[Gk.OR,1],[Gk.MUL_UPPER_S_S,1],[Gk.MUL_UPPER_U_U,1],[Gk.MUL_UPPER_S_U,1],[Gk.SET_LT_U,1],[Gk.SET_LT_S,1],[Gk.CMOV_IZ,1],[Gk.CMOV_NZ,1],[Gk.ROT_L_64,1],[Gk.ROT_L_32,1],[Gk.ROT_R_64,1],[Gk.ROT_R_32,1],[Gk.AND_INV,1],[Gk.OR_INV,1],[Gk.XNOR,1],[Gk.MAX,1],[Gk.MAX_U,1],[Gk.MIN,1],[Gk.MIN_U,1]].reduce((e,t)=>{const[r,s]=(([e,t])=>[e,{gas:zk(t)}])(t);return e[r]=s,e},{}),ex=(()=>{const e=new Array(jk+1);return e.fill(!1),e[Gk.TRAP]=!0,e[Gk.FALLTHROUGH]=!0,e[Gk.JUMP]=!0,e[Gk.JUMP_IND]=!0,e[Gk.LOAD_IMM_JUMP]=!0,e[Gk.LOAD_IMM_JUMP_IND]=!0,e[Gk.BRANCH_EQ]=!0,e[Gk.BRANCH_NE]=!0,e[Gk.BRANCH_GE_U]=!0,e[Gk.BRANCH_GE_S]=!0,e[Gk.BRANCH_LT_U]=!0,e[Gk.BRANCH_LT_S]=!0,e[Gk.BRANCH_EQ_IMM]=!0,e[Gk.BRANCH_NE_IMM]=!0,e[Gk.BRANCH_LT_U_IMM]=!0,e[Gk.BRANCH_LT_S_IMM]=!0,e[Gk.BRANCH_LE_U_IMM]=!0,e[Gk.BRANCH_LE_S_IMM]=!0,e[Gk.BRANCH_GE_U_IMM]=!0,e[Gk.BRANCH_GE_S_IMM]=!0,e[Gk.BRANCH_GT_U_IMM]=!0,e[Gk.BRANCH_GT_S_IMM]=!0,e})();class tx{basicBlocks=new Set;reset(e,t){this.basicBlocks.clear(),this.basicBlocks.add(0);const r=e.length,s=r=>t.isInstruction(r)&&ex[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 rx=(()=>{const e=new Array(jk+1);for(let t=0;t<jk+1;t++){const r=Zk[t]?.gas;e[t]=r}return e})();class sx{nextPc=0;status=null;exitParam=null;reset(){this.nextPc=0,this.status=null,this.exitParam=null}}const ix=e=>S(e,e>=0&&e<Sk,`Incorect page index: ${e}!`),nx=e=>S(e,e>=0&&e<=kk,`Incorrect page number: ${e}!`);function ax(e){return nx(e===kk?0:e+1)}function ox(e){return Sk*Math.ceil(e/Sk)}function cx(e){return nx(e>>>12)}function lx(e){return Bk(e>>>12<<12)}function dx(e){return Bk(e<<12>>>0)}class ux{address;isAccessFault;constructor(e,t=!0){this.address=e,this.isAccessFault=t}static fromPageNumber(e,t=!1){const r=dx(nx(e));return new ux(r,t)}static fromMemoryIndex(e,t=!1){const r=lx(Bk(e%wk));return new ux(r,t)}}class hx extends Error{constructor(){super("Out of bounds")}}Error,Error;class fx extends Error{constructor(){super("Space between sbrk index and max heap index should be empty!")}}class gx extends Error{constructor(){super("MemoryBuilder was finalized and cannot be changed!")}}class px extends Error{constructor(){super("You are trying to access reserved memory!")}}class bx extends Error{constructor(){super("You try to fill data on memory page that does not exist!")}}Error;class mx extends Error{constructor(){super("Out of memory")}}class yx{start;length;end;lastIndex=null;constructor(e,t){this.start=e,this.length=t,this.end=Bk((this.start+this.length)%wk),t>0&&(this.lastIndex=Bk((this.end-1+wk)%wk))}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>wk)throw new TypeError(`length must be a non-negative integer and less than 4294967296, got ${t}`);return new yx(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 Ax=yx.fromStartAndLength(Bk(0),65536);class Ix{start;length;end;constructor(e,t){this.start=e,this.length=t,this.end=nx((this.start+this.length)%xk)}static fromMemoryRange(e){const t=cx(e.start);if(e.isEmpty())return new Ix(t,0);const r=cx(e.lastIndex??e.end),s=ax(r);if((t===s||t===r)&&e.length>Sk)return new Ix(t,xk);const i=t<s?s-t:xk-t+s;return Ix.fromStartAndLength(t,i)}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>xk)throw new TypeError(`length must be a non-negative integer and less than 1048576, got ${t}`);return new Ix(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=ax(t)}while(t!==e)}}class vx{start;constructor(e){this.start=dx(e)}}class wx extends vx{data;constructor(e,t){super(e),this.data=t}loadInto(e,t,r){const s=t+r;if(s>Sk)return D.error(ux.fromMemoryIndex(this.start+Sk));const i=this.data.subarray(t,s);return e.fill(0,i.length,r),e.set(i),D.ok(O)}storeFrom(e,t){return D.error(ux.fromMemoryIndex(this.start,!0))}setData(e,t){this.data.set(t,e)}isWriteable(){return!1}getPageDump(){return this.data}}class Sx extends vx{buffer;view;constructor(e,t){super(e);const r=t?.length??0,s=Math.min(Sk,Math.max(r,Ck));this.buffer=new ArrayBuffer(s,{maxByteLength:Sk}),this.view=new Uint8Array(this.buffer),void 0!==t&&this.view.set(t)}loadInto(e,t,r){const s=t+r;if(s>Sk)return D.error(ux.fromMemoryIndex(this.start+Sk));const i=this.view.subarray(t,s);return e.fill(0,i.length,r),e.set(i),D.ok(O)}storeFrom(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Sk){const r=Math.min(Sk,Math.max(Ck,e+t.length));this.buffer.resize(r)}return this.view.set(t,e),D.ok(O)}setData(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Sk){const r=Math.min(Sk,Math.max(Ck,e+t.length));this.buffer.resize(r)}this.view.set(t,e)}isWriteable(){return!0}getPageDump(){return this.view}}var Ex;!function(e){e[e.READ=0]="READ",e[e.WRITE=1]="WRITE"}(Ex||(Ex={}));class Cx{sbrkIndex;virtualSbrkIndex;endHeapIndex;memory;static fromInitialMemory(e){return new Cx(e?.sbrkIndex,e?.sbrkIndex,e?.endHeapIndex,e?.memory)}constructor(e=_k(Ax.end),t=_k(Ax.end),r=_k(vk),s=new Map){this.sbrkIndex=e,this.virtualSbrkIndex=t,this.endHeapIndex=r,this.memory=s}reset(){this.sbrkIndex=_k(Ax.end),this.virtualSbrkIndex=_k(Ax.end),this.endHeapIndex=_k(vk),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 D.ok(O);const r=this.getPages(e,t.length,Ex.WRITE);if(r.isError)return D.error(r.error);const s=r.ok;let i=e,n=t.length;for(const r of s){const s=ix(i%Sk),a=Math.min(Sk-s,n),o=i-e,c=t.subarray(o,o+a);r.storeFrom(s,c),i+=a,n-=a}return D.ok(O)}getPages(e,t,r){if(0===t)return D.ok([]);const s=yx.fromStartAndLength(e,t),i=Ix.fromMemoryRange(s),n=[];for(const e of i){if(e<16)return D.error(ux.fromPageNumber(e,!0));const t=this.memory.get(e);if(void 0===t)return D.error(ux.fromPageNumber(e));if(r===Ex.WRITE&&!t.isWriteable())return D.error(ux.fromPageNumber(e,!0));n.push(t)}return D.ok(n)}loadInto(e,t){if(0===e.length)return D.ok(O);const r=this.getPages(t,e.length,Ex.READ);if(r.isError)return D.error(r.error);const s=r.ok;let i=t,n=e.length;for(const r of s){const s=ix(i%Sk),a=Math.min(Sk-s,n),o=i-t,c=e.subarray(o);r.loadInto(c,s,a),i+=a,n-=a}return D.ok(O)}sbrk(e){const t=this.sbrkIndex,r=this.virtualSbrkIndex;if(vk<r+e||r+e>this.endHeapIndex)throw new mx;const s=_k(this.virtualSbrkIndex+e);if(s<=t)return this.virtualSbrkIndex=s,r;const i=_k(ox(s)),n=cx(t),a=(i-t)/Sk,o=Ix.fromStartAndLength(n,a);for(const e of o){const t=new Sx(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 kx{initialMemory=new Map;isFinalized=!1;ensureNotFinalized(){if(this.isFinalized)throw new gx}ensureNoReservedMemoryUsage(e){if(e.overlapsWith(Ax))throw new px}setReadablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),w(e<t,"end has to be bigger than start"),w(e%Sk===0,"start needs to be a multiple of page size (4096)"),w(t%Sk===0,"end needs to be a multiple of page size (4096)"),w(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=yx.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(Ix.fromMemoryRange(i)),a=n.length;for(let e=0;e<a;e++){const t=n[e],s=r.subarray(e*Sk,(e+1)*Sk),i=new wx(t,s);this.initialMemory.set(t,i)}return this}setWriteablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),w(e<t,"end has to be bigger than start"),w(e%Sk===0,"start needs to be a multiple of page size (4096)"),w(t%Sk===0,"end needs to be a multiple of page size (4096)"),w(r.length<=t-e,"the initial data is longer than address range");const s=t-e,i=yx.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(Ix.fromMemoryRange(i)),a=n.length;for(let e=0;e<a;e++){const t=n[e],s=r.subarray(e*Sk,(e+1)*Sk),i=new Sx(t,s);this.initialMemory.set(t,i)}return this}setData(e,t){this.ensureNotFinalized();const r=Sk-e%Sk;w(t.length<=r,"The data has to fit into a single page.");const s=t.length,i=yx.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=cx(e),a=this.initialMemory.get(n);if(void 0===a)throw new bx;const o=ix(e-a.start);return a.setData(o,t),this}finalize(e,t){w(e<=t,`startHeapIndex (${e}) has to be less than or equal to endHeapIndex (${t})`),this.ensureNotFinalized();const r=yx.fromStartAndLength(e,t-e),s=Ix.fromMemoryRange(r);for(const e of s)if(this.initialMemory.has(e))throw new fx;const i=Cx.fromInitialMemory({memory:this.initialMemory,sbrkIndex:_k(e),endHeapIndex:t});return this.isFinalized=!0,i}}class xx{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 Gk.ADD_32:this.mathOps.addU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.ADD_64:this.mathOps.addU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.MUL_32:this.mathOps.mulU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.MUL_64:this.mathOps.mulU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.MUL_UPPER_U_U:this.mathOps.mulUpperUU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.MUL_UPPER_S_S:this.mathOps.mulUpperSS(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.MUL_UPPER_S_U:this.mathOps.mulUpperSU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.SUB_32:this.mathOps.subU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.SUB_64:this.mathOps.subU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.DIV_S_32:this.mathOps.divSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.DIV_S_64:this.mathOps.divSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.DIV_U_32:this.mathOps.divUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.DIV_U_64:this.mathOps.divUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.REM_S_32:this.mathOps.remSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.REM_S_64:this.mathOps.remSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.REM_U_32:this.mathOps.remUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.REM_U_64:this.mathOps.remUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.SHLO_L_32:this.shiftOps.shiftLogicalLeftU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.SHLO_L_64:this.shiftOps.shiftLogicalLeftU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.SHLO_R_32:this.shiftOps.shiftLogicalRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.SHLO_R_64:this.shiftOps.shiftLogicalRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.SHAR_R_32:this.shiftOps.shiftArithmeticRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.SHAR_R_64:this.shiftOps.shiftArithmeticRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.OR:this.bitOps.or(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.AND:this.bitOps.and(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.XOR:this.bitOps.xor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.SET_LT_S:this.booleanOps.setLessThanSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.SET_LT_U:this.booleanOps.setLessThanUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.CMOV_IZ:this.moveOps.cmovIfZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.CMOV_NZ:this.moveOps.cmovIfNotZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.ROT_L_64:this.bitRotationOps.rotL64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.ROT_L_32:this.bitRotationOps.rotL32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.ROT_R_64:this.bitRotationOps.rotR64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.ROT_R_32:this.bitRotationOps.rotR32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.AND_INV:this.bitOps.andInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.OR_INV:this.bitOps.orInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.XNOR:this.bitOps.xnor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.MAX:this.mathOps.max(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.MAX_U:this.mathOps.maxU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.MIN:this.mathOps.min(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case Gk.MIN_U:this.mathOps.minU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex)}}}class Bx{mathOps;shiftOps;bitOps;booleanOps;moveOps;storeOps;loadOps;bitRotationOps;constructor(e,t,r,s,i,n,a,o){this.mathOps=e,this.shiftOps=t,this.bitOps=r,this.booleanOps=s,this.moveOps=i,this.storeOps=n,this.loadOps=a,this.bitRotationOps=o}dispatch(e,t){switch(e){case Gk.ADD_IMM_32:this.mathOps.addImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.ADD_IMM_64:this.mathOps.addImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.MUL_IMM_32:this.mathOps.mulImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.MUL_IMM_64:this.mathOps.mulImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.NEG_ADD_IMM_32:this.mathOps.negAddImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.NEG_ADD_IMM_64:this.mathOps.negAddImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SHLO_L_IMM_32:this.shiftOps.shiftLogicalLeftImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SHLO_L_IMM_64:this.shiftOps.shiftLogicalLeftImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SHLO_L_IMM_ALT_32:this.shiftOps.shiftLogicalLeftImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SHLO_L_IMM_ALT_64:this.shiftOps.shiftLogicalLeftImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SHLO_R_IMM_32:this.shiftOps.shiftLogicalRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SHLO_R_IMM_64:this.shiftOps.shiftLogicalRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SHLO_R_IMM_ALT_32:this.shiftOps.shiftLogicalRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SHLO_R_IMM_ALT_64:this.shiftOps.shiftLogicalRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SHAR_R_IMM_32:this.shiftOps.shiftArithmeticRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SHAR_R_IMM_64:this.shiftOps.shiftArithmeticRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SHAR_R_IMM_ALT_32:this.shiftOps.shiftArithmeticRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SHAR_R_IMM_ALT_64:this.shiftOps.shiftArithmeticRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.OR_IMM:this.bitOps.orImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.AND_IMM:this.bitOps.andImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.XOR_IMM:this.bitOps.xorImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SET_LT_S_IMM:this.booleanOps.setLessThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SET_LT_U_IMM:this.booleanOps.setLessThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SET_GT_S_IMM:this.booleanOps.setGreaterThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.SET_GT_U_IMM:this.booleanOps.setGreaterThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.CMOV_IZ_IMM:this.moveOps.cmovIfZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.CMOV_NZ_IMM:this.moveOps.cmovIfNotZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.STORE_IND_U8:this.storeOps.storeIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Gk.STORE_IND_U16:this.storeOps.storeIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Gk.STORE_IND_U32:this.storeOps.storeIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Gk.STORE_IND_U64:this.storeOps.storeIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Gk.LOAD_IND_U8:this.loadOps.loadIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Gk.LOAD_IND_U16:this.loadOps.loadIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Gk.LOAD_IND_U32:this.loadOps.loadIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Gk.LOAD_IND_U64:this.loadOps.loadIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Gk.LOAD_IND_I8:this.loadOps.loadIndI8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Gk.LOAD_IND_I16:this.loadOps.loadIndI16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Gk.LOAD_IND_I32:this.loadOps.loadIndI32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case Gk.ROT_R_64_IMM:this.bitRotationOps.rotR64Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.ROT_R_64_IMM_ALT:this.bitRotationOps.rotR64ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.ROT_R_32_IMM:this.bitRotationOps.rotR32Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case Gk.ROT_R_32_IMM_ALT:this.bitRotationOps.rotR32ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex)}}}class _x{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 Gk.MOVE_REG:this.moveOps.moveRegister(t.firstRegisterIndex,t.secondRegisterIndex);break;case Gk.SBRK:this.memoryOps.sbrk(t.firstRegisterIndex,t.secondRegisterIndex);break;case Gk.COUNT_SET_BITS_64:this.bitOps.countSetBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case Gk.COUNT_SET_BITS_32:this.bitOps.countSetBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case Gk.LEADING_ZERO_BITS_64:this.bitOps.leadingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case Gk.LEADING_ZERO_BITS_32:this.bitOps.leadingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case Gk.TRAILING_ZERO_BITS_64:this.bitOps.trailingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case Gk.TRAILING_ZERO_BITS_32:this.bitOps.trailingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case Gk.SIGN_EXTEND_8:this.bitOps.signExtend8(t.firstRegisterIndex,t.secondRegisterIndex);break;case Gk.SIGN_EXTEND_16:this.bitOps.signExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case Gk.ZERO_EXTEND_16:this.bitOps.zeroExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case Gk.REVERSE_BYTES:this.bitRotationOps.reverseBytes(t.firstRegisterIndex,t.secondRegisterIndex)}}}class Rx{branchOps;loadOps;constructor(e,t){this.branchOps=e,this.loadOps=t}dispatch(e,t){switch(e){case Gk.LOAD_IMM_JUMP:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder),this.branchOps.jump(t.nextPc);break;case Gk.BRANCH_EQ_IMM:this.branchOps.branchEqImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Gk.BRANCH_NE_IMM:this.branchOps.branchNeImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Gk.BRANCH_LT_U_IMM:this.branchOps.branchLtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Gk.BRANCH_LE_U_IMM:this.branchOps.branchLeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Gk.BRANCH_GE_U_IMM:this.branchOps.branchGeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Gk.BRANCH_GT_U_IMM:this.branchOps.branchGtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Gk.BRANCH_LT_S_IMM:this.branchOps.branchLtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Gk.BRANCH_LE_S_IMM:this.branchOps.branchLeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Gk.BRANCH_GE_S_IMM:this.branchOps.branchGeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case Gk.BRANCH_GT_S_IMM:this.branchOps.branchGtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc)}}}class Ox{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){switch(e){case Gk.BRANCH_EQ:this.branchOps.branchEq(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Gk.BRANCH_NE:this.branchOps.branchNe(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Gk.BRANCH_LT_U:this.branchOps.branchLtUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Gk.BRANCH_LT_S:this.branchOps.branchLtSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Gk.BRANCH_GE_U:this.branchOps.branchGeUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case Gk.BRANCH_GE_S:this.branchOps.branchGeSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc)}}}class Ux{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){e===Gk.JUMP&&this.branchOps.jump(t.nextPc)}}class Tx{loadOps;storeOps;dynamicJumpOps;constructor(e,t,r){this.loadOps=e,this.storeOps=t,this.dynamicJumpOps=r}dispatch(e,t){switch(e){case Gk.LOAD_IMM:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder);break;case Gk.STORE_U8:this.storeOps.storeU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Gk.STORE_U16:this.storeOps.storeU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Gk.STORE_U32:this.storeOps.storeU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Gk.STORE_U64:this.storeOps.storeU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Gk.LOAD_U8:this.loadOps.loadU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Gk.LOAD_U16:this.loadOps.loadU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Gk.LOAD_U32:this.loadOps.loadU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Gk.LOAD_U64:this.loadOps.loadU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Gk.LOAD_I8:this.loadOps.loadI8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Gk.LOAD_I16:this.loadOps.loadI16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Gk.LOAD_I32:this.loadOps.loadI32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case Gk.JUMP_IND:{const e=this.dynamicJumpOps.caluclateJumpAddress(t.immediateDecoder,t.registerIndex);this.dynamicJumpOps.jumpInd(e);break}}}}class Nx{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case Gk.STORE_IMM_IND_U8:this.storeOps.storeImmediateIndU8(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case Gk.STORE_IMM_IND_U16:this.storeOps.storeImmediateIndU16(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case Gk.STORE_IMM_IND_U32:this.storeOps.storeImmediateIndU32(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case Gk.STORE_IMM_IND_U64:this.storeOps.storeImmediateIndU64(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder)}}}class Dx{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case Gk.STORE_IMM_U8:this.storeOps.storeImmediateU8(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case Gk.STORE_IMM_U16:this.storeOps.storeImmediateU16(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case Gk.STORE_IMM_U32:this.storeOps.storeImmediateU32(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case Gk.STORE_IMM_U64:this.storeOps.storeImmediateU64(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder)}}}class Mx{noArgsOps;constructor(e){this.noArgsOps=e}dispatch(e){switch(e){case Gk.TRAP:this.noArgsOps.trap();break;case Gk.FALLTHROUGH:this.noArgsOps.fallthrough()}}}class Px{loadOps;dynamicJumpOps;constructor(e,t){this.loadOps=e,this.dynamicJumpOps=t}dispatch(e,t){switch(e){case Gk.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 Lx{hostCallOps;constructor(e){this.hostCallOps=e}dispatch(e,t){e===Gk.ECALLI&&this.hostCallOps.hostCall(t.immediateDecoder)}}class Hx{loadOps;constructor(e){this.loadOps=e}dispatch(e,t){e===Gk.LOAD_IMM_64&&this.loadOps.loadImmediateU64(t.registerIndex,t.immediateDecoder)}}class Vx{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 Kx=4294967295,Qx=-(2**31),Fx=32,$x=64n;function Gx(e,t){return e>Kx-t?Kx-(Kx-e+(Kx-t))-1:e+t}function jx(e,t){return(e+t)%2n**64n}function qx(e,t){return t>e?Kx-t+e+1:e-t}function zx(e,t){return(2n**64n+e-t)%2n**64n}function Wx(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 Jx(e,t){return e*t%2n**64n}function Yx(e){return e>=1n<<63n?e-(1n<<64n):e}function Xx(e,t){return(0xffffffffffffffffn&e)*(0xffffffffffffffffn&t)>>64n&0xffffffffffffffffn}function Zx(e,t){return Yx(0xffffffffffffffffn&e*t>>64n)}function eB(e,t){w(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 tB(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t>e?t:e)}function rB(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t<e?t:e)}class sB{regs;constructor(e){this.regs=e}shiftLogicalLeftU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<this.regs.getLowerU32(t)%Fx)}shiftLogicalLeftU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<this.regs.getU64(t)%$x)}shiftLogicalRightU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>this.regs.getLowerU32(t)%Fx)}shiftLogicalRightU64(e,t,r){this.regs.setU64(r,eB(this.regs.getU64(e),this.regs.getU64(t)%$x))}shiftArithmeticRightU32(e,t,r){this.regs.setI32(r,this.regs.getLowerI32(e)>>this.regs.getLowerU32(t)%Fx)}shiftArithmeticRightU64(e,t,r){this.regs.setI64(r,this.regs.getI64(e)>>this.regs.getU64(t)%$x)}shiftLogicalLeftImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<t.getU32()%Fx)}shiftLogicalLeftImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<t.getU64()%$x)}shiftLogicalRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>t.getU32()%Fx)}shiftLogicalRightImmediateU64(e,t,r){this.regs.setU64(r,eB(this.regs.getU64(e),t.getU64()%$x))}shiftArithmeticRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerI32(e)>>t.getU32()%Fx)}shiftArithmeticRightImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getI64(e)>>t.getU64()%$x)}shiftLogicalLeftImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()<<this.regs.getLowerU32(e)%Fx)}shiftLogicalLeftImmediateAlternativeU64(e,t,r){this.regs.setU64(r,t.getU64()<<this.regs.getU64(e)%$x)}shiftLogicalRightImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()>>>this.regs.getLowerU32(e)%Fx)}shiftLogicalRightImmediateAlternativeU64(e,t,r){this.regs.setU64(r,eB(t.getU64(),this.regs.getU64(e)%$x))}shiftArithmeticRightImmediateAlternativeU32(e,t,r){this.regs.setI32(r,t.getU32()>>this.regs.getLowerU32(e)%Fx)}shiftArithmeticRightImmediateAlternativeU64(e,t,r){this.regs.setI64(r,t.getI64()>>this.regs.getU64(e)%$x)}}class iB{regs;constructor(e){this.regs=e}addU32(e,t,r){this.regs.setU64(r,Nk(Gx(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}addU64(e,t,r){this.regs.setU64(r,jx(this.regs.getU64(e),this.regs.getU64(t)))}addImmediateU32(e,t,r){this.regs.setU64(r,Nk(Gx(this.regs.getLowerU32(e),t.getU32())))}addImmediateU64(e,t,r){this.regs.setU64(r,jx(this.regs.getU64(e),t.getU64()))}mulU32(e,t,r){this.regs.setU64(r,Nk(Wx(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}mulU64(e,t,r){this.regs.setU64(r,Jx(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperUU(e,t,r){this.regs.setU64(r,Xx(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperSS(e,t,r){this.regs.setI64(r,Zx(this.regs.getI64(e),this.regs.getI64(t)))}mulUpperSU(e,t,r){this.regs.setI64(r,Yx(0xffffffffffffffffn&this.regs.getI64(e)*(0xffffffffffffffffn&this.regs.getU64(t))>>64n))}mulImmediateU32(e,t,r){this.regs.setU64(r,Nk(Wx(this.regs.getLowerU32(e),t.getU32())))}mulImmediateU64(e,t,r){this.regs.setU64(r,Jx(this.regs.getU64(e),t.getU64()))}mulUpperSSImmediate(e,t,r){this.regs.setI64(r,Zx(this.regs.getI64(e),t.getI64()))}mulUpperUUImmediate(e,t,r){this.regs.setU64(r,Xx(this.regs.getU64(e),t.getU64()))}subU32(e,t,r){this.regs.setU64(r,Nk(qx(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}subU64(e,t,r){this.regs.setU64(r,zx(this.regs.getU64(e),this.regs.getU64(t)))}negAddImmediateU32(e,t,r){this.regs.setU64(r,Nk(qx(t.getU32(),this.regs.getLowerU32(e))))}negAddImmediateU64(e,t,r){this.regs.setU64(r,zx(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)===Qx?this.regs.setU64(r,Nk(this.regs.getLowerU32(e))):this.regs.setI64(r,Nk(~~(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,Nk(~~(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)===Qx?this.regs.setU64(r,0n):this.regs.setI64(r,Nk(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,Nk(this.regs.getLowerU32(e))):this.regs.setU64(r,Nk(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,tB(this.regs.getI64(e),this.regs.getI64(t)))}maxU(e,t,r){this.regs.setU64(r,tB(this.regs.getU64(e),this.regs.getU64(t)))}min(e,t,r){this.regs.setI64(r,rB(this.regs.getI64(e),this.regs.getI64(t)))}minU(e,t,r){this.regs.setU64(r,rB(this.regs.getU64(e),this.regs.getU64(t)))}}class nB{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 aB{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 oB,cB;(cB=oB||(oB={}))[cB.HALT=0]="HALT",cB[cB.PANIC=1]="PANIC",cB[cB.FAULT_ACCESS=2]="FAULT_ACCESS",cB[cB.FAULT=3]="FAULT",cB[cB.HOST=4]="HOST";class lB{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=oB.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 dB{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),Bk(e));i.isError?i.error.isAccessFault?this.instructionResult.status=oB.FAULT_ACCESS:(this.instructionResult.status=oB.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),Bk(e));i.isError?i.error.isAccessFault?this.instructionResult.status=oB.FAULT_ACCESS:(this.instructionResult.status=oB.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=Gx(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,1)}loadIndU16(e,t,r){const s=Gx(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,2)}loadIndU32(e,t,r){const s=Gx(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,4)}loadIndU64(e,t,r){const s=Gx(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,8)}loadIndI8(e,t,r){const s=Gx(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,1)}loadIndI16(e,t,r){const s=Gx(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,2)}loadIndI32(e,t,r){const s=Gx(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,4)}}class uB{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=Gx(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,1))}storeIndU16(e,t,r){const s=Gx(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,2))}storeIndU32(e,t,r){const s=Gx(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,4))}storeIndU64(e,t,r){const s=Gx(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=Gx(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,1))}storeImmediateIndU16(e,t,r){const s=Gx(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,2))}storeImmediateIndU32(e,t,r){const s=Gx(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,4))}storeImmediateIndU64(e,t,r){const s=Gx(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getExtendedBytesAsLittleEndian())}store(e,t){const r=this.memory.storeFrom(Bk(e),t);r.isOk||(r.error.isAccessFault?this.instructionResult.status=oB.FAULT_ACCESS:(this.instructionResult.status=oB.FAULT,this.instructionResult.exitParam=lx(r.error.address)))}}class hB{instructionResult;constructor(e){this.instructionResult=e}trap(){this.instructionResult.status=oB.PANIC}fallthrough(){}}class fB{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=oB.HALT);if(0===e||e%2!=0)return void(this.instructionResult.status=oB.PANIC);const t=e/2-1;if(!this.jumpTable.hasIndex(t))return void(this.instructionResult.status=oB.PANIC);const r=this.jumpTable.getDestination(t);this.basicBlocks.isBeginningOfBasicBlock(r)?this.instructionResult.nextPc=r:this.instructionResult.status=oB.PANIC}caluclateJumpAddress(e,t){return Gx(this.regs.getLowerU32(t),e.getU32())}jumpInd(e){this.djump(e)}}class gB{instructionResult;constructor(e){this.instructionResult=e}hostCall(e){this.instructionResult.status=oB.HOST,this.instructionResult.exitParam=e.getUnsigned()}}class pB{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=oB.FAULT}}}class bB{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|eB(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(eB(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 mB{indices;constructor(e,t){w(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 mB(0,new Uint8Array)}copyFrom(e){this.indices=e.indices}}const yB=ri.new(void 0,"pvm-interpreter");var AB;!function(e){e[e.InvalidProgramError=0]="InvalidProgramError"}(AB||(AB={}));class IB{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 Hk(r),this.jumpTable=new mB(i,s)}decodeProgram(e){const t=fe.fromBlob(e),r=t.varU32(),s=t.u8(),i=t.varU32(),n=r*s,a=t.bytes(n).raw,o=t.bytes(i).raw,c=t.bitVecFixLen(i);return t.finish(),{mask:c,code:o,jumpTableItemLength:s,jumpTable:a}}getMask(){return this.mask}getCode(){return this.code}getJumpTable(){return this.jumpTable}static deblob(e){try{return D.ok(new IB(e))}catch(e){return yB.error(`Invalid program: ${e}`),D.error(AB.InvalidProgramError)}}}class vB{useSbrkGas;ignoreInstructionGas;registers=new Tk;code=new Uint8Array;mask=Hk.empty();pc=0;gas=Yk(Jk(0));initialGas=Yk(Jk(0));argsDecoder;threeRegsDispatcher;twoRegsOneImmDispatcher;twoRegsDispatcher;oneRegOneImmOneOffsetDispatcher;twoRegsOneOffsetDispatcher;oneOffsetDispatcher;oneRegOneImmDispatcher;instructionResult=new sx;memory=new Cx;twoImmsDispatcher;oneRegTwoImmsDispatcher;noArgsDispatcher;twoRegsTwoImmsDispatcher;oneImmDispatcher;oneRegOneExtImmDispatcher;status=Rk.OK;argsDecodingResults=(()=>{const e=new Array($k);return e[Pk.NO_ARGUMENTS]={type:Pk.NO_ARGUMENTS,noOfBytesToSkip:1},e[Pk.ONE_IMMEDIATE]={type:Pk.ONE_IMMEDIATE,noOfBytesToSkip:1,immediateDecoder:new Vk},e[Pk.TWO_REGISTERS]={type:Pk.TWO_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0},e[Pk.THREE_REGISTERS]={type:Pk.THREE_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,thirdRegisterIndex:0},e[Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET]={type:Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new Vk,nextPc:0},e[Pk.TWO_REGISTERS_ONE_OFFSET]={type:Pk.TWO_REGISTERS_ONE_OFFSET,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,nextPc:0},e[Pk.TWO_REGISTERS_ONE_IMMEDIATE]={type:Pk.TWO_REGISTERS_ONE_IMMEDIATE,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,immediateDecoder:new Vk},e[Pk.ONE_REGISTER_ONE_IMMEDIATE]={type:Pk.ONE_REGISTER_ONE_IMMEDIATE,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new Vk},e[Pk.ONE_REGISTER_TWO_IMMEDIATES]={type:Pk.ONE_REGISTER_TWO_IMMEDIATES,noOfBytesToSkip:1,registerIndex:0,firstImmediateDecoder:new Vk,secondImmediateDecoder:new Vk},e[Pk.ONE_OFFSET]={type:Pk.ONE_OFFSET,noOfBytesToSkip:1,nextPc:0},e[Pk.TWO_IMMEDIATES]={type:Pk.TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new Vk,secondImmediateDecoder:new Vk},e[Pk.TWO_REGISTERS_TWO_IMMEDIATES]={type:Pk.TWO_REGISTERS_TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new Vk,secondImmediateDecoder:new Vk,firstRegisterIndex:0,secondRegisterIndex:0},e[Pk.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE]={type:Pk.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,noOfBytesToSkip:9,registerIndex:0,immediateDecoder:new Fk},e})();basicBlocks;jumpTable=mB.empty();constructor({useSbrkGas:e=!1,ignoreInstructionGas:t=!1}={}){this.useSbrkGas=e,this.ignoreInstructionGas=t,this.argsDecoder=new Qk,this.basicBlocks=new tx;const r=new iB(this.registers),s=new sB(this.registers),i=new Vx(this.registers),n=new nB(this.registers),a=new aB(this.registers),o=new lB(this.registers,this.instructionResult,this.basicBlocks),c=new dB(this.registers,this.memory,this.instructionResult),l=new uB(this.registers,this.memory,this.instructionResult),d=new hB(this.instructionResult),u=new fB(this.registers,this.jumpTable,this.instructionResult,this.basicBlocks),h=new gB(this.instructionResult),f=new pB(this.registers,this.memory,this.instructionResult),g=new bB(this.registers);this.threeRegsDispatcher=new xx(r,s,i,n,a,g),this.twoRegsOneImmDispatcher=new Bx(r,s,i,n,a,l,c,g),this.twoRegsDispatcher=new _x(a,f,i,g),this.oneRegOneImmOneOffsetDispatcher=new Rx(o,c),this.twoRegsOneOffsetDispatcher=new Ox(o),this.oneOffsetDispatcher=new Ux(o),this.oneRegOneImmDispatcher=new Tx(c,l,u),this.twoImmsDispatcher=new Dx(l),this.oneRegTwoImmsDispatcher=new Nx(l),this.noArgsDispatcher=new Mx(d),this.twoRegsTwoImmsDispatcher=new Px(c,u),this.oneImmDispatcher=new Lx(h),this.oneRegOneExtImmDispatcher=new Hx(c)}reset(e,t,r,s,i){const n=new IB(e);this.code=n.getCode(),this.mask=n.getMask(),this.jumpTable.copyFrom(n.getJumpTable()),this.pc=t,this.gas=Yk(r),this.initialGas=Yk(r),this.status=Rk.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([Gk[t]]):e[e.length-1].push(t),e),[]));var t,r;return console.table(e),e}runProgram(){for(;this.nextStep()===Rk.OK;);}nextStep(){this.status===Rk.HOST&&(this.status=Rk.OK,this.pc=this.instructionResult.nextPc,this.instructionResult.reset());const e=this.code[this.pc]??Gk.TRAP,t=void 0!==Gk[e],r=rx[e]??rx[Gk.TRAP];if(!this.ignoreInstructionGas&&this.gas.sub(r))return this.status=Rk.OOG,this.status;const s=qk[e]??Pk.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 Pk.NO_ARGUMENTS:this.noArgsDispatcher.dispatch(e);break;case Pk.ONE_IMMEDIATE:this.oneImmDispatcher.dispatch(e,i);break;case Pk.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET:this.oneRegOneImmOneOffsetDispatcher.dispatch(e,i);break;case Pk.TWO_REGISTERS:if(this.useSbrkGas&&e===Gk.SBRK){const e=e=>ox(e)/Sk*16;if(this.gas.sub(Jk(e(this.registers.getLowerU32(i.firstRegisterIndex)))))return this.status=Rk.OOG,this.status}this.twoRegsDispatcher.dispatch(e,i);break;case Pk.THREE_REGISTERS:this.threeRegsDispatcher.dispatch(e,i);break;case Pk.TWO_REGISTERS_ONE_IMMEDIATE:this.twoRegsOneImmDispatcher.dispatch(e,i);break;case Pk.TWO_REGISTERS_ONE_OFFSET:this.twoRegsOneOffsetDispatcher.dispatch(e,i);break;case Pk.ONE_OFFSET:this.oneOffsetDispatcher.dispatch(e,i);break;case Pk.ONE_REGISTER_ONE_IMMEDIATE:this.oneRegOneImmDispatcher.dispatch(e,i);break;case Pk.TWO_IMMEDIATES:this.twoImmsDispatcher.dispatch(e,i);break;case Pk.ONE_REGISTER_TWO_IMMEDIATES:this.oneRegTwoImmsDispatcher.dispatch(e,i);break;case Pk.TWO_REGISTERS_TWO_IMMEDIATES:this.twoRegsTwoImmsDispatcher.dispatch(e,i);break;case Pk.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE:this.oneRegOneExtImmDispatcher.dispatch(e,i)}else this.instructionResult.status=oB.PANIC;if(null!==this.instructionResult.status){switch(this.instructionResult.status!==oB.FAULT&&this.instructionResult.status!==oB.FAULT_ACCESS||this.gas.sub(rx[Gk.TRAP]),this.instructionResult.status){case oB.FAULT:this.status=Rk.FAULT;break;case oB.HALT:this.status=Rk.HALT;break;case oB.PANIC:case oB.FAULT_ACCESS:this.status=Rk.PANIC;break;case oB.HOST:this.status=Rk.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=Wk(this.initialGas.get())-Wk(this.gas.get());return e<0?this.initialGas.get():Wk(e)}getGasCounter(){return this.gas}getStatus(){return this.status}getExitParam(){const e=this.instructionResult.exitParam;return null!==e?ne(e):e}getMemory(){return this.memory}getMemoryPage(e){return this.memory.getPageDump(nx(e))}}class wB{memory;constructor(e){this.memory=e}storeFrom(e,t){return 0===t.length?D.ok(O):e+oe(t.length)>wk?D.error(new hx):this.memory.storeFrom(Bk(Number(e)),t)}loadInto(e,t){return 0===e.length?D.ok(O):t+oe(e.length)>wk?D.error(new hx):this.memory.loadInto(e,Bk(Number(t)))}getMemory(){return this.memory}}class SB{registers;constructor(e){this.registers=e}get(e){return oe(this.registers.getU64(e))}set(e,t){this.registers.setU64(e,t)}}class EB{consumedGas;status;memorySlice;constructor(e,t,r){this.consumedGas=e,this.status=t,this.memorySlice=r,w(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 EB(e,t,null)}static fromMemorySlice(e,t){return new EB(e,null,t)}hasMemorySlice(){return this.memorySlice instanceof Uint8Array&&null===this.status}hasStatus(){return!this.hasMemorySlice()}}class CB{pvmInstanceManager;hostCalls;constructor(e,t){this.pvmInstanceManager=e,this.hostCalls=t}getReturnValue(e,t){const r=t.getGasConsumed();if(e===Rk.OOG)return EB.fromStatus(r,e);if(e===Rk.HALT){const e=t.getMemory(),s=t.getRegisters(),i=s.getLowerU32(7),n=s.getLowerU32(8),a=new Uint8Array(n),o=Bk(i);return e.loadInto(a,o).isError?EB.fromMemorySlice(r,new Uint8Array):EB.fromMemorySlice(r,a)}return EB.fromStatus(r,Rk.PANIC)}async execute(e){for(e.runProgram();;){let t=e.getStatus();if(t!==Rk.HOST)return this.getReturnValue(t,e);w(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 SB(e.getRegisters()),n=new wB(e.getMemory()),a=Dk(r),o=this.hostCalls.get(a),c=s.get(),l="number"==typeof o.gasCost?o.gasCost:o.gasCost(i);if(s.sub(l))return this.hostCalls.traceHostCall("OOG",a,o,i,s.get()),EB.fromStatus(e.getGasConsumed(),Rk.OOG);this.hostCalls.traceHostCall("Invoking",a,o,i,c);const d=await o.execute(s,i,n);if(this.hostCalls.traceHostCall(void 0===d?"Result":`Status(${d})`,a,o,i,s.get()),d===Mk.Halt)return t=Rk.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 kB{instances=[];waitingQueue=[];constructor(e){const t=v.isGreaterOrEqual(h.V0_6_7)||v.isSuite(f.JAMDUNA,h.V0_6_5)||v.isSuite(f.W3F_DAVXY,h.V0_6_6);for(let r=0;r<e;r++)this.instances.push(new vB({useSbrkGas:!1,ignoreInstructionGas:!t}))}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 xB={NONE:oe(0xffffffffffffffffn),WHAT:oe(0xfffffffffffffffen),OOB:oe(0xfffffffffffffffdn),WHO:oe(0xfffffffffffffffcn),FULL:oe(0xfffffffffffffffbn),CORE:oe(0xfffffffffffffffan),CASH:oe(0xfffffffffffffff9n),LOW:oe(0xfffffffffffffff8n),HUH:oe(0xfffffffffffffff7n),OK:oe(0n)},BB=ne(2**32-1),_B=oe(BB),RB=Nr(2**32-1);function OB(e,t,r){const s=t.get(e);return s===2n**64n-1n?r:UB(s)}function UB(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?Nr(t):null}function TB(e){return e>_B?BB:ne(Number(e))}const NB=ri.new(void 0,"host-calls");class DB{hostCalls=new Map;missing=new MB;constructor(...e){for(const t of e)w(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}traceHostCall(e,t,r,s,i){const{currentServiceId:n}=r,a=t!==r.index?` (${t})`:"",o=`${r.constructor.name}:${r.index}`,c=r.tracedRegisters.map(e=>[e.toString().padStart(2,"0"),s.get(e)]).filter(e=>0n!==e[1]).map(([e,t])=>`r${e}=${t} (0x${t.toString(16)})`).join(", ");NB.trace(`[${n}] ${e} ${o}${a}. Gas: ${i}. Regs: ${c}.`)}}class MB{index=Dk(2**32-1);gasCost=zk(10);currentServiceId=RB;tracedRegisters=Lk(7);execute(e,t,r){return t.set(7,xB.WHAT),Promise.resolve(void 0)}}const PB=4096,LB=65536,HB=2**24,VB=4278059008,KB=4278124544;function QB(e){return PB*Math.ceil(e/PB)}class FB extends B{start;end;data;static from({start:e,end:t,data:r}){return new FB(e,t,r)}constructor(e,t,r){super(),this.start=e,this.end=t,this.data=r}}class $B extends B{readable;writeable;sbrkIndex;heapEnd;constructor(e,t,r,s){super(),this.readable=e,this.writeable=t,this.sbrkIndex=r,this.heapEnd=s}}class GB extends B{code;memory;registers;constructor(e,t,r){super(),this.code=e,this.memory=t,this.registers=r}}function jB(e,t,r=null){return new FB(e,t,r)}class qB{code;registers;memory;metadata;static fromSpi(e,t,r){const{code:s,metadata:i}=r?zB(e):{code:e},{code:n,memory:a,registers:o}=function(e,t){const r=fe.fromBlob(e),s=r.u24(),i=r.u24(),n=S(t.length,t.length<=HB,"Incorrect arguments length"),a=S(s,s<=HB,"Incorrect readonly segment length"),o=S(i,i<=HB,"Incorrect heap segment length"),c=r.u16(),l=r.u24(),d=r.bytes(a).raw,u=r.bytes(o).raw,h=r.u32(),f=r.bytes(h).raw;r.finish();const g=LB+QB(a),p=131072+(b=a,LB*Math.ceil(b/LB));var b;const m=p+QB(o),y=p+QB(o)+c*PB,A=VB-QB(l),I=VB,v=KB,w=v+QB(n),E=w+QB(n);function C(e){return!1!==e}const k=[a>0&&jB(65536,g,d),n>0&&jB(v,w,t),w<E&&jB(w,E)].filter(C),x=[o>0&&jB(p,m,u),m<y&&jB(m,y),A<I&&jB(A,I)].filter(C);return new GB(f,new $B(k,x,y,A),function(e){const t=new BigUint64Array(13);return t[0]=BigInt(4294901760),t[1]=BigInt(VB),t[7]=BigInt(KB),t[8]=BigInt(e),t}(t.length))}(s,t),c=new Tk;c.copyFrom(o);const l=new kx;for(const{start:e,end:t,data:r}of a.readable){const s=Bk(e),i=Bk(t);l.setReadablePages(s,i,r??new Uint8Array)}for(const{start:e,end:t,data:r}of a.writeable){const s=Bk(e),i=Bk(t);l.setWriteablePages(s,i,r??new Uint8Array)}const d=Bk(a.sbrkIndex),u=_k(a.heapEnd),h=l.finalize(d,u);return new qB(n,c,h,i)}static fromGeneric(e,t){const{code:r,metadata:s}=t?zB(e):{code:e},i=new Tk,n=new Cx;return new qB(r,i,n,s)}constructor(e,t,r,s=new Uint8Array){this.code=e,this.registers=t,this.memory=r,this.metadata=s}}function zB(e){const t=fe.fromBlob(e);return{metadata:t.bytesBlob().raw,code:t.remainingBytes().raw}}var WB,JB,YB;!function(e){e[e.NoLookup=0]="NoLookup",e[e.NoState=1]="NoState",e[e.NoServiceCode=2]="NoServiceCode",e[e.ServiceCodeMismatch=3]="ServiceCodeMismatch"}(WB||(WB={}));class XB{context;keccakHasher;allocator;constructor(e,t,r){this.context=e,this.keccakHasher=t,this.allocator=r}hashConcat(e,t){return gt(this.keccakHasher,[e,t])}hashConcatPrepend(e,t,r){return gt(this.keccakHasher,[e,t,r])}header(e){return new He(qe(e.encoded(),this.allocator).asOpaque(),e)}extrinsic(e){const t=e.guarantees.view().map(e=>e.view()).map(e=>{const t=qe(e.report.encoded(),this.allocator).asOpaque();return P.blobFromParts([t.raw,e.slot.encoded().raw,e.credentials.encoded().raw])}),r=Ae.encodeObject(Be.sequenceVarLen(UC),t,this.context),s=qe(e.tickets.encoded(),this.allocator).asOpaque(),i=qe(e.preimages.encoded(),this.allocator).asOpaque(),n=qe(r,this.allocator).asOpaque(),a=qe(e.assurances.encoded(),this.allocator).asOpaque(),o=qe(e.disputes.encoded(),this.allocator).asOpaque(),c=P.blobFromParts([s.raw,i.raw,n.raw,a.raw,o.raw]);return new Ve(qe(c,this.allocator).asOpaque(),e,c)}workPackage(e){return this.encode(Jr.Codec,e)}encode(e,t){const r=Ae.encodeObject(e,t,this.context);return new Ve(qe(r,this.allocator).asOpaque(),t,r)}}!function(e){e.PreimageUnneeded="preimage_unneeded",e.PreimagesNotSortedUnique="preimages_not_sorted_unique",e.AccountNotFound="account_not_found"}(JB||(JB={}));class ZB{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 D.error(JB.PreimagesNotSortedUnique)}const{preimages:t,slot:r}=e,s=[];for(const e of t){const{requester:t,blob:i}=e,n=qe(i).asOpaque(),a=this.state.getService(t);if(null===a)return D.error(JB.AccountNotFound);const o=a.hasPreimage(n),c=a.getLookupHistory(n,ne(i.length));if(o||null===c||!cC.isRequested(c))return D.error(JB.PreimageUnneeded);s.push(hC.provide({serviceId:t,preimage:nC.create({hash:n,blob:i}),slot:r}))}return D.ok({preimages:s})}}class e_{spec;importer;toImport=At.fromSortedArray((e,t)=>{const r=e.timeSlot-t.timeSlot;return r<0?g.Greater:r>0?g.Less:g.Equal});queuedBlocks=bt.new();lastEpoch=Pr(2**32-1);constructor(e,t){this.spec=e,this.importer=t}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))}static getBlockDetails(e){let t,r;try{t=e.header.encoded(),r=e.header.view().timeSlotIndex.materialize()}catch{return D.error("invalid")}const s=qe(t).asOpaque();return D.ok(new He(s,{block:e,timeSlot:r}))}push(e){const t=e.hash;if(this.queuedBlocks.has(t))return D.error("already queued");const{timeSlot:r,block:s}=e.data,i={headerHash:t,timeSlot:r,block:s,seal:this.isCurrentEpoch(r)?this.importer.preverifySeal(r,s):Promise.resolve(null)};return this.toImport.insert(i),this.queuedBlocks.insert(t),D.ok(O)}shift(){const e=this.toImport.pop();if(void 0!==e){this.queuedBlocks.delete(e.headerHash);const t=Math.floor(e.timeSlot/this.spec.epochLength),r=this.lastEpoch!==t;this.lastEpoch=Pr(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"}(YB||(YB={}));const t_=L.zero(Pe).asOpaque();class r_{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 D.error(YB.AlreadyImported,`Block ${r.hash} is already imported.`);const s=t.parentHeaderHash.materialize();if(!s.isEqualTo(t_)){const e=this.blocks.getHeader(s);if(null===e)return D.error(YB.ParentNotFound,`Parent ${s.toString()} not found`);const r=t.timeSlotIndex.materialize(),i=e.timeSlotIndex.materialize();if(r<=i)return D.error(YB.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 D.error(YB.InvalidExtrinsic,`Invalid extrinsic hash: ${i.toString()}, expected ${n.hash.toString()}`);const a=t.priorStateRoot.materialize(),o=this.blocks.getPostStateRoot(s);return null===o?D.error(YB.StateRootNotFound,`Posterior state root ${s.toString()} not found`):a.isEqualTo(o)?D.ok(r.hash):D.error(YB.InvalidStateRoot,`Invalid prior state root: ${a.toString()}, expected ${o.toString()} (ours)`)}hashHeader(e){return this.hasher.header(e.header.view())}}var s_;function i_(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"}(s_||(s_={}));const n_=P.blobFromString("jam_valid").raw,a_=P.blobFromString("jam_invalid").raw,o_=P.blobFromString("jam_guarantee").raw;function c_({key:e,signature:t,workReportHash:r}){return{key:e,signature:t,message:P.blobFromParts(o_,r.raw)}}function l_({workReportHash:e,wasConsideredValid:t,signature:r,key:s}){const i=t?n_:a_;return{key:s,signature:r,message:P.blobFromParts(i,e.raw)}}function d_(e,t,r){const{isWorkReportValid:s,signature:i}=e,n=s?n_:a_;return{key:r,signature:i,message:P.blobFromParts(n,t.raw)}}class u_{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}verifyCulprits(e,t,r,s){if(!i_(e.culprits,"key"))return D.error(s_.CulpritsNotSortedUnique);const i=e.culprits.length;for(let n=0;n<i;n++){const{key:i,workReportHash:a}=e.culprits[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return D.error(s_.OffenderAlreadyReported);if(!s.has(i))return D.error(s_.BadGuarantorKey);if(void 0===t.toAddToBadSet.findExact(a))return D.error(s_.CulpritsVerdictNotBad);const o=r.culprits[n];if(!o?.isValid)return D.error(s_.BadSignature)}return D.ok(null)}verifyFaults(e,t,r,s){if(!i_(e.faults,"key"))return D.error(s_.FaultsNotSortedUnique);const i=e.faults.length;for(let n=0;n<i;n++){const{key:i,workReportHash:a,wasConsideredValid:o}=e.faults[n];if(void 0!==this.state.disputesRecords.punishSet.findExact(i))return D.error(s_.OffenderAlreadyReported);if(!s.has(i))return D.error(s_.BadAuditorKey);if(o){const e=t.toAddToGoodSet.findExact(a),r=t.toAddToBadSet.findExact(a);if(void 0!==e||void 0===r)return D.error(s_.FaultVerdictWrong)}if(!r.faults[n].isValid)return D.error(s_.BadSignature)}return D.ok(null)}verifyVerdicts(e,t){if(!i_(e.verdicts,"workReportHash"))return D.error(s_.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 D.error(s_.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 D.error(s_.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 D.error(s_.BadValidatorIndex);if(!t.judgements[s].isValid)return D.error(s_.BadSignature);s+=1}}return D.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 D.error(s_.AlreadyJudged)}return D.ok(null)}calculateVotesForWorkReports(e){const t=pt.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 D.error(s_.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 D.error(s_.NotEnoughCulprits)}else if(s!==this.chainSpec.thirdOfValidators)return D.error(s_.BadVoteSplit);return D.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:It.fromArrayUnique(HE,t),toAddToBadSet:It.fromArrayUnique(HE,r),toAddToWonkySet:It.fromArrayUnique(HE,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 NE(t,this.chainSpec)}getOffenders(e){const t=bt.new();for(const{key:r}of e.culprits)t.insert(r);for(const{key:r}of e.faults)t.insert(r);return t}getUpdatedDisputesRecords(e,t){const r=At.fromArray(HE,Array.from(t));return LE.create({goodSet:It.fromTwoSortedCollections(this.state.disputesRecords.goodSet,e.toAddToGoodSet),badSet:It.fromTwoSortedCollections(this.state.disputesRecords.badSet,e.toAddToBadSet),wonkySet:It.fromTwoSortedCollections(this.state.disputesRecords.wonkySet,e.toAddToWonkySet),punishSet:It.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 D.error(s_.BadValidatorIndex);const i=s.ed25519;t.judgements.push(d_(r,n,i))}}return t.culprits=e.culprits.map(c_),t.faults=e.faults.map(l_),D.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 bt.from(s)}async transition(e){const t=this.prepareSignaturesToVerification(e);if(t.isError)return D.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 wr(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,a=this.getValidatorKeys(),o=[this.verifyVerdicts(e,n),this.verifyVotesForWorkReports(s,e),this.verifyCulprits(e,i,n,a),this.verifyFaults(e,i,n,a),this.verifyIfAlreadyJudged(e)].find(e=>e.isError);if(o?.isError)return D.error(o.error);const c=this.getOffenders(e),l=this.getUpdatedDisputesRecords(i,c),d=this.getClearedCoreAssignment(s);return D.ok({offendersMark:c,stateUpdate:{disputesRecords:l,availabilityAssignment:d}})}}const h_=P.blobFromString("jam_entropy").raw,f_=P.blobFromString("jam_fallback_seal").raw,g_=P.blobFromString("jam_ticket_seal").raw;var p_;!function(e){e[e.Ok=0]="Ok",e[e.Error=1]="Error"}(p_||(p_={}));const b_=async function(e,t,r,s,i,n){const a=P.blobFromParts(t.map(e=>e.raw)).raw,o=await e.verifySeal(a,r,s.raw,i.raw,n.raw);return o[0]===p_.Error?D.error(null):D.ok(L.fromBlob(o.subarray(1),Pe).asOpaque())},m_=async function(e,t,r,s){const i=s.length+g_.length+1,n=P.blobFromParts(r.map(e=>P.blobFromParts([e.signature.raw,g_,s.raw,Uint8Array.of(e.attempt)]).raw)).raw,a=P.blobFromParts(t.map(e=>e.raw)).raw;try{const t=await e.batchVerifyTicket(a,n,i);return Array.from(P.blobFrom(t).chunks(33)).map(e=>({isValid:e.raw[0]===p_.Ok,entropyHash:L.fromBlob(e.raw.subarray(1,33),Pe).asOpaque()}))}catch(e){if("RuntimeError: unreachable"==`${e}`)return Array.from({length:r.length},()=>({isValid:!1,entropyHash:L.zero(Pe).asOpaque()}));throw e}},y_=async function(e,t){const r=P.blobFromParts(t.map(e=>e.raw)).raw,s=await e.getRingCommitment(r);return s[0]===p_.Error?D.error(null):D.ok(L.fromBlob(s.subarray(1),De).asOpaque())};class A_{runInternal;state;static new(e,t){return new A_(e,t)}constructor(e,t){this.runInternal=e,this.state=t}listenToParentPort(){if(null===EE.parentPort)throw new Error("This method is meant to be run inside a worker thread!");EE.parentPort.once("close",()=>{process.exit(0)}),EE.parentPort.once("message",e=>{this.listenTo(e),EE.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=D.ok(t);e.postMessage(r,t.getTransferList())}).catch(t=>{const r=D.error(`${t}`);e.postMessage(r,[])})})}async run(e){return await this.runInternal(e,this.state)}async destroy(){}}class I_{workers;maxWorkers;workerPath;static async initialize(e,t){w(t.maxWorkers>0,"Max workers has to be positive."),w(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 v_(e));return new I_(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 v_(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 v_(e){const{port1:t,port2:r}=new MessageChannel,s=new EE.Worker(e,{});return s.postMessage(t,[t]),await new Promise((e,t)=>{s.once("message",e),s.once("error",t)}),s.unref(),new w_(s,r)}class w_{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 S_;!function(e){e[e.RingCommitment=0]="RingCommitment",e[e.BatchVerifyTickets=1]="BatchVerifyTickets",e[e.VerifySeal=2]="VerifySeal"}(S_||(S_={}));class E_{data;constructor(e){this.data=e}getTransferList(){return[]}}class C_{params;constructor(e){this.params=e}getTransferList(){return[]}}const k_=A_.new(e=>{const t=e.params,r=t.method;return r===S_.RingCommitment?Promise.resolve(new E_(Ue.ring_commitment(t.keys))):r===S_.BatchVerifyTickets?Promise.resolve(new E_(Ue.batch_verify_tickets(t.keys,t.ticketsData,t.contextLength))):r===S_.VerifySeal?Promise.resolve(new E_(Ue.verify_seal(t.keys,t.authorIndex,t.signature,t.payload,t.auxData))):void E(r)},null);class x_{executor;constructor(e){this.executor=e}destroy(){return this.executor.destroy()}static async new({synchronous:e}){const t=gE().cpus().length;return new x_(e?k_:await I_.initialize(new URL(a(884),a.b),{minWorkers:Math.max(1,Math.floor(t/2)),maxWorkers:t}))}async verifySeal(e,t,r,s,i){return(await this.executor.run(new C_({method:S_.VerifySeal,keys:e,authorIndex:t,signature:r,payload:s,auxData:i}))).data}async getRingCommitment(e){return(await this.executor.run(new C_({method:S_.RingCommitment,keys:e}))).data}async batchVerifyTicket(e,t,r){return(await this.executor.run(new C_({method:S_.BatchVerifyTickets,keys:e,ticketsData:t,contextLength:r}))).data}}const B_=(e,t)=>W(e.id,t.id);var __,R_,O_,U_,T_,N_,D_,M_,P_;!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"}(__||(__={}));class L_{chainSpec;state;bandersnatch;constructor(e,t,r=x_.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=je([r.raw,t]).asOpaque();return this.isEpochChanged(e)?yt.new([i,r,s[0],s[1]],4):yt.new([i,...s],4)}async getValidatorKeys(e,t){if(!this.isEpochChanged(e)){const{nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s}=this.state;return D.ok({nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s})}const r=this.state.designatedValidatorData.map(e=>!1!==t.has(e.ed25519)?YE.create({bandersnatch:L.zero(Te).asOpaque(),ed25519:L.zero(mr).asOpaque(),bls:L.zero(Me).asOpaque(),metadata:e.metadata}):e),{nextValidatorData:s,currentValidatorData:i}=this.state,n=await y_(await this.bandersnatch,r.map(e=>e.bandersnatch));return n.isOk?D.ok({nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n.ok}):D.error(__.IncorrectData)}outsideInSequencer(e){const t=e.length,r=new Array(t),s=Math.floor(t/2);for(let i=0;i<s;i+=1)r[2*i]=e[i],r[2*i+1]=e[t-i-1];return 2*s<t&&(r[2*s]=e[s]),Vr(r,this.chainSpec)}fallbackKeySequencer(e,t){const r=this.chainSpec.epochLength,s=[],i=t.length;for(let n=ne(0);n<r;n++){const r=de(n),a=je([e.raw,r]).raw,o=fe.fromBlob(a).u32()%i;s.push(t[o].bandersnatch)}return Vr(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?eC.tickets(this.outsideInSequencer(this.state.ticketsAccumulator)):this.isSameEpoch(e)?this.state.sealingKeySeries:eC.keys(this.fallbackKeySequencer(r,t))}getEpochMark(e,t){if(!this.isEpochChanged(e))return null;const r=this.state.entropy;return hs.create({entropy:r[0],ticketsEntropy:r[1],validators:t.map(e=>us.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 D.error(__.DuplicateTicket);if(t.isGreater())return D.error(__.BadTicketOrder)}return D.ok(null)}async getNewTicketAccumulator(e,t,r,s){const i=0===t.length?[]:await m_(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 D.error(__.BadTicketProof);const a=this.verifyTickets(n);if(a.isError)return D.error(a.error);if(this.isEpochChanged(e))return D.ok(n);const o=It.fromSortedArray(B_,this.state.ticketsAccumulator),c=It.fromSortedArray(B_,n),l=It.fromTwoSortedCollections(o,c);return o.length+c.length!==l.length?D.error(__.DuplicateTicket):D.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 D.error(__.BadSlot);if(!this.isExtrinsicLengthValid(e.slot,e.extrinsic))return D.error(__.UnexpectedTicket);if(!this.areTicketAttemptsValid(e.extrinsic))return D.error(__.BadTicketAttempt);const t=await this.getValidatorKeys(e.slot,e.punishSet);if(t.isError)return D.error(t.error);const{nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n}=t.ok,a=this.getEntropy(e.slot,e.entropy),o=this.getSlotKeySequence(e.slot,s,a[2]),c=await this.getNewTicketAccumulator(e.slot,e.extrinsic,this.state.nextValidatorData,a[2]);if(c.isError)return D.error(c.error);const l={nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n,timeslot:e.slot,entropy:a,sealingKeySeries:o,ticketsAccumulator:c.ok},d={epochMark:this.getEpochMark(e.slot,r),ticketsMark:this.getTicketsMark(e.slot),stateUpdate:l};return D.ok(d)}}!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"}(R_||(R_={}));class H_{bandersnatch;constructor(e=x_.new({synchronous:!0})){this.bandersnatch=e}async verifyHeaderSeal(e,t){const r=await this.verifySeal(e,t);if(r.isError)return r;const s=P.blobFromParts(h_,r.ok.raw),i=await b_(await this.bandersnatch,t.currentValidatorData.map(e=>e.bandersnatch),e.bandersnatchBlockAuthorIndex.materialize(),e.entropySource.materialize(),s,P.blobFromNumbers([]));return i.isError?D.error(R_.IncorrectEntropySource):D.ok(i.ok)}async verifySeal(e,t){const r=t.currentValidatorData,s=e.bandersnatchBlockAuthorIndex.materialize(),i=r[s];if(void 0===i)return D.error(R_.InvalidValidatorIndex);const n=e.timeSlotIndex.materialize(),a=t.sealingKeySeries,o=t.currentEntropy;return a.kind===XE.Tickets?await this.verifySealWithTicket(a.tickets,n,o,r,s,e):await this.verifySealWithKeys(a.keys,i,n,o,r,s,e)}async verifySealWithTicket(e,t,r,s,i,n){const a=t%e.length,{id:o,attempt:c}=e[a],l=P.blobFromParts(g_,r.raw,new Uint8Array([c])),d=await b_(await this.bandersnatch,s.map(e=>e.bandersnatch),i,n.seal.materialize(),l,fs(n));return d.isError?D.error(R_.IncorrectSeal):o.isEqualTo(d.ok)?D.ok(d.ok):D.error(R_.InvalidTicket)}async verifySealWithKeys(e,t,r,s,i,n,a){const o=e[r%e.length];if(!o.isEqualTo(t.bandersnatch))return D.error(R_.InvalidValidator,`Expected: ${o}, got: ${t.bandersnatch}`);const c=P.blobFromParts(f_,s.raw),l=await b_(await this.bandersnatch,i.map(e=>e.bandersnatch),n,a.seal.materialize(),c,fs(a));return l.isError?D.error(R_.IncorrectSeal):D.ok(l.ok)}}function V_(e){if(e.length===O_.Requested)return{status:O_.Requested};if(e.length===O_.Available)return{status:O_.Available,data:[e[0]]};if(e.length===O_.Unavailable)return{status:O_.Unavailable,data:[e[0],e[1]]};if(e.length===O_.Reavailable)return{status:O_.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"}(O_||(O_={})),function(e){e[e.AlreadyRequested=0]="AlreadyRequested",e[e.AlreadyAvailable=1]="AlreadyAvailable",e[e.InsufficientFunds=2]="InsufficientFunds"}(U_||(U_={})),function(e){e[e.NotFound=0]="NotFound",e[e.NotExpired=1]="NotExpired",e[e.StorageUtilisationError=2]="StorageUtilisationError"}(T_||(T_={})),function(e){e[e.DestinationNotFound=0]="DestinationNotFound",e[e.GasTooLow=1]="GasTooLow",e[e.BalanceBelowThreshold=2]="BalanceBelowThreshold"}(N_||(N_={})),function(e){e[e.InvalidService=0]="InvalidService",e[e.InvalidPreimage=1]="InvalidPreimage"}(D_||(D_={})),function(e){e[e.ServiceNotFound=0]="ServiceNotFound",e[e.WasNotRequested=1]="WasNotRequested",e[e.AlreadyProvided=2]="AlreadyProvided"}(M_||(M_={})),function(e){e[e.InsufficientFunds=0]="InsufficientFunds",e[e.UnprivilegedService=1]="UnprivilegedService"}(P_||(P_={}));class K_{source;destination;amount;memo;gas;static Codec=Be.Class(K_,{source:Be.u32.asOpaque(),destination:Be.u32.asOpaque(),amount:Be.u64,memo:Be.bytes(128),gas:Be.u64.asOpaque()});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 K_(e,t,r,s,i)}}const Q_="insufficient funds";class F_{services;transfers;yieldedRoots;authorizationQueues=new Map;validatorsData=null;privilegedServices=null;constructor(e,t,r=new Map){this.services=e,this.transfers=t,this.yieldedRoots=r}static empty(){return new F_({servicesUpdates:[],servicesRemoved:[],preimages:[],storage:[]},[])}static new(e){return new F_({...e},[])}static copyFrom(e){const t={servicesUpdates:[...e.services.servicesUpdates],servicesRemoved:[...e.services.servicesRemoved],preimages:[...e.services.preimages],storage:[...e.services.storage]},r=[...e.transfers],s=new F_(t,r,new Map(e.yieldedRoots));for(const[t,r]of e.authorizationQueues)s.authorizationQueues.set(t,r);return null!==e.validatorsData&&(s.validatorsData=[...e.validatorsData]),null!==e.privilegedServices&&(s.privilegedServices=KE.create({...e.privilegedServices,authManager:[...e.privilegedServices.authManager]})),s}}class $_{state;stateUpdate;constructor(e,t){this.state=e,this.stateUpdate=void 0===t?F_.empty():F_.copyFrom(t)}getServiceInfo(e){if(null===e)return null;const t=this.stateUpdate.services.servicesRemoved.some(t=>t===e);if(t)return null;const r=this.stateUpdate.services.servicesUpdates.find(t=>t.serviceId===e);if(void 0!==r)return r.action.account;const s=this.state.getService(e);return null===s?null:s.getInfo()}getStorage(e,t){const r=this.stateUpdate.services.storage.find(r=>r.serviceId===e&&r.key.isEqualTo(t));if(void 0!==r)return r.value;const s=this.state.getService(e);return s?.getStorage(t)??null}hasPreimage(e,t){if(void 0!==this.stateUpdate.services.preimages.find(r=>r.serviceId===e&&r.hash.isEqualTo(t)))return!0;const r=this.state.getService(e);return void 0!==r&&(r?.hasPreimage(t)??!1)}getPreimage(e,t){const r=this.stateUpdate.services.preimages.find(r=>r.serviceId===e&&r.hash.isEqualTo(t));if(void 0!==r&&r.action.kind===lC.Provide)return r.action.preimage.blob;const s=this.state.getService(e);return s?.getPreimage(t)??null}getLookupHistory(e,t,r,s){const i=this.stateUpdate.services.preimages.findLast(e=>e.serviceId===t&&e.hash.isEqualTo(r)&&BigInt(e.length)===s),n=()=>{const e=this.state.getService(t),i=function(e){return e>=2n**32n?null:ne(Number(e))}(s);if(null===i||null===e)return null;const n=e.getLookupHistory(r,i);return null===n?null:new cC(r,i,n)};if(void 0===i)return n();const{action:a}=i;switch(a.kind){case lC.Provide:return new cC(r,i.length,oC([e]));case lC.Remove:{const t=n();return null===t?null:new cC(r,t.length,oC([...t.slots,e]))}case lC.UpdateOrAdd:return a.item}E(a)}updateStorage(e,t,r){const s=null===r?gC.remove({serviceId:e,key:t}):gC.set({serviceId:e,storage:aC.create({key:t,value:r})}),i=this.stateUpdate.services.storage.findIndex(e=>e.serviceId===s.serviceId&&e.key.isEqualTo(t)),n=-1===i?0:1;this.stateUpdate.services.storage.splice(i,n,s)}updatePreimage(e){this.stateUpdate.services.preimages.push(e)}updateServiceStorageUtilisation(e,t,r,s){w(t>=0,`storageUtilisationCount has to be a positive number, got: ${t}`),w(r>=0,`storageUtilisationBytes has to be a positive number, got: ${r}`);const i=!ae(t),n=!ce(r);if(i||n)return D.error(Q_);const a=iC.calculateThresholdBalance(t,r,s.gratisStorage);return s.balance<a?D.error(Q_):(this.updateServiceInfo(e,iC.create({...s,storageUtilisationBytes:r,storageUtilisationCount:t})),D.ok(O))}updateServiceInfo(e,t){const r=this.stateUpdate.services.servicesUpdates.findIndex(t=>t.serviceId===e),s=-1===r?0:1,i=this.stateUpdate.services.servicesUpdates[r];i?.action.kind!==dC.Create?this.stateUpdate.services.servicesUpdates.splice(r,s,fC.update({serviceId:e,serviceInfo:t})):this.stateUpdate.services.servicesUpdates.splice(r,s,fC.create({serviceId:e,serviceInfo:t,lookupHistory:i.action.lookupHistory}))}getPrivilegedServices(){return null!==this.stateUpdate.privilegedServices?this.stateUpdate.privilegedServices:this.state.privilegedServices}}const G_=oe(81),j_=v.isGreaterOrEqual(h.V0_6_7)?oe(34):oe(32),q_=ri.new(void 0,"accumulate-externalities");class z_{chainSpec;updatedState;currentServiceId;currentTimeslot;checkpointedState=null;nextNewServiceId;constructor(e,t,r,s,i){if(this.chainSpec=e,this.updatedState=t,this.currentServiceId=r,this.currentTimeslot=i,this.nextNewServiceId=this.getNextAvailableServiceId(s),null===this.updatedState.getServiceInfo(this.currentServiceId))throw new Error(`Invalid state initialization. Service info missing for ${this.currentServiceId}.`)}getStateUpdates(){return[this.updatedState.stateUpdate,this.checkpointedState]}getNextNewServiceId(){return this.nextNewServiceId}getCurrentServiceInfo(){const e=this.updatedState.getServiceInfo(this.currentServiceId);if(null===e)throw new Error(`Missing service info for current service! ${this.currentServiceId}`);return e}getServiceInfo(e){return this.updatedState.getServiceInfo(e)}isPreviousCodeExpired(e,t,r){const s=this.updatedState.getLookupHistory(this.currentTimeslot,e,t,r),i=null===s?null:V_(s.slots);if(i?.status!==O_.Unavailable)return[!1,"wrong status"];const n=this.currentTimeslot,a=i.data[1]<n-this.chainSpec.preimageExpungePeriod;return[a,a?"":"not expired"]}getNextAvailableServiceId(e){let t=e;const r=2**32-512;for(;;){if(null===this.getServiceInfo(t))return t;t=Nr((t-256+1+r)%r+256)}}getManager(){return this.updatedState.getPrivilegedServices().manager}checkPreimageStatus(e,t){const r=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);return null===r?null:V_(r.slots)}requestPreimage(e,t){const r=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);if(null!==r){const e=r.slots.length;if(e===O_.Requested)return D.error(U_.AlreadyRequested);if(e===O_.Available||e===O_.Reavailable)return D.error(U_.AlreadyAvailable);w(e===O_.Unavailable)}const s=this.getCurrentServiceInfo(),i=null!==r,n=i?0:2,a=t-BigInt(r?.length??0),o=s.storageUtilisationCount+n,c=s.storageUtilisationBytes+BigInt(a)+(i?0n:G_),l=this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,o,c,s);if(l.isError)return D.error(U_.InsufficientFunds,l.details);const d=TB(t);return null===r?this.updatedState.updatePreimage(hC.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new cC(e,d,oC([]))})):this.updatedState.updatePreimage(hC.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new cC(e,d,oC([...r.slots,this.currentTimeslot]))})),D.ok(O)}forgetPreimage(e,t){const r=this.currentServiceId,s=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);if(null===s)return D.error(T_.NotFound);const i=V_(s.slots),n=()=>{const e=this.getCurrentServiceInfo(),r=e.storageUtilisationCount-2,s=e.storageUtilisationBytes-t-G_;return this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,r,s,e)};if(i.status===O_.Requested)return n().isError?D.error(T_.StorageUtilisationError):(this.updatedState.updatePreimage(hC.remove({serviceId:r,hash:s.hash,length:s.length})),D.ok(O));const a=this.currentTimeslot;return i.status===O_.Unavailable?i.data[1]<a-this.chainSpec.preimageExpungePeriod?n().isError?D.error(T_.StorageUtilisationError):(this.updatedState.updatePreimage(hC.remove({serviceId:r,hash:s.hash,length:s.length})),D.ok(O)):D.error(T_.NotExpired):i.status===O_.Available?(this.updatedState.updatePreimage(hC.updateOrAdd({serviceId:r,lookupHistory:new cC(s.hash,s.length,oC([i.data[0],a]))})),D.ok(O)):i.status===O_.Reavailable?i.data[1]<a-this.chainSpec.preimageExpungePeriod?(this.updatedState.updatePreimage(hC.updateOrAdd({serviceId:r,lookupHistory:new cC(s.hash,s.length,oC([i.data[2],a]))})),D.ok(O)):D.error(T_.NotExpired):void E(i)}transfer(e,t,r,s){const i=this.getCurrentServiceInfo(),n=this.getServiceInfo(e);if(null===n||null===e)return D.error(N_.DestinationNotFound);if(r<n.onTransferMinGas)return D.error(N_.GasTooLow);const a=i.balance-t;return a<iC.calculateThresholdBalance(i.storageUtilisationCount,i.storageUtilisationBytes,i.gratisStorage)?D.error(N_.BalanceBelowThreshold):(this.updatedState.stateUpdate.transfers.push(K_.create({source:this.currentServiceId,destination:e,amount:t,memo:s,gas:r})),this.updatedState.updateServiceInfo(this.currentServiceId,iC.create({...i,balance:oe(a)})),D.ok(O))}newService(e,t,r,s,i){const n=this.nextNewServiceId,a=ne(2),o=le(G_,t),c=TB(t);if(i!==oe(0)&&this.currentServiceId!==this.getManager())return D.error(P_.UnprivilegedService);const l=iC.calculateThresholdBalance(a,o.value,i),d=this.getCurrentServiceInfo(),u=iC.calculateThresholdBalance(d.storageUtilisationCount,d.storageUtilisationBytes,d.gratisStorage),h=d.balance-l;return h<u||o.overflow?D.error(P_.InsufficientFunds):(this.updatedState.stateUpdate.services.servicesUpdates.push(fC.create({serviceId:n,serviceInfo:iC.create({codeHash:e,balance:l,accumulateMinGas:r,onTransferMinGas:s,storageUtilisationBytes:o.value,storageUtilisationCount:a,gratisStorage:i,created:this.currentTimeslot,lastAccumulation:Ur(0),parentService:this.currentServiceId}),lookupHistory:new cC(e.asOpaque(),c,oC([]))})),this.updatedState.updateServiceInfo(this.currentServiceId,iC.create({...d,balance:oe(h)})),this.nextNewServiceId=this.getNextAvailableServiceId(function(e){const t=2**32-512;return Nr(256+(e-256+42+t)%t)}(n)),D.ok(n))}upgradeService(e,t,r){const s=this.getCurrentServiceInfo();this.updatedState.updateServiceInfo(this.currentServiceId,iC.create({...s,codeHash:e,accumulateMinGas:Dr(t),onTransferMinGas:Dr(r)}))}updateValidatorsData(e){const t=this.updatedState.getPrivilegedServices().validatorsManager;t===this.currentServiceId?this.updatedState.stateUpdate.validatorsData=e:q_.trace(`Current service id (${this.currentServiceId}) is not a validator manager (${t}) and cannot update validators. Ignoring.`)}checkpoint(){this.checkpointedState=F_.copyFrom(this.updatedState.stateUpdate)}updateAuthorizationQueue(e,t){const r=this.updatedState.getPrivilegedServices().authManager[e];r===this.currentServiceId?this.updatedState.stateUpdate.authorizationQueues.set(e,t):q_.trace(`Current service id (${this.currentServiceId}) is not an auth manager of core ${e} (expected: ${r}) and cannot update authorization queue. Ignoring`)}updatePrivilegedServices(e,t,r,s){const i=this.updatedState.getPrivilegedServices().manager;i===this.currentServiceId?this.updatedState.stateUpdate.privilegedServices=KE.create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s.map(([e,t])=>VE.create({service:e,gasLimit:t}))}):q_.trace(`Current service id (${this.currentServiceId}) is not a manager (${i}) and cannot update privileged services. Ignoring.`)}yield(e){this.updatedState.stateUpdate.yieldedRoots.set(this.currentServiceId,e)}providePreimage(e,t){if(null===(null===e?null:this.updatedState.state.getService(e))||null===e)return D.error(M_.ServiceNotFound);const r=qe(t).asOpaque(),s=this.updatedState.getLookupHistory(this.currentTimeslot,e,r,oe(t.length));return null!==s&&cC.isRequested(s)?this.updatedState.hasPreimage(e,r)?D.error(M_.AlreadyProvided):(this.updatedState.updatePreimage(hC.provide({serviceId:e,preimage:nC.create({hash:r,blob:t}),slot:this.currentTimeslot})),D.ok(O)):D.error(M_.WasNotRequested)}eject(e,t){const r=this.getServiceInfo(e);if(null===r||null===e)return D.error(D_.InvalidService,"Service missing");const s=this.getCurrentServiceInfo(),i=L.zero(Pe).asOpaque();if(function(e,t){w(t.length>=4,"Not enough space in the destination."),t.set(de(e))}(this.currentServiceId,i.raw),!r.codeHash.isEqualTo(i))return D.error(D_.InvalidService,"Invalid code hash");if(2!==r.storageUtilisationCount)return D.error(D_.InvalidPreimage,"Too many storage items");const n=oe(((e,...t)=>t.reduce((e,t)=>t<e?e:t,e))(r.storageUtilisationBytes,G_)-G_),[a,o]=this.isPreviousCodeExpired(e,t,n);if(!a)return D.error(D_.InvalidPreimage,`Previous code available: ${o}`);const c=le(s.balance,r.balance);return c.overflow?D.error(D_.InvalidService,"Balance overflow"):(this.updatedState.updateServiceInfo(this.currentServiceId,iC.create({...s,balance:c.value})),this.updatedState.stateUpdate.services.servicesRemoved.push(e),D.ok(O))}read(e,t){return null===e?null:this.updatedState.getStorage(e,t)}write(e,t){const r=oe(e.length),s=this.read(this.currentServiceId,e),i=null===s&&null!==t,n=null!==s&&null===t,a=i?1:n?-1:0,o=(t?.length??0)-(s?.length??0),c=i?j_:n?-j_:0n,l=v.isGreaterOrEqual(h.V0_6_7)?i?r:n?-r:0n:0n,d=this.getCurrentServiceInfo(),u=d.storageUtilisationCount+a,f=d.storageUtilisationBytes+BigInt(o)+c+l,g=this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,u,f,d);return g.isError?D.error("full",g.details):(this.updatedState.updateStorage(this.currentServiceId,e,t),D.ok(null===s?null:s.length))}lookup(e,t){return null===e?null:this.updatedState.getPreimage(e,t)}}class W_ extends B{static Codec=Be.Class(W_,v.isSuite(f.JAMDUNA,h.V0_6_5)?{hash:Be.bytes(Pe).asOpaque(),exportsRoot:Be.bytes(Pe).asOpaque(),authorizerHash:Be.bytes(Pe).asOpaque(),authorizationOutput:Be.blob,payloadHash:Be.bytes(Pe),gas:Be.varU64.asOpaque(),result:Zr.Codec}:{hash:Be.bytes(Pe).asOpaque(),exportsRoot:Be.bytes(Pe).asOpaque(),authorizerHash:Be.bytes(Pe).asOpaque(),payloadHash:Be.bytes(Pe),gas:Be.varU64.asOpaque(),result:Zr.Codec,authorizationOutput:Be.blob});hash;exportsRoot;authorizerHash;payloadHash;gas;result;authorizationOutput;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,gas:s,hash:i,payloadHash:n,result:a}){return new W_({gas:Dr(s),payloadHash:n.asOpaque(),result:a,authorizationOutput:P.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 W_(e)}}class J_{operands;reportsLength;gasCost;constructor(e,t,r){this.operands=e,this.reportsLength=t,this.gasCost=r}static empty(){return new J_([],ne(0),Dr(0n))}}class Y_{reportsDataByServiceId;autoAccumulateServicesByServiceId;serviceIds;constructor(e,t){const{autoAccumulateServicesByServiceId:r,serviceIds:s}=this.transformAutoAccumulateServices(t);this.autoAccumulateServicesByServiceId=r;const{reportsDataByServiceId:i,serviceIds:n}=this.transformReports(e);this.reportsDataByServiceId=i,this.serviceIds=this.mergeServiceIds(n,s)}mergeServiceIds(e,t){const r=new Set;for(const t of e)r.add(t);for(const e of t)r.add(e);return Array.from(r)}transformAutoAccumulateServices(e){const t=new Set,r=new Map;for(const s of e)r.set(s.service,s),t.add(s.service);return{autoAccumulateServicesByServiceId:r,serviceIds:t}}transformReports(e){const t=new Map,r=new Set;for(const s of e)for(const e of s.results){const i=e.serviceId;r.add(i);const n=t.get(i)??J_.empty();n.reportsLength=ne(n.reportsLength+1),n.gasCost=Dr(n.gasCost+e.gas),n.operands.push(W_.new({gas:e.gas,payloadHash:e.payloadHash,result:e.result,authorizationOutput:s.authorizationOutput,exportsRoot:s.workPackageSpec.exportsRoot,hash:s.workPackageSpec.hash,authorizerHash:s.authorizerHash})),t.set(i,n)}for(const e of r){const r=t.get(e)??null,s=this.autoAccumulateServicesByServiceId.get(e)??null;null!==r&&null!==s&&(r.gasCost=Dr(r.gasCost+s.gasLimit))}return{reportsDataByServiceId:t,serviceIds:r}}getOperands(e){return this.reportsDataByServiceId.get(e)?.operands??[]}getReportsLength(e){return this.reportsDataByServiceId.get(e)?.reportsLength??ne(0)}getGasCost(e){return this.reportsDataByServiceId.get(e)?.gasCost??Dr(0n)}getServiceIds(){return this.serviceIds}}function X_(e){const t=e.map(e=>e.workPackageSpec.hash);return bt.from(t)}const Z_=Be.object({serviceId:Be.u32.asOpaque(),entropy:Be.bytes(Pe).asOpaque(),timeslot:Be.u32.asOpaque()});class eR{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(bt.from(e.context.prerequisites.concat(e.segmentRootLookup.map(e=>e.workPackageHash))))}getWorkReportsToAccumulateLater(e){const t=this.state.recentlyAccumulated.flatMap(e=>Array.from(e));return tR(e.filter(e=>e.context.prerequisites.length>0||e.segmentRootLookup.length>0).map(e=>xC.create({report:e,dependencies:this.getWorkReportDependencies(e)})),bt.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=tR(r,X_(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 tR(e,t){return e.filter(({report:e})=>!t.has(e.workPackageSpec.hash)).map(e=>{const{report:r,dependencies:s}=e;return xC.create({report:r,dependencies:s.filter(e=>!t.has(e))})})}const rR=Be.object({serviceId:Be.u32.convert(e=>e,e=>e),gas:Be.u64.convert(e=>oe(e),e=>Dr(e))});class sR{currentServiceId;index=Dk(0);gasCost=zk(10);tracedRegisters=Lk(7);constructor(e){this.currentServiceId=e}execute(e,t){const r=v.isSuite(f.JAMDUNA,h.V0_6_5)?BigInt(e.get())-10n:e.get();return t.set(7,oe(r)),Promise.resolve(void 0)}}const iR=be(YE.Codec.sizeHint),nR=e=>oe(e);var aR,oR,cR,lR,dR;!function(e){e[e.Void=0]="Void",e[e.ZeroRead=1]="ZeroRead",e[e.ZeroWrite=2]="ZeroWrite",e[e.Read=3]="Read",e[e.Write=4]="Write"}(aR||(aR={})),function(e){e[e.SourcePageFault=0]="SourcePageFault",e[e.DestinationPageFault=1]="DestinationPageFault",e[e.NoMachine=2]="NoMachine"}(oR||(oR={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidPage=1]="InvalidPage"}(cR||(cR={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidOperation=1]="InvalidOperation",e[e.InvalidPage=2]="InvalidPage"}(lR||(lR={})),Symbol("Machine index not found."),Symbol("Too many segments already exported.");class uR{currentServiceId;fetch;index=Dk(v.selectIfGreaterOrEqual({fallback:18,versions:{[h.V0_6_7]:1}}));gasCost=zk(10);tracedRegisters=Lk(7,8,9,10,11,12);constructor(e,t){this.currentServiceId=e,this.fetch=t}async execute(e,t,r){const s=this.getValue(t),i=t.get(7),n=oe(s?.length??0),a=he(t.get(8),n),o=he(t.get(9),oe(n-a)),c=null===s?new Uint8Array:s.raw.subarray(Number(a),Number(a+o));if(r.storeFrom(i,c).isError)return Mk.Panic;t.set(7,null===s?xB.NONE:n)}getValue(e){const t=TB(e.get(10));if(t===dR.Constants)return this.fetch.constants();if(t===dR.Entropy)return this.fetch.entropy();if(t===dR.AuthorizerTrace)return this.fetch.authorizerTrace();if(t===dR.OtherWorkItemExtrinsics){const t=e.get(11),r=e.get(12);return this.fetch.workItemExtrinsic(t,r)}if(t===dR.MyExtrinsics){const t=e.get(11);return this.fetch.workItemExtrinsic(null,t)}if(t===dR.OtherWorkItemImports){const t=e.get(11),r=e.get(12);return this.fetch.workItemImport(t,r)}if(t===dR.MyImports){const t=e.get(11);return this.fetch.workItemImport(null,t)}if(t===dR.WorkPackage)return this.fetch.workPackage();if(t===dR.Authorizer)return this.fetch.authorizer();if(t===dR.AuthorizationToken)return this.fetch.authorizationToken();if(t===dR.RefineContext)return this.fetch.refineContext();if(t===dR.AllWorkItems)return this.fetch.allWorkItems();if(t===dR.OneWorkItem){const t=e.get(11);return this.fetch.oneWorkItem(t)}if(t===dR.WorkItemPayload){const t=e.get(11);return this.fetch.workItemPayload(t)}if(t===dR.AllOperands)return this.fetch.allOperands();if(t===dR.OneOperand){const t=e.get(11);return this.fetch.oneOperand(t)}if(t===dR.AllTransfers)return this.fetch.allTransfers();if(t===dR.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"}(dR||(dR={}));class hR{currentServiceId;account;index=Dk(v.selectIfGreaterOrEqual({fallback:4,versions:{[h.V0_6_7]:5}}));gasCost=zk(10);tracedRegisters=Lk(7,8);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=OB(7,t,this.currentServiceId),i=t.get(8),n=this.account.getServiceInfo(s),a=null===n?P.empty():Ae.encodeObject(fR,{...n,thresholdBalance:iC.calculateThresholdBalance(n.storageUtilisationCount,n.storageUtilisationBytes,n.gratisStorage)});if(r.storeFrom(i,a.raw).isError)return Mk.Panic;null!==n?t.set(7,xB.OK):t.set(7,xB.NONE)}}const fR=v.isGreaterOrEqual(h.V0_6_7)?Be.object({codeHash:Be.bytes(Pe),balance:Be.u64,thresholdBalance:Be.u64,accumulateMinGas:Be.u64.convert(e=>e,Dr),onTransferMinGas:Be.u64.convert(e=>e,Dr),storageUtilisationBytes:Be.u64,storageUtilisationCount:Be.u32,gratisStorage:Be.u64,created:Be.u32.convert(e=>e,Ur),lastAccumulation:Be.u32.convert(e=>e,Ur),parentService:Be.u32.convert(e=>e,Nr)},"ServiceAccountInfoWithThresholdBalance"):Be.object({codeHash:Be.bytes(Pe),balance:Be.varU64,thresholdBalance:Be.varU64,accumulateMinGas:Be.varU64.convert(e=>e,Dr),onTransferMinGas:Be.varU64.convert(e=>e,Dr),storageUtilisationBytes:Be.varU64,storageUtilisationCount:Be.varU32,gratisStorage:sC(oe(0)),created:sC(Ur(0)),lastAccumulation:sC(Ur(0)),parentService:sC(Nr(0))},"ServiceAccountInfoWithThresholdBalance"),gR=ri.new(void 0,"host-calls"),pR=new TextDecoder("utf8");class bR{currentServiceId;index=Dk(100);gasCost=zk(0);tracedRegisters=Lk();constructor(e){this.currentServiceId=e}execute(e,t,r){const s=t.get(7),i=t.get(8),n=t.get(9),a=t.get(10),o=t.get(11),c=new Uint8Array(TB(n)),l=new Uint8Array(TB(o));return 0n!==i&&r.loadInto(c,i),r.loadInto(l,a),gR.trace(`[${this.currentServiceId}] [${s}] ${pR.decode(c)} ${pR.decode(l)}`),Promise.resolve(void 0)}}class mR{currentServiceId;account;index=Dk(v.selectIfGreaterOrEqual({fallback:1,versions:{[h.V0_6_7]:2}}));gasCost=zk(10);tracedRegisters=Lk(7,8,9,10,11);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=OB(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),a=L.zero(Pe);if(r.loadInto(a.raw,i).isError)return Mk.Panic;const o=this.account.lookup(s,a),c=oe(null===o?0:o.raw.length),l=t.get(10),d=t.get(11),u=he(l,c),h=he(d,oe(c-u)),f=null===o?new Uint8Array(0):o.raw.subarray(Number(u),Number(u+h));if(r.storeFrom(n,f).isError)return Mk.Panic;null!==o?t.set(7,c):t.set(7,xB.NONE)}}class yR{currentServiceId;account;index=Dk(v.selectIfGreaterOrEqual({fallback:2,versions:{[h.V0_6_7]:3}}));gasCost=zk(10);tracedRegisters=Lk(7,8,9,10,11,12);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=OB(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),a=t.get(10),o=TB(n),c=new Uint8Array(o);if(r.loadInto(c,i).isError)return Mk.Panic;const l=this.account.read(s,P.blobFrom(c)),d=oe(null===l?0:l.raw.length),u=t.get(11),h=t.get(12),f=he(u,d),g=he(h,oe(d-f)),p=null===l?new Uint8Array(0):l.raw.subarray(Number(f),Number(f+g));if(r.storeFrom(a,p).isError)return Mk.Panic;null!==l?t.set(7,d):t.set(7,xB.NONE)}}class AR{currentServiceId;account;index=Dk(v.selectIfGreaterOrEqual({fallback:3,versions:{[h.V0_6_7]:4}}));gasCost=zk(10);tracedRegisters=Lk(7,8,9,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),a=t.get(10),o=TB(i),c=new Uint8Array(o);if(r.loadInto(c,s).isError)return Mk.Panic;const l=P.blobFrom(c),d=TB(a),u=new Uint8Array(d);if(r.loadInto(u,n).isError)return Mk.Panic;const h=0n===a?null:P.blobFrom(u),f=this.account.write(l,h);f.isError?t.set(7,xB.FULL):t.set(7,null===f.ok?xB.NONE:oe(f.ok))}}const IR=[class{currentServiceId;partialState;chainSpec;index=Dk(v.selectIfGreaterOrEqual({fallback:5,versions:{[h.V0_6_7]:14}}));gasCost=zk(10);tracedRegisters=Lk(7,8,9,10,11);constructor(e,t,r){this.currentServiceId=e,this.partialState=t,this.chainSpec=r}async execute(e,t,r){const s=UB(t.get(7)),i=UB(t.get(8)),n=UB(t.get(9)),a=t.get(10),o=t.get(11),c=new Array,l=new Uint8Array(be(rR.sizeHint)),d=fe.fromBlob(l);let u=a;for(let e=0n;e<o;e+=1n){if(d.resetTo(0),r.loadInto(l,u).isError)return Mk.Panic;const{serviceId:e,gas:t}=d.object(rR);c.push([e,t]),u=oe(u+oe(d.bytesRead()))}null!==s&&null!==i&&null!==n?(this.partialState.updatePrivilegedServices(s,NE(new Array(this.chainSpec.coresCount).fill(i),this.chainSpec),n,c),t.set(7,xB.OK)):t.set(7,xB.WHO)}},class{currentServiceId;partialState;chainSpec;index=Dk(v.selectIfGreaterOrEqual({fallback:6,versions:{[h.V0_6_7]:15}}));gasCost=zk(10);tracedRegisters=Lk(7,8);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 Mk.Panic;if(s>=this.chainSpec.coresCount)return void t.set(7,xB.CORE);const a=fe.fromBlob(n).sequenceFixLen(Be.bytes(Pe),80),o=yt.new(a,80);t.set(7,xB.OK),this.partialState.updateAuthorizationQueue(Mr(Number(s)),o)}},class{currentServiceId;partialState;chainSpec;index=Dk(v.selectIfGreaterOrEqual({fallback:7,versions:{[h.V0_6_7]:16}}));gasCost=zk(10);tracedRegisters=Lk(7);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(iR*this.chainSpec.validatorsCount);if(r.loadInto(i,s).isError)return Mk.Panic;const n=fe.fromBlob(i).sequenceFixLen(YE.Codec,this.chainSpec.validatorsCount);t.set(7,xB.OK),this.partialState.updateValidatorsData(Lr(n,this.chainSpec))}},class{currentServiceId;partialState;index=Dk(v.selectIfGreaterOrEqual({fallback:8,versions:{[h.V0_6_7]:17}}));gasCost=zk(10);tracedRegisters;gasHostCall;constructor(e,t){this.currentServiceId=e,this.partialState=t,this.gasHostCall=new sR(e),this.tracedRegisters=this.gasHostCall.tracedRegisters}async execute(e,t){await this.gasHostCall.execute(e,t),this.partialState.checkpoint()}},class{currentServiceId;partialState;index=Dk(v.selectIfGreaterOrEqual({fallback:9,versions:{[h.V0_6_7]:18}}));gasCost=zk(10);tracedRegisters=Lk(7,8,9,10,11);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=Dr(t.get(9)),a=Dr(t.get(10)),o=v.isGreaterOrEqual(h.V0_6_7)?t.get(11):oe(0),c=L.zero(Pe);if(r.loadInto(c.raw,s).isError)return Mk.Panic;const l=this.partialState.newService(c.asOpaque(),i,n,a,o);if(l.isOk)return void t.set(7,oe(l.ok));const d=l.error;d!==P_.InsufficientFunds?d!==P_.UnprivilegedService?E(d):t.set(7,xB.HUH):t.set(7,xB.CASH)}},class{currentServiceId;partialState;index=Dk(v.selectIfGreaterOrEqual({fallback:10,versions:{[h.V0_6_7]:19}}));gasCost=zk(10);tracedRegisters=Lk(7,8,9);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),a=L.zero(Pe);if(r.loadInto(a.raw,s).isError)return Mk.Panic;this.partialState.upgradeService(a.asOpaque(),i,n),t.set(7,xB.OK)}},class{currentServiceId;partialState;index=Dk(v.selectIfGreaterOrEqual({fallback:11,versions:{[h.V0_6_7]:20}}));gasCost=e=>{const t=10n+e.get(9);return Jk(t)};tracedRegisters=Lk(7,8,9,10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=UB(t.get(7)),i=t.get(8),n=Dr(t.get(9)),a=t.get(10),o=L.zero(128);if(r.loadInto(o.raw,a).isError)return Mk.Panic;const c=this.partialState.transfer(s,i,n,o);if(c.isOk)return void t.set(7,xB.OK);const l=c.error;l!==N_.DestinationNotFound?l!==N_.GasTooLow?l!==N_.BalanceBelowThreshold?E(l):t.set(7,xB.CASH):t.set(7,xB.LOW):t.set(7,xB.WHO)}},class{currentServiceId;partialState;index=Dk(v.selectIfGreaterOrEqual({fallback:12,versions:{[h.V0_6_7]:21}}));gasCost=zk(10);tracedRegisters=Lk(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=UB(t.get(7)),i=t.get(8),n=L.zero(Pe).asOpaque();if(r.loadInto(n.raw,i).isError)return Mk.Panic;if(s===this.currentServiceId)return void t.set(7,xB.WHO);const a=this.partialState.eject(s,n);if(a.isOk)return void t.set(7,xB.OK);const o=a.error;o===D_.InvalidService?t.set(7,xB.WHO):o===D_.InvalidPreimage?t.set(7,xB.HUH):E(o)}},class{currentServiceId;partialState;index=Dk(v.selectIfGreaterOrEqual({fallback:13,versions:{[h.V0_6_7]:22}}));gasCost=zk(10);tracedRegisters=Lk(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=L.zero(Pe);if(r.loadInto(n.raw,s).isError)return Mk.Panic;const a=this.partialState.checkPreimageStatus(n.asOpaque(),i),o=oe(0n);if(null===a)return t.set(7,xB.NONE),void t.set(8,o);switch(a.status){case O_.Requested:return t.set(7,o),void t.set(8,o);case O_.Available:return t.set(7,oe(1n+(BigInt(a.data[0])<<32n))),void t.set(8,o);case O_.Unavailable:return t.set(7,oe(2n+(BigInt(a.data[0])<<32n))),void t.set(8,oe(a.data[1]));case O_.Reavailable:return t.set(7,oe(3n+(BigInt(a.data[0])<<32n))),void t.set(8,oe((BigInt(a.data[2])<<32n)+BigInt(a.data[1])))}}},class{currentServiceId;partialState;index=Dk(v.selectIfGreaterOrEqual({fallback:14,versions:{[h.V0_6_7]:23}}));gasCost=zk(10);tracedRegisters=Lk(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=L.zero(Pe);if(r.loadInto(n.raw,s).isError)return Mk.Panic;const a=this.partialState.requestPreimage(n.asOpaque(),i);if(a.isOk)return void t.set(7,xB.OK);const o=a.error;o!==U_.AlreadyAvailable&&o!==U_.AlreadyRequested?o!==U_.InsufficientFunds?E(o):t.set(7,xB.FULL):t.set(7,xB.HUH)}},class{currentServiceId;partialState;index=Dk(v.selectIfGreaterOrEqual({fallback:15,versions:{[h.V0_6_7]:24}}));gasCost=zk(10);tracedRegisters=Lk(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=t.get(8),n=L.zero(Pe);if(r.loadInto(n.raw,s).isError)return Mk.Panic;this.partialState.forgetPreimage(n.asOpaque(),i).isOk?t.set(7,xB.OK):t.set(7,xB.HUH)}},class{currentServiceId;partialState;index=Dk(v.selectIfGreaterOrEqual({fallback:16,versions:{[h.V0_6_7]:25}}));gasCost=zk(10);tracedRegisters=Lk(7);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=L.zero(Pe);if(r.loadInto(i.raw,s).isError)return Mk.Panic;this.partialState.yield(i),t.set(7,xB.OK)}},class{currentServiceId;partialState;index=Dk(v.selectIfGreaterOrEqual({fallback:27,versions:{[h.V0_6_7]:26}}));gasCost=zk(10);tracedRegisters=Lk(7,8,9);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=OB(7,t,this.currentServiceId),i=t.get(8),n=TB(t.get(9)),a=P.blobFrom(new Uint8Array(n));if(r.loadInto(a.raw,i).isError)return Mk.Panic;const o=this.partialState.providePreimage(s,a);if(o.isOk)return void t.set(7,xB.OK);const c=o.error;c!==M_.ServiceNotFound?c!==M_.WasNotRequested&&c!==M_.AlreadyProvided?E(c):t.set(7,xB.HUH):t.set(7,xB.WHO)}}];var vR,wR;!function(e){e.IS_AUTHORIZED=nR(0),e.REFINE=nR(0),e.ACCUMULATE=nR(5),e.ON_TRANSFER=nR(10)}(vR||(vR={}));class SR{serviceCode;entrypoint;pvm;hostCalls;pvmInstanceManager=new kB(4);constructor(e,t,r){this.serviceCode=e,this.entrypoint=r,this.hostCalls=new DB(...t),this.pvm=new CB(this.pvmInstanceManager,this.hostCalls)}static prepareAccumulateHostCalls(e,t,r){const s=IR.map(s=>new s(e,t.partialState,r)),i=[new bR(e),new sR(e),new yR(e,t.serviceExternalities),new AR(e,t.serviceExternalities),new uR(e,t.fetchExternalities),new mR(e,t.serviceExternalities),new hR(e,t.serviceExternalities)];return s.concat(i)}static prepareOnTransferHostCalls(e,t){return[new bR(e),new sR(e),new uR(e,t.fetchExternalities),new yR(e,t.partialState),new AR(e,t.partialState),new mR(e,t.partialState),new hR(e,t.partialState)]}async run(e,t){const r=qB.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=SR.prepareAccumulateHostCalls(e,r,s);return new SR(t,i,vR.ACCUMULATE)}static createOnTransferExecutor(e,t,r){const s=SR.prepareOnTransferHostCalls(e,r);return new SR(t,s,vR.ON_TRANSFER)}}!function(e){e[e.NoService=0]="NoService",e[e.NoPreimage=1]="NoPreimage"}(wR||(wR={}));const ER=10000000n,CR=ri.new(void 0,"accumulate"),kR=Be.object({slot:Be.u32.asOpaque(),serviceId:Be.u32.asOpaque(),operands:Be.sequenceVarLen(W_.Codec)}),xR=Be.object({slot:Be.varU32.asOpaque(),serviceId:Be.varU32.asOpaque(),operands:Be.varU32});class BR{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,n){const a=this.state.getService(t);if(null===a)return CR.log(`Service with id ${t} not found.`),D.error(wR.NoService);const o=a.getInfo().codeHash,c=a.getPreimage(o.asOpaque());if(null===c)return CR.log(`Code with hash ${o} not found for service ${t}.`),D.error(wR.NoPreimage);const l=function({serviceId:e,entropy:t,timeslot:r},s){const i=ue(qe(Ae.encodeObject(Z_,{serviceId:e,entropy:t,timeslot:r},s)).raw.subarray(0,4))>>>0;return Nr(i%(2**32-512)+256)}({serviceId:t,entropy:i,timeslot:e},this.chainSpec),d=new z_(this.chainSpec,new $_(this.state,n),t,l,e),u={partialState:d,serviceExternalities:d,fetchExternalities:PR.createForAccumulate({entropy:i,operands:r},this.chainSpec)},f=SR.createAccumulateExecutor(t,c,u,this.chainSpec);let g=P.empty();g=v.is(h.V0_6_5)?Ae.encodeObject(kR,{slot:e,serviceId:t,operands:r},this.chainSpec):Ae.encodeObject(xR,{slot:e,serviceId:t,operands:ne(r.length)});const p=await f.run(g,Jk(s)),[b,m]=d.getStateUpdates();if(p.hasStatus()){const e=p.status;if(e===Rk.OOG||e===Rk.PANIC)return D.ok({stateUpdate:m,consumedGas:Dr(p.consumedGas)})}if(p.hasMemorySlice()&&p.memorySlice.length===Pe){const e=L.fromBlob(p.memorySlice,Pe);b.yieldedRoots.set(t,e.asOpaque())}return D.ok({stateUpdate:b,consumedGas:Dr(p.consumedGas)})}async accumulateSingleService(e,t,r,s,i,n){CR.trace(`Accumulating service ${e}, items: ${t.length} at slot: ${s}.`);const a=await this.pvmAccumulateInvocation(s,e,t,r,i,n);return a.isError?(CR.trace(`Accumulation failed for ${e}.`),{stateUpdate:null,consumedGas:r}):(CR.trace(`Accumulation successful for ${e}. Consumed: ${a.ok.consumedGas}`),a.ok)}async accumulateSequentially(e,t,r,s,i,n){const a=this.findReportCutoffIndex(e,t);if(0===a)return{accumulatedReports:ne(0),gasCost:Dr(0),state:n};const o=t.slice(0,a),c=this.state.privilegedServices.autoAccumulateServices,l=new Y_(o,c),d=t.slice(a),{gasCost:u,state:h,...f}=await this.accumulateInParallel(l,r,s,i,n);C(f);const{accumulatedReports:g,gasCost:p,state:b,...m}=await this.accumulateSequentially(Dr(e-u),d,r,s,i,h);return C(m),{accumulatedReports:ne(a+g),gasCost:Dr(u+p),state:b}}async accumulateInParallel(e,t,r,s,i){const n=e.getServiceIds();let a=Dr(0),o=i;for(const i of n){const n=F_.copyFrom(o),{consumedGas:c,stateUpdate:l}=await this.accumulateSingleService(i,e.getOperands(i),e.getGasCost(i),t,r,o);a=Dr(a+c);const d=s.get(i)??{count:ne(0),gasUsed:Dr(0)};d.count=ne(d.count+e.getReportsLength(i)),d.gasUsed=Dr(d.gasUsed+c),s.set(i,d),o=null===l?n:l}return{state:o,gasCost:a}}getAccumulationStateUpdate(e,t,r,s,i){const n=this.chainSpec.epochLength,a=r%n,o=X_(e),c=Array.from(o).sort((e,t)=>HE(e,t).value),l=Vr(this.state.recentlyAccumulated.slice(1).concat(bt.from(c)),this.chainSpec),d=this.state.accumulationQueue.slice();d[a]=tR(t,o);for(let e=1;e<n;e++){const t=(a+n-e)%n;e<r-this.state.timeslot?d[t]=[]:d[t]=tR(d[t],o)}const u=new $_(this.state,F_.new(i));if(v.isGreaterOrEqual(h.V0_6_7))for(const e of s){const t=u.getServiceInfo(e);null!==t&&u.updateServiceInfo(e,iC.create({...t,lastAccumulation:r}))}return{recentlyAccumulated:l,accumulationQueue:Vr(d,this.chainSpec),timeslot:r,...u.stateUpdate.services}}getGasLimit(){const e=ER*BigInt(this.chainSpec.coresCount)+this.state.privilegedServices.autoAccumulateServices.reduce((e,{gasLimit:t})=>e+t,0n),t=Dr(this.chainSpec.maxBlockGas>e?this.chainSpec.maxBlockGas:e);return Dr(t)}async transition({reports:e,slot:t,entropy:r}){const s=new Map,i=new eR(this.chainSpec,this.state),n=i.getWorkReportsToAccumulateImmediately(e),a=i.getWorkReportsToAccumulateLater(e),o=tR(i.getQueueFromState(t).concat(a),X_(n)),c=i.enqueueReports(o),l=n.concat(c),d=this.getGasLimit(),{accumulatedReports:u,gasCost:h,state:f,...g}=await this.accumulateSequentially(d,l,t,r,s,F_.empty());C(g);const p=l.slice(0,u),{services:b,yieldedRoots:m,transfers:y,validatorsData:A,privilegedServices:I,authorizationQueues:v,...w}=f;C(w);const S=this.getAccumulationStateUpdate(p,a,t,Array.from(s.keys()),b),E=await async function(e){const t=await ft.create(),r=(s=t,{hashConcat:(e,t=[])=>gt(s,[e,...t].map(P.blobFrom)).asOpaque()});var s;return function(e,t){return 1===e.length?t.hashConcat(e[0].raw):function e(t,r){if(0===t.length)return L.zero(Pe).asOpaque();if(1===t.length)return t[0];const s=Math.ceil(t.length/2),i=t.slice(0,s),n=t.slice(s);return r.hashConcat(P.blobFromString("node").raw,[e(i,r).raw,e(n,r).raw])}(e,t)}(e.sort((e,t)=>e[0]-t[0]).map(([e,t])=>P.blobFromParts([de(e),t.raw])),r)}(Array.from(m.entries())),k=(()=>{if(0===v.size)return{};const e=this.state.authQueues.slice();for(const[t,r]of v.entries())e[t]=r;return{authQueues:NE(e,this.chainSpec)}})();return D.ok({root:E,stateUpdate:{...S,...null===A?{}:{designatedValidatorData:A},...null===I?{}:{privilegedServices:I},...k},accumulationStatistics:s,pendingTransfers:y})}}var _R;!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"}(_R||(_R={}));class RR{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=yt.new(Array(t).fill(0),t);let n=-1;for(const r of s){const{anchor:s,validatorIndex:a,bitfield:o}=r;if(!s.isEqualTo(e.parentHash))return D.error(_R.InvalidAnchor,`anchor: expected: ${e.parentHash}, got ${s}`);if(n>=a)return D.error(_R.InvalidOrder,`order: expected: ${n+1}, got: ${a}`);n=r.validatorIndex,w(o.bitLength===t,`Invalid bitfield length of ${o.bitLength}`);const c=o.indicesOfSetBits();for(const e of c)i[e]+=1}const a=[],o=[],c=this.chainSpec.validatorsSuperMajority,l=e.disputesAvailAssignment.slice();for(let r=0;r<t;r++){const t=i[r],s=l[r],n=null!==s;if(t>0&&!n)return D.error(_R.NoReportPending,`no report pending for core ${r} yet we got an assurance`);n&&(e.slot>=s.timeout+5&&o.push(r),t>=c&&(a.push(s.workReport.data),o.push(r)))}const d=await r;if(d.isError)return d;for(const e of o)l[e]=null;return D.ok({availableReports:a,stateUpdate:{availabilityAssignment:l}})}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 D.error(_R.InvalidValidatorIndex);r.push({signature:e.signature.materialize(),key:i.ed25519,message:UR(e.anchor.encoded(),e.bitfield.encoded())})}const s=await wr(r),i=s.every(e=>e);if(!i){const e=s.reduce((e,t,r)=>t?e:e.concat(r),[]);return D.error(_R.InvalidSignature,`invalid signatures at ${e.join(", ")}`)}return D.ok(O)}}const OR=P.blobFromString("jam_available").raw;function UR(e,t){return P.blobFromParts(OR,qe(P.blobFromParts(e.raw,t.raw)).raw)}var TR;!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",e[e.BannedValidator=23]="BannedValidator"}(TR||(TR={}));const NR=Be.object({B_I:Be.u64,B_L:Be.u64,B_S:Be.u64,C:Be.u16,D:Be.u32,E:Be.u32,G_A:Be.u64,G_I:Be.u64,G_R:Be.u64,G_T:Be.u64,H:Be.u16,I:Be.u16,J:Be.u16,K:Be.u16,L:Be.u32,N:Be.u16,O:Be.u16,P:Be.u16,Q:Be.u16,R:Be.u16,T:Be.u16,U:Be.u16,V:Be.u16,W_A:Be.u32,W_B:Be.u32,W_C:Be.u32,W_E:Be.u32,W_M:Be.u32,W_P:Be.u32,W_R:Be.u32,W_T:Be.u32,W_X:Be.u32,Y:Be.u32}),DR=new Map;var MR;!function(e){e[e.Accumulate=0]="Accumulate",e[e.OnTransfer=1]="OnTransfer"}(MR||(MR={}));class PR{fetchData;chainSpec;constructor(e,t){this.fetchData=e,this.chainSpec=t}static createForAccumulate(e,t){return new PR({context:MR.Accumulate,...e},t)}static createForOnTransfer(e,t){return new PR({context:MR.OnTransfer,...e},t)}constants(){return function(e){const t=DR.get(e);if(void 0!==t)return t;const r=Ae.encodeObject(NR,{B_I:oe(10n),B_L:oe(1n),B_S:oe(100n),C:se(e.coresCount),D:ne(e.preimageExpungePeriod),E:ne(e.epochLength),G_A:oe(ER),G_I:oe(5e7),G_R:oe(e.maxRefineGas),G_T:oe(e.maxBlockGas),H:se(8),I:se(Wr),J:se(8),K:se(16),L:ne(14400),N:se(2),O:se(8),P:se(e.slotDuration),Q:se(80),R:se(e.rotationPeriod),T:se(128),U:se(5),V:e.validatorsCount,W_A:ne(64e3),W_B:ne(13794305),W_C:ne(4e6),W_E:ne(e.erasureCodedPieceSize),W_M:ne(3072),W_P:ne(e.numberECPiecesPerSegment),W_R:ne(49152),W_T:ne(128),W_X:ne(3072),Y:ne(e.contestLength)});return DR.set(e,r),r}(this.chainSpec)}entropy(){const{entropy:e}=this.fetchData;return void 0===e?null:e.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(){if(this.fetchData.context!==MR.Accumulate)return null;const e=this.fetchData.operands;return Ae.encodeObject(Be.sequenceVarLen(W_.Codec),e,this.chainSpec)}oneOperand(e){if(this.fetchData.context!==MR.Accumulate)return null;const{operands:t}=this.fetchData;if(e>=2n**32n)return null;const r=t[Number(e)];return void 0===r?null:Ae.encodeObject(W_.Codec,r,this.chainSpec)}allTransfers(){if(this.fetchData.context!==MR.OnTransfer)return null;const{transfers:e}=this.fetchData;return Ae.encodeObject(Be.sequenceVarLen(K_.Codec),e,this.chainSpec)}oneTransfer(e){if(this.fetchData.context!==MR.OnTransfer)return null;const{transfers:t}=this.fetchData;if(e>=2n**32n)return null;const r=t[Number(e)];return void 0===r?null:Ae.encodeObject(K_.Codec,r,this.chainSpec)}}const LR=Be.object({timeslot:Be.u32.asOpaque(),serviceId:Be.u32.asOpaque(),transfers:Be.sequenceVarLen(K_.Codec)}),HR=Be.object({timeslot:Be.varU32.asOpaque(),serviceId:Be.varU32.asOpaque(),transfersLength:Be.varU32});var VR;!function(e){e[e.ServiceBalanceOverflow=1]="ServiceBalanceOverflow",e[e.ServiceInfoNotExist=2]="ServiceInfoNotExist"}(VR||(VR={}));const KR=ri.new(void 0,"deferred-transfers");class QR{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}async transition({pendingTransfers:e,timeslot:t,servicesUpdate:r,entropy:s}){const i=new Map,n=function(e){const t=new Set;for(const r of e)t.add(r);return Array.from(t)}(e.flatMap(e=>[e.source,e.destination]));let a=F_.new(r);for(const r of n){const n=new $_(this.state,a),o=e.filter(e=>e.destination===r),c=n.getServiceInfo(r);if(null===c)return D.error(VR.ServiceInfoNotExist);const l=c.codeHash,d=n.getPreimage(r,l.asOpaque()),u=le(c.balance,...o.map(e=>e.amount));if(u.overflow)return D.error(VR.ServiceBalanceOverflow);const f=iC.create({...c,balance:u.value});n.updateServiceInfo(r,f);const g=new z_(this.chainSpec,n,r,r,t),p=PR.createForOnTransfer({entropy:s,transfers:o},this.chainSpec);let b=Jk(0);if(null===d||0===o.length)KR.trace(`Skipping ON_TRANSFER execution for service ${r}, code is null or no transfers`);else{const e=()=>v.isGreaterOrEqual(h.V0_6_7)?Ae.encodeObject(HR,{timeslot:t,serviceId:r,transfersLength:ne(o.length)},this.chainSpec):Ae.encodeObject(LR,{timeslot:t,serviceId:r,transfers:o},this.chainSpec),s=SR.createOnTransferExecutor(r,d,{partialState:g,fetchExternalities:p}),i=e(),n=o.reduce((e,t)=>e+t.gas,0n);b=(await s.run(i,Jk(n))).consumedGas}i.set(r,{count:ne(o.length),gasUsed:Dr(b)});const[m,y]=g.getStateUpdates();a=m,w(null===y,"On transfer cannot invoke checkpoint.")}return D.ok({servicesUpdate:a.services,transferStatistics:i})}}class FR{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}transition(e){const t=this.state.authPools.slice();for(let r=Mr(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]=mt(s)}return{authPools:NE(t,this.chainSpec)}}}class $R{hasher;state;constructor(e,t){this.hasher=e,this.state=t}partialTransition(e){const t=this.state.recentBlocks.blocks.slice(),r=t.length>0?t[t.length-1]:null;return null!==r&&(r.postStateRoot=e.priorStateRoot),{recentBlocks:this.state.recentBlocks.updateBlocks(t)}}transition(e){const t=e.partial.recentBlocks.blocks.slice(),r=t.length>0?t[t.length-1]:null,s=v.isGreaterOrEqual(h.V0_6_7)?null!==this.state.recentBlocks.asCurrent().accumulationLog?FE.fromPeaks(this.hasher,this.state.recentBlocks.asCurrent().accumulationLog):FE.empty(this.hasher):null!==r?FE.fromPeaks(this.hasher,r.mmr):FE.empty(this.hasher);s.append(e.accumulateRoot);const i=s.getPeaks();return v.isGreaterOrEqual(h.V0_6_7)?t.push(qE.create({headerHash:e.headerHash,accumulationResult:s.getSuperPeakHash(),postStateRoot:L.zero(Pe).asOpaque(),reported:e.workPackages})):t.push(GE.create({headerHash:e.headerHash,mmr:i,postStateRoot:L.zero(Pe).asOpaque(),reported:e.workPackages})),t.length>8&&t.shift(),{recentBlocks:v.isGreaterOrEqual(h.V0_6_7)?WE.create(zE.create({blocks:t,accumulationLog:i})):WE.legacyCreate(jE.create({blocks:t}))}}}function GR(e,t,r){return function(e,t,r){const s=jR(Ur(t%r.epochLength),r.rotationPeriod),i=(n=function(e,t){w(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(de(ne(Math.floor(e/8))),32);const t=4*e%32,i=t+4,n=ue(qe(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)=>Mr(Math.floor(t*r.coresCount/r.validatorsCount))),e),a=s,o=r.coresCount,n.map(e=>(e+a)%o));var n,a,o;return i}(t,r,e)}function jR(e,t){return Math.floor(e/t)}const qR=P.blobFromString("jam_guarantee").raw;function zR(e){return P.blobFromParts(qR,e.raw)}const WR=1e7;class JR{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 D.error(TR.OutOfOrderGuarantee,`Core indices of work reports are not unique or in order. Got: ${e}, expected at least: ${s+1}`);if(e>=r)return D.error(TR.BadCoreIndex,`Invalid core index. Got: ${e}, max: ${r}`);s=e}return D.ok(O)}(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 D.error(TR.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 D.error(TR.WorkReportTooBig,`Work report at ${e.coreIndex.materialize()} too big. Got ${i} + ${n}, max: 49152`)}return D.ok(O)}(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=wr(i.ok),a=this.verifyPostSignatureChecks(e.guarantees,e.assurancesAvailAssignment);if(a.isError)return a;const o=this.verifyContextualValidity(e);if(o.isError)return o;const c=this.checkSignatures(i.ok,await n);if(c.isError)return c;let l=0;const d=e.assurancesAvailAssignment.slice();for(const t of e.guarantees){const r=t.view().report.materialize(),i=s[l];d[r.coreIndex]=TE.create({workReport:new He(i,r),timeout:e.slot}),l+=1}const u=It.fromArray(W,i.ok.map(e=>e.key)).slice();return function(e,t){for(const r of e)if(t.has(r))return!0;return!1}(u,e.offenders)?D.error(TR.BannedValidator):D.ok({stateUpdate:{availabilityAssignment:NE(d,this.chainSpec)},reported:o.ok,reporters:u})}workReportHashes(e){const t=[];for(const r of e)t.push(_(qe(r.view().report.encoded())));return t}verifyCredentials(e,t){return function(e,t,r,s){const i=[],n=r;let a=0;for(const r of e){const e=r.view(),o=e.report.view().coreIndex.materialize(),c=t[a];a+=1;const l=e.credentials.view();if(l.length<os[0]||l.length>os[1])return D.error(TR.InsufficientGuarantees,`Invalid number of credentials. Expected ${os}, got ${l.length}`);const d=s(n,e.slot.materialize());if(d.isError)return d;const u=d.ok;let h=-1;for(const e of l){const t=e.view(),r=t.validatorIndex.materialize();if(h>=r)return D.error(TR.NotSortedOrUniqueGuarantors,`Credentials must be sorted by validator index. Got ${r}, expected at least ${h+1}`);h=r;const s=t.signature.materialize(),n=u[r];if(void 0===n)return D.error(TR.BadValidatorIndex,`Invalid validator index: ${r}`);if(n.core!==o)return D.error(TR.WrongAssignment,`Invalid core assignment for validator ${r}. Expected: ${n.core}, got: ${o}`);i.push({signature:s,key:n.ed25519,message:zR(c)})}}return D.ok(i)}(e.guarantees,t,e.slot,(t,r)=>this.getGuarantorAssignment(t,r,e.newEntropy))}verifyPostSignatureChecks(e,t){return function(e,t,r,s){for(const i of e){const e=i.materialize().report,n=e.coreIndex;if(null!==t[n])return D.error(TR.CoreEngaged,`Report pending availability at core: ${n}`);const a=e.authorizerHash;if(void 0===r[n].find(e=>e.isEqualTo(a)))return D.error(TR.CoreUnauthorized,`Authorizer hash not found in the pool of core ${n}: ${a}`);for(const t of e.results){const e=s(t.serviceId);if(null===e)return D.error(TR.BadServiceId,`No service with id: ${t.serviceId}`);const r=e.getInfo();if(t.gas<r.accumulateMinGas)return D.error(TR.ServiceItemGasTooLow,`Service (${t.serviceId}) gas is less than minimal. Got: ${t.gas}, expected at least: ${r.accumulateMinGas}`)}const o=le(...e.results.map(e=>e.gas));if(o.overflow||o.value>WR)return D.error(TR.WorkReportGasTooHigh,`Total gas too high. Got: ${o.value} (ovfl: ${o.overflow}), maximal: ${WR}`)}return D.ok(O)}(e,t,this.state.authPools,e=>this.state.getService(e))}verifyContextualValidity(e){return function(e,t,r,s){const i=[],n=pt.new(),a=bt.new(),o=bt.new();for(const r of e.guarantees){const e=r.materialize();i.push(e.report.context);const s=ss.create({workPackageHash:e.report.workPackageSpec.hash,segmentTreeRoot:e.report.workPackageSpec.exportsRoot});n.set(s.workPackageHash,s),a.insertAll(e.report.context.prerequisites),o.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 D.error(TR.BadServiceId,`No service with id: ${r.serviceId}`);if(!r.codeHash.isEqualTo(e.getInfo().codeHash))return D.error(TR.BadCodeHash,`Service (${r.serviceId}) code hash mismatch. Got: ${r.codeHash}, expected: ${e.getInfo().codeHash}`)}}if(n.size!==e.guarantees.length)return D.error(TR.DuplicatePackage,"Duplicate work package detected.");const c=function(e,t,r,s,i){const n=pt.new();for(const e of r.blocks)n.set(e.headerHash,e);for(const r of t){const t=n.get(r.anchor);if(void 0===t)return D.error(TR.AnchorNotRecent,`Anchor block ${r.anchor} not found in recent blocks.`);if(!t.postStateRoot.isEqualTo(r.stateRoot))return D.error(TR.BadStateRoot,`Anchor state root mismatch. Got: ${r.stateRoot}, expected: ${t.postStateRoot}.`);const a=WE.accumulationResult(t,{hasher:s});if(!a.isEqualTo(r.beefyRoot))return D.error(TR.BadBeefyMmrRoot,`Invalid BEEFY super peak hash. Got: ${r.beefyRoot}, expected: ${a}. Anchor: ${t.headerHash}`);if(r.lookupAnchorSlot<e)return D.error(TR.SegmentRootLookupInvalid,`Lookup anchor slot's too old. Got: ${r.lookupAnchorSlot}, minimal: ${e}`);if(!i.isInChain(r.lookupAnchor))return D.error(TR.SegmentRootLookupInvalid,`Lookup anchor is not found in chain. Hash: ${r.lookupAnchor} (slot: ${r.lookupAnchorSlot})`)}return D.ok(O)}(Math.max(0,e.slot-14400),i,e.recentBlocksPartialUpdate,r,s);if(c.isError)return c;const l=function(e,t){const r=bt.new();for(const e of t.recentBlocks.blocks)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 D.error(TR.DuplicatePackage,`The same work package hash found in the pipeline (workPackageHash: ${e})`);return D.ok(O)}(bt.viewDictionaryKeys(n),t);if(l.isError)return l;const d=pt.new();for(const e of t.recentBlocks.blocks)for(const t of e.reported.values())d.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 D.error(s?TR.SegmentRootLookupInvalid:TR.DependencyMissing,`Missing work package ${i} in current extrinsic or recent history.`);return D.ok(O)},n=i(r);if(n.isError)return n;const a=i(s,!0);return a.isError?a:D.ok(O)}({currentWorkPackages:n,recentlyReported:d,prerequisiteHashes:a,segmentRootLookupHashes:o});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=d.get(t.workPackageHash);e=void 0!==r?ss.create({workPackageHash:t.workPackageHash,segmentTreeRoot:r}):void 0}if(void 0===e||!e.segmentTreeRoot.isEqualTo(t.segmentTreeRoot))return D.error(TR.SegmentRootLookupInvalid,`Mismatching segment tree root for package ${t.workPackageHash}. Got: ${t.segmentTreeRoot}, expected: ${e?.segmentTreeRoot}`)}}return D.ok(n)}(e,this.state,this.mmrHasher,this.headerChain)}checkSignatures(e,t){if(t.every(e=>e))return D.ok(O);const r=t.map((t,r)=>t?null:e[r].key).filter(e=>null!==e);return D.error(TR.BadSignature,`Invalid signatures for validators with keys: ${r.join(", ")}`)}getGuarantorAssignment(e,t,r){const s=this.chainSpec.epochLength,i=this.chainSpec.rotationPeriod,n=jR(e,i),a=jR(t,i),o=Math.max(0,n-1)*i;if(t>e)return D.error(TR.FutureReportSlot,`Report slot is in future. Block ${e}, Report: ${t}`);if(t<o)return D.error(TR.ReportEpochBeforeLast,`Report slot is too old. Block ${e}, Report: ${t}`);let c=r[2],l=this.state.currentValidatorData,d=e;n>a&&(d=Ur(e-i),function(e,t,r){const s=Math.floor(t/r);return Math.floor(e/r)!==s}(d,e,s)&&(c=r[3],l=this.state.previousValidatorData));const u=GR(this.chainSpec,c,d);return D.ok((h=l,f=(e,t)=>({core:e,ed25519:t.ed25519}),u.map((e,t)=>f(e,h[t]))));var h,f}}class YR{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=Lr(Array.from({length:this.chainSpec.validatorsCount},()=>bC.empty()),this.chainSpec);return vC.create({...this.state.statistics,current:t,previous:this.state.statistics.current})}calculateDAScoreCore(e){if(void 0===e)return ne(0);let t=0;return t+=e.workPackageSpec.length+4104*Math.ceil(65*e.workPackageSpec.exportsCount/64),ne(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:Dr(t.gasUsed),exported:se(t.exported),imported:se(t.imported),extrinsicCount:se(t.extrinsicCount),extrinsicSize:ne(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:se(t.count),size:ne(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,a=this.getStatistics(t),{current:o,cores:c,services:l}=a;w(void 0!==o[r],"authorIndex is out of bounds");const d=o[r].blocks+1;o[r].blocks=ne(d);const u=o[r].tickets+s.tickets.length;o[r].tickets=ne(u);const h=o[r].preImages+s.preimages.length;o[r].preImages=ne(h);const f=s.preimages.reduce((e,t)=>e+t.blob.length,0),g=o[r].preImagesSize+f;o[r].preImagesSize=ne(g);const p=new Set;for(const e of s.guarantees)for(const{validatorIndex:t}of e.credentials)if(!p.has(t)){const e=o[t].guarantees+1;o[t].guarantees=ne(e),p.add(t)}for(const{validatorIndex:e}of s.assurances){const t=o[e].assurances+1;o[e].assurances=ne(t)}for(let e=0;e<this.chainSpec.coresCount;e++){const t=Mr(e),r=i.find(e=>e.coreIndex===t),{imported:a,extrinsicCount:o,extrinsicSize:l,exported:d,gasUsed:u}=void 0!==r?this.calculateRefineScore(r.results.map(e=>e)):{imported:se(0),extrinsicCount:se(0),extrinsicSize:ne(0),exported:se(0),gasUsed:Dr(0n)},h=n.find(e=>e.coreIndex===t),f=s.assurances.reduce((t,{bitfield:r})=>t+(r.isSet(e)?1:0),0);c[t].imports=a,c[t].extrinsicCount=o,c[t].extrinsicSize=l,c[t].exports=d,c[t].gasUsed=u,c[t].bundleSize=ne(r?.workPackageSpec.length??0),c[t].dataAvailabilityLoad=this.calculateDAScoreCore(h),c[t].popularity=se(f)}l.clear();const b=this.collectServiceIds(s.preimages,i.flatMap(e=>e.results),e.accumulationStatistics.keys(),e.transferStatistics.keys());for(const t of b){const r=i.flatMap(e=>e.results.filter(e=>e.serviceId===t)),{gasUsed:n,imported:a,extrinsicCount:o,extrinsicSize:c,exported:d}=this.calculateRefineScore(r),u=s.preimages.filter(e=>e.requester===t),{count:h,size:f}=this.calculateProvidedScoreService(u),{count:g,gasUsed:p}=e.accumulationStatistics.get(t)??{count:ne(0),gasUsed:Dr(0n)},{count:b,gasUsed:m}=e.transferStatistics.get(t)??{count:ne(0),gasUsed:Dr(0n)},y=IC.empty();y.refinementCount=ne(r.length),y.refinementGasUsed=n,y.imports=a,y.extrinsicCount=o,y.extrinsicSize=c,y.exports=d,y.providedCount=h,y.providedSize=f,y.providedCount=h,y.providedSize=f,y.accumulateCount=g,y.accumulateGasUsed=p,y.onTransfersCount=b,y.onTransfersGasUsed=m,l.set(t,y)}return{statistics:a}}}class XR{blocks;constructor(e){this.blocks=e}isInChain(e){return null!==this.blocks.getHeader(e)}}const ZR="offenders not matching header";var eO;!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",e[e.DeferredTransfers=7]="DeferredTransfers",e[e.Offenders=8]="Offenders"}(eO||(eO={}));const tO=(e,t)=>D.taggedError(eO,e,t),rO=ri.new(void 0,"stf");class sO{chainSpec;state;hasher;safrole;safroleSeal;disputes;reports;assurances;accumulate;deferredTransfers;preimages;recentHistory;authorization;statistics;constructor(e,t,r,s,{enableParallelSealVerification:i}){this.chainSpec=e,this.state=t,this.hasher=s;const n=x_.new({synchronous:!i});this.statistics=new YR(e,t),this.safrole=new L_(e,t,n),this.safroleSeal=new H_(n),this.recentHistory=new $R(s,t),this.disputes=new u_(e,t),this.reports=new JR(e,t,s,new XR(r)),this.assurances=new RR(e,t),this.accumulate=new BR(e,t),this.deferredTransfers=new QR(e,t),this.preimages=new ZB(t),this.authorization=new FR(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 a=r;if(s&&(a=qe(i.seal).asOpaque()),null===a){const t=await this.verifySeal(n,e);if(t.isError)return tO(eO.SafroleSeal,t);a=t.ok}const o=await this.disputes.transition(e.extrinsic.view().disputes.materialize());if(o.isError)return tO(eO.Disputes,o);const{stateUpdate:{disputesRecords:c,availabilityAssignment:l,...d},offendersMark:u}=o.ok;C(d);const h=function(e,t){if(e.size!==t.length)return D.error(ZR,`Length mismatch: ${e.size} vs ${t.length}`);for(const r of t)if(!e.has(r))return D.error(ZR,`Missing key: ${r}`);return D.ok(O)}(u,e.header.view().offendersMarker.materialize());if(h.isError)return tO(eO.Offenders,h);const f=await this.safrole.transition({slot:n,entropy:a,extrinsic:e.extrinsic.view().tickets.materialize(),punishSet:c.punishSet});if(f.isError)return tO(eO.Safrole,f);const{timeslot:g,ticketsAccumulator:p,sealingKeySeries:b,epochRoot:m,entropy:y,nextValidatorData:A,currentValidatorData:I,previousValidatorData:v,...w}=f.ok.stateUpdate;C(w);const S=this.recentHistory.partialTransition({priorStateRoot:i.priorStateRoot}),{recentBlocks:E,...k}=S;C(k);const B=await this.assurances.transition({assurances:e.extrinsic.view().assurances.view(),slot:n,parentHash:i.parentHeaderHash,disputesAvailAssignment:l});if(B.isError)return tO(eO.Assurances,B);const{availableReports:_,stateUpdate:R,...U}=B.ok;C(U);const{availabilityAssignment:T,...N}=R;C(N);const M=await this.reports.transition({slot:n,guarantees:e.extrinsic.view().guarantees.view(),newEntropy:y,recentBlocksPartialUpdate:E,assurancesAvailAssignment:T,offenders:u});if(M.isError)return tO(eO.Reports,M);const{reported:P,reporters:L,stateUpdate:H,...V}=M.ok;C(V);const{availabilityAssignment:K,...Q}=H;C(Q);const F=this.preimages.integrate({slot:n,preimages:e.extrinsic.view().preimages.materialize()});if(F.isError)return tO(eO.Preimages,F);const{preimages:$,...G}=F.ok;C(G);const j=x("import:accumulate"),q=await this.accumulate.transition({slot:n,reports:_,entropy:y[0]});if(rO.log(j()),q.isError)return tO(eO.Accumulate,q);const{root:z,stateUpdate:W,accumulationStatistics:J,pendingTransfers:Y,...X}=q.ok;C(X);const{privilegedServices:Z,authQueues:ee,designatedValidatorData:te,timeslot:re,preimages:se,accumulationQueue:ie,recentlyAccumulated:ne,...ae}=W,oe=await this.deferredTransfers.transition({entropy:y[0],pendingTransfers:Y,servicesUpdate:{...ae,preimages:se},timeslot:n});if(oe.isError)return tO(eO.DeferredTransfers,oe);const{servicesUpdate:ce,transferStatistics:le,...de}=oe.ok;C(de);const ue=this.recentHistory.transition({partial:S,headerHash:t,accumulateRoot:z,workPackages:P}),{recentBlocks:he,...fe}=ue;C(fe);const ge=this.authorization.transition({slot:n,used:this.getUsedAuthorizerHashes(e.extrinsic.view().guarantees.view())}),{authPools:pe,...be}=ge;C(be);const me=e.extrinsic.materialize(),ye=this.statistics.transition({slot:n,authorIndex:i.bandersnatchBlockAuthorIndex,extrinsic:me,incomingReports:me.guarantees.map(e=>e.report),availableReports:_,accumulationStatistics:J,transferStatistics:le}),{statistics:Ae,...Ie}=ye;return C(Ie),D.ok({...void 0!==ee?{authQueues:ee}:{},...void 0!==te?{designatedValidatorData:te}:{},...void 0!==Z?{privilegedServices:Z}:{},authPools:pe,disputesRecords:c,availabilityAssignment:K,recentBlocks:he,statistics:Ae,timeslot:g,epochRoot:m,entropy:y,currentValidatorData:I,nextValidatorData:A,previousValidatorData:v,sealingKeySeries:b,ticketsAccumulator:p,accumulationQueue:ie,recentlyAccumulated:ne,...ce,preimages:$.concat(se)})}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)??bt.new();i.insert(e.authorizerHash.materialize()),t.set(s,i)}return t}}var iO;!function(e){e[e.Verifier=0]="Verifier",e[e.Stf=1]="Stf",e[e.Update=2]="Update"}(iO||(iO={}));const nO=(e,t)=>D.taggedError(iO,e,t);class aO{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(),a=i.getState(n);if(null===a)throw new Error(`Unable to load best state from header hash: ${n}.`);this.verifier=new r_(t,s),this.stf=new sO(e,a,s,t,{enableParallelSealVerification:!0}),this.state=a,r.info(`😎 Best time slot: ${a.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: ${N(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=x("import:verify"),n=await this.verifier.verifyBlock(e);if(s.log(i()),n.isError)return nO(iO.Verifier,n);const a=e.header.view().timeSlotIndex.materialize(),o=n.ok;s.log(`🧱 Verified block: Got hash ${o} for block at slot ${a}.`);const c=x("import:stf"),l=await this.stf.transition(e,o,t,r);if(s.log(c()),l.isError)return nO(iO.Stf,l);const d=l.ok,u=x("import:state"),h=await this.states.updateAndSetState(o,this.state,d);if(h.isError)return s.error(`🧱 Unable to update state: ${N(h)}`),nO(iO.Update,h);const f=this.states.getState(o);if(null===f)throw new Error("Freshly updated state not in the DB?");this.state.updateBackend(f.backend),s.log(u());const g=x("import:db"),p=this.blocks.insertBlock(new He(o,e)),b=await this.states.getStateRoot(f);s.log(`🧱 Storing post-state-root for ${o}: ${b}.`);const m=this.blocks.setPostStateRoot(o,b);return await Promise.all([p,m]),s.log(g()),await this.blocks.setBestHeaderHash(o),D.ok(new He(o,e.header.view()))}bestBlockHash(){return this.blocks.getBestHeaderHash()}}const oO=ri.new(void 0,"importer");class cO extends bk{onBestBlock=new fk;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=fe.decodeObject(ms,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 lO extends bk{onBlock=new fk;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=Ae.encodeObject(ms,t,r.chainSpec).raw;e.sendSignal("bestBlock",s,[s.buffer])}triggerOnBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=fe.decodeObject(vs.Codec.View,e,t.chainSpec);this.onBlock.emit(r)}else oO.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 dO=ri.new(void 0,"importer");if(!EE.isMainThread){ri.configureAll(process.env.JAM_LOG??"",qs.LOG);const e=function(){const e=new Ak("ready(importer)",Ct.reInit),t=new lO,r=new mk;return new gk("importer",e,[e,t,r])}();dk.receiveChannel(e,EE.parentPort).then(e=>async function(e){dO.info(`📥 Importer starting ${e.currentState()}`);const t=await e.waitForState("ready(importer)"),r=await t.doUntil("finished",async(e,t)=>{dO.info("📥 Importer waiting for blocks.");const r=e.getConfig(),s=new RE(r.dbPath),i=new kE(r.chainSpec,s),n=new sk(r.chainSpec,s),a=new aO(r.chainSpec,new XB(r.chainSpec,await uO,new Ke),dO,i,n);let o=!1;const c=new e_(r.chainSpec,a);e.onBlock.on(async s=>{const n=e_.getBlockDetails(s);if(n.isError)dO.trace("🧊 Ignoring invalid block.");else if(null===i.getHeader(n.ok.hash)){if(c.push(n.ok).isError)dO.trace(`🧊 Already queued block: #${n.ok.data.timeSlot}.`);else if(dO.log(`🧊 Queued block: #${n.ok.data.timeSlot}`),!o){o=!0;try{for(;;){const s=c.shift();if(void 0===s)return;const{block:i,seal:n,timeSlot:o}=s,l=x("importBlock"),d=await a.importBlock(i,await n,r.omitSealVerification);if(d.isOk){const r=d.ok;e.announce(t,r),dO.info(`🧊 Best block: #${r.data.timeSlotIndex.materialize()} (${r.hash})`)}else dO.log(`❌ Rejected block #${o}: ${N(d)}`);dO.log(l())}}finally{o=!1}}}else dO.trace(`🧊 Already imported block: #${n.ok.data.timeSlot}.`)})});dO.info("📥 Importer finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>dO.error(e))}const uO=ft.create(),hO=ri.new(void 0,"net:worker");class fO{genericConfig;genesisHeaderHash;key;host;port;bootnodes;static reInit(e){const{genericConfig:t,genesisHeaderHash:r,key:s,host:i,port:n,bootnodes:a}=e;return new fO(Ct.reInit(t),L.fromBlob(r.raw,Pe).asOpaque(),L.fromBlob(s.raw,32).asOpaque(),i,n,a)}static new({genericConfig:e,genesisHeaderHash:t,key:r,host:s,port:i,bootnodes:n}){return new fO(e,t,r,s,i,n)}constructor(e,t,r,s,i,n){this.genericConfig=e,this.genesisHeaderHash=t,this.key=r,this.host=s,this.port=i,this.bootnodes=n}}class gO extends bk{onNewBlocks=new fk;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{newBlocks:e=>this.triggerNewBlocks(e)}})}triggerNewBlocks(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=fe.decodeObject(Be.sequenceVarLen(vs.Codec.View),e,t.genericConfig.chainSpec);this.onNewBlocks.emit(r)}else hO.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}announceHeader(e,t){const r=Ae.encodeObject(ms,t);e.sendSignal("announceHeader",r.raw,[r.raw.buffer])}getConfig(){if(null===this.data)throw new Error("Did not receive network config!");return this.data}finish(e){return this.onNewBlocks.markDone(),{state:"finished",data:e.sendRequest("finish",null)}}}class pO extends bk{onNewHeader=new fk;constructor(){super({name:"ready(network)",allowedTransitions:["finished"],requestHandlers:{finish:async()=>this.endWork()},signalListeners:{announceHeader:e=>this.triggerHeaderAnnouncement(e)}})}triggerHeaderAnnouncement(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=fe.decodeObject(ms,e,t.genericConfig.chainSpec);this.onNewHeader.emit(r)}else hO.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}sendBlocks(e,t){const r=this.getConfig(),s=Ae.encodeObject(Be.sequenceVarLen(vs.Codec.View),t,r.genericConfig.chainSpec);e.sendSignal("newBlocks",s.raw,[s.raw.buffer])}getConfig(){if(null===this.data)throw new Error("Did not receive chain spec config!");return this.data}async endWork(){return{response:null,transitionTo:{state:"finished",data:Promise.resolve(null)}}}}class bO{chainSpec;keccakHasher;blocks;states;hashAllocator=new Ke;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:a}=bO.getLastHeaderAndState(r,s);this.lastHeaderHash=i,this.lastHeader=n,this.lastState=a}refreshLastHeaderAndState(){const{lastHeaderHash:e,lastHeader:t,lastState:r}=bO.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 Ae.encodeObject(vs.Codec,e,this.chainSpec)}async nextBlock(){this.refreshLastHeaderAndState();const e=this.lastHeader.timeSlotIndex+1,t=Tr(e%6),r=new XB(this.chainSpec,this.keccakHasher,this.hashAllocator),s=this.lastHeaderHash,i=this.states.getStateRoot(this.lastState),n=Is.create({tickets:[],preimages:[],guarantees:[],assurances:[],disputes:Or.create({verdicts:[],culprits:[],faults:[]})}),a=Ae.encodeObject(Is.Codec,n,this.chainSpec),o=fe.decodeObject(Is.Codec.View,a,this.chainSpec),c=r.extrinsic(o).hash,l=L.zero(Ne),d=Ae.create({destination:l.raw});d.i32(e),d.i16(t);const u=ps.create({parentHeaderHash:s,priorStateRoot:await i,extrinsicHash:c,timeSlotIndex:Ur(e),epochMarker:null,ticketsMarker:null,offendersMarker:[],bandersnatchBlockAuthorIndex:t,entropySource:L.fill(Ne,42*e%256).asOpaque(),seal:l.asOpaque()}),h=Ae.encodeObject(ps.Codec,u,this.chainSpec),f=fe.decodeObject(ps.Codec.View,h,this.chainSpec);return this.lastHeaderHash=r.header(f).hash,this.lastHeader=u,vs.create({header:u,extrinsic:n})}}const mO=ri.new(void 0,"block-generator");class yO extends bk{onBlock=new fk;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{block:e=>this.triggerOnBlock(e)}})}triggerOnBlock(e){e instanceof Uint8Array?this.onBlock.emit(e):mO.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 AO extends bk{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 IO=ri.new(void 0,"block-generator");if(!EE.isMainThread){ri.configureAll(process.env.JAM_LOG??"",qs.LOG);const e=function(){const e=new Ak("ready(generator)",Ct.reInit),t=new AO,r=new mk;return new gk("block-generator",e,[e,t,r])}();dk.receiveChannel(e,EE.parentPort).then(e=>async function(e){IO.info(`🎁 Block Generator running ${e.currentState()}`);const t=await e.waitForState("ready(generator)"),r=t.currentState().getConfig(),s=new RE(r.dbPath),i=new kE(r.chainSpec,s),n=new sk(r.chainSpec,s),a=await t.doUntil("finished",async(e,t,s)=>{let a=0;const o=new bO(r.chainSpec,await ft.create(),i,n);for(;!s();){await(0,js.setTimeout)(1e3*r.chainSpec.slotDuration),a+=1;const s=await o.nextEncodedBlock();IO.trace(`Sending block ${a}`),e.sendBlock(t,s)}});IO.info("Block Generator finished. Closing channel."),a.currentState().close(e)}(e)).catch(e=>{IO.error(e),void 0!==e.stack&&IO.error(e.stack),void 0!==e.cause&&IO.error(e.cause)})}const vO=t(import.meta.url)("node:net"),wO=t(import.meta.url)("node:path");class SO{socket;constructor(e){this.socket=e}send(e){!function(e,t){e.write(yS(t)),e.write(t)}(this.socket,e.raw)}close(){this.socket.end()}}var EO;!function(e){e[e.Msg=0]="Msg",e[e.Open=1]="Open",e[e.Close=2]="Close"}(EO||(EO={}));class CO{streamId;type;data;static Codec=Be.Class(CO,{streamId:Be.u32,type:Be.u8.convert(e=>te(e),e=>{switch(e){case EO.Msg:return EO.Msg;case EO.Open:return EO.Open;case EO.Close:return EO.Close;default:throw new Error(`Invalid 'StreamEnvelopeType' value: ${e}`)}}),data:Be.blob});static create({streamId:e,type:t,data:r}){return new CO(e,t,r)}constructor(e,t,r){this.streamId=e,this.type=t,this.data=r}}class kO{streamByte;static Codec=Be.Class(kO,{streamByte:Be.u8});static create({streamByte:e}){return new kO(e)}constructor(e){this.streamByte=e}}const xO=ri.new(void 0,"ext-ipc");class BO{sender;streams=new Map;pendingStreams=new Map;streamHandlers=new Map;onEnd;constructor(e){this.sender=e;let t=()=>{},r=e=>{};const s=new Promise((e,s)=>{t=e,r=s});this.onEnd={finished:!1,listen:s,resolve:t,reject:r}}registerStreamHandlers(...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 _O(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 _O(i,this.sender);n.open(kO.create({streamByte:e})),t(r,n)}onSocketMessage(e){const t=fe.decodeObject(CO.Codec,e),r=t.streamId;xO.log(`[${r}] incoming message: ${t.type} ${t.data}`);const s=this.streams.get(r),i=new _O(r,this.sender);if(void 0===s){if(t.type!==EO.Open)return void xO.warn(`[${r}] (unknown) got invalid type ${t.type}.`);const e=fe.decodeObject(kO.Codec,t.data),s=this.streamHandlers.get(e.streamByte);return void 0!==s?(xO.log(`[${r}] new stream for ${s.kind}`),this.streams.set(r,s),void i.open(e)):void i.close()}if(t.type===EO.Close){const e=this.streams.get(r);return e?.onClose(r,!1),void this.streams.delete(r)}t.type===EO.Msg?s.onStreamMessage(i,t.data):this.pendingStreams.delete(r)||xO.warn(`[${r}] got invalid type ${t.type}.`)}onClose({error:e}){xO.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 xO.log("Waiting for the handler to be closed."),this.onEnd.listen}}class _O{streamId;sender;constructor(e,t){this.streamId=e,this.sender=t}open(e){const t=Ae.encodeObject(kO.Codec,e);this.sender.send(Ae.encodeObject(CO.Codec,CO.create({streamId:this.streamId,type:EO.Open,data:t})))}bufferAndSend(e){return this.sender.send(Ae.encodeObject(CO.Codec,CO.create({streamId:this.streamId,type:EO.Msg,data:e}))),!0}close(){this.sender.send(Ae.encodeObject(CO.Codec,CO.create({streamId:this.streamId,type:EO.Close,data:P.blobFromNumbers([])})))}}function RO(e,t,r,s,i){return function(n){const a="win32"===fE.platform()?`\\\\.\\pipe\\${n}`:wO.join(fE.tmpdir(),`${n}.ipc`),o=ri.new(void 0,"ext-ipc"),d=(0,vO.createServer)(n=>{o.log("Client connected");const a=(n=>{const a=new BO(n),o=e=>{if(!(e instanceof c.Announcement))throw new Error(`Invalid annoncement received: ${e}`);a.withStreamOfKind(c.STREAM_KIND,(t,r)=>{t.sendAnnouncement(r,e)})};return t.on(o),a.waitForEnd().finally(()=>{t.off(o)}),a.registerStreamHandlers(new c.Handler(e,r,()=>{},()=>{})),a.registerStreamHandlers(new l.Handler(!0,s,i)),a})(new SO(n));n.on("data",AS(e=>{try{a.onSocketMessage(e)}catch(e){o.error(`Received invalid data on socket: ${e}. Closing connection.`),n.end()}},()=>{o.error("Received too much data on socket. Closing connection."),n.end()})),n.on("end",()=>{o.log("Client disconnected"),a.onClose({})}),n.on("error",e=>{o.error(`Socket error: ${e}`),a.onClose({error:e}),n.end()})});try{uE.unlinkSync(a)}catch{}const u=new AbortController;return d.listen({path:a,signal:u.signal},()=>{o.log(`IPC server is listening at ${a}`)}),d.on("error",e=>{throw e}),()=>{o.info("Closing IPC server."),d.close(),u.abort(),d.unref()}}("typeberry-jamnp")}const OO=ri.new(void 0,"net");if(!EE.isMainThread){ri.configureAll(process.env.JAM_LOG??"",qs.LOG);const e=function(){const e=new Ak("ready(network)",fO.reInit),t=new pO,r=new mk;return new gk("network",e,[e,t,r])}();dk.receiveChannel(e,EE.parentPort).then(e=>async function(e){OO.trace(`🛜 Network starting ${e.currentState()}`);const t=await e.waitForState("ready(network)"),r=await t.doUntil("finished",async(e,r)=>{const s=e.getConfig(),i=await Ir(s.key),n=new RE(s.genericConfig.dbPath),a=new kE(s.genericConfig.chainSpec,n);OO.info(`🛜 Listening at ${s.host}:${s.port}`);const o=await async function(e,t,r,s,i,n,a){const o=t.toString().substring(2,10),c=await bS.setup({host:e.host,port:e.port,key:r,protocols:[`jamnp-s/0/${o}`]}),l=new wS(c);l.addPersistentRetry(s);const d=new kS,u=aE.start(i,d,l,n,a);return setImmediate(async()=>{for(;c.isRunning;)await(0,js.setTimeout)(3e3),u.maintainSync()}),function(e,t,r){t.peers.onPeerConnected(t=>(t.addOnIncomingStream(e=>(ES(()=>r.onIncomingStream(t,e),r=>{cE.error(`[${t.id}:${e.streamId}]🚰 Stream error: ${r}. Disconnecting peer.`),t.disconnect()}),O)),e.openUp0(t),O))}(u,c,d),{network:c,syncTask:u,streamManager:d}}({host:s.host,port:s.port},s.genesisHeaderHash,i,s.bootnodes.map(lE).filter(e=>e.host!==s.host||e.port!==s.port),s.genericConfig.chainSpec,a,t=>e.sendBlocks(r,t));e.onNewHeader.on(e=>{o.syncTask.broadcastHeader(e)}),t.waitForState("finished").then(()=>o.network.stop()),await o.network.start()});OO.info("🛜 Network worker finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>OO.error(e))}const UO=e=>e.endsWith(".json");function TO(e,t){const r=hE().readFileSync(e),s=P.blobFrom(new Uint8Array(r));return fe.decodeObject(vs.Codec.View,s,t)}function NO(e,t){const r=hE().readFileSync(e,"utf-8"),s=JSON.parse(r),i=X("block"in s?s.block:s,(n=t,ee.object({header:Gs,extrinsic:(a=n,ee.object({tickets:Vs,preimages:Ls,guarantees:Ms,assurances:kr(a),disputes:ks},({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})=>Is.create({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})))},({header:e,extrinsic:t})=>vs.create({header:e,extrinsic:t}))));var n,a;const o=Ae.encodeObject(vs.Codec,i,t);return fe.decodeObject(vs.Codec.View,o,t)}const DO={genesisPath:"",timeSlot:Ur(0),validatorIndex:Tr(0)};class MO{isAuthoring;blocksToImport;nodeName;node;dev;network;static new({isAuthoring:e,blocksToImport:t,nodeName:r,nodeConfig:s,devConfig:i,seedConfig:n,networkConfig:a}){let o=i??{...DO};return void 0!==n&&(o={...o,...n}),new MO(e??!1,t??null,r,s,o,a??null)}constructor(e,t,r,s,i,n){this.isAuthoring=e,this.blocksToImport=t,this.nodeName=r,this.node=s,this.dev=i,this.network=n}}const PO=ri.new(void 0,"jam");var LO;async function HO(e,t){if(!EE.isMainThread)return void PO.error("The main binary cannot be running as a Worker!");PO.info(`🫐 Typeberry 0.0.1. GP: ${A} (${I})`),PO.info(`🎸 Starting node: ${e.nodeName}.`);const r=FO(e.node.flavor),{rootDb:s,dbPath:i,genesisHeaderHash:n}=function(e,t,r,{readOnly:s=!1}={}){const i=ze(e).toString().substring(2,10),n=qe(t).asOpaque(),a=`${r}/${i}/${n.toString().substring(2,10)}`;PO.info(`🛢️ Opening database at ${a}`);try{return{dbPath:a,rootDb:new RE(a,s),genesisHeaderHash:n}}catch(e){throw new Error(`Unable to open database at ${a}: ${e}`)}}(e.nodeName,e.node.chainSpec.genesisHeader,t(e.node.databaseBasePath));await async function(e,t,r,s){const i=new kE(e,r),n=new sk(e,r),a=i.getBestHeaderHash(),o=i.getPostStateRoot(a);if(PO.log(`🛢️ Best header hash: ${a}`),PO.log(`🛢️ Best state root: ${o}`),null!==o&&!o.isEqualTo(L.zero(Pe))&&!a.isEqualTo(L.zero(Pe)))return void await r.db.close();PO.log("🛢️ Database looks fresh. Initializing.");const c=fe.decodeObject(ps.Codec,s.genesisHeader,e),l=vs.create({header:ps.empty(),extrinsic:Is.create({tickets:[],preimages:[],assurances:[],guarantees:[],disputes:{verdicts:[],culprits:[],faults:[]}})}).extrinsic,d=vs.create({header:c,extrinsic:l}),u=fe.decodeObject(vs.Codec.View,Ae.encodeObject(vs.Codec,d,e),e);PO.log(`🧬 Writing genesis block #${c.timeSlotIndex}: ${t}`);const{genesisStateSerialized:h,genesisStateRootHash:f}=function(e,t){const r=qC.fromEntriesUnsafe(t.entries()),s=MC.fromStateEntries(e,r),i=r.getRootHash();return PO.info(`🧬 Genesis state root: ${i}`),{genesisState:s,genesisStateSerialized:r,genesisStateRootHash:i}}(e,s.genesisState);await i.insertBlock(new He(t,u)),await n.insertState(t,h),await i.setPostStateRoot(t,f),await i.setBestHeaderHash(t),await r.db.close()}(r,n,s,e.node.chainSpec);const a=await async function(){const e=dO,t=new cO;return Ik(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/importer/index.ts"),e,"ready(main)",t)}(),o=a.getState("ready(main)").onBestBlock,d=function(e){const t=function(e){const t=function(e){const t=new fk;let r=null;return e.bestHeader.on(e=>{const s=e.data.materialize(),i=e.hash,n=c.HashAndSlot.create({hash:i,slot:s.timeSlotIndex});r=n,t.emit(c.Announcement.create({header:s,final:n}))}),RO(e.chainSpec,t,()=>{const e=r??c.HashAndSlot.create({hash:L.zero(Pe).asOpaque(),slot:Ur(0)});return c.Handshake.create({final:e,leafs:[]})},()=>[],(e,t)=>{let r=P.blobFromNumbers([255,255,0,0]);return L.fromBlob(ze("0x83bd3bde264a79a2e67c487696c1d7f0b549da89").raw.subarray(0,Le),Le).isEqualTo(t)&&(r=P.blobFromNumbers([255,255,255,0])),[new l.KeyValuePair(t,r)]})}(e);return()=>{t()}}(e);return()=>{t()}}({chainSpec:r,bestHeader:o}),u=new Ct(r,i,e.node.authorship.omitSealVerification),h=a.transition((e,t)=>e.sendConfig(t,u)),f=KO(h,r,e.blocksToImport),g=await VO(h,e.isAuthoring&&null===e.blocksToImport,u),p=await QO(h,u,n,e.network,null===e.blocksToImport,o);PO.info("[main]⌛ waiting for importer to finish");const b=await f;PO.log("[main] ☠️ Closing the extensions"),d(),PO.log("[main]⌛ waiting for tasks to finish"),await b.currentState().waitForWorkerToFinish(),PO.log("[main] ☠️ Closing the authorship module"),g(),PO.log("[main] ☠️ Closing the networking module"),p(),PO.info("[main] ✅ Done.")}!function(e){e[e.InMemory=0]="InMemory",e[e.Lmdb=1]="Lmdb"}(LO||(LO={}));const VO=async(e,t,r)=>{if(!t)return PO.log("✍️ Authorship off: disabled"),()=>Promise.resolve();PO.info("✍️ Starting block generator.");const{generator:s,finish:i}=await async function(e){const t=(await async function(){const e=IO,t=new yO;return Ik(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"))}}(r);return e.doUntil("finished",async(e,t)=>{s.currentState().onBlock.on(r=>{PO.log(`✍️ Produced block. Size: [${r.length}]`),e.sendBlock(t,r)})}),i},KO=async(e,t,r)=>null===r?e.waitForState("finished"):(PO.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=UO(r)?NO(r,t):TO(r,t);yield e}}({files:r,chainSpec:t});for(const t of i)PO.log(`📖 Importing block: #${t.header.view().timeSlotIndex.materialize()}`),e.sendBlock(s,t.encoded().raw);return PO.info("All blocks scheduled to be imported."),e.finish(s)})),QO=async(e,t,r,s,i,n)=>{if(!i||null===s)return PO.log("🛜 Networking off: "+(null===s?"no config":"disabled")),()=>Promise.resolve();const{key:o,host:c,port:l,bootnodes:d}=s,{network:u,finish:h}=await async function(e){const t=(await async function(){return Ik(new URL(a(493),a.b),OO,"ready(main)",new gO)}()).transition((t,r)=>t.sendConfig(r,e));return{network:t,finish:()=>(t.transition((e,t)=>e.finish(t)),t.waitForState("finished"))}}(fO.new({genericConfig:t,genesisHeaderHash:r,key:o,host:c,port:l,bootnodes:d.map(e=>e.toString())}));return e.doUntil("finished",async(e,t)=>{u.currentState().onNewBlocks.on(r=>{for(const s of r)e.sendBlock(t,s.encoded().raw)})}),u.doUntil("finished",async(e,t)=>{n.on(r=>{e.announceHeader(t,r)})}),h},FO=e=>{if(e===vE.Full)return Et;if(e===vE.Tiny)return St;throw new Error(`Unknown chain spec: ${e}. Possible options: ${[vE.Full,vE.Tiny]}`)},$O=(e=>{var t={};return a.d(t,e),t})({default:()=>s.default}),GO=`\n@typeberry/jam 0.0.1 by Fluffy Labs.\n\nUsage:\n jam [options]\n jam [options] dev <dev-validator-index>\n jam [options] import <bin-or-json-blocks>\n\nOptions:\n --name Override node name. Affects networking key and db location.\n [default: ${IE.name}]\n --config Path to a config file or one of: ['${yE}', '${AE}'].\n [default: ${IE.config}]\n`;var jO;function qO(e,t){const{name:r}=WO(e,"name",e=>e,IE.name),{config:s}=WO(e,"config",e=>e===yE?yE:t(e),IE.config);return{nodeName:r,configPath:s}}function zO(e,t){const r=(0,$O.default)(e),s=r._.shift()??jO.Run;switch(s){case jO.Run:{const e=qO(r,t);return JO(r),{command:jO.Run,args:e}}case jO.Dev:{const e=qO(r,t),s=r._.shift();if(void 0===s)throw new Error("Missing dev-validator index.");const i=Number(s);if(!ie(i))throw new Error(`Invalid dev-validator index: ${i}, need U16`);return JO(r),{command:jO.Dev,args:{...e,index:i}}}case jO.Import:{const e=qO(r,t),s=r._.map(e=>t(e));return r._=[],JO(r),{command:jO.Import,args:{...e,files:s}}}default:r._.unshift(s),JO(r)}throw new Error(`Invalid arguments: ${JSON.stringify(r)}`)}function WO(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 JO(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.Dev="dev",e.Import="import"}(jO||(jO={}));const YO=e=>{const t=e.command===jO.Import?e.args.files:null,r=function(e){if(e===AE)return X(pE,SE.fromJson);if(e===yE)return X(bE,SE.fromJson);try{const t=hE().readFileSync(e,"utf8");return X(JSON.parse(t),SE.fromJson)}catch(t){throw new Error(`Unable to load config file from ${e}: ${t}`)}}(e.args.configPath),s=e.command===jO.Dev?`${e.args.nodeName}-${e.args.index}`:e.args.nodeName,i=e.command===jO.Dev?e.args.index:0,n=function(e,t=new Ke){return qe(P.blobFromParts([Sr.raw,e.raw]),t).asOpaque()}(ze(s).asOpaque());return MO.new({isAuthoring:e.command===jO.Dev,nodeName:s,blocksToImport:t,nodeConfig:r,networkConfig:{key:n,host:"127.0.0.1",port:12345+i,bootnodes:r.chainSpec.bootnodes??[]}})};if("file:///home/runner/work/typeberry/typeberry/bin/jam/index.ts"===(0,d.pathToFileURL)(process.argv[1]).href){ri.configureAll(process.env.JAM_LOG??"",qs.LOG);const e="undefined/../..",t=t=>t.startsWith("/")?t:`${e}/${t}`;let r;try{r=zO(process.argv.slice(2),t)}catch(e){console.error(`\n${e}\n`),console.info(GO),process.exit(1)}HO(YO(r),t).catch(e=>{console.error(`${e}`),process.exit(-1)})}let XO;ri.configureAll(process.env.JAM_LOG??"",qs.LOG);try{XO=zO(process.argv.slice(2),ZO)}catch(e){console.error(`\n${e}\n`),console.info(GO),process.exit(1)}function ZO(e){return e}HO(YO(XO),ZO).catch(e=>{console.error(`${e}`),process.exit(-1)});export{jO as Command,GO as HELP,zO as parseArgs,YO as prepareConfigFile};
|
|
3
3
|
//# sourceMappingURL=typeberry.mjs.map
|