@typeberry/jam 0.0.1-1e529cb → 0.0.1-2341f48
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"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),o=r(8),a=r(8),c=r(8),l=r(154),h=r(984),u=r(872),d=r(984);class g{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=g;class f extends g{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 f(e)}static fromDecimalDottedString(e){return new f(e)}static fromString(e){return f.fromDecimalDottedString(e)}static fromBinaryString(e){let t=i.Validator.isValidBinaryString(e);if(t[0])return new f(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 f.fromNumber(this.getValue()+1n)}previousIPNumber(){return f.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=f;class p extends g{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 g{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 f(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 f{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 g=n.__wbindgen_add_to_stack_pointer(-16),f=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(g,f,p,t,y,m,b,A,I,v);var o=u()[g/4+0],a=u()[g/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),g=c,f=l(t,n.__wbindgen_malloc),p=c;n.batch_verify_tickets(a,h,g,f,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 g=s(928).join(i,"bandersnatch_bg.wasm"),f=s(896).readFileSync(g),p=new WebAssembly.Module(f),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,g=(e.exports.KEYBYTES=32,e.exports.SALTBYTES=16),f=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===g,"salt must be exactly "+g+", was given "+r.length)),null!=i&&(s(i instanceof Uint8Array,"personal must be Uint8Array or Buffer"),s(i.length===f,"personal must be exactly "+f+", 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),g=new WebAssembly.Module(d),f=new WebAssembly.Instance(g,o);n=f.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],g=d[a+1];n(u,e,t),o(u,e,c,l);var f=u[s]^u[e],p=u[s+1]^u[e+1];u[s]=p,u[s+1]=f,n(u,r,s),f=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=f>>>24^p<<8,u[t+1]=p>>>24^f<<8,n(u,e,t),o(u,e,h,g),f=u[s]^u[e],p=u[s+1]^u[e+1],u[s]=f>>>16^p<<16,u[s+1]=p>>>16^f<<16,n(u,r,s),f=u[t]^u[r],p=u[t+1]^u[r+1],u[t]=p>>>31^f<<1,u[t+1]=f>>>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 g(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 f=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){f.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=e,f[0]=e,t&&(f[1]=t.length),f[2]=1,f[3]=1,r&&f.set(r,32),s&&f.set(s,48);for(var i=0;i<16;i++)this.h[i]=l[i]^a(f,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,g(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;g(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)})},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 Q(Object.create(null))}:a?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]}},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}(),g="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}}(),f=s?Symbol.for("@reflect-metadata:registry"):void 0,p=function(){var e;return!C(f)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[f]),C(e)&&(e=function(){var e,r,s,i;C(f)||void 0===t.Reflect||f 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 g,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 g,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(f)&&x(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}(),y=function(e){var t=new g,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()),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=V(t,r,!1);return!C(s)&&_(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=V(t,r,!1);if(!C(s))return s.OrdinaryGetOwnMetadata(e,t,r)}function v(e,t,r,s){V(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=V(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 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 V(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 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)),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=V(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})},o.b=new URL("./",import.meta.url);var a={};o.r(a),o.d(a,{Any:()=>gm,BaseBlock:()=>xp,BaseStringBlock:()=>_p,BitString:()=>xy,BmpString:()=>zy,Boolean:()=>Sy,CharacterString:()=>nm,Choice:()=>fm,Constructed:()=>by,DATE:()=>cm,DateTime:()=>hm,Duration:()=>um,EndOfContent:()=>Iy,Enumerated:()=>Ty,GeneralString:()=>im,GeneralizedTime:()=>am,GraphicString:()=>rm,HexBlock:()=>vp,IA5String:()=>tm,Integer:()=>Uy,Null:()=>vy,NumericString:()=>Yy,ObjectIdentifier:()=>My,OctetString:()=>Cy,Primitive:()=>gy,PrintableString:()=>Xy,RawData:()=>ym,RelativeObjectIdentifier:()=>Hy,Repeated:()=>pm,Sequence:()=>Ky,Set:()=>Vy,TIME:()=>dm,TeletexString:()=>Zy,TimeOfDay:()=>lm,UTCTime:()=>om,UniversalString:()=>Jy,Utf8String:()=>jy,ValueBlock:()=>Sp,VideotexString:()=>em,ViewWriter:()=>rp,VisibleString:()=>sm,compareSchema:()=>mm,fromBER:()=>py,verifySchema:()=>bm});const c=t(import.meta.url)("node:url");var l,h,u;!function(e){e[e.Less=-1]="Less",e[e.Equal=0]="Equal",e[e.Greater=1]="Greater"}(l||(l={}));class d{value;constructor(e){this.value=e}static Less=new d(l.Less);static Greater=new d(l.Greater);static Equal=new d(l.Equal);isLess(){return this.value===l.Less}isGreater(){return this.value===l.Greater}isEqual(){return this.value===l.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"}(h||(h={})),function(e){e.W3F_DAVXY="w3f-davxy",e.W3F="w3f",e.JAMDUNA="jamduna",e.JAVAJAM="javajam"}(u||(u={}));const g=u.W3F,f=[h.V0_6_4,h.V0_6_5,h.V0_6_6,h.V0_6_7,h.V0_7_0],p="undefined"==typeof process?{}:process.env,y=h.V0_6_5;let m=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: ${f}`);return t}(p.GP_VERSION);const b=p.TEST_SUITE??g;class A{static override(e){m=e}static is(...e){return void 0===m?e.includes(y):e.includes(m)}static isSuite(e){return void 0!==b&&e===b}static isGreaterOrEqual(e){const t=f.indexOf(e);if(-1===t)throw new Error(`Invalid version: ${e}. Not found amongst supported versions: ${f}`);return A.is(...f.slice(t))}}function I(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 w(e){throw new Error(`Unexpected value: ${e}`)}function S(e){const t=Object.keys(e);if(t.length>0)throw new Error(`Unexpected keys: ${t.join(", ")}`)}function E(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(e))}]`;if(e instanceof Map)return E(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&&k.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(e[r]))}`,s+=n?",":"");return s+=n?"}":"\n}",s}const C="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 k{toString(){return E(this)}}function x(e){return e}function B(e){return e}const _=Symbol("ok");class R{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}) - ${O(this.error)}`}}const O=e=>{return null!==(t=e)&&"object"==typeof t&&"kind"in t&&"error"in t?e instanceof R?e.toString():`${e.kind} - ${O(e.error)}`:`${e}`;var t};function U(e){return e.isOk?`OK: ${"symbol"==typeof e.ok?e.ok.toString():e.ok}`:`${e.details}\nError: ${O(e.error)}`}const T={ok:e=>(I(void 0!==e,"`Ok` type cannot be undefined."),{isOk:!0,isError:!1,ok:e}),error:(e,t="")=>(I(void 0!==e,"`Error` type cannot be undefined."),{isOk:!1,isError:!0,error:e,details:t}),taggedError:(e,t,r)=>T.error(new R(t,r.error,e),r.details)},N=(t(import.meta.url)("node:assert"),Symbol("compare using"));class D{[N](){return this.toString()}raw;length=0;constructor(e){this.raw=e,this.length=e.byteLength}toString(){return function(e){const t=e=>e>=G?String.fromCharCode(e+K-G):String.fromCharCode(e+L);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&&j(this.raw,e.raw)}compare(e){const t=Math.min(this.length,e.length),r=this.raw,s=e.raw;for(let e=0;e<t;e++){if(r[e]<s[e])return d.Less;if(r[e]>s[e])return d.Greater}return this.length<e.length?d.Less:this.length>e.length?d.Greater:d.Equal}static empty(){return new D(new Uint8Array)}static blobFromString(e){const t=new TextEncoder;return D.blobFrom(t.encode(e))}static blobFrom(e){return new D(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 D(i)}static blobFromNumbers(e){I(void 0===e.find(e=>(255&e)!==e),"BytesBlob.blobFromNumbers used with non-byte number array.");const t=new Uint8Array(e);return new D(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]=P(t)}return new D(s)}static parseBlob(e){if(!e.startsWith("0x"))throw new Error(`Missing 0x prefix: ${e}.`);return D.parseBlobNoPrefix(e.substring(2))}*chunks(e){for(let t=0;t<this.length;t+=e)yield D.blobFrom(this.raw.subarray(t,t+e))}}class M extends D{length;constructor(e,t){super(e),I(e.byteLength===t,`Given buffer has incorrect size ${e.byteLength} vs expected ${t}`),this.length=t}static fromBlob(e,t){return new M(e,t)}static fromNumbers(e,t){I(void 0===e.find(e=>(255&e)!==e),"Bytes.fromNumbers used with non-byte number array.");const r=new Uint8Array(e);return new M(r,t)}static zero(e){return new M(new Uint8Array(e),e)}static fill(e,t){I((255&t)===t,"Input has to be a byte.");const r=M.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=D.parseBlobNoPrefix(e);return new M(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=D.parseBlob(e);return new M(r.raw,t)}isEqualTo(e){return I(this.length===e.length,"Comparing incorrectly typed bytes!"),j(this.raw,e.raw)}asOpaque(){return this}}function P(e){return I(2===e.length,"Two-character string expected"),$(e.charCodeAt(0))<<4|$(e.charCodeAt(1))}const L="0".charCodeAt(0),H="9".charCodeAt(0),K="a".charCodeAt(0),V="f".charCodeAt(0),Q="A".charCodeAt(0),F="F".charCodeAt(0),G=10;function $(e){if(e>=L&&e<=H)return e-L;if(e>=K&&e<=V)return e-K+G;if(e>=Q&&e<=F)return e-Q+G;throw new Error(`Invalid characters in hex byte string: ${String.fromCharCode(e)}`)}function j(e,t){for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}const q=(e,t)=>e.compare(t);class z{data;bitLength;static fromBlob(e,t){return new z(e,t)}static fromBytes(e,t){return new z(e.raw,t)}static empty(e){const t=new Uint8Array(Math.ceil(e/8));return new z(t,e)}byteLength;constructor(e,t){this.data=e,this.bitLength=t,I(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){I(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){I(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){I(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 W=Symbol("no key");function J(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]=J(t,s,`${r}.${e}`);return n}if("optional"===s)return null==e?e:J(e,t[1],r);if("object"===s)return Y(t[1],e,r);if("string"===s)return Y(t[1],J(e,s,r),r);if("number"===s){const s=t[0];return Y(t[1],J(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]=J(t,o[e],`${r}.${e}`)}else Array.isArray(o[e])&&"optional"===o[e][0]&&(i[e]=W);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]===W&&delete i[e];return i}function Y(e,t,r){try{return e(t,r)}catch(e){throw new Error(`[${r}] Error while parsing the value: ${e}`)}}var X;!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]=J(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(J(n,e,`${s}.key`),J(o,t,`${s}.value`));return i})},e.object=function(e,t){return r((r,s)=>{const i=J(r,e,s);return t(i)})}}(X||(X={}));const Z=e=>v(e,ee(e),`input must have one-byte representation, got ${e}`),ee=e=>(255&e)===e,te=e=>v(e,re(e),`input must have two-byte representation, got ${e}`),re=e=>(65535&e)===e,se=e=>v(e,ie(e),`input must have four-byte representation, got ${e}`),ie=e=>(4294967295&e)>>>0===e,ne=e=>{const t=BigInt(e);return v(t,oe(t),`input must have eight-byte representation, got ${e}`)},oe=e=>(18446744073709551615n&e)===e;function ae(...e){let t=0n;for(const r of e)t+=r;const r=!oe(t);return t&=0xffffffffffffffffn,{overflow:r,value:ne(t)}}function ce(e){return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}function le(e){return I(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 ue{source;offset;context;static fromBytesBlob(e,t){return new ue(e.raw,t)}static fromBlob(e){return new ue(e)}static decodeObject(e,t,r){const s=t instanceof D?ue.fromBytesBlob(t):ue.fromBlob(t);s.attachContext(r);const i=s.object(e);return s.finish(),i}static decodeSequence(e,t,r){const s=t instanceof D?ue.fromBytesBlob(t):ue.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 ue(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,M.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=ge(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=ge(e);if(this.offset+=1,0===t)return ne(e);if(this.ensureHasBytes(t),this.offset+=t,8===t)return ne(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 ne(r)}bytes(e){if(0===e)return M.zero(e);this.ensureHasBytes(e);const t=this.source.subarray(this.offset,this.offset+e);return this.offset+=e,M.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,D.blobFrom(t)}bitVecFixLen(e){if(0===e)return z.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 z.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):(I(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(I(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 de=[255,254,252,248,240,224,192,128];function ge(e){I(e>=0&&e<256,`Incorrect byte value: ${e}`);for(let t=0;t<de.length;t++)if(e>=de[t])return 8-t;return 0}function fe(e){return I(e.isExact,"The value is not exact size estimation!"),e.bytes}function pe(e,t){return{bytes:e.bytes+t.bytes,isExact:e.isExact&&t.isExact}}const ye=10485760;class me{destination;buffer;static create(e){if(void 0!==e&&"destination"in e)return new me(e.destination);const t=e?.expectedLength??512,r=new ArrayBuffer(Math.min(ye,t),{maxByteLength:ye}),s=new Uint8Array(r);return new me(s,r)}static encodeObject(e,t,r){const s=me.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 D.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;I(e<t,"Only for numbers up to 2**64 - 1"),I(-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(se(e?1:0))}prepareIntegerN(e,t){const r=2**(8*t);I(e<r,`Only for numbers up to 2**${8*t} - 1`),I(-e<=r/2,"Only for numbers down to -2**"+(8*t-1)),this.ensureBigEnough(t)}varU32(e){I(e>=0,"Only for natural numbers."),I(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(se(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(M.fromBlob(t,t.length))}bitVecVarLen(e){const t=e.bitLength;this.varU32(se(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){I(t.length<=2**32,"Wow, that's a nice long sequence you've got here."),this.varU32(se(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}){I(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 be{decoder;constructor(e){this.decoder=e}u64=()=>this.decoder.skip(8);u32=()=>this.decoder.skip(4);u24=()=>this.decoder.skip(3);u16=()=>this.decoder.skip(2);u8=()=>this.decoder.skip(1);bool=()=>this.decoder.skip(1);varU32=()=>this.varU64();varU64(){const e=ge(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 Ae(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 Ie{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 ve{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 D.blobFromNumbers([]);if(this.lastDecodedFieldIdx<e.length-1){const t=e[e.length-1];this.decodeUpTo(t)}return D.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];I(this.lastDecodedFieldIdx<t,`Unjustified call to 'decodeUpTo' -\n the index ($Blobindex}, ${String(e)})\n is already decoded (${this.lastDecodedFieldIdx}, ${String(r)}).\n `);let s=this.cache.get(r);const i=new be(this.decoder);for(let e=this.lastDecodedFieldIdx+1;e<=t;e++){const t=i.decoder.clone(),r=this.descriptorsKeys[e],n=this.descriptors[r];s=new Ie(()=>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 we{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?D.blobFromNumbers([]):(this.lastDecodedIdx<this.length-1&&this.decodeUpTo(this.length-1),D.blobFrom(this.decoder.source.subarray(this.initialDecoderOffset,this.decoder.bytesRead())))}decodeUpTo(e){I(this.lastDecodedIdx<e,`Unjustified call to 'decodeUpTo' - the index (${e}) is already decoded (${this.lastDecodedIdx}).`);let t=this.cache.get(this.lastDecodedIdx);const r=new be(this.decoder);for(let s=this.lastDecodedIdx+1;s<=e;s++){const e=r.decoder.clone(),i=this.descriptor;t=new Ie(()=>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 Se{name;sizeHint;encode;decode;skip;View;static withView(e,t,r,s,i,n){return new Se(e,t,r,s,i,n)}static new(e,t,r,s,i){return new Se(e,t,r,s,i,null)}constructor(e,t,r,s,i,n){this.name=e,this.sizeHint=t,this.encode=r,this.decode=s,this.skip=i,this.View=n??this}skipEncoded(e){const t=e.bytesRead();this.skip(new be(e));const r=e.bytesRead();return D.blobFrom(e.source.subarray(t,r))}convert(e,t){return new Se(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 Ee(e){return e.convert(e=>(I(Array.isArray(e),`Non-arrays are not supported as 'readonly': got ${typeof e}, ${e}`),e),e=>e)}function Ce(e){return{bytes:e,isExact:!0}}var ke,xe;function Be(e,t){for(const r in e)"string"==typeof r&&r in e&&t(r,e[r])}function _e(e){return e.View!==e}(xe=ke||(ke={})).bytes=(()=>{const e=new Map;return t=>{let r=e.get(t);return void 0===r&&(r=Se.new(`Bytes<${t}>`,Ce(t),(e,t)=>e.bytes(t),e=>e.bytes(t),e=>e.bytes(t)),e.set(t,r)),r}})(),xe.varU32=Se.new("var_u32",{bytes:4,isExact:!1},(e,t)=>e.varU32(t),e=>e.varU32(),e=>e.varU32()),xe.varU64=Se.new("var_u64",{bytes:8,isExact:!1},(e,t)=>e.varU64(t),e=>e.varU64(),e=>e.varU64()),xe.u64=Se.withView("u64",Ce(8),(e,t)=>e.i64(t),e=>e.u64(),e=>e.u64(),xe.bytes(8)),xe.u32=Se.withView("u32",Ce(4),(e,t)=>e.i32(t),e=>e.u32(),e=>e.u32(),xe.bytes(4)),xe.u24=Se.withView("u24",Ce(3),(e,t)=>e.i24(t),e=>e.u24(),e=>e.u24(),xe.bytes(3)),xe.u16=Se.withView("u16",Ce(2),(e,t)=>e.i16(t),e=>e.u16(),e=>e.u16(),xe.bytes(2)),xe.u8=Se.new("u8",Ce(1),(e,t)=>e.i8(t),e=>e.u8(),e=>e.u8()),xe.i64=Se.withView("u64",Ce(8),(e,t)=>e.i64(t),e=>e.i64(),e=>e.u64(),xe.bytes(8)),xe.i32=Se.withView("i32",Ce(4),(e,t)=>e.i32(t),e=>e.i32(),e=>e.u32(),xe.bytes(4)),xe.i24=Se.withView("i24",Ce(3),(e,t)=>e.i24(t),e=>e.i24(),e=>e.u24(),xe.bytes(3)),xe.i16=Se.withView("i16",Ce(2),(e,t)=>e.i16(t),e=>e.i16(),e=>e.u16(),xe.bytes(2)),xe.i8=Se.new("i8",Ce(1),(e,t)=>e.i8(t),e=>e.i8(),e=>e.u8()),xe.bool=Se.new("bool",Ce(1),(e,t)=>e.bool(t),e=>e.bool(),e=>e.bool()),xe.blob=Se.new("BytesBlob",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(t),e=>e.bytesBlob(),e=>e.bytesBlob()),xe.string=Se.withView("string",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(D.blobFrom((new TextEncoder).encode(t))),e=>new TextDecoder("utf8",{fatal:!0}).decode(e.bytesBlob().raw),e=>e.bytesBlob(),xe.blob),xe.bitVecVarLen=Se.new("BitVec[?]",{bytes:8,isExact:!1},(e,t)=>e.bitVecVarLen(t),e=>e.bitVecVarLen(),e=>e.bitVecVarLen()),xe.bitVecFixLen=e=>Se.new(`BitVec[${e}]`,Ce(e>>>3),(e,t)=>e.bitVecFixLen(t),t=>t.bitVecFixLen(e),t=>t.bitVecFixLen(e)),xe.optional=e=>{const t=Se.new(`Optional<${e.name}>`,pe({bytes:1,isExact:!1},e.sizeHint),(t,r)=>t.optional(e,r),t=>t.optional(e),t=>t.optional(e));return _e(e)?Se.withView(t.name,t.sizeHint,t.encode,t.decode,t.skip,xe.optional(e.View)):t},xe.sequenceVarLen=(e,t={minLength:0,maxLength:2**32-1})=>{const r=`Sequence<${e.name}>[?]`,s=t.typicalLength??64;return Se.withView(r,{bytes:s*e.sizeHint.bytes,isExact:!1},(s,i)=>{Ae(t,i.length,r),s.sequenceVarLen(e,i)},s=>{const i=s.varU32();return Ae(t,i,r),s.sequenceFixLen(e,i)},s=>{const i=s.decoder.varU32();return Ae(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 Ae(t,s,i),r.sequenceFixLen(e,s)};return Se.new(i,r,(e,r)=>{Ae(t,r.length,i);const s=r.encoded();e.bytes(M.fromBlob(s.raw,s.length))},t=>{const r=new we(t.clone(),e);return n(new be(t)),r},n)}(e,t))},xe.sequenceFixLen=(e,t)=>Se.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 Se.new(n,r,(e,t)=>{const r=t.encoded();e.bytes(M.fromBlob(r.raw,r.length))},r=>{const i=new we(r.clone(),e,t);return s(new be(r)),i},s)}(e,{fixedLength:t})),xe.dictionary=(e,t,{sortKeys:r,fixedLength:s})=>{const i=Se.new(`Dictionary<${e.name}, ${t.name}>[${s??"?"}]`,{bytes:void 0!==s?s*pe(e.sizeHint,t.sizeHint).bytes:32*(pe(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(se(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 _e(t)?Se.withView(i.name,i.sizeHint,i.encode,i.decode,i.skip,xe.dictionary(e,t.View,{sortKeys:r,fixedLength:s})):i},xe.custom=({name:e,sizeHint:t={bytes:0,isExact:!1}},r,s,i)=>Se.new(e,t,r,s,i),xe.select=({name:e,sizeHint:t},r)=>Se.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),xe.object=(e,t="object",r=e=>e)=>xe.Class({name:t,create:r},e),xe.Class=(e,t)=>{let r=Ce(0);Be(t,(e,t)=>{r=pe(r,t.sizeHint)});const s=e=>{if(r.isExact)return e.decoder.skip(r.bytes);Be(t,(t,r)=>{r.skip(e)})},i=function(e,t,r,s){class i extends ve{constructor(r){super(r,e,t)}}return Be(t,e=>{"string"==typeof e&&Object.defineProperty(i.prototype,e,{get:function(){return this.get(e)}})}),Se.new(`View<${e.name}>`,r,(e,t)=>{const r=t.encoded();e.bytes(M.fromBlob(r.raw,r.length))},e=>{const t=new i(e.clone());return s(new be(e)),t},s)}(e,t,r,s);return Se.withView(e.name,r,(e,r)=>{Be(t,(t,s)=>{const i=r[t];s.encode(e,i)})},r=>{const s={};return Be(t,(e,t)=>{const i=t.decode(r);s[e]=i}),e.create(s)},s,i)};var Re=o(405);const Oe=32,Ue=144,Te=144,Ne=32,De=31;class Me extends k{hash;data;constructor(e,t){super(),this.hash=e,this.data=t}}class Pe extends Me{encoded;constructor(e,t,r){super(e,t),this.encoded=r}}class Le{emptyHash(){return M.zero(Ne)}}const He=new Le;var Ke,Ve=o(675),Qe=o.n(Ve);function Fe(e,t=He){const r=t.emptyHash();if(0===e.length)return r.asOpaque();const s=Qe()(Ne);for(const t of e)s?.update(t instanceof D?t.raw:t);return s?.digest(r.raw),r.asOpaque()}function Ge(e,t=He){const r=Qe()(Ne),s=e instanceof D?e.raw:e;r?.update(s);const i=t.emptyHash();return r?.digest(i.raw),i}function $e(e,t=He){return Ge(D.blobFromString(e),t)}function je(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 qe{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 je(this,void 0,void 0,function*(){const t=yield this.lock();try{return yield Promise.resolve(e())}finally{t()}})}}const ze="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,We=null!==(Ke=ze.Buffer)&&void 0!==Ke?Ke:null,Je=ze.TextEncoder?new ze.TextEncoder:null;function Ye(e,t){return(15&e)+(e>>6|e>>3&8)<<4|(15&t)+(t>>6|t>>3&8)}const Xe="a".charCodeAt(0)-10,Ze="0".charCodeAt(0);function et(e,t,r){let s=0;for(let i=0;i<r;i++){let r=t[i]>>>4;e[s++]=r>9?r+Xe:r+Ze,r=15&t[i],e[s++]=r>9?r+Xe:r+Ze}return String.fromCharCode.apply(null,e)}const tt=null!==We?e=>{if("string"==typeof e){const t=We.from(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.length)}if(We.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 Je.encode(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")},rt=new Uint8Array(256);for(let e=0;e<64;e++)rt["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;function st(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=rt[e.charCodeAt(t)],n=rt[e.charCodeAt(t+1)],o=rt[e.charCodeAt(t+2)],a=rt[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 it=16384,nt=new qe,ot=new Map;function at(e,t){return je(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=nt.dispatch(()=>je(this,void 0,void 0,function*(){if(!ot.has(e.name)){const t=st(e.data),r=WebAssembly.compile(t);ot.set(e.name,r)}const t=yield ot.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+it);t+=i.length,s.set(i),r.exports.Hash_Update(i.length)}})(tt(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):et(l,s,t)},u=e=>"string"==typeof e?e.length<4096:e.byteLength<it;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(()=>je(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,it)}))(),{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]=Ye(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]!==Ye(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=tt(e);return s.set(o),r.exports.Hash_Calculate(o.length,i,n),et(l,s,t)},hashLength:t}})}new qe,new qe,new DataView(new ArrayBuffer(4)),new qe,new qe,new qe,new qe,new Uint8Array(8),new qe,new qe,new qe;var ct={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 lt(e){return[224,256,384,512].includes(e)?null:new Error("Invalid variant! Valid values: 224, 256, 384, 512")}new qe,new qe,new qe,new qe,new qe,new qe,new qe,new qe,new Uint8Array(8),new qe,new Uint8Array(8),new qe,new Uint8Array(8),new qe,new qe,new qe;class ht{hasher;static async create(){return new ht(await function(e=512){if(lt(e))return Promise.reject(lt(e));const t=e/8;return at(ct,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 ut(e,t){e.hasher.init();for(const r of t)e.hasher.update(r.raw);return M.fromBlob(e.hasher.digest("binary"),Ne)}class dt{map=new Map;constructor(){}static new(){return new dt}static fromEntries(e){const t=new dt;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 gt{map;static viewDictionaryKeys(e){return new gt(e)}static from(e){const t=gt.new();return t.insertAll(e),t}static new(){return new gt}constructor(e=dt.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 ft(e){return e}class pt extends Array{fixedLength;constructor(...e){super(...e),this.fixedLength=this.length}static new(e,t){I(e.length===t,`Expected an array of size: ${t}, got: ${e.length}`);const r=new pt(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 pt.new(r,t)}toString(){return E(Array.from(this))}}class yt{array;comparator;static fromArray(e,t=[]){const r=t.slice();return r.sort((t,r)=>e(t,r).value),new yt(r,e)}static fromSortedArray(e,t=[]){const r=t.length;if(0===r)return new yt([],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 yt(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){I(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 yt.fromSortedArray(r,a)}*[Symbol.iterator](){for(const e of this.array)yield e}}class mt extends yt{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 mt(r,e)}static fromSortedArray(e,t=[]){if(0===t.length)return new mt([],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 mt(r,e)}insert(e){const t=this.binarySearch(e);t.isEqual||this.array.splice(t.idx,0,e)}static fromTwoSortedCollections(e,t){I(e.comparator===t.comparator,"Cannot merge arrays if they do not use the same comparator");const r=e.comparator;if(0===e.length)return mt.fromSortedArray(r,t.array);if(0===t.length)return mt.fromSortedArray(r,e.array);const s=yt.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,mt.fromSortedArray(r,s)}}class bt{dict;static fromEntries(e){const t=Array.from(e).map(([e,t])=>{const r=M.zero(Ne).asOpaque();return r.raw.set(e.raw.subarray(0,De)),[r,t]});return new bt(dt.fromEntries(t))}truncatedKey=M.zero(Ne).asOpaque();constructor(e){this.dict=e}[N](){return this.dict}get size(){return this.dict.size}get(e){return this.truncatedKey.raw.set(e.raw.subarray(0,De)),this.dict.get(this.truncatedKey)}has(e){return this.truncatedKey.raw.set(e.raw.subarray(0,De)),this.dict.has(this.truncatedKey)}set(e,t){const r=M.zero(Ne);r.raw.set(e.raw.subarray(0,De)),this.dict.set(r.asOpaque(),t)}delete(e){this.truncatedKey.raw.set(e.raw.subarray(0,De)),this.dict.delete(this.truncatedKey)}values(){return this.dict.values()}[Symbol.iterator](){return this.dict[Symbol.iterator]()}}class At extends k{validatorsCount;thirdOfValidators;validatorsSuperMajority;coresCount;slotDuration;epochLength;rotationPeriod;contestLength;ticketsPerValidator;maxTicketsPerExtrinsic;numberECPiecesPerSegment;preimageExpungePeriod;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,this.preimageExpungePeriod=e.preimageExpungePeriod}}const It=new At({contestLength:10,coresCount:2,epochLength:12,maxTicketsPerExtrinsic:3,rotationPeriod:4,slotDuration:6,ticketsPerValidator:3,validatorsCount:6,numberECPiecesPerSegment:1026,preimageExpungePeriod:6}),vt=new At({contestLength:500,coresCount:341,epochLength:600,maxTicketsPerExtrinsic:16,rotationPeriod:10,slotDuration:6,ticketsPerValidator:2,validatorsCount:1023,numberECPiecesPerSegment:6,preimageExpungePeriod:19200});class wt{chainSpec;dbPath;omitSealVerification;static reInit(e){const{chainSpec:t,dbPath:r,omitSealVerification:s}=e;return new wt(new At(t),r,s)}constructor(e,t,r=!1){this.chainSpec=e,this.dbPath=t,this.omitSealVerification=r}}function St(e){const t=vt,{name:r,sizeHint:s}=e(t),i=new Map;return ke.select({name:r,sizeHint:{bytes:s.bytes,isExact:!1}},s=>{if(s instanceof At){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 Et=(e,t,r)=>"fixedLength"in t?Ee(ke.sequenceFixLen(e,t.fixedLength)).convert(B,ft):Ee(ke.sequenceVarLen(e,t)).convert(B,ft),Ct=(e,t)=>{const r=r=>{if(t!==r)throw new Error(`[${e.name}] Invalid size of fixed-size array. Got ${r}, expected: ${t}`)};return ke.sequenceFixLen(e,t).convert(e=>(r(e.length),e),e=>(r(e.length),pt.new(e,t)))},kt=(e,t,{typicalLength:r=32,compare:s=(e,r)=>t(e).compare(t(r))}={})=>Se.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(se(i.length));for(const r of i)e.encode(t,r)},r=>{const i=dt.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 xt extends k{attempt;signature;static Codec=ke.Class(xt,{attempt:ke.u8.asOpaque(),signature:ke.bytes(784).asOpaque()});static create({attempt:e,signature:t}){return new xt(e,t)}constructor(e,t){super(),this.attempt=e,this.signature=t}}class Bt extends k{id;attempt;static Codec=ke.Class(Bt,{id:ke.bytes(Ne),attempt:ke.u8.asOpaque()});static create({id:e,attempt:t}){return new Bt(e,t)}constructor(e,t){super(),this.id=e,this.attempt=t}}const _t=Et(xt.Codec,{minLength:0,maxLength:16,typicalLength:16});var Rt;!function(e){e.bytesN=e=>X.fromString(t=>M.parseBytes(t,e).asOpaque()),e.bytesNNoPrefix=e=>X.fromString(t=>M.parseBytesNoPrefix(t,e).asOpaque()),e.bytes32=()=>X.fromString(e=>M.parseBytes(e,32).asOpaque()),e.bytes32NoPrefix=()=>X.fromString(e=>M.parseBytesNoPrefix(e,32).asOpaque()),e.bytesBlob=X.fromString(D.parseBlob),e.bytesBlobNoPrefix=X.fromString(D.parseBlobNoPrefix),e.ed25519Signature=X.fromString(e=>M.parseBytes(e,64).asOpaque()),e.ticketAttempt=X.fromNumber(e=>{if(0!==e&&1!==e&&2!==e)throw new Error("Invalid TicketAttempt value.");return Z(e)}),e.uint8Array=X.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=X.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=X.fromAny(e=>BigInt(e))}(Rt||(Rt={}));const Ot=2n**255n-19n,Ut=2n**252n+27742317777372353535851937790883648493n,Tt=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Nt=0x6666666666666666666666666666666666666666666666666666666666666658n,Dt={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Ot,n:Ut,h:8,Gx:Tt,Gy:Nt},Mt=(e="")=>{throw new Error(e)},Pt=e=>"string"==typeof e,Lt=(e,t)=>!(e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name)(e)||"number"==typeof t&&t>0&&e.length!==t?Mt("Uint8Array of valid length expected"):e,Ht=e=>new Uint8Array(e),Kt=(e,t=Ot)=>{let r=e%t;return r>=0n?r:t+r},Vt=e=>e instanceof Qt?e:Mt("Point expected");class Qt{constructor(e,t,r,s){this.ex=e,this.ey=t,this.ez=r,this.et=s}static fromAffine(e){return new Qt(e.x,e.y,1n,Kt(e.x*e.y))}static fromHex(e,t=!1){const{d:r}=Dt,s=(n=e,o=32,e=Lt(Pt(n)?zt(n):Ht(Lt(n)),o)).slice(),i=e[31];var n,o;s[31]=-129&i;const a=Jt(s);!t||0n<=a&&a<2n**256n||Mt("bad y coord 1"),t||0n<=a&&a<Ot||Mt("bad y coord 2");const c=Kt(a*a),l=Kt(c-1n),h=Kt(r*c+1n);let{isValid:u,value:d}=tr(l,h);u||Mt("bad y coordinate 3");const g=1n==(1n&d),f=!!(128&i);return!t&&0n===d&&f&&Mt("bad y coord 3"),f!==g&&(d=Kt(-d)),new Qt(d,a,1n,Kt(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}=Vt(e),a=Kt(t*o),c=Kt(i*s),l=Kt(r*o),h=Kt(n*s);return a===c&&l===h}is0(){return this.equals(Gt)}negate(){return new Qt(Kt(-this.ex),this.ey,this.ez,Kt(-this.et))}double(){const{ex:e,ey:t,ez:r}=this,{a:s}=Dt,i=Kt(e*e),n=Kt(t*t),o=Kt(2n*Kt(r*r)),a=Kt(s*i),c=e+t,l=Kt(Kt(c*c)-i-n),h=a+n,u=h-o,d=a-n,g=Kt(l*u),f=Kt(h*d),p=Kt(l*d),y=Kt(u*h);return new Qt(g,f,y,p)}add(e){const{ex:t,ey:r,ez:s,et:i}=this,{ex:n,ey:o,ez:a,et:c}=Vt(e),{a:l,d:h}=Dt,u=Kt(t*n),d=Kt(r*o),g=Kt(i*h*c),f=Kt(s*a),p=Kt((t+r)*(n+o)-u-d),y=Kt(f-g),m=Kt(f+g),b=Kt(d-l*u),A=Kt(p*y),I=Kt(m*b),v=Kt(p*b),w=Kt(y*m);return new Qt(A,I,w,v)}mul(e,t=!0){if(0n===e)return!0===t?Mt("cannot multiply by 0"):Gt;if("bigint"==typeof e&&0n<e&&e<Ut||Mt("invalid scalar, must be < L"),!t&&this.is0()||1n===e)return this;if(this.equals(Ft))return or(e).p;let r=Gt,s=Ft;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(Dt.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(Ut/2n,!1).double();return e=e.add(this),e.is0()}toAffine(){const{ex:e,ey:t,ez:r}=this;if(this.equals(Gt))return{x:0n,y:1n};const s=Xt(r,Ot);return 1n!==Kt(r*s)&&Mt("invalid inverse"),{x:Kt(e*s),y:Kt(t*s)}}toRawBytes(){const{x:e,y:t}=this.toAffine(),r=Wt(t);return r[31]|=1n&e?128:0,r}toHex(){return jt(this.toRawBytes())}}Qt.BASE=new Qt(Tt,Nt,1n,Kt(Tt*Nt)),Qt.ZERO=new Qt(0n,1n,1n,0n);const{BASE:Ft,ZERO:Gt}=Qt,$t=(e,t)=>e.toString(16).padStart(t,"0"),jt=e=>Array.from(Lt(e)).map(e=>$t(e,2)).join(""),qt=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0,zt=e=>{const t="hex invalid";if(!Pt(e))return Mt(t);const r=e.length,s=r/2;if(r%2)return Mt(t);const i=Ht(s);for(let r=0,n=0;r<s;r++,n+=2){const s=qt(e.charCodeAt(n)),o=qt(e.charCodeAt(n+1));if(void 0===s||void 0===o)return Mt(t);i[r]=16*s+o}return i},Wt=e=>zt($t(e,64)).reverse(),Jt=e=>BigInt("0x"+jt(Ht(Lt(e)).reverse())),Yt=(...e)=>{const t=Ht(e.reduce((e,t)=>e+Lt(t).length,0));let r=0;return e.forEach(e=>{t.set(e,r),r+=e.length}),t},Xt=(e,t)=>{(0n===e||t<=0n)&&Mt("no inverse n="+e+" mod="+t);let r=Kt(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?Kt(i,t):Mt("no inverse")},Zt=(e,t)=>{let r=e;for(;t-- >0n;)r*=r,r%=Ot;return r},er=19681161376707505956807079304988542015446066515923890162744021073123829784752n,tr=(e,t)=>{const r=Kt(t*t*t),s=(e=>{const t=e*e%Ot*e%Ot,r=Zt(t,2n)*t%Ot,s=Zt(r,1n)*e%Ot,i=Zt(s,5n)*s%Ot,n=Zt(i,10n)*i%Ot,o=Zt(n,20n)*n%Ot,a=Zt(o,40n)*o%Ot,c=Zt(a,80n)*a%Ot,l=Zt(c,80n)*a%Ot,h=Zt(l,10n)*i%Ot;return{pow_p_5_8:Zt(h,2n)*e%Ot,b2:t}})(e*Kt(r*r*t)).pow_p_5_8;let i=Kt(e*r*s);const n=Kt(t*i*i),o=i,a=Kt(i*er),c=n===e,l=n===Kt(-e),h=n===Kt(-e*er);return c&&(i=o),(l||h)&&(i=a),1n==(1n&Kt(i))&&(i=Kt(-i)),{isValid:c||l,value:i}};let rr;const sr=()=>"object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,ir={bytesToHex:jt,hexToBytes:zt,concatBytes:Yt,mod:Kt,invert:Xt,randomBytes:(e=32)=>{const t=sr();return t&&t.getRandomValues||Mt("crypto.getRandomValues must be defined"),t.getRandomValues(Ht(e))},sha512Async:async(...e)=>{const t=sr(),r=t&&t.subtle;r||Mt("etc.sha512Async or crypto.subtle must be defined");const s=Yt(...e);return Ht(await r.digest("SHA-512",s.buffer))},sha512Sync:void 0};let nr;Object.defineProperties(ir,{sha512Sync:{configurable:!1,get:()=>rr,set(e){rr||(rr=e)}}});const or=e=>{const t=nr||(nr=(()=>{const e=[];let t=Ft,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=Gt,i=Ft;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,g=l<0;0===l?i=i.add(r(d,t[h])):s=s.add(r(g,t[u]))}return{p:s,f:i}};var ar=o(625);const cr=32,lr=64;async function hr(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+=cr,r.set(n.raw,s),s+=lr;const e=i.length;I(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,ar.verify_ed25519)(r)).map(e=>1===e);return Promise.resolve(i)}M.blobFromString("jam_val_key_ed25519"),M.blobFromString("jam_val_key_bandersnatch");class ur extends k{anchor;bitfield;validatorIndex;signature;static Codec=ke.Class(ur,{anchor:ke.bytes(Ne).asOpaque(),bitfield:St(e=>ke.bitVecFixLen(e.coresCount)),validatorIndex:ke.u16.asOpaque(),signature:ke.bytes(lr).asOpaque()});static create({anchor:e,bitfield:t,validatorIndex:r,signature:s}){return new ur(e,t,r,s)}constructor(e,t,r,s){super(),this.anchor=e,this.bitfield=t,this.validatorIndex=r,this.signature=s}}const dr=St(e=>Et(ur.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2})),gr=e=>X.array((e=>X.object({anchor:Rt.bytes32(),bitfield:X.fromString(t=>{const r=Math.ceil(e.coresCount/8);return z.fromBytes(M.parseBytes(t,r),e.coresCount)}),validator_index:"number",signature:Rt.ed25519Signature},({anchor:e,bitfield:t,validator_index:r,signature:s})=>ur.create({anchor:e,bitfield:t,validatorIndex:r,signature:s})))(e));class fr extends k{workReportHash;wasConsideredValid;key;signature;static Codec=ke.Class(fr,{workReportHash:ke.bytes(Ne).asOpaque(),wasConsideredValid:ke.bool,key:ke.bytes(cr).asOpaque(),signature:ke.bytes(lr).asOpaque()});static create({workReportHash:e,wasConsideredValid:t,key:r,signature:s}){return new fr(e,t,r,s)}constructor(e,t,r,s){super(),this.workReportHash=e,this.wasConsideredValid=t,this.key=r,this.signature=s}}class pr extends k{workReportHash;key;signature;static Codec=ke.Class(pr,{workReportHash:ke.bytes(Ne).asOpaque(),key:ke.bytes(cr).asOpaque(),signature:ke.bytes(lr).asOpaque()});static create({workReportHash:e,key:t,signature:r}){return new pr(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.key=t,this.signature=r}}class yr extends k{isWorkReportValid;index;signature;static Codec=ke.Class(yr,{isWorkReportValid:ke.bool,index:ke.u16.asOpaque(),signature:ke.bytes(lr).asOpaque()});static create({isWorkReportValid:e,index:t,signature:r}){return new yr(e,t,r)}constructor(e,t,r){super(),this.isWorkReportValid=e,this.index=t,this.signature=r}}class mr extends k{workReportHash;votesEpoch;votes;static Codec=ke.Class(mr,{workReportHash:ke.bytes(Ne).asOpaque(),votesEpoch:ke.u32.asOpaque(),votes:St(e=>Ee(ke.sequenceFixLen(yr.Codec,e.validatorsSuperMajority)).convert(B,ft))});static create({workReportHash:e,votesEpoch:t,votes:r}){return new mr(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.votesEpoch=t,this.votes=r}}class br extends k{verdicts;culprits;faults;static Codec=ke.Class(br,{verdicts:ke.sequenceVarLen(mr.Codec),culprits:ke.sequenceVarLen(pr.Codec),faults:ke.sequenceVarLen(fr.Codec)});static create({verdicts:e,culprits:t,faults:r}){return new br(e,t,r)}constructor(e,t,r){super(),this.verdicts=e,this.culprits=t,this.faults=r}}const Ar=e=>se(e),Ir=e=>te(e),vr=e=>se(e),wr=e=>ne(e),Sr=e=>te(e),Er=e=>se(e);function Cr(e,t){return I(e.length===t.validatorsCount,`Invalid per-validator array length. Expected ${t.validatorsCount}, got: ${e.length}`),e}const kr=e=>St(t=>Et(e,{fixedLength:t.validatorsCount}));function xr(e,t){return I(e.length===t.epochLength,`Invalid per-epoch-block array length. Expected ${t.epochLength}, got: ${e.length}`),e}const Br=e=>St(t=>Et(e,{fixedLength:t.epochLength}));class _r extends k{anchor;stateRoot;beefyRoot;lookupAnchor;lookupAnchorSlot;prerequisites;static Codec=ke.Class(_r,{anchor:ke.bytes(Ne).asOpaque(),stateRoot:ke.bytes(Ne).asOpaque(),beefyRoot:ke.bytes(Ne).asOpaque(),lookupAnchor:ke.bytes(Ne).asOpaque(),lookupAnchorSlot:ke.u32.asOpaque(),prerequisites:ke.sequenceVarLen(ke.bytes(Ne).asOpaque())});static create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n}){return new _r(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 Rr extends k{treeRoot;index;static Codec=ke.Class(Rr,{treeRoot:ke.bytes(Ne),index:ke.u16.asOpaque()});static create({treeRoot:e,index:t}){return new Rr(e,t)}constructor(e,t){super(),this.treeRoot=e,this.index=t}}class Or extends k{hash;len;static Codec=ke.Class(Or,{hash:ke.bytes(Ne).asOpaque(),len:ke.u32});static create({hash:e,len:t}){return new Or(e,t)}constructor(e,t){super(),this.hash=e,this.len=t}}class Ur extends k{service;codeHash;payload;refineGasLimit;accumulateGasLimit;importSegments;extrinsic;exportCount;static Codec=ke.Class(Ur,{service:ke.u32.asOpaque(),codeHash:ke.bytes(Ne).asOpaque(),payload:ke.blob,refineGasLimit:ke.u64.asOpaque(),accumulateGasLimit:ke.u64.asOpaque(),importSegments:Et(Rr.Codec,{minLength:0,maxLength:2048,typicalLength:2048}),extrinsic:ke.sequenceVarLen(Or.Codec),exportCount:ke.u16});static create({service:e,codeHash:t,payload:r,refineGasLimit:s,accumulateGasLimit:i,importSegments:n,extrinsic:o,exportCount:a}){return new Ur(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 Tr(e){return v(e,e>=Nr&&e<=Dr,`WorkItemsCount: Expected '${Nr} <= count <= ${Dr}' got ${e}`)}const Nr=1,Dr=16;class Mr extends k{authorization;authCodeHost;authCodeHash;parametrization;context;items;static Codec=ke.Class(Mr,{authorization:ke.blob,authCodeHost:ke.u32.asOpaque(),authCodeHash:ke.bytes(Ne).asOpaque(),parametrization:ke.blob,context:_r.Codec,items:ke.sequenceVarLen(Ur.Codec).convert(e=>e,e=>pt.new(e,Tr(e.length)))});static create({authorization:e,authCodeHost:t,authCodeHash:r,parametrization:s,context:i,items:n}){return new Mr(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 Pr,Lr;(Lr=Pr||(Pr={}))[Lr.ok=0]="ok",Lr[Lr.outOfGas=1]="outOfGas",Lr[Lr.panic=2]="panic",Lr[Lr.badCode=3]="badCode",Lr[Lr.codeOversize=4]="codeOversize";class Hr extends k{kind;okBlob;static Codec=ke.custom({name:"WorkExecResult",sizeHint:{bytes:1,isExact:!1}},(e,t)=>{e.varU32(se(t.kind)),t.kind===Pr.ok&&null!==t.okBlob&&e.bytesBlob(t.okBlob)},e=>{const t=e.varU32();if(t===Pr.ok){const r=e.bytesBlob();return new Hr(t,r)}if(t>Pr.codeOversize)throw new Error(`Invalid WorkExecResultKind: ${t}`);return new Hr(t)},e=>{e.decoder.varU32()===Pr.ok&&e.bytesBlob()});constructor(e,t=null){super(),this.kind=e,this.okBlob=t}}class Kr extends k{gasUsed;importedSegments;extrinsicCount;extrinsicSize;exportedSegments;static Codec=ke.Class(Kr,{gasUsed:ke.varU64.asOpaque(),importedSegments:ke.varU32,extrinsicCount:ke.varU32,extrinsicSize:ke.varU32,exportedSegments:ke.varU32});static create({gasUsed:e,importedSegments:t,extrinsicCount:r,extrinsicSize:s,exportedSegments:i}){return new Kr(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 Vr{serviceId;codeHash;payloadHash;gas;result;load;static Codec=ke.Class(Vr,{serviceId:ke.u32.asOpaque(),codeHash:ke.bytes(Ne).asOpaque(),payloadHash:ke.bytes(Ne),gas:ke.u64.asOpaque(),result:Hr.Codec,load:Kr.Codec});static create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n}){return new Vr(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 Qr extends k{hash;length;erasureRoot;exportsRoot;exportsCount;static Codec=ke.Class(Qr,{hash:ke.bytes(Ne).asOpaque(),length:ke.u32,erasureRoot:ke.bytes(Ne),exportsRoot:ke.bytes(Ne).asOpaque(),exportsCount:ke.u16});static create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i}){return new Qr(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 Fr extends k{workPackageHash;segmentTreeRoot;static Codec=ke.Class(Fr,{workPackageHash:ke.bytes(Ne).asOpaque(),segmentTreeRoot:ke.bytes(Ne).asOpaque()});constructor(e,t){super(),this.workPackageHash=e,this.segmentTreeRoot=t}static create({workPackageHash:e,segmentTreeRoot:t}){return new Fr(e,t)}}class Gr extends k{workPackageSpec;context;coreIndex;authorizerHash;authorizationOutput;segmentRootLookup;results;authorizationGasUsed;static Codec=ke.Class(Gr,{workPackageSpec:Qr.Codec,context:_r.Codec,coreIndex:A.isGreaterOrEqual(h.V0_6_5)?ke.varU32.convert(e=>se(e),e=>{if(!re(e))throw new Error(`Core index exceeds U16: ${e}`);return Sr(e)}):ke.u16.asOpaque(),authorizerHash:ke.bytes(Ne).asOpaque(),authorizationOutput:ke.blob,segmentRootLookup:Ee(ke.sequenceVarLen(Fr.Codec)),results:ke.sequenceVarLen(Vr.Codec).convert(e=>e,e=>pt.new(e,Tr(e.length))),authorizationGasUsed:ke.varU64.asOpaque()});static create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:n,results:o,authorizationGasUsed:a}){return new Gr(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 $r=[2,3];class jr extends k{validatorIndex;signature;static Codec=ke.Class(jr,{validatorIndex:ke.u16.asOpaque(),signature:ke.bytes(lr).asOpaque()});static create({validatorIndex:e,signature:t}){return new jr(e,t)}constructor(e,t){super(),this.validatorIndex=e,this.signature=t}}class qr extends k{report;slot;credentials;static Codec=ke.Class(qr,{report:Gr.Codec,slot:ke.u32.asOpaque(),credentials:Et(jr.Codec,{minLength:$r[0],maxLength:$r[1],typicalLength:$r[1]})});static create({report:e,slot:t,credentials:r}){return new qr(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.credentials=r}}const zr=St(e=>Et(qr.Codec,{minLength:0,maxLength:e.coresCount,typicalLength:e.coresCount}));class Wr extends k{bandersnatch;ed25519;static Codec=ke.Class(Wr,{bandersnatch:ke.bytes(Oe).asOpaque(),ed25519:ke.bytes(cr).asOpaque()});static create({bandersnatch:e,ed25519:t}){return new Wr(e,t)}constructor(e,t){super(),this.bandersnatch=e,this.ed25519=t}}class Jr extends k{entropy;ticketsEntropy;validators;static Codec=ke.Class(Jr,{entropy:ke.bytes(Ne).asOpaque(),ticketsEntropy:ke.bytes(Ne).asOpaque(),validators:kr(Wr.Codec)});static create({entropy:e,ticketsEntropy:t,validators:r}){return new Jr(e,t,r)}constructor(e,t,r){super(),this.entropy=e,this.ticketsEntropy=t,this.validators=r}}const Yr=e=>{const t=e.encoded().raw,r=t.length-96;return D.blobFrom(t.subarray(0,r))};class Xr extends k{static Codec=ke.Class(Xr,{parentHeaderHash:ke.bytes(Ne).asOpaque(),priorStateRoot:ke.bytes(Ne).asOpaque(),extrinsicHash:ke.bytes(Ne).asOpaque(),timeSlotIndex:ke.u32.asOpaque(),epochMarker:ke.optional(Jr.Codec),ticketsMarker:ke.optional(Br(Bt.Codec)),offendersMarker:ke.sequenceVarLen(ke.bytes(cr).asOpaque()),bandersnatchBlockAuthorIndex:ke.u16.asOpaque(),entropySource:ke.bytes(96).asOpaque(),seal:ke.bytes(96).asOpaque()});static create(e){return Object.assign(Xr.empty(),e)}parentHeaderHash=M.zero(Ne).asOpaque();priorStateRoot=M.zero(Ne).asOpaque();extrinsicHash=M.zero(Ne).asOpaque();timeSlotIndex=Ar(0);epochMarker=null;ticketsMarker=null;offendersMarker=[];bandersnatchBlockAuthorIndex=Ir(0);entropySource=M.zero(96).asOpaque();seal=M.zero(96).asOpaque();constructor(){super()}static empty(){return new Xr}}class Zr extends Me{static Codec=ke.Class(Zr,{hash:ke.bytes(Ne).asOpaque(),data:Xr.Codec.View});static create({hash:e,data:t}){return new Me(e,t)}}const es=Zr.Codec;class ts extends k{requester;blob;static Codec=ke.Class(ts,{requester:ke.u32.asOpaque(),blob:ke.blob});static create({requester:e,blob:t}){return new ts(e,t)}constructor(e,t){super(),this.requester=e,this.blob=t}}const rs=ke.sequenceVarLen(ts.Codec);class ss extends k{tickets;preimages;guarantees;assurances;disputes;static Codec=ke.Class(ss,{tickets:_t,preimages:rs,guarantees:zr,assurances:dr,disputes:br.Codec});static create({tickets:e,preimages:t,assurances:r,disputes:s,guarantees:i}){return new ss(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 is extends k{header;extrinsic;static Codec=ke.Class(is,{header:Xr.Codec,extrinsic:ss.Codec});static create({header:e,extrinsic:t}){return new is(e,t)}constructor(e,t){super(),this.header=e,this.extrinsic=t}}const ns=X.object({target:Rt.bytes32(),vote:"boolean",key:Rt.bytes32(),signature:Rt.ed25519Signature},({target:e,vote:t,key:r,signature:s})=>fr.create({workReportHash:e,wasConsideredValid:t,key:r,signature:s})),os=X.object({target:Rt.bytes32(),key:Rt.bytes32(),signature:Rt.ed25519Signature},({target:e,key:t,signature:r})=>pr.create({workReportHash:e,key:t,signature:r})),as=X.object({vote:"boolean",index:"number",signature:Rt.ed25519Signature},({vote:e,index:t,signature:r})=>yr.create({isWorkReportValid:e,index:t,signature:r})),cs=X.object({target:Rt.bytes32(),age:"number",votes:X.array(as)},({target:e,age:t,votes:r})=>mr.create({workReportHash:e,votesEpoch:t,votes:r})),ls=X.object({verdicts:X.array(cs),culprits:X.array(os),faults:X.array(ns)},({verdicts:e,culprits:t,faults:r})=>br.create({verdicts:e,culprits:t,faults:r})),hs=X.object({anchor:Rt.bytes32(),state_root:Rt.bytes32(),beefy_root:Rt.bytes32(),lookup_anchor:Rt.bytes32(),lookup_anchor_slot:"number",prerequisites:X.array(Rt.bytes32())},({anchor:e,state_root:t,beefy_root:r,lookup_anchor:s,lookup_anchor_slot:i,prerequisites:n})=>_r.create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n})),us=X.object({ok:X.optional(X.fromString(D.parseBlob)),out_of_gas:X.optional(X.fromAny(()=>null)),panic:X.optional(X.fromAny(()=>null)),bad_code:X.optional(X.fromAny(()=>null)),code_oversize:X.optional(X.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 Hr(se(Pr.ok),t);if(null===r)return new Hr(se(Pr.outOfGas));if(null===s)return new Hr(se(Pr.panic));if(null===i)return new Hr(se(Pr.badCode));if(null===n)return new Hr(se(Pr.codeOversize));throw new Error("Invalid WorkExecResult")}),ds=X.object({gas_used:X.fromNumber(e=>wr(e)),imports:"number",extrinsic_count:"number",extrinsic_size:"number",exports:"number"},({gas_used:e,imports:t,extrinsic_count:r,extrinsic_size:s,exports:i})=>Kr.create({gasUsed:wr(e),importedSegments:se(t),extrinsicCount:se(r),extrinsicSize:se(s),exportedSegments:se(i)})),gs=X.object({service_id:"number",code_hash:Rt.bytes32(),payload_hash:Rt.bytes32(),accumulate_gas:X.fromNumber(e=>wr(e)),result:us,refine_load:ds},({service_id:e,code_hash:t,payload_hash:r,accumulate_gas:s,result:i,refine_load:n})=>Vr.create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n})),fs=X.object({hash:Rt.bytes32(),length:"number",erasure_root:Rt.bytes32(),exports_root:Rt.bytes32(),exports_count:"number"},({hash:e,length:t,erasure_root:r,exports_root:s,exports_count:i})=>Qr.create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i})),ps=X.object({work_package_hash:Rt.bytes32(),segment_tree_root:Rt.bytes32()},({work_package_hash:e,segment_tree_root:t})=>Fr.create({workPackageHash:e,segmentTreeRoot:t})),ys=X.object({package_spec:fs,context:hs,core_index:"number",authorizer_hash:Rt.bytes32(),auth_output:X.fromString(D.parseBlob),segment_root_lookup:X.array(ps),results:X.array(gs),auth_gas_used:X.fromNumber(e=>wr(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=pt.new(n,Tr(n.length));return Gr.create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:o,results:c,authorizationGasUsed:a})}),ms=X.object({validator_index:"number",signature:Rt.ed25519Signature},({validator_index:e,signature:t})=>jr.create({validatorIndex:e,signature:t})),bs=X.object({report:ys,slot:"number",signatures:X.array(ms)},({report:e,slot:t,signatures:r})=>qr.create({report:e,slot:t,credentials:r})),As=X.array(bs),Is=X.object({requester:"number",blob:X.fromString(D.parseBlob)},({requester:e,blob:t})=>ts.create({requester:e,blob:t})),vs=X.array(Is),ws=X.object({attempt:Rt.ticketAttempt,signature:X.fromString(e=>M.parseBytes(e,784).asOpaque())},e=>xt.create({attempt:e.attempt,signature:e.signature})),Ss=X.array(ws),Es=X.fromString(e=>M.parseBytes(e,96).asOpaque()),Cs=X.object({bandersnatch:Rt.bytes32(),ed25519:Rt.bytes32()},Wr.create),ks=X.object({entropy:Rt.bytes32(),tickets_entropy:Rt.bytes32(),validators:X.array(Cs)},e=>Jr.create({entropy:e.entropy,ticketsEntropy:e.tickets_entropy,validators:e.validators})),xs=X.object({id:Rt.bytes32(),attempt:Rt.ticketAttempt},e=>Bt.create({id:e.id,attempt:e.attempt})),Bs=X.object({parent:Rt.bytes32(),parent_state_root:Rt.bytes32(),extrinsic_hash:Rt.bytes32(),slot:"number",epoch_mark:X.optional(ks),tickets_mark:X.optional(X.array(xs)),offenders_mark:X.array(Rt.bytes32()),author_index:"number",entropy_source:Es,seal:Es},({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=Xr.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 _s extends k{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(!re(n))throw new Error(`Invalid port number: "${i}"`);return new _s(t,s,n)}constructor(e,t,r){super(),this.name=e,this.ip=t,this.port=r}}class Rs extends k{bootnodes;id;genesisHeader;genesisState;static fromJson=X.object({bootnodes:X.optional(X.array(X.fromString(_s.fromString))),id:"string",genesis_header:Rt.bytesBlobNoPrefix,genesis_state:X.map(Rt.bytesNNoPrefix(31),Rt.bytesBlobNoPrefix)},e=>Rs.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=D.empty(),genesisState:s=new Map}){return new Rs({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 Os=t(import.meta.url)("node:fs");var Us=o.n(Os);const Ts=t(import.meta.url)("node:os");var Ns=o.n(Ts);const Ds=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-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 Ms{omitSealVerification;static fromJson=X.object({omit_seal_verification:"boolean"},Ms.new);static new({omit_seal_verification:e}){return new Ms(e)}constructor(e){this.omitSealVerification=e}}const Ps="dev",Ls={name:Ns().hostname(),config:Ps};var Hs;!function(e){e.Tiny="tiny",e.Full="full"}(Hs||(Hs={}));const Ks=X.fromString((e,t)=>{switch(e){case Hs.Tiny:return Hs.Tiny;case Hs.Full:return Hs.Full;default:throw Error(`unknown network flavor: ${e} at ${t}`)}});class Vs{$schema;version;flavor;chainSpec;databaseBasePath;authorship;static fromJson=X.object({$schema:"string",version:"number",flavor:Ks,chain_spec:Rs.fromJson,database_base_path:"string",authorship:Ms.fromJson},Vs.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 Vs(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}}var Qs;function Fs(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 Gs{options;static create(e,t){return e===Qs.TRACE?new $s(t):e===Qs.LOG?new js(t):e===Qs.INFO?new qs(t):new Gs(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,""),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=Qs[e].padEnd(5);if(e<o)return;const c=`${a} [${n}] ${s}\n\t@ ${i}`;e===Qs.WARN?console.warn(c):e===Qs.ERROR?console.error(c):console.info(c)}}class $s extends Gs{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 js extends Gs{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 qs extends Gs{trace(e,t,r){}log(e,t,r){}info(e,t,r){this.push(Qs.INFO,e,t,r)}}const zs={workingDir:"",defaultLevel:Qs.LOG,modules:new Map},Ws={options:zs,transport:Gs.create(zs.defaultLevel,zs)};class Js{moduleName;fileName;config;static new(e,t){const r=e??"unknown";return new Js(t??r,r,Ws)}static configureAllFromOptions(e){const t=Array.from(e.modules.values()).reduce((e,t)=>e<t?e:t,e.defaultLevel),r=Gs.create(t,e);Ws.options=e,Ws.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(),Fs(r.trim()))}else n=Fs(t)}const o="".split("/");return o.pop(),o.pop(),{defaultLevel:n,modules:s,workingDir:r??o.join("/")}}(e,t,r);Js.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 Ys=t(import.meta.url)("node:worker_threads"),Xs="best hash and posterior state root";class Zs{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:M.fromBlob(t,Ne).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(Xs,e.raw)}getBestHeaderHash(){const e=this.root.db.get(Xs);return void 0===e?M.zero(Ne).asOpaque():M.fromBlob(e,Ne).asOpaque()}getHeader(e){const t=this.headers.get(e.raw);return void 0===t?null:ue.decodeObject(Xr.Codec.View,t,this.chainSpec)}getExtrinsic(e){const t=this.extrinsics.get(e.raw);return void 0===t?null:ue.decodeObject(ss.Codec.View,t,this.chainSpec)}}const ei=(ti={open:()=>r.open},ri={},o.d(ri,ti),ri);var ti,ri;class si{db;constructor(e,t=!1){this.db=ei.open(e,{compression:!0,keyEncoding:"binary",encoding:"binary",readOnly:t})}subDb(e){return this.db.openDB({name:e})}}const ii=e=>Se.withView(e.name,e.sizeHint,(t,r)=>e.encode(t,r.data),t=>{const r=t.clone(),s=Ge(e.skipEncoded(r));return new Me(s.asOpaque(),e.decode(t))},e.skip,e.View);class ni extends k{workReport;timeout;static Codec=ke.Class(ni,{workReport:ii(Gr.Codec),timeout:ke.u32.asOpaque()});static create({workReport:e,timeout:t}){return new ni(e,t)}constructor(e,t){super(),this.workReport=e,this.timeout=t}}class oi extends k{headerHash;mmr;postStateRoot;reported;static Codec=ke.Class(oi,{headerHash:ke.bytes(Ne).asOpaque(),mmr:ke.object({peaks:Ee(ke.sequenceVarLen(ke.optional(ke.bytes(Ne))))}),postStateRoot:ke.bytes(Ne).asOpaque(),reported:kt(Fr.Codec,e=>e.workPackageHash)});static create({headerHash:e,mmr:t,postStateRoot:r,reported:s}){return new oi(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.mmr=t,this.postStateRoot=r,this.reported=s}}function ai(e,t){return I(e.length===t.coresCount,`Invalid per-core array length. Expected ${t.coresCount}, got: ${e.length}`),e}const ci=e=>St(t=>Et(e,{fixedLength:t.coresCount})),li=()=>Ee(ke.sequenceVarLen(ke.bytes(Ne))).convert(e=>e.array,e=>{const t=e.map(e=>e.asOpaque());return mt.fromSortedArray(di,t)}),hi=li();class ui{goodSet;badSet;wonkySet;punishSet;static Codec=ke.Class(ui,{goodSet:hi,badSet:hi,wonkySet:hi,punishSet:li()});static create({goodSet:e,badSet:t,wonkySet:r,punishSet:s}){return new ui(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 ui(mt.fromSortedArray(di,e),mt.fromSortedArray(di,t),mt.fromSortedArray(di,r),mt.fromSortedArray(di,s))}}function di(e,t){return e.compare(t)}class gi{service;gasLimit;static Codec=ke.Class(gi,{service:ke.u32.asOpaque(),gasLimit:ke.u64.asOpaque()});static create({service:e,gasLimit:t}){return new gi(e,t)}constructor(e,t){this.service=e,this.gasLimit=t}}class fi{manager;authManager;validatorsManager;autoAccumulateServices;static Codec=ke.Class(fi,{manager:ke.u32.asOpaque(),authManager:A.isGreaterOrEqual(h.V0_6_7)?ci(ke.u32.asOpaque()):St(e=>ke.u32.asOpaque().convert(e=>e[0],t=>ai(new Array(e.coresCount).fill(t),e))),validatorsManager:ke.u32.asOpaque(),autoAccumulateServices:Ee(ke.sequenceVarLen(gi.Codec))});static create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s}){return new fi(e,t,r,s)}constructor(e,t,r,s){this.manager=e,this.authManager=t,this.validatorsManager=r,this.autoAccumulateServices=s}}const pi=128;class yi extends k{bandersnatch;ed25519;bls;metadata;static Codec=ke.Class(yi,{bandersnatch:ke.bytes(Oe).asOpaque(),ed25519:ke.bytes(cr).asOpaque(),bls:ke.bytes(Te).asOpaque(),metadata:ke.bytes(pi)});static create({ed25519:e,bandersnatch:t,bls:r,metadata:s}){return new yi(t,e,r,s)}constructor(e,t,r,s){super(),this.bandersnatch=e,this.ed25519=t,this.bls=r,this.metadata=s}}var mi;!function(e){e[e.Tickets=0]="Tickets",e[e.Keys=1]="Keys"}(mi||(mi={}));const bi=ke.bytes(Oe).asOpaque();class Ai extends k{kind;keys;tickets;static Codec=St(e=>ke.custom({name:"SafroleSealingKeys",sizeHint:{bytes:1+Ne*e.epochLength,isExact:!1}},(e,t)=>{e.varU32(se(t.kind)),t.kind===mi.Keys?e.sequenceFixLen(bi,t.keys):e.sequenceFixLen(Bt.Codec,t.tickets)},t=>{const r=e.epochLength,s=t.varU32();if(s===mi.Keys){const s=t.sequenceFixLen(bi,r);return Ai.keys(xr(s,e))}if(s===mi.Tickets){const s=t.sequenceFixLen(Bt.Codec,r);return Ai.tickets(xr(s,e))}throw new Error(`Unexpected safrole sealing keys kind: ${s}`)},t=>{const r=t.decoder.varU32();if(r!==mi.Keys){if(r!==mi.Tickets)throw new Error(`Unexpected safrole sealing keys kind: ${r}`);t.sequenceFixLen(Bt.Codec,e.epochLength)}else t.sequenceFixLen(bi,e.epochLength)}));static keys(e){return new Ai(mi.Keys,e,void 0)}static tickets(e){return new Ai(mi.Tickets,void 0,e)}constructor(e,t,r){super(),this.kind=e,this.keys=t,this.tickets=r}}class Ii{nextValidatorData;epochRoot;sealingKeySeries;ticketsAccumulator;static Codec=ke.Class(Ii,{nextValidatorData:kr(yi.Codec),epochRoot:ke.bytes(Ue).asOpaque(),sealingKeySeries:Ai.Codec,ticketsAccumulator:Ee(ke.sequenceVarLen(Bt.Codec)).convert(B,ft)});static create({nextValidatorData:e,epochRoot:t,sealingKeySeries:r,ticketsAccumulator:s}){return new Ii(e,t,r,s)}constructor(e,t,r,s){this.nextValidatorData=e,this.epochRoot=t,this.sealingKeySeries=r,this.ticketsAccumulator=s}}class vi extends k{codeHash;balance;accumulateMinGas;onTransferMinGas;storageUtilisationBytes;storageUtilisationCount;static Codec=ke.Class(vi,{codeHash:ke.bytes(Ne).asOpaque(),balance:ke.u64,accumulateMinGas:ke.u64.convert(e=>e,wr),onTransferMinGas:ke.u64.convert(e=>e,wr),storageUtilisationBytes:ke.u64,storageUtilisationCount:ke.u32});static create(e){return new vi(e.codeHash,e.balance,e.accumulateMinGas,e.onTransferMinGas,e.storageUtilisationBytes,e.storageUtilisationCount)}static calculateThresholdBalance(e,t){const r=ae(ne(100n),ne(10n*BigInt(e)),ne(1n*t));return r.overflow?ne(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 wi extends k{hash;blob;static Codec=ke.Class(wi,{hash:ke.bytes(Ne).asOpaque(),blob:ke.blob});static create({hash:e,blob:t}){return new wi(e,t)}constructor(e,t){super(),this.hash=e,this.blob=t}}class Si extends k{key;value;static Codec=ke.Class(Si,{key:ke.bytes(Ne).asOpaque(),value:ke.blob});static create({key:e,value:t}){return new Si(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}function Ei(e){const t=e;if(t.length>3)throw new Error("Lookup history items must contain 0-3 timeslots.");return t}class Ci{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 ki,xi,Bi;!function(e){e[e.Provide=0]="Provide",e[e.Remove=1]="Remove",e[e.UpdateOrAdd=2]="UpdateOrAdd"}(ki||(ki={}));class _i{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static provide({serviceId:e,preimage:t,slot:r}){return new _i(e,{kind:ki.Provide,preimage:t,slot:r})}static remove({serviceId:e,hash:t,length:r}){return new _i(e,{kind:ki.Remove,hash:t,length:r})}static updateOrAdd({serviceId:e,lookupHistory:t}){return new _i(e,{kind:ki.UpdateOrAdd,item:t})}get hash(){switch(this.action.kind){case ki.Provide:return this.action.preimage.hash;case ki.Remove:return this.action.hash;case ki.UpdateOrAdd:return this.action.item.hash}throw w(this.action)}get length(){switch(this.action.kind){case ki.Provide:return se(this.action.preimage.blob.length);case ki.Remove:return this.action.length;case ki.UpdateOrAdd:return this.action.item.length}throw w(this.action)}}!function(e){e[e.Update=0]="Update",e[e.Create=1]="Create"}(xi||(xi={}));class Ri{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static update({serviceId:e,serviceInfo:t}){return new Ri(e,{kind:xi.Update,account:t})}static create({serviceId:e,serviceInfo:t,lookupHistory:r}){return new Ri(e,{kind:xi.Create,account:t,lookupHistory:r})}}!function(e){e[e.Set=0]="Set",e[e.Remove=1]="Remove"}(Bi||(Bi={}));class Oi{serviceId;action;constructor(e,t){this.serviceId=e,this.action=t}static set({serviceId:e,storage:t}){return new Oi(e,{kind:Bi.Set,storage:t})}static remove({serviceId:e,key:t}){return new Oi(e,{kind:Bi.Remove,key:t})}get key(){return this.action.kind===Bi.Remove?this.action.key:this.action.storage.key}get value(){return this.action.kind===Bi.Remove?null:this.action.storage.value}}const Ui=A.isSuite(u.W3F_DAVXY)?ke.u32.asOpaque():ke.varU32.convert(e=>se(e),e=>vr(e));class Ti{blocks;tickets;preImages;preImagesSize;guarantees;assurances;static Codec=ke.Class(Ti,{blocks:ke.u32,tickets:ke.u32,preImages:ke.u32,preImagesSize:ke.u32,guarantees:ke.u32,assurances:ke.u32});static create({blocks:e,tickets:t,preImages:r,preImagesSize:s,guarantees:i,assurances:n}){return new Ti(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=se(0);return new Ti(e,e,e,e,e,e)}}const Ni=ke.varU32.convert(e=>se(e),e=>te(e)),Di=ke.varU64.convert(e=>ne(e),e=>wr(e));class Mi{dataAvailabilityLoad;popularity;imports;exports;extrinsicSize;extrinsicCount;bundleSize;gasUsed;static Codec=ke.Class(Mi,{dataAvailabilityLoad:ke.varU32,popularity:Ni,imports:Ni,exports:Ni,extrinsicSize:ke.varU32,extrinsicCount:Ni,bundleSize:ke.varU32,gasUsed:Di});static create(e){return new Mi(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=se(0),t=te(0),r=wr(0);return new Mi(e,t,t,t,e,t,e,r)}}class Pi{providedCount;providedSize;refinementCount;refinementGasUsed;imports;exports;extrinsicSize;extrinsicCount;accumulateCount;accumulateGasUsed;onTransfersCount;onTransfersGasUsed;static Codec=ke.Class(Pi,{providedCount:Ni,providedSize:ke.varU32,refinementCount:ke.varU32,refinementGasUsed:Di,imports:Ni,exports:Ni,extrinsicSize:ke.varU32,extrinsicCount:Ni,accumulateCount:ke.varU32,accumulateGasUsed:Di,onTransfersCount:ke.varU32,onTransfersGasUsed:Di});static create(e){return new Pi(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=se(0),t=te(0),r=wr(0);return new Pi(t,e,e,r,t,t,e,t,e,r,e,r)}}class Li{current;previous;cores;services;static Codec=ke.Class(Li,{current:kr(Ti.Codec),previous:kr(Ti.Codec),cores:ci(Mi.Codec),services:ke.dictionary(Ui,Pi.Codec,{sortKeys:(e,t)=>e-t})});static create(e){return new Li(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 Hi,Ki;(Ki=Hi||(Hi={}))[Ki.DuplicateService=0]="DuplicateService",Ki[Ki.NoService=1]="NoService",Ki[Ki.PreimageExists=2]="PreimageExists";class Vi extends k{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=dt.new(),i=dt.new(),n=dt.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,wi.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 Ci(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,Si.create({key:r,value:t}))}return new Vi(e.serviceId,{info:r,preimages:s,storage:i,lookupHistory:n})}}class Qi extends k{static create(e){return new Qi(e)}static partial(e,t){const r=Qi.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=Vi.copyFrom(t,i);r.set(s,n)}return Qi.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),T.ok(_))))}removeServices(e){for(const t of e??[])I(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 T.error(Hi.NoService,`Attempting to update storage of non-existing service: ${t}`);e===Bi.Set?s.data.storage.set(r.storage.key,r.storage):e===Bi.Remove?(I(s.data.storage.has(r.key),`Attempting to remove non-existing storage item at ${t}: ${r.key}`),s.data.storage.delete(r.key)):w(e)}return T.ok(_)}updatePreimages(e){for(const{serviceId:t,action:r}of e??[]){const e=this.services.get(t);if(void 0===e)return T.error(Hi.NoService,`Attempting to update preimage of non-existing service: ${t}`);const{kind:s}=r;if(s===ki.Provide){const{preimage:s,slot:i}=r;if(e.data.preimages.has(s.hash))return T.error(Hi.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=se(s.blob.length),n=new Ci(s.hash,r,Ei([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===ki.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===ki.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 w(s)}return T.ok(_)}updateServices(e){for(const{serviceId:t,action:r}of e??[]){const{kind:e,account:s}=r;if(e===xi.Create){const{lookupHistory:e}=r;if(this.services.has(t))return T.error(Hi.DuplicateService,`${t} already exists!`);this.services.set(t,new Vi(t,{info:s,preimages:dt.new(),storage:dt.new(),lookupHistory:dt.fromEntries(null===e?[]:[[e.hash,[e]]])}))}else if(e===xi.Update){const e=this.services.get(t);if(void 0===e)return T.error(Hi.NoService,`Cannot update ${t} because it does not exist.`);e.data.info=s}else w(e)}return T.ok(_)}availabilityAssignment;designatedValidatorData;nextValidatorData;currentValidatorData;previousValidatorData;disputesRecords;timeslot;entropy;authPools;authQueues;recentBlocks;statistics;accumulationQueue;recentlyAccumulated;ticketsAccumulator;sealingKeySeries;epochRoot;privilegedServices;services;recentServiceIds(){return Array.from(this.services.keys())}getService(e){return this.services.get(e)??null}constructor(e){super(),this.availabilityAssignment=e.availabilityAssignment,this.designatedValidatorData=e.designatedValidatorData,this.nextValidatorData=e.nextValidatorData,this.currentValidatorData=e.currentValidatorData,this.previousValidatorData=e.previousValidatorData,this.disputesRecords=e.disputesRecords,this.timeslot=e.timeslot,this.entropy=e.entropy,this.authPools=e.authPools,this.authQueues=e.authQueues,this.recentBlocks=e.recentBlocks,this.statistics=e.statistics,this.accumulationQueue=e.accumulationQueue,this.recentlyAccumulated=e.recentlyAccumulated,this.ticketsAccumulator=e.ticketsAccumulator,this.sealingKeySeries=e.sealingKeySeries,this.epochRoot=e.epochRoot,this.privilegedServices=e.privilegedServices,this.services=e.services}static empty(e){return new Qi({availabilityAssignment:ai(Array.from({length:e.coresCount},()=>null),e),designatedValidatorData:Cr(Array.from({length:e.validatorsCount},()=>yi.create({bandersnatch:M.zero(Oe).asOpaque(),bls:M.zero(Te).asOpaque(),ed25519:M.zero(cr).asOpaque(),metadata:M.zero(pi).asOpaque()})),e),nextValidatorData:Cr(Array.from({length:e.validatorsCount},()=>yi.create({bandersnatch:M.zero(Oe).asOpaque(),bls:M.zero(Te).asOpaque(),ed25519:M.zero(cr).asOpaque(),metadata:M.zero(pi).asOpaque()})),e),currentValidatorData:Cr(Array.from({length:e.validatorsCount},()=>yi.create({bandersnatch:M.zero(Oe).asOpaque(),bls:M.zero(Te).asOpaque(),ed25519:M.zero(cr).asOpaque(),metadata:M.zero(pi).asOpaque()})),e),previousValidatorData:Cr(Array.from({length:e.validatorsCount},()=>yi.create({bandersnatch:M.zero(Oe).asOpaque(),bls:M.zero(Te).asOpaque(),ed25519:M.zero(cr).asOpaque(),metadata:M.zero(pi).asOpaque()})),e),disputesRecords:ui.create({goodSet:mt.fromSortedArray(di,[]),badSet:mt.fromSortedArray(di,[]),wonkySet:mt.fromSortedArray(di,[]),punishSet:mt.fromSortedArray(di,[])}),timeslot:Ar(0),entropy:pt.fill(()=>M.zero(Ne).asOpaque(),4),authPools:ai(Array.from({length:e.coresCount},()=>[]),e),authQueues:ai(Array.from({length:e.coresCount},()=>pt.fill(()=>M.zero(Ne).asOpaque(),80)),e),recentBlocks:[],statistics:Li.create({current:Cr(Array.from({length:e.validatorsCount},()=>Ti.empty()),e),previous:Cr(Array.from({length:e.validatorsCount},()=>Ti.empty()),e),cores:ai(Array.from({length:e.coresCount},()=>Mi.empty()),e),services:new Map}),accumulationQueue:xr(Array.from({length:e.epochLength},()=>[]),e),recentlyAccumulated:xr(Array.from({length:e.epochLength},()=>gt.new()),e),ticketsAccumulator:[],sealingKeySeries:Ai.keys(xr(Array.from({length:e.epochLength},()=>M.zero(Oe).asOpaque()),e)),epochRoot:M.zero(Ue).asOpaque(),privilegedServices:fi.create({manager:vr(0),authManager:ai(new Array(e.coresCount).fill(vr(0)),e),validatorsManager:vr(0),autoAccumulateServices:[]}),services:new Map})}}const Fi=ke.object({storageKeys:ke.sequenceVarLen(ke.bytes(Ne).asOpaque()),preimages:ke.sequenceVarLen(ke.bytes(Ne).asOpaque()),lookupHistory:ke.sequenceVarLen(ke.object({hash:ke.bytes(Ne).asOpaque(),length:ke.u32}))});ke.dictionary(ke.u32.asOpaque(),Fi,{sortKeys:(e,t)=>e-t});class Gi extends k{report;dependencies;static Codec=ke.Class(Gi,{report:Gr.Codec,dependencies:Et(ke.bytes(Ne).asOpaque(),{typicalLength:4,maxLength:8,minLength:0})});static create({report:e,dependencies:t}){return new Gi(e,t)}constructor(e,t){super(),this.report=e,this.dependencies=t}}var $i,ji,qi;!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"}($i||($i={})),function(e){function t(e,t){const r=M.zero(Ne);let s=0;for(const i of ce(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,Ne-i),s),r.asOpaque()}e.index=function(e){const t=M.zero(Ne);return t.raw[0]=e,t.asOpaque()},e.serviceInfo=function(e){const t=M.zero(Ne);t.raw[0]=$i.Delta;let r=1;for(const s of ce(e))t.raw[r]=s,r+=2;return t.asOpaque()},e.serviceStorage=function(e,r){const s=M.zero(Ne);return s.raw.set(ce(se(2**32-1)),0),s.raw.set(r.raw.subarray(0,28),4),t(e,s)},e.servicePreimage=function(e,r){const s=M.zero(Ne);return s.raw.set(ce(se(2**32-2)),0),s.raw.set(r.raw.subarray(1,29),4),t(e,s)},e.serviceLookupHistory=function(e,r,s){const i=Ge(r),n=M.zero(Ne);return n.raw.set(ce(s),0),n.raw.set(i.raw.subarray(2,30),4),t(e,n)},e.serviceNested=t}(ji||(ji={})),function(e){e.authPools={key:ji.index($i.Alpha),Codec:ci(Et(ke.bytes(Ne).asOpaque(),{minLength:0,maxLength:8,typicalLength:8})),extract:e=>e.authPools},e.authQueues={key:ji.index($i.Phi),Codec:ci(Ct(ke.bytes(Ne).asOpaque(),80)),extract:e=>e.authQueues},e.recentBlocks={key:ji.index($i.Beta),Codec:Et(oi.Codec,{minLength:0,maxLength:8,typicalLength:8}),extract:e=>e.recentBlocks},e.safrole={key:ji.index($i.Gamma),Codec:Ii.Codec,extract:e=>Ii.create({nextValidatorData:e.nextValidatorData,epochRoot:e.epochRoot,sealingKeySeries:e.sealingKeySeries,ticketsAccumulator:e.ticketsAccumulator})},e.disputesRecords={key:ji.index($i.Psi),Codec:ui.Codec,extract:e=>e.disputesRecords},e.entropy={key:ji.index($i.Eta),Codec:Ct(ke.bytes(Ne).asOpaque(),4),extract:e=>e.entropy},e.designatedValidators={key:ji.index($i.Iota),Codec:kr(yi.Codec),extract:e=>e.designatedValidatorData},e.currentValidators={key:ji.index($i.Kappa),Codec:kr(yi.Codec),extract:e=>e.currentValidatorData},e.previousValidators={key:ji.index($i.Lambda),Codec:kr(yi.Codec),extract:e=>e.previousValidatorData},e.availabilityAssignment={key:ji.index($i.Rho),Codec:ci(ke.optional(ni.Codec)),extract:e=>e.availabilityAssignment},e.timeslot={key:ji.index($i.Tau),Codec:ke.u32.asOpaque(),extract:e=>e.timeslot},e.privilegedServices={key:ji.index($i.Chi),Codec:fi.Codec,extract:e=>e.privilegedServices},e.statistics={key:ji.index($i.Pi),Codec:Li.Codec,extract:e=>e.statistics},e.accumulationQueue={key:ji.index($i.Theta),Codec:Br(Ee(ke.sequenceVarLen(Gi.Codec))),extract:e=>e.accumulationQueue},e.recentlyAccumulated={key:ji.index($i.Xi),Codec:Br(ke.sequenceVarLen(ke.bytes(Ne).asOpaque()).convert(e=>Array.from(e),e=>gt.from(e))),extract:e=>e.recentlyAccumulated},e.serviceData=e=>({key:ji.serviceInfo(e),Codec:vi.Codec}),e.serviceStorage=(e,t)=>({key:ji.serviceStorage(e,t),Codec:zi}),e.servicePreimages=(e,t)=>({key:ji.servicePreimage(e,t),Codec:zi}),e.serviceLookupHistory=(e,t,r)=>({key:ji.serviceLookupHistory(e,t,r),Codec:Ee(ke.sequenceVarLen(ke.u32))})}(qi||(qi={}));const zi=Se.new("Dump",{bytes:64,isExact:!1},(e,t)=>e.bytes(M.fromBlob(t.raw,t.raw.length)),e=>D.blobFrom(e.bytes(e.source.length-e.bytesRead()).raw),e=>e.bytes(e.decoder.source.length-e.decoder.bytesRead()));var Wi;!function(e){e[e.Insert=0]="Insert",e[e.Remove=1]="Remove"}(Wi||(Wi={}));const Ji=D.empty();class Yi{spec;backend;_recentServiceIds;static fromStateEntries(e,t,r=[]){return new Yi(e,t,r)}static new(e,t,r=[]){return new Yi(e,t,r)}constructor(e,t,r){this.spec=e,this.backend=t,this._recentServiceIds=r}[N](){return this.backend}updateBackend(e){this.backend=e}recentServiceIds(){return this._recentServiceIds}getService(e){const t=this.retrieveOptional(qi.serviceData(e));return void 0===t?null:(this._recentServiceIds.includes(e)||this._recentServiceIds.push(e),new Xi(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 ue.decodeObject(t,s,this.spec)}retrieveOptional({key:e,Codec:t}){const r=this.backend.get(e);if(null!==r)return ue.decodeObject(t,r,this.spec)}get availabilityAssignment(){return this.retrieve(qi.availabilityAssignment,"availabilityAssignment")}get designatedValidatorData(){return this.retrieve(qi.designatedValidators,"designatedValidatorData")}get nextValidatorData(){return this.retrieve(qi.safrole,"safroleData.nextValidatorData").nextValidatorData}get currentValidatorData(){return this.retrieve(qi.currentValidators,"currentValidators")}get previousValidatorData(){return this.retrieve(qi.previousValidators,"previousValidators")}get disputesRecords(){return this.retrieve(qi.disputesRecords,"disputesRecords")}get timeslot(){return this.retrieve(qi.timeslot,"timeslot")}get entropy(){return this.retrieve(qi.entropy,"entropy")}get authPools(){return this.retrieve(qi.authPools,"authPools")}get authQueues(){return this.retrieve(qi.authQueues,"authQueues")}get recentBlocks(){return this.retrieve(qi.recentBlocks,"recentBlocks")}get statistics(){return this.retrieve(qi.statistics,"statistics")}get accumulationQueue(){return this.retrieve(qi.accumulationQueue,"accumulationQueue")}get recentlyAccumulated(){return this.retrieve(qi.recentlyAccumulated,"recentlyAccumulated")}get ticketsAccumulator(){return this.retrieve(qi.safrole,"safroleData.ticketsAccumulator").ticketsAccumulator}get sealingKeySeries(){return this.retrieve(qi.safrole,"safrole.sealingKeySeries").sealingKeySeries}get epochRoot(){return this.retrieve(qi.safrole,"safrole.epochRoot").epochRoot}get privilegedServices(){return this.retrieve(qi.privilegedServices,"privilegedServices")}}class Xi{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(qi.serviceStorage(this.serviceId,e))??null}hasPreimage(e){return void 0!==this.retrieveOptional(qi.servicePreimages(this.serviceId,e))}getPreimage(e){return this.retrieveOptional(qi.servicePreimages(this.serviceId,e))??null}getLookupHistory(e,t){const r=this.retrieveOptional(qi.serviceLookupHistory(this.serviceId,e,t));return void 0===r?null:Ei(r.map(Ar))}}const Zi=31;var en;!function(e){e[e.Branch=0]="Branch",e[e.Leaf=1]="Leaf",e[e.EmbedLeaf=2]="EmbedLeaf"}(en||(en={}));class tn{raw;constructor(e=new Uint8Array(64)){this.raw=e}getNodeType(){return 128&this.raw[0]?192&~this.raw[0]?en.EmbedLeaf:en.Leaf:en.Branch}asBranchNode(){return I(this.getNodeType()===en.Branch),new rn(this)}asLeafNode(){return I(this.getNodeType()!==en.Branch),new sn(this)}toString(){return D.blobFrom(this.raw).toString()}}class rn{node;constructor(e){this.node=e}static fromSubNodes(e,t){const r=new tn;return r.raw.set(e.raw,0),r.raw.set(t.raw,Ne),r.raw[0]&=127,new rn(r)}getLeft(){return M.fromBlob(this.node.raw.subarray(0,Ne),Ne).asOpaque()}getRight(){return M.fromBlob(this.node.raw.subarray(Ne),Ne).asOpaque()}}class sn{node;constructor(e){this.node=e}static fromValue(e,t,r){const s=new tn;return t.length<=Ne?(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 sn(s)}getKey(){return M.fromBlob(this.node.raw.subarray(1,32),Zi).asOpaque()}hasEmbeddedValue(){return this.node.getNodeType()===en.EmbedLeaf}getValueLength(){return 63&this.node.raw[0]}getValue(){const e=this.getValueLength();return D.blobFrom(this.node.raw.subarray(Ne,Ne+e))}getValueHash(){return M.fromBlob(this.node.raw.subarray(Ne),Ne).asOpaque()}toString(){return`LeafNode {\n key: ${this.getKey()},\n valueHash: ${this.getValueHash()}\n}`}}class nn{hasher;nodes=dt.new();constructor(e){this.hasher=e}get(e){return nn.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()!==en.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 on extends nn{remove(e){return nn.withHashCompat(e,e=>{this.nodes.delete(e)})}insert(e,t){const r=t??this.hashNode(e);return nn.withHashCompat(r,t=>{this.nodes.set(t,e)}),r}}class an{nodes;root;static empty(e){return new an(new on(e))}static computeStateRoot(e,t){return an.fromLeaves(e,t).getRootHash()}static fromLeaves(e,t){let r=null;const s=new on(e);for(const e of t)r=cn(r,s,e);return new an(s,r)}constructor(e,t=null){this.nodes=e,this.root=t}set(e,t,r){const s=sn.fromValue(e,t,()=>r??this.nodes.hasher.hashConcat(t.raw).asOpaque());return this.root=cn(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?M.zero(Ne).asOpaque():this.nodes.hashNode(this.root)}toString(){return un(this.root,this.nodes)}}function cn(e,t,r){if(null===e)return t.insert(r.node),r.node;const s=function(e,t,r){const s=new ln;let i=e,n=t.hashNode(e);for(;;){if(i.getNodeType()!==en.Branch){const e=i.asLeafNode();return s.leafToReplace=[e,n],s}const e=i.asBranchNode(),o=hn(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(M.zero(Ne)))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=hn(i,e.bitIndex);for(;e.bitIndex<248;){h=hn(i,e.bitIndex);const t=hn(a,e.bitIndex);if(h!==t)break;l.push(t),e.bitIndex+=1}const u=M.zero(Ne).asOpaque();(()=>{const t=e.branchingHistory.length;return t>0&&!1===e.branchingHistory[t-1][2]})()&&!h&&(o=t.hashNode(n.node));let d=h?rn.fromSubNodes(o,c):rn.fromSubNodes(c,o),g=t.insert(d.node),f=l.pop();for(;void 0!==f;)d=f?rn.fromSubNodes(u,g):rn.fromSubNodes(g,u),g=t.insert(d.node),f=l.pop();return[d.node,g]}(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?rn.fromSubNodes(e.getLeft(),a):rn.fromSubNodes(a,e.getRight());a=t.insert(c.node),o=c.node,n=s.branchingHistory.pop()}return o}class ln{branchingHistory=[];bitIndex=0;leafToReplace}function hn(e,t){I(t<248);const r=t>>>3,s=128>>>t-(r<<3);return 0!==(e.raw[r]&s)}function un(e,t){if(null===e)return"<empty tree>";if(e.getNodeType()===en.Branch){const r=e.asBranchNode(),s=r.getLeft(),i=r.getRight(),n=e=>e.split("\n").map(e=>`\t\t${e}`).join("\n"),o=un(t.get(s),t),a=un(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 dn={hashConcat:(e,t=[])=>Fe([e,...t])};class gn{entries;static serializeInMemory(e,t){return new gn({full:!0,data:fn(e,t)})}static fromDictionaryUnsafe(e){return new gn({full:!0,data:e})}static fromTruncatedDictionaryUnsafe(e){return new gn({full:!1,data:e})}trieCache=null;constructor(e){this.entries=e}[N](){return this.entries.data}getTrie(){if(null===this.trieCache){const e=an.empty(dn);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===Wi.Insert?this.entries.data.set(r,s):t===Wi.Remove?this.entries.data.delete(r):w(t)}getRootHash(){return this.getTrie().getRootHash().asOpaque()}}function fn(e,t){const r=dt.new();function s(s){r.set(s.key,me.encodeObject(s.Codec,s.extract(t),e))}s(qi.authPools),s(qi.authQueues),s(qi.recentBlocks),s(qi.safrole),s(qi.disputesRecords),s(qi.entropy),s(qi.designatedValidators),s(qi.currentValidators),s(qi.previousValidators),s(qi.availabilityAssignment),s(qi.timeslot),s(qi.privilegedServices),s(qi.statistics),s(qi.accumulationQueue),s(qi.recentlyAccumulated);for(const[e,s]of t.services.entries()){const{key:t,Codec:i}=qi.serviceData(e);r.set(t,me.encodeObject(i,s.getInfo()));for(const t of s.data.preimages.values()){const{key:s,Codec:i}=qi.servicePreimages(e,t.hash);r.set(s,me.encodeObject(i,t.blob))}for(const t of s.data.storage.values()){const{key:s,Codec:i}=qi.serviceStorage(e,t.key);r.set(s,me.encodeObject(i,t.value))}for(const t of s.data.lookupHistory.values())for(const s of t){const{key:t,Codec:i}=qi.serviceLookupHistory(e,s.hash,s.length);r.set(t,me.encodeObject(i,s.slots.slice()))}}return r}const pn=ke.object({hash:ke.bytes(Ne).asOpaque(),length:ke.u32,slots:Ee(ke.sequenceVarLen(ke.u32.asOpaque())).convert(B,Ei)},"LookupHistoryItem",({hash:e,length:t,slots:r})=>new Ci(e,t,r)),yn=ke.object({key:ke.bytes(Ne).asOpaque(),data:ke.sequenceVarLen(pn)}),mn=ke.sequenceVarLen(yn).convert(e=>{const t=[];for(const[r,s]of e)t.push({key:r,data:s});return t},e=>{const t=dt.new();for(const{key:r,data:s}of e){const e=t.get(r)??[];e.push(...s),t.set(r,e)}return t});class bn extends Vi{static Codec=ke.Class(bn,{serviceId:ke.u32.asOpaque(),data:ke.object({info:vi.Codec,preimages:kt(wi.Codec,e=>e.hash),lookupHistory:mn,storage:kt(Si.Codec,e=>e.key)})});constructor(e,t){super(e,t)}static create({serviceId:e,data:t}){return new bn(e,t)}}var An,In,vn;ke.Class(Qi,{authPools:qi.authPools.Codec,authQueues:qi.authQueues.Codec,recentBlocks:qi.recentBlocks.Codec,nextValidatorData:kr(yi.Codec),epochRoot:ke.bytes(Ue).asOpaque(),sealingKeySeries:Ai.Codec,ticketsAccumulator:Ee(ke.sequenceVarLen(Bt.Codec)).convert(e=>e,ft),disputesRecords:qi.disputesRecords.Codec,entropy:qi.entropy.Codec,designatedValidatorData:qi.designatedValidators.Codec,currentValidatorData:qi.currentValidators.Codec,previousValidatorData:qi.previousValidators.Codec,availabilityAssignment:qi.availabilityAssignment.Codec,timeslot:qi.timeslot.Codec,privilegedServices:qi.privilegedServices.Codec,statistics:qi.statistics.Codec,accumulationQueue:qi.accumulationQueue.Codec,recentlyAccumulated:qi.recentlyAccumulated.Codec,services:ke.dictionary(ke.u32.asOpaque(),bn.Codec,{sortKeys:(e,t)=>e-t})}),function(e){e[e.Conflict=0]="Conflict",e[e.Commit=1]="Commit"}(An||(An={})),function(e){e[e.InvalidLeafData=0]="InvalidLeafData"}(In||(In={}));class wn{leaves;db;static fromLeavesBlob(e,t){if(e.length%64!=0)return T.error(In.InvalidLeafData,`${e.length} is not a multiply of 64: ${e}`);const r=[];for(const t of e.chunks(64)){const e=new tn(t.raw);if(e.getNodeType()===en.Branch)return T.error(In.InvalidLeafData,`Branch node detected: ${t}`);r.push(e.asLeafNode())}return T.ok(new wn(r,t))}lookup;constructor(e,t){this.leaves=e,this.db=t,this.lookup=bt.fromEntries(e.map(e=>[e.getKey().asOpaque(),e.hasEmbeddedValue()?{kind:vn.EmbeddedValue,value:e.getValue()}:{kind:vn.DbKey,key:e.getValueHash().raw}]))}get(e){const t=this.lookup.get(e);return void 0===t?null:t.kind===vn.EmbeddedValue?t.value:t.kind===vn.DbKey?D.blobFrom(this.db.get(t.key)):void w(t)}getStateRoot(){return an.computeStateRoot(dn,this.leaves).asOpaque()}}!function(e){e[e.EmbeddedValue=0]="EmbeddedValue",e[e.DbKey=1]="DbKey"}(vn||(vn={}));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=an.empty(dn);return await this.updateAndCommit(e,r,Array.from(t.entries.data).map(e=>[Wi.Insert,e[0],e[1]]))}async updateAndCommit(e,t,r){const s=[];for(const[e,i,n]of r)if(e===Wi.Insert){const e=t.set(i.asOpaque(),n);e.hasEmbeddedValue()||s.push([e.getValueHash(),n])}else e===Wi.Remove?t.remove(i.asOpaque()):w(e);const i=D.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),T.error(An.Commit)}return T.ok(_)}async updateAndSetState(e,t,r){const s=an.fromLeaves(dn,t.backend.leaves),i=function*(e,t){yield*function*(e,t){function r(t,r){return[Wi.Insert,r.key,me.encodeObject(r.Codec,t,e)]}void 0!==t.authPools&&(yield r(t.authPools,qi.authPools)),void 0!==t.authQueues&&(yield r(t.authQueues,qi.authQueues)),void 0!==t.recentBlocks&&(yield r(t.recentBlocks,qi.recentBlocks));const s=function(e,t,r,s){if(void 0!==e&&void 0!==t&&void 0!==r&&void 0!==s)return Ii.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,qi.safrole)),void 0!==t.disputesRecords&&(yield r(t.disputesRecords,qi.disputesRecords)),void 0!==t.entropy&&(yield r(t.entropy,qi.entropy)),void 0!==t.designatedValidatorData&&(yield r(t.designatedValidatorData,qi.designatedValidators)),void 0!==t.currentValidatorData&&(yield r(t.currentValidatorData,qi.currentValidators)),void 0!==t.previousValidatorData&&(yield r(t.previousValidatorData,qi.previousValidators)),void 0!==t.availabilityAssignment&&(yield r(t.availabilityAssignment,qi.availabilityAssignment)),void 0!==t.timeslot&&(yield r(t.timeslot,qi.timeslot)),void 0!==t.privilegedServices&&(yield r(t.privilegedServices,qi.privilegedServices)),void 0!==t.statistics&&(yield r(t.statistics,qi.statistics)),void 0!==t.accumulationQueue&&(yield r(t.accumulationQueue,qi.accumulationQueue)),void 0!==t.recentlyAccumulated&&(yield r(t.recentlyAccumulated,qi.recentlyAccumulated))}(e,t);const r=(t,r)=>me.encodeObject(t,r,e);yield*function*(e,t){for(const{action:r,serviceId:s}of e??[]){const e=qi.serviceData(s);if(yield[Wi.Insert,e.key,t(e.Codec,r.account)],r.kind===xi.Create&&null!==r.lookupHistory){const{lookupHistory:e}=r,i=qi.serviceLookupHistory(s,e.hash,e.length);yield[Wi.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 ki.Provide:{const{hash:e,blob:i}=r.preimage,n=qi.servicePreimages(s,e);if(yield[Wi.Insert,n.key,i],null!==r.slot){const n=qi.serviceLookupHistory(s,e,se(i.length));yield[Wi.Insert,n.key,t(n.Codec,Ei([r.slot]))]}break}case ki.UpdateOrAdd:{const{hash:e,length:i,slots:n}=r.item,o=qi.serviceLookupHistory(s,e,i);yield[Wi.Insert,o.key,t(o.Codec,n)];break}case ki.Remove:{const{hash:e,length:t}=r,i=qi.servicePreimages(s,e);yield[Wi.Remove,i.key,Ji];const n=qi.serviceLookupHistory(s,e,t);yield[Wi.Remove,n.key,Ji];break}default:w(r)}}(t.preimages,r),yield*function*(e){for(const{action:t,serviceId:r}of e??[])switch(t.kind){case Bi.Set:{const e=qi.serviceStorage(r,t.storage.key);yield[Wi.Insert,e.key,t.storage.value];break}case Bi.Remove:{const e=qi.serviceStorage(r,t.key);yield[Wi.Remove,e.key,Ji];break}default:w(t)}}(t.storage),yield*function*(e){for(const t of e??[]){const e=qi.serviceData(t);yield[Wi.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=wn.fromLeavesBlob(D.blobFrom(t),{get(e){const t=r.get(e);if(void 0===t)throw new Error(`Missing required value: ${D.blobFrom(e)} in the DB`);return t}});if(s.isError)throw new Error(`Inconsistent DB. Invalid leaf nodes for ${e}: ${U(s)}`);return Yi.new(this.spec,s.ok)}}const En=t(import.meta.url)("node:events"),Cn=2**32,kn=Js.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(Bn(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){I("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":I(-1!==this.responseListeners.eventNames().indexOf(Bn(e.id))),this.responseListeners.emit(Bn(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 Bn(e){return`req:${e}`}const _n=Js.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 _n.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 _n.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);_n.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 _n.trace(`[${this.machine.name}] transitioned to ${this.currentState()}`),this}static async createAndTransferChannel(e,t){const r=new Ys.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){_n.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{I("request"===t.kind,"The initial message should be a request with channel."),I(t.name===Rn),I(t.data instanceof Ys.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 I(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=Js.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 Vn(e,t,r,s){const i=new Ys.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 Qn=4294967295,Fn=4294967296,Gn=4096,$n=(I(!0,"incorrect minimal allocation shift"),7),jn=Gn>>$n,qn=1048575,zn=1048576,Wn=e=>v(e,e>=0&&e<=Qn,`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=>se(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 I(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(z.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,I(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 I(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,go=(()=>{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})(),fo=e=>se(e),po=e=>ne(e),yo=e=>"number"==typeof e&&e<2**32?fo(e):po(e);function mo(e){return new bo(ne(e))}class bo{gas;constructor(e){this.gas=e}set(e){this.gas=ne(e)}get(){return yo(this.gas)}sub(e){const t=this.gas-ne(e);return t>=0n?(this.gas=ne(t),!1):(this.gas=ne(0n),!0)}}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:fo(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<Gn,`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 Gn*Math.ceil(e/Gn)}function Bo(e){return Co(e>>>12)}function _o(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=_o(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=Bo(e.start);if(e.isEmpty())return new Ko(t,0);const r=Bo(e.lastIndex??e.end),s=ko(r);if((t===s||t===r)&&e.length>Gn)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 Vo{start;constructor(e){this.start=Ro(e)}}class Qo extends Vo{data;constructor(e,t){super(e),this.data=t}loadInto(e,t,r){const s=t+r;if(s>Gn)return T.error(Oo.fromMemoryIndex(this.start+Gn));const i=this.data.subarray(t,s);return e.fill(0,i.length,r),e.set(i),T.ok(_)}storeFrom(e,t){return T.error(Oo.fromMemoryIndex(this.start,!0))}setData(e,t){this.data.set(t,e)}isWriteable(){return!1}getPageDump(){return this.data}}class Fo extends Vo{buffer;view;constructor(e,t){super(e);const r=t?.length??0,s=Math.min(Gn,Math.max(r,jn));this.buffer=new ArrayBuffer(s,{maxByteLength:Gn}),this.view=new Uint8Array(this.buffer),void 0!==t&&this.view.set(t)}loadInto(e,t,r){const s=t+r;if(s>Gn)return T.error(Oo.fromMemoryIndex(this.start+Gn));const i=this.view.subarray(t,s);return e.fill(0,i.length,r),e.set(i),T.ok(_)}storeFrom(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Gn){const r=Math.min(Gn,Math.max(jn,e+t.length));this.buffer.resize(r)}return this.view.set(t,e),T.ok(_)}setData(e,t){if(this.buffer.byteLength<e+t.length&&this.buffer.byteLength<Gn){const r=Math.min(Gn,Math.max(jn,e+t.length));this.buffer.resize(r)}this.view.set(t,e)}isWriteable(){return!0}getPageDump(){return this.view}}var Go;!function(e){e[e.READ=0]="READ",e[e.WRITE=1]="WRITE"}(Go||(Go={}));class $o{sbrkIndex;virtualSbrkIndex;endHeapIndex;memory;static fromInitialMemory(e){return new $o(e?.sbrkIndex,e?.sbrkIndex,e?.endHeapIndex,e?.memory)}constructor(e=Jn(Ho.end),t=Jn(Ho.end),r=Jn(Qn),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(Qn),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 T.ok(_);const r=this.getPages(e,t.length,Go.WRITE);if(r.isError)return T.error(r.error);const s=r.ok;let i=e,n=t.length;for(const r of s){const s=Eo(i%Gn),o=Math.min(Gn-s,n),a=i-e,c=t.subarray(a,a+o);r.storeFrom(s,c),i+=o,n-=o}return T.ok(_)}getPages(e,t,r){if(0===t)return T.ok([]);const s=Lo.fromStartAndLength(e,t),i=Ko.fromMemoryRange(s),n=[];for(const e of i){if(e<16)return T.error(Oo.fromPageNumber(e,!0));const t=this.memory.get(e);if(void 0===t)return T.error(Oo.fromPageNumber(e));if(r===Go.WRITE&&!t.isWriteable())return T.error(Oo.fromPageNumber(e,!0));n.push(t)}return T.ok(n)}loadInto(e,t){if(0===e.length)return T.ok(_);const r=this.getPages(t,e.length,Go.READ);if(r.isError)return T.error(r.error);const s=r.ok;let i=t,n=e.length;for(const r of s){const s=Eo(i%Gn),o=Math.min(Gn-s,n),a=i-t,c=e.subarray(a);r.loadInto(c,s,o),i+=o,n-=o}return T.ok(_)}sbrk(e){const t=this.sbrkIndex,r=this.virtualSbrkIndex;if(Qn<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=Bo(t),o=(i-t)/Gn,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 jo{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(),I(e<t,"end has to be bigger than start"),I(e%Gn===0,"start needs to be a multiple of page size (4096)"),I(t%Gn===0,"end needs to be a multiple of page size (4096)"),I(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*Gn,(e+1)*Gn),i=new Qo(t,s);this.initialMemory.set(t,i)}return this}setWriteablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),I(e<t,"end has to be bigger than start"),I(e%Gn===0,"start needs to be a multiple of page size (4096)"),I(t%Gn===0,"end needs to be a multiple of page size (4096)"),I(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*Gn,(e+1)*Gn),i=new Fo(t,s);this.initialMemory.set(t,i)}return this}setData(e,t){this.ensureNotFinalized();const r=Gn-e%Gn;I(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=Bo(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){I(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=$o.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 ga(e,t){return t>e?aa-t+e+1:e-t}function fa(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){I(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(ga(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}subU64(e,t,r){this.regs.setU64(r,fa(this.regs.getU64(e),this.regs.getU64(t)))}negAddImmediateU32(e,t,r){this.regs.setU64(r,no(ga(t.getU32(),this.regs.getLowerU32(e))))}negAddImmediateU64(e,t,r){this.regs.setU64(r,fa(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,Ba;(Ba=xa||(xa={}))[Ba.HALT=0]="HALT",Ba[Ba.PANIC=1]="PANIC",Ba[Ba.FAULT_ACCESS=2]="FAULT_ACCESS",Ba[Ba.FAULT=3]="FAULT",Ba[Ba.HOST=4]="HOST";class _a{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=_o(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){I(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=Js.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=ue.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 T.ok(new Ka(e))}catch(e){return La.error(`Invalid program: ${e}`),T.error(Ha.InvalidProgramError)}}}class Va{useSbrkGas;ignoreInstructionGas;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 $o;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({useSbrkGas:e=!1,ignoreInstructionGas:t=!1}={}){this.useSbrkGas=e,this.ignoreInstructionGas=t,this.argsDecoder=new ao,this.basicBlocks=new vo;const r=new Ea(this.registers),s=new Sa(this.registers),i=new oa(this.registers),n=new Ca(this.registers),o=new ka(this.registers),a=new _a(this.registers,this.instructionResult,this.basicBlocks),c=new Ra(this.registers,this.memory,this.instructionResult),l=new Oa(this.registers,this.memory,this.instructionResult),h=new Ua(this.instructionResult),u=new Ta(this.registers,this.jumpTable,this.instructionResult,this.basicBlocks),d=new Na(this.instructionResult),g=new Da(this.registers,this.memory,this.instructionResult),f=new Ma(this.registers);this.threeRegsDispatcher=new qo(r,s,i,n,o,f),this.twoRegsOneImmDispatcher=new zo(r,s,i,n,o,l,c,f),this.twoRegsDispatcher=new Wo(o,g,i,f),this.oneRegOneImmOneOffsetDispatcher=new Jo(a,c),this.twoRegsOneOffsetDispatcher=new Yo(a),this.oneOffsetDispatcher=new Xo(a),this.oneRegOneImmDispatcher=new Zo(c,l,u),this.twoImmsDispatcher=new ta(l),this.oneRegTwoImmsDispatcher=new ea(l),this.noArgsDispatcher=new ra(h),this.twoRegsTwoImmsDispatcher=new sa(c,u),this.oneImmDispatcher=new ia(d),this.oneRegOneExtImmDispatcher=new na(c)}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.ignoreInstructionGas&&this.gas.sub(r))return this.status=Yn.OOG,this.status;const s=go[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)/Gn*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?se(e):e}getMemory(){return this.memory}getMemoryPage(e){return this.memory.getPageDump(Co(e))}}class Qa{memory;constructor(e){this.memory=e}storeFrom(e,t){return 0===t.length?T.ok(_):e+ne(t.length)>Fn?T.error(new Uo):this.memory.storeFrom(Wn(Number(e)),t)}loadInto(e,t){return 0===e.length?T.ok(_):t+ne(e.length)>Fn?T.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 ne(this.registers.getU64(e))}set(e,t){this.registers.setU64(e,t)}}class Ga{consumedGas;status;memorySlice;constructor(e,t,r){this.consumedGas=e,this.status=t,this.memorySlice=r,I(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 Ga(e,t,null)}static fromMemorySlice(e,t){return new Ga(e,null,t)}hasMemorySlice(){return this.memorySlice instanceof Uint8Array&&null===this.status}hasStatus(){return!this.hasMemorySlice()}}class $a{pvmInstanceManager;hostCalls;constructor(e,t){this.pvmInstanceManager=e,this.hostCalls=t}getReturnValue(e,t){const r=t.getGasConsumed();if(e===Yn.OOG)return Ga.fromStatus(r,e);if(e===Yn.HALT){const e=t.getMemory(),s=t.getRegisters(),i=s.getLowerU32(7),n=s.getLowerU32(8),o=new Uint8Array(n),a=Wn(i);return e.loadInto(o,a).isError?Ga.fromMemorySlice(r,new Uint8Array):Ga.fromMemorySlice(r,o)}return Ga.fromStatus(r,Yn.PANIC)}async execute(e){for(e.runProgram();;){let t=e.getStatus();if(t!==Yn.HOST)return this.getReturnValue(t,e);I(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 Qa(e.getMemory()),o=this.hostCalls.get(Zn(r)),a="number"==typeof o.gasCost?o.gasCost:o.gasCost(i);if(s.sub(a))return Ga.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 ja{instances=[];waitingQueue=[];constructor(e){for(let t=0;t<e;t++)this.instances.push(new Va({useSbrkGas:!1,ignoreInstructionGas:!0}))}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:ne(0xffffffffffffffffn),WHAT:ne(0xfffffffffffffffen),OOB:ne(0xfffffffffffffffdn),WHO:ne(0xfffffffffffffffcn),FULL:ne(0xfffffffffffffffbn),CORE:ne(0xfffffffffffffffan),CASH:ne(0xfffffffffffffff9n),LOW:ne(0xfffffffffffffff8n),HUH:ne(0xfffffffffffffff7n),OK:ne(0n)},za=se(2**32-1),Wa=ne(za),Ja=vr(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?vr(t):null}function Za(e,t){I(t.length>=4,"Not enough space in the destination."),t.set(ce(e))}function ec(e){return e>Wa?za:se(Number(e))}const tc=Js.new(void 0,"host-calls");class rc{hostCalls=new Map;missing=new sc;constructor(...e){for(const t of e)I(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=fo(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 k{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 k{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 k{code;memory;registers;constructor(e,t,r){super(),this.code=e,this.memory=t,this.registers=r}}function gc(e,t,r=null){return new hc(e,t,r)}class fc{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=ue.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(),g=r.bytes(d).raw;r.finish();const f=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,w=cc,S=w+lc(n),E=S+lc(n);function C(e){return!1!==e}const k=[o>0&&gc(65536,f,h),n>0&&gc(w,S,t),S<E&&gc(S,E)].filter(C),x=[a>0&&gc(p,m,u),m<b&&gc(m,b),A<I&&gc(A,I)].filter(C);return new dc(g,new uc(k,x,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 jo;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 fc(n,c,d,i)}static fromGeneric(e,t){const{code:r,metadata:s}=t?pc(e):{code:e},i=new io,n=new $o;return new fc(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=ue.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 ut(this.keccakHasher,[e,t])}hashConcatPrepend(e,t,r){return ut(this.keccakHasher,[e,t,r])}header(e){return new Me(Ge(e.encoded(),this.allocator).asOpaque(),e)}extrinsic(e){const t=e.guarantees.view().map(e=>e.view()).map(e=>{const t=Ge(e.report.encoded(),this.allocator).asOpaque();return D.blobFromParts([t.raw,e.slot.encoded().raw,e.credentials.encoded().raw])}),r=me.encodeObject(ke.sequenceVarLen(zi),t,this.context),s=Ge(e.tickets.encoded(),this.allocator).asOpaque(),i=Ge(e.preimages.encoded(),this.allocator).asOpaque(),n=Ge(r,this.allocator).asOpaque(),o=Ge(e.assurances.encoded(),this.allocator).asOpaque(),a=Ge(e.disputes.encoded(),this.allocator).asOpaque(),c=D.blobFromParts([s.raw,i.raw,n.raw,o.raw,a.raw]);return new Pe(Ge(c,this.allocator).asOpaque(),e,c)}workPackage(e){return this.encode(Mr.Codec,e)}encode(e,t){const r=me.encodeObject(e,t,this.context);return new Pe(Ge(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 T.error(mc.PreimagesNotSortedUnique)}const{preimages:t,slot:r}=e,s=[];for(const e of t){const{requester:t,blob:i}=e,n=Ge(i).asOpaque(),o=this.state.getService(t);if(null===o)return T.error(mc.AccountNotFound);const a=o.hasPreimage(n),c=o.getLookupHistory(n,se(i.length));if(a||null===c||!Ci.isRequested(c))return T.error(mc.PreimageUnneeded);s.push(_i.provide({serviceId:t,preimage:wi.create({hash:n,blob:i}),slot:r}))}return T.ok({preimages:s})}}class vc{spec;importer;toImport=yt.fromSortedArray((e,t)=>{const r=e.timeSlot-t.timeSlot;return r<0?d.Greater:r>0?d.Less:d.Equal});lastEpoch=Er(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=Er(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=M.zero(Ne).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 T.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 T.error(bc.ParentNotFound,`Parent ${s.toString()} not found`);const r=t.timeSlotIndex.materialize(),i=e.timeSlotIndex.materialize();if(r<=i)return T.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 T.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?T.error(bc.StateRootNotFound,`Posterior state root ${s.toString()} not found`):o.isEqualTo(a)?T.ok(r.hash):T.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=D.blobFromString("jam_valid").raw,xc=D.blobFromString("jam_invalid").raw,Bc=D.blobFromString("jam_guarantee").raw;function _c({key:e,signature:t,workReportHash:r}){return{key:e,signature:t,message:D.blobFromParts(Bc,r.raw)}}function Rc({workReportHash:e,wasConsideredValid:t,signature:r,key:s}){const i=t?kc:xc;return{key:s,signature:r,message:D.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:D.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 T.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 T.error(Ec.OffenderAlreadyReported);if(!s.has(i))return T.error(Ec.BadGuarantorKey);if(void 0===t.toAddToBadSet.findExact(o))return T.error(Ec.CulpritsVerdictNotBad);const a=r.culprits[n];if(!a?.isValid)return T.error(Ec.BadSignature)}return T.ok(null)}verifyFaults(e,t,r,s){if(!Cc(e.faults,"key"))return T.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 T.error(Ec.OffenderAlreadyReported);if(!s.has(i))return T.error(Ec.BadAuditorKey);if(a){const e=t.toAddToGoodSet.findExact(o),r=t.toAddToBadSet.findExact(o);if(void 0!==e||void 0===r)return T.error(Ec.FaultVerdictWrong)}if(!r.faults[n].isValid)return T.error(Ec.BadSignature)}return T.ok(null)}verifyVerdicts(e,t){if(!Cc(e.verdicts,"workReportHash"))return T.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 T.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 T.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 T.error(Ec.BadValidatorIndex);if(!t.judgements[s].isValid)return T.error(Ec.BadSignature);s+=1}}return T.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 T.error(Ec.AlreadyJudged)}return T.ok(null)}calculateVotesForWorkReports(e){const t=dt.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 T.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 T.error(Ec.NotEnoughCulprits)}else if(s!==this.chainSpec.thirdOfValidators)return T.error(Ec.BadVoteSplit);return T.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:mt.fromArray(di,t),toAddToBadSet:mt.fromArray(di,r),toAddToWonkySet:mt.fromArray(di,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 ai(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=yt.fromArray(di,t);return ui.create({goodSet:mt.fromTwoSortedCollections(this.state.disputesRecords.goodSet,e.toAddToGoodSet),badSet:mt.fromTwoSortedCollections(this.state.disputesRecords.badSet,e.toAddToBadSet),wonkySet:mt.fromTwoSortedCollections(this.state.disputesRecords.wonkySet,e.toAddToWonkySet),punishSet:mt.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 T.error(Ec.BadValidatorIndex);const i=s.ed25519;t.judgements.push(Oc(r,n,i))}}return t.culprits=e.culprits.map(_c),t.faults=e.faults.map(Rc),T.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 gt.from(s)}async transition(e){const t=this.prepareSignaturesToVerification(e);if(t.isError)return T.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 hr(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 T.error(a.error);const c=this.getOffenders(e),l=this.getUpdatedDisputesRecords(i,c),h=this.getClearedCoreAssignment(s);return T.ok({offendersMark:c,stateUpdate:{disputesRecords:l,availabilityAssignment:h}})}}const Tc=D.blobFromString("jam_entropy").raw,Nc=D.blobFromString("jam_fallback_seal").raw,Dc=D.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=D.blobFromParts(t.map(e=>e.raw)).raw,a=await e.verifySeal(o,r,s.raw,i.raw,n.raw);return a[0]===Mc.Error?T.error(null):T.ok(M.fromBlob(a.subarray(1),Ne).asOpaque())},Lc=async function(e,t,r,s){const i=s.length+Dc.length+1,n=D.blobFromParts(r.map(e=>D.blobFromParts([e.signature.raw,Dc,s.raw,Uint8Array.of(e.attempt)]).raw)).raw,o=D.blobFromParts(t.map(e=>e.raw)).raw;try{const t=await e.batchVerifyTicket(o,n,i);return Array.from(D.blobFrom(t).chunks(33)).map(e=>({isValid:e.raw[0]===Mc.Ok,entropyHash:M.fromBlob(e.raw.subarray(1,33),Ne).asOpaque()}))}catch(e){if("RuntimeError: unreachable"==`${e}`)return Array.from({length:r.length},()=>({isValid:!1,entropyHash:M.zero(Ne).asOpaque()}));throw e}},Hc=async function(e,t){const r=D.blobFromParts(t.map(e=>e.raw)).raw,s=await e.getRingCommitment(r);return s[0]===Mc.Error?T.error(null):T.ok(M.fromBlob(s.subarray(1),Ue).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===Ys.parentPort)throw new Error("This method is meant to be run inside a worker thread!");Ys.parentPort.once("close",()=>{process.exit(0)}),Ys.parentPort.once("message",e=>{this.listenTo(e),Ys.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=T.ok(t);e.postMessage(r,t.getTransferList())}).catch(t=>{const r=T.error(`${t}`);e.postMessage(r,[])})})}async run(e){return await this.runInternal(e,this.state)}async destroy(){}}class Vc{workers;maxWorkers;workerPath;static async initialize(e,t){I(t.maxWorkers>0,"Max workers has to be positive."),I(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 Qc(e));return new Vc(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 Qc(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 Qc(e){const{port1:t,port2:r}=new MessageChannel,s=new Ys.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 Gc;!function(e){e[e.RingCommitment=0]="RingCommitment",e[e.BatchVerifyTickets=1]="BatchVerifyTickets",e[e.VerifySeal=2]="VerifySeal"}(Gc||(Gc={}));class $c{data;constructor(e){this.data=e}getTransferList(){return[]}}class jc{params;constructor(e){this.params=e}getTransferList(){return[]}}const qc=Kc.new(e=>{const t=e.params,r=t.method;return r===Gc.RingCommitment?Promise.resolve(new $c((0,Re.hc)(t.keys))):r===Gc.BatchVerifyTickets?Promise.resolve(new $c((0,Re.ZJ)(t.keys,t.ticketsData,t.contextLength))):r===Gc.VerifySeal?Promise.resolve(new $c((0,Re.KG)(t.keys,t.authorIndex,t.signature,t.payload,t.auxData))):void w(r)},null);class zc{executor;constructor(e){this.executor=e}destroy(){return this.executor.destroy()}static async new({synchronous:e}){const t=Ns().cpus().length;return new zc(e?qc:await Vc.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 jc({method:Gc.VerifySeal,keys:e,authorIndex:t,signature:r,payload:s,auxData:i}))).data}async getRingCommitment(e){return(await this.executor.run(new jc({method:Gc.RingCommitment,keys:e}))).data}async batchVerifyTicket(e,t,r){return(await this.executor.run(new jc({method:Gc.BatchVerifyTickets,keys:e,ticketsData:t,contextLength:r}))).data}}const Wc=(e,t)=>q(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=Fe([r.raw,t]).asOpaque();return this.isEpochChanged(e)?pt.new([i,r,s[0],s[1]],4):pt.new([i,...s],4)}async getValidatorKeys(e,t){if(!this.isEpochChanged(e)){const{nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s}=this.state;return T.ok({nextValidatorData:e,currentValidatorData:t,previousValidatorData:r,epochRoot:s})}const r=this.state.designatedValidatorData.map(e=>!1!==t.has(e.ed25519)?yi.create({bandersnatch:M.zero(Oe).asOpaque(),ed25519:M.zero(cr).asOpaque(),bls:M.zero(Te).asOpaque(),metadata:e.metadata}):e),{nextValidatorData:s,currentValidatorData:i}=this.state,n=await Hc(await this.bandersnatch,r.map(e=>e.bandersnatch));return n.isOk?T.ok({nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n.ok}):T.error(Jc.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]),xr(r,this.chainSpec)}fallbackKeySequencer(e,t){const r=this.chainSpec.epochLength,s=[],i=t.length;for(let n=se(0);n<r;n++){const r=ce(n),o=Fe([e.raw,r]).raw,a=ue.fromBlob(o).u32()%i;s.push(t[a].bandersnatch)}return xr(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?Ai.tickets(this.outsideInSequencer(this.state.ticketsAccumulator)):this.isSameEpoch(e)?this.state.sealingKeySeries:Ai.keys(this.fallbackKeySequencer(r,t))}getEpochMark(e,t){if(!this.isEpochChanged(e))return null;const r=this.state.entropy;return Jr.create({entropy:r[0],ticketsEntropy:r[1],validators:t.map(e=>Wr.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 T.error(Jc.DuplicateTicket);if(t.isGreater())return T.error(Jc.BadTicketOrder)}return T.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 T.error(Jc.BadTicketProof);const o=this.verifyTickets(n);if(o.isError)return T.error(o.error);if(this.isEpochChanged(e))return T.ok(n);const a=mt.fromSortedArray(Wc,this.state.ticketsAccumulator),c=mt.fromSortedArray(Wc,n),l=mt.fromTwoSortedCollections(a,c);return a.length+c.length!==l.length?T.error(Jc.DuplicateTicket):T.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 T.error(Jc.BadSlot);if(!this.isExtrinsicLengthValid(e.slot,e.extrinsic))return T.error(Jc.UnexpectedTicket);if(!this.areTicketAttemptsValid(e.extrinsic))return T.error(Jc.BadTicketAttempt);const t=await this.getValidatorKeys(e.slot,e.punishSet);if(t.isError)return T.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 T.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 T.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=D.blobFromParts(Tc,r.ok.raw),i=await Pc(await this.bandersnatch,t.currentValidatorData.map(e=>e.bandersnatch),e.bandersnatchBlockAuthorIndex.materialize(),e.entropySource.materialize(),s,D.blobFromNumbers([]));return i.isError?T.error(Yc.IncorrectEntropySource):T.ok(i.ok)}async verifySeal(e,t){const r=t.currentValidatorData,s=e.bandersnatchBlockAuthorIndex.materialize(),i=r[s];if(void 0===i)return T.error(Yc.InvalidValidatorIndex);const n=e.timeSlotIndex.materialize(),o=t.sealingKeySeries,a=t.currentEntropy;return o.kind===mi.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=D.blobFromParts(Dc,r.raw,new Uint8Array([c])),h=await Pc(await this.bandersnatch,s.map(e=>e.bandersnatch),i,n.seal.materialize(),l,Yr(n));return h.isError?T.error(Yc.IncorrectSeal):a.isEqualTo(h.ok)?T.ok(h.ok):T.error(Yc.InvalidTicket)}async verifySealWithKeys(e,t,r,s,i,n,o){if(!e[r%e.length].isEqualTo(t.bandersnatch))return T.error(Yc.InvalidValidator);const a=D.blobFromParts(Nc,s.raw),c=await Pc(await this.bandersnatch,i.map(e=>e.bandersnatch),n,o.seal.materialize(),a,Yr(o));return c.isError?T.error(Yc.IncorrectSeal):T.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;static Codec=ke.Class(ol,{source:ke.u32.asOpaque(),destination:ke.u32.asOpaque(),amount:ke.u64,memo:ke.bytes(128),gas:ke.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 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:fi.create({...e.privilegedServices,authManager:[...e.privilegedServices.authManager]}),s}}class cl{state;stateUpdate;constructor(e,t=al.empty()){this.state=e,this.stateUpdate=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===ki.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:se(Number(e))}(s);if(null===i||null===e)return null;const n=e.getLookupHistory(r,i);return null===n?null:new Ci(r,i,n)};if(void 0===i)return n();const{action:o}=i;switch(o.kind){case ki.Provide:return new Ci(r,i.length,Ei([e]));case ki.Remove:{const t=n();return null===t?null:new Ci(r,t.length,Ei([...t.slots,e]))}case ki.UpdateOrAdd:return o.item}w(o)}updateStorage(e,t,r){const s=null===r?Oi.remove({serviceId:e,key:t}):Oi.set({serviceId:e,storage:Si.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){if(t.overflow||r.overflow)return T.error("insufficient funds");const i=vi.calculateThresholdBalance(t.value,r.value);return s.balance<i?T.error("insufficient funds"):(this.updateServiceInfo(e,vi.create({...s,storageUtilisationBytes:r.value,storageUtilisationCount:t.value})),T.ok(_))}updateServiceInfo(e,t){const r=this.stateUpdate.services.servicesUpdates.findIndex(t=>t.serviceId===e),s=-1===r?0:1;this.stateUpdate.services.servicesUpdates.splice(r,s,Ri.update({serviceId:e,serviceInfo:t}))}}class ll{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:nl(s.slots);if(i?.status!==Xc.Unavailable)return[!1,"wrong status"];const n=this.currentTimeslot,o=i.data[1]<n-this.chainSpec.preimageExpungePeriod;return[o,o?"":"not expired"]}getNextAvailableServiceId(e){let t=e;const r=2**32-512;for(;;){if(null===this.getServiceInfo(t))return t;t=vr((t-256+1+r)%r+256)}}checkPreimageStatus(e,t){const r=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);return null===r?null:nl(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===Xc.Requested)return T.error(Zc.AlreadyRequested);if(e===Xc.Available||e===Xc.Reavailable)return T.error(Zc.AlreadyAvailable);I(e===Xc.Unavailable)}const s=this.getCurrentServiceInfo(),i=null!==r,n=i?0:2,o=t-BigInt(r?.length??0),a=s.storageUtilisationCount+n,c=s.storageUtilisationBytes+BigInt(o)+(i?0n:81n);I(a>=0,`storageUtilisationCount has to be a positive number, got: ${a}`),I(c>=0,`storageUtilisationBytes has to be a positive number, got: ${c}`);const l=!ie(a),h=!oe(c),u=this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,{overflow:l,value:l?se(0):a},{overflow:h,value:h?ne(0):c},s);if(u.isError)return T.error(Zc.InsufficientFunds,u.details);const d=ec(t);return null===r?this.updatedState.updatePreimage(_i.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new Ci(e,d,Ei([]))})):this.updatedState.updatePreimage(_i.updateOrAdd({serviceId:this.currentServiceId,lookupHistory:new Ci(e,d,Ei([...r.slots,this.currentTimeslot]))})),T.ok(_)}forgetPreimage(e,t){const r=this.currentServiceId,s=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);if(null===s)return T.error(null);const i=nl(s.slots);if(i.status===Xc.Requested)return this.updatedState.updatePreimage(_i.remove({serviceId:r,hash:s.hash,length:s.length})),T.ok(_);const n=this.currentTimeslot;return i.status===Xc.Unavailable?i.data[1]<n-this.chainSpec.preimageExpungePeriod?(this.updatedState.updatePreimage(_i.remove({serviceId:r,hash:s.hash,length:s.length})),T.ok(_)):T.error(null):i.status===Xc.Available?(this.updatedState.updatePreimage(_i.updateOrAdd({serviceId:r,lookupHistory:new Ci(s.hash,s.length,Ei([i.data[0],n]))})),T.ok(_)):i.status===Xc.Reavailable?i.data[1]<n-this.chainSpec.preimageExpungePeriod?(this.updatedState.updatePreimage(_i.updateOrAdd({serviceId:r,lookupHistory:new Ci(s.hash,s.length,Ei([i.data[2],n]))})),T.ok(_)):T.error(null):void w(i)}transfer(e,t,r,s){const i=this.getCurrentServiceInfo(),n=this.getServiceInfo(e);if(null===n||null===e)return T.error(el.DestinationNotFound);if(r<n.onTransferMinGas)return T.error(el.GasTooLow);const o=i.balance-t;return o<vi.calculateThresholdBalance(i.storageUtilisationCount,i.storageUtilisationBytes)?T.error(el.BalanceBelowThreshold):(this.updatedState.stateUpdate.transfers.push(ol.create({source:this.currentServiceId,destination:e,amount:t,memo:s,gas:r})),this.updatedState.updateServiceInfo(this.currentServiceId,vi.create({...i,balance:ne(o)})),T.ok(_))}newService(e,t,r,s){const i=this.nextNewServiceId,n=se(2),o=ae(ne(81),t),a=ec(t),c=vi.calculateThresholdBalance(n,o.value),l=this.getCurrentServiceInfo(),h=vi.calculateThresholdBalance(l.storageUtilisationCount,l.storageUtilisationBytes),u=l.balance-c;return u<h||o.overflow?T.error("insufficient funds"):(this.updatedState.stateUpdate.services.servicesUpdates.push(Ri.create({serviceId:i,serviceInfo:vi.create({codeHash:e,balance:c,accumulateMinGas:r,onTransferMinGas:s,storageUtilisationBytes:o.value,storageUtilisationCount:n}),lookupHistory:new Ci(e.asOpaque(),a,Ei([]))})),this.updatedState.updateServiceInfo(this.currentServiceId,vi.create({...l,balance:ne(u)})),this.nextNewServiceId=this.getNextAvailableServiceId(function(e){const t=2**32-512;return vr(256+(e-256+42+t)%t)}(i)),T.ok(i))}upgradeService(e,t,r){const s=this.getCurrentServiceInfo();this.updatedState.updateServiceInfo(this.currentServiceId,vi.create({...s,codeHash:e,accumulateMinGas:wr(t),onTransferMinGas:wr(r)}))}updateValidatorsData(e){this.updatedState.stateUpdate.validatorsData=e}checkpoint(){this.checkpointedState=al.copyFrom(this.updatedState.stateUpdate)}updateAuthorizationQueue(e,t){this.updatedState.stateUpdate.authorizationQueues.set(e,t)}updatePrivilegedServices(e,t,r,s){this.updatedState.stateUpdate.privilegedServices=fi.create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s.map(([e,t])=>gi.create({service:e,gasLimit:t}))})}yield(e){this.updatedState.stateUpdate.yieldedRoot=e}providePreimage(e,t){if(null===(null===e?null:this.updatedState.state.getService(e))||null===e)return T.error(rl.ServiceNotFound);const r=Ge(t).asOpaque(),s=this.updatedState.getLookupHistory(this.currentTimeslot,e,r,ne(t.length));return null!==s&&Ci.isRequested(s)?this.updatedState.hasPreimage(e,r)?T.error(rl.AlreadyProvided):(this.updatedState.updatePreimage(_i.provide({serviceId:e,preimage:wi.create({hash:r,blob:t}),slot:this.currentTimeslot})),T.ok(_)):T.error(rl.WasNotRequested)}eject(e,t){const r=this.getServiceInfo(e);if(null===r||null===e)return T.error(tl.InvalidService,"Service missing");const s=this.getCurrentServiceInfo(),i=M.zero(Ne).asOpaque();if(Za(this.currentServiceId,i.raw),!r.codeHash.isEqualTo(i))return T.error(tl.InvalidService,"Invalid code hash");if(2!==r.storageUtilisationCount)return T.error(tl.InvalidPreimage,"Too many storage items");const n=ne(81),o=ne(((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 T.error(tl.InvalidPreimage,`Previous code available: ${c}`);const l=ae(s.balance,r.balance);return l.overflow?T.error(tl.InvalidService,"Balance overflow"):(this.updatedState.updateServiceInfo(this.currentServiceId,vi.create({...s,balance:l.value})),this.updatedState.stateUpdate.services.servicesRemoved.push(e),T.ok(_))}read(e,t){return null===e?null:this.updatedState.getStorage(e,t)}write(e,t){const r=this.read(this.currentServiceId,e),s=null===r&&null!==t,i=null!==r&&null===t,n=s?1:i?-1:0,o=(t?.length??0)-(r?.length??0),a=s?BigInt(Ne):i?BigInt(-32):0n,c=this.getCurrentServiceInfo(),l=c.storageUtilisationCount+n,h=c.storageUtilisationBytes+BigInt(o)+a;I(l>=0,`storageUtilisationCount has to be a positive number, got: ${l}`),I(h>=0,`storageUtilisationBytes has to be a positive number, got: ${h}`);const u=!ie(l),d=!oe(h),g=this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,{overflow:u,value:u?se(0):l},{overflow:d,value:d?ne(0):h},c);return g.isError?T.error("full",g.details):(this.updatedState.updateStorage(this.currentServiceId,e,t),T.ok(_))}readSnapshotLength(e){const t=this.updatedState.state.getService(this.currentServiceId);return t?.getStorage(e)?.length??null}lookup(e,t){return null===e?null:this.updatedState.getPreimage(e,t)}}function hl(e){const t=e.map(e=>e.workPackageSpec.hash);return gt.from(t)}const ul=ke.object({serviceId:ke.u32.asOpaque(),entropy:ke.bytes(Ne).asOpaque(),timeslot:ke.u32.asOpaque()}),dl=ke.object({serviceId:ke.u32.convert(e=>e,e=>e),gas:ke.u64.convert(e=>ne(e),e=>wr(e))});class gl{currentServiceId;index=Zn(0);gasCost=fo(10);constructor(e){this.currentServiceId=e}execute(e,t){return t.set(7,ne(e.get())),Promise.resolve(void 0)}}const fl=fe(yi.Codec.sizeHint),pl=e=>ne(e);var yl,ml,bl;!function(e){e[e.SourcePageFault=0]="SourcePageFault",e[e.DestinationPageFault=1]="DestinationPageFault",e[e.NoMachine=2]="NoMachine"}(yl||(yl={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidPage=1]="InvalidPage"}(ml||(ml={})),Symbol("Machine index not found."),Symbol("Too many segments already exported.");class Al{currentServiceId;fetch;index=Zn(18);gasCost=fo(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=ne(s?.length??0),o=he(t.get(8),n),a=he(t.get(9),ne(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===bl.Constants)return this.fetch.constants();if(t===bl.Entropy)return this.fetch.entropy();if(t===bl.AuthorizerTrace)return this.fetch.authorizerTrace();if(t===bl.OtherWorkItemExtrinsics){const t=e.get(11),r=e.get(12);return this.fetch.workItemExtrinsic(t,r)}if(t===bl.MyExtrinsics){const t=e.get(11);return this.fetch.workItemExtrinsic(null,t)}if(t===bl.OtherWorkItemImports){const t=e.get(11),r=e.get(12);return this.fetch.workItemImport(t,r)}if(t===bl.MyImports){const t=e.get(11);return this.fetch.workItemImport(null,t)}if(t===bl.WorkPackage)return this.fetch.workPackage();if(t===bl.Authorizer)return this.fetch.authorizer();if(t===bl.AuthorizationToken)return this.fetch.authorizationToken();if(t===bl.RefineContext)return this.fetch.refineContext();if(t===bl.AllWorkItems)return this.fetch.allWorkItems();if(t===bl.OneWorkItem){const t=e.get(11);return this.fetch.oneWorkItem(t)}if(t===bl.WorkItemPayload){const t=e.get(11);return this.fetch.workItemPayload(t)}if(t===bl.AllOperands)return this.fetch.allOperands();if(t===bl.OneOperand){const t=e.get(11);return this.fetch.oneOperand(t)}if(t===bl.AllTransfers)return this.fetch.allTransfers();if(t===bl.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"}(bl||(bl={}));class Il{currentServiceId;account;index=Zn(4);gasCost=fo(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?D.empty():me.encodeObject(vl,{...n,thresholdBalance:vi.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 vl=ke.object({codeHash:ke.bytes(Ne),balance:ke.u64,thresholdBalance:ke.u64,accumulateMinGas:ke.u64.convert(e=>e,wr),onTransferMinGas:ke.u64.convert(e=>e,wr),storageUtilisationBytes:ke.u64,storageUtilisationCount:ke.u32},"ServiceAccountInfoWithThresholdBalance"),wl=Js.new(void 0,"host-calls"),Sl=new TextDecoder("utf8");class El{currentServiceId;index=Zn(100);gasCost=fo(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),wl.trace(`[${this.currentServiceId}] [${s}] ${Sl.decode(c)} ${Sl.decode(l)}`),Promise.resolve(void 0)}}class Cl{currentServiceId;account;index=Zn(1);gasCost=fo(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=M.zero(Ne);if(r.loadInto(o.raw,i).isError)return eo.Panic;const a=this.account.lookup(s,o),c=ne(null===a?0:a.raw.length),l=t.get(10),h=t.get(11),u=he(l,c),d=he(h,ne(c-u)),g=null===a?new Uint8Array(0):a.raw.subarray(Number(u),Number(u+d));if(r.storeFrom(n,g).isError)return eo.Panic;null!==a?t.set(7,c):t.set(7,qa.NONE)}}class kl{currentServiceId;account;index=Zn(2);gasCost=fo(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=Ge(c),h=this.account.read(s,l),u=ne(null===h?0:h.raw.length),d=t.get(11),g=t.get(12),f=he(d,u),p=he(g,ne(u-f)),y=null===h?new Uint8Array(0):h.raw.subarray(Number(f),Number(f+p));if(r.storeFrom(o,y).isError)return eo.Panic;null!==h?t.set(7,u):t.set(7,qa.NONE)}}class xl{currentServiceId;account;index=Zn(3);gasCost=fo(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=Ge(c),h=ec(o),u=new Uint8Array(h);if(r.loadInto(u,n).isError)return eo.Panic;const d=0n===o?null:D.blobFrom(u);if(this.account.write(l,d).isError)return void t.set(7,qa.FULL);const g=this.account.readSnapshotLength(l);t.set(7,null===g?qa.NONE:ne(g))}}const Bl=[class{currentServiceId;partialState;chainSpec;index=Zn(5);gasCost=fo(10);constructor(e,t,r){this.currentServiceId=e,this.partialState=t,this.chainSpec=r}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(fe(dl.sizeHint)),h=ue.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(dl);c.push([e,t]),u=ne(u+ne(h.bytesRead()))}null!==s&&null!==i&&null!==n?(this.partialState.updatePrivilegedServices(s,ai(new Array(this.chainSpec.coresCount).fill(i),this.chainSpec),n,c),t.set(7,qa.OK)):t.set(7,qa.WHO)}},class{currentServiceId;partialState;chainSpec;index=Zn(6);gasCost=fo(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=ue.fromBlob(n).sequenceFixLen(ke.bytes(Ne),80),a=pt.new(o,80);t.set(7,qa.OK),this.partialState.updateAuthorizationQueue(Sr(Number(s)),a)}},class{currentServiceId;partialState;chainSpec;index=Zn(7);gasCost=fo(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(fl*this.chainSpec.validatorsCount);if(r.loadInto(i,s).isError)return eo.Panic;const n=ue.fromBlob(i).sequenceFixLen(yi.Codec,this.chainSpec.validatorsCount);t.set(7,qa.OK),this.partialState.updateValidatorsData(Cr(n,this.chainSpec))}},class{currentServiceId;partialState;index=Zn(8);gasCost=fo(10);gasHostCall;constructor(e,t){this.currentServiceId=e,this.partialState=t,this.gasHostCall=new gl(e)}async execute(e,t){await this.gasHostCall.execute(e,t),this.partialState.checkpoint()}},class{currentServiceId;partialState;index=Zn(9);gasCost=fo(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=wr(t.get(9)),o=wr(t.get(10)),a=M.zero(Ne);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,ne(c.ok)):t.set(7,qa.CASH)}},class{currentServiceId;partialState;index=Zn(10);gasCost=fo(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=M.zero(Ne);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=wr(t.get(9)),o=t.get(10),a=M.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?w(l):t.set(7,qa.CASH):t.set(7,qa.LOW):t.set(7,qa.WHO)}},class{currentServiceId;partialState;index=Zn(12);gasCost=fo(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=M.zero(Ne).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):w(a)}},class{currentServiceId;partialState;index=Zn(13);gasCost=fo(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=M.zero(Ne);if(r.loadInto(n.raw,s).isError)return eo.Panic;const o=this.partialState.checkPreimageStatus(n.asOpaque(),i),a=ne(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,ne(1n+(BigInt(o.data[0])<<32n))),void t.set(8,a);case Xc.Unavailable:return t.set(7,ne(2n+(BigInt(o.data[0])<<32n))),void t.set(8,ne(o.data[1]));case Xc.Reavailable:return t.set(7,ne(3n+(BigInt(o.data[0])<<32n))),void t.set(8,ne((BigInt(o.data[2])<<32n)+BigInt(o.data[1])))}}},class{currentServiceId;partialState;index=Zn(14);gasCost=fo(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=M.zero(Ne);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?w(a):t.set(7,qa.FULL):t.set(7,qa.HUH)}},class{currentServiceId;partialState;index=Zn(15);gasCost=fo(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=M.zero(Ne);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=fo(10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=M.zero(Ne);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=fo(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=D.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?w(c):t.set(7,qa.HUH):t.set(7,qa.WHO)}}];var _l;!function(e){e.IS_AUTHORIZED=pl(0),e.REFINE=pl(0),e.ACCUMULATE=pl(5),e.ON_TRANSFER=pl(10)}(_l||(_l={}));class Rl{serviceCode;entrypoint;pvm;hostCalls;pvmInstanceManager=new ja(4);constructor(e,t,r){this.serviceCode=e,this.entrypoint=r,this.hostCalls=new rc(...t),this.pvm=new $a(this.pvmInstanceManager,this.hostCalls)}static prepareAccumulateHostCalls(e,t,r){const s=Bl.map(s=>new s(e,t.partialState,r)),i=[new El(e),new gl(e),new kl(e,t.serviceExternalities),new xl(e,t.serviceExternalities),new Al(e,t.fetchExternalities),new Cl(e,t.serviceExternalities),new Il(e,t.serviceExternalities)];return s.concat(i)}static prepareOnTransferHostCalls(e,t){return[new El(e),new gl(e),new kl(e,t.partialState),new xl(e,t.partialState),new Cl(e,t.partialState),new Il(e,t.partialState)]}async run(e,t){const r=fc.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=Rl.prepareAccumulateHostCalls(e,r,s);return new Rl(t,i,_l.ACCUMULATE)}static createOnTransferExecutor(e,t,r){const s=Rl.prepareOnTransferHostCalls(e,r);return new Rl(t,s,_l.ON_TRANSFER)}}const Ol=ke.object({timeslot:ke.u32.asOpaque(),serviceId:ke.u32.asOpaque(),transfers:ke.sequenceVarLen(ol.Codec)});var Ul;!function(e){e[e.ServiceBalanceOverflow=1]="ServiceBalanceOverflow",e[e.ServiceInfoNotExist=2]="ServiceInfoNotExist"}(Ul||(Ul={}));const Tl=Js.new(void 0,"deferred-transfers");class Nl{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}getPotentiallyUpdatedServiceInfo(e,t,r){if(r.includes(e))return null;const s=t.find(t=>t.serviceId===e);return void 0!==s?s.action.account:this.state.getService(e)?.getInfo()??null}getPotentiallyUpdatedPreimage(e,t,r){const s=e.findLast(e=>e.serviceId===t&&e.hash.isEqualTo(r));if(void 0===s)return this.state.getService(t)?.getPreimage(r)??null;switch(s.action.kind){case ki.Provide:return s.action.preimage.blob;case ki.Remove:return null;case ki.UpdateOrAdd:return this.state.getService(t)?.getPreimage(r)??null}}async transition({pendingTransfers:e,timeslot:t,servicesUpdates:r,servicesRemoved:s,preimages:i}){const n=new Map,o=[...r],a=[],c=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]));for(const r of c){const c=e.filter(e=>e.destination===r),l=this.getPotentiallyUpdatedServiceInfo(r,o,s);if(null===l)return T.error(Ul.ServiceInfoNotExist);const h=l.codeHash,u=this.getPotentiallyUpdatedPreimage(i,r,h.asOpaque()),d=o.findIndex(e=>e.serviceId===r),g=ae(l.balance,...c.map(e=>e.amount));if(g.overflow)return T.error(Ul.ServiceBalanceOverflow);const f=vi.create({...l,balance:g.value}),p=Ri.update({serviceId:r,serviceInfo:f});if(d<0||o[d].action.kind===xi.Create?o.push(p):o[d]=p,null===u||0===c.length){Tl.trace(`Skipping ON_TRANSFER execution for service ${r}, code is null or no transfers`),n.set(r,{count:se(c.length),gasUsed:wr(0)});continue}const y=new ll(this.chainSpec,new cl(this.state),r,r,t),m=Rl.createOnTransferExecutor(r,u,{partialState:y}),b=me.encodeObject(Ol,{timeslot:t,serviceId:r,transfers:c},this.chainSpec),A=c.reduce((e,t)=>e+t.gas,0n),{consumedGas:I}=await m.run(b,yo(A)),[v]=y.getStateUpdates();a.push(...v.services.storage),n.set(r,{count:se(c.length),gasUsed:wr(I)})}return T.ok({servicesUpdates:o,storageUpdates:a,transferStatistics:n})}}class Dl extends k{static Codec=ke.Class(Dl,{hash:ke.bytes(Ne).asOpaque(),exportsRoot:ke.bytes(Ne).asOpaque(),authorizerHash:ke.bytes(Ne).asOpaque(),payloadHash:ke.bytes(Ne),gas:ke.varU64.asOpaque(),result:Hr.Codec,authorizationOutput:ke.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 Dl({gas:wr(s),payloadHash:n.asOpaque(),result:o,authorizationOutput:D.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 Dl(e)}}class Ml{static Codec=ke.Class(Ml,{hash:ke.bytes(Ne).asOpaque(),exportsRoot:ke.bytes(Ne).asOpaque(),authorizerHash:ke.bytes(Ne).asOpaque(),authorizationOutput:ke.blob,payloadHash:ke.bytes(Ne),result:Hr.Codec});hash;exportsRoot;authorizerHash;authorizationOutput;payloadHash;result;static create({authorizationOutput:e,authorizerHash:t,exportsRoot:r,hash:s,payloadHash:i,result:n}){return new Ml({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 Ml(e)}}class Pl{operands;reportsLength;gasCost;constructor(e,t,r){this.operands=e,this.reportsLength=t,this.gasCost=r}static empty(){return new Pl([],se(0),wr(0n))}}class Ll{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)??Pl.empty();n.reportsLength=se(n.reportsLength+1),n.gasCost=wr(n.gasCost+e.gas),n.operands.push(Dl.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=wr(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??se(0)}getGasCost(e){return this.reportsDataByServiceId.get(e)?.gasCost??wr(0n)}getServiceIds(){return this.serviceIds}}class Hl{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(gt.from(e.context.prerequisites.concat(e.segmentRootLookup.map(e=>e.workPackageHash))))}getWorkReportsToAccumulateLater(e){const t=this.state.recentlyAccumulated.flatMap(e=>Array.from(e));return Kl(e.filter(e=>e.context.prerequisites.length>0||e.segmentRootLookup.length>0).map(e=>Gi.create({report:e,dependencies:this.getWorkReportDependencies(e)})),gt.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=Kl(r,hl(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 Kl(e,t){return e.filter(({report:e})=>!t.has(e.workPackageSpec.hash)).map(e=>{const{report:r,dependencies:s}=e;return Gi.create({report:r,dependencies:s.filter(e=>!t.has(e))})})}var Vl;!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"}(Vl||(Vl={}));class Ql{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=pt.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 T.error(Vl.InvalidAnchor,`anchor: expected: ${e.parentHash}, got ${s}`);if(n>=o)return T.error(Vl.InvalidOrder,`order: expected: ${n+1}, got: ${o}`);n=r.validatorIndex,I(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 T.error(Vl.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 T.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 T.error(Vl.InvalidValidatorIndex);r.push({signature:e.signature.materialize(),key:i.ed25519,message:Gl(e.anchor.encoded(),e.bitfield.encoded())})}const s=await hr(r),i=s.every(e=>e);if(!i){const e=s.reduce((e,t,r)=>t?e:e.concat(r),[]);return T.error(Vl.InvalidSignature,`invalid signatures at ${e.join(", ")}`)}return T.ok(_)}}const Fl=D.blobFromString("jam_available").raw;function Gl(e,t){return D.blobFromParts(Fl,Ge(D.blobFromParts(e.raw,t.raw)).raw)}const $l=D.blobFromString("peak");class jl{hasher;mountains;static empty(e){return new jl(e)}static fromPeaks(e,t){return new jl(e,t.peaks.reduce((e,t,r)=>(null!==t&&e.push(ql.fromPeak(t,2**r)),e),[]).reverse())}constructor(e,t=[]){this.hasher=e,this.mountains=t}append(e){let t=ql.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 M.zero(Ne).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($l,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 ql{peak;size;constructor(e,t){this.peak=e,this.size=t}static fromPeak(e,t){return new ql(e,t)}static fromChildren(e,t){const[r,s]=t,i=e.hashConcat(r.peak,s.peak),n=r.size+s.size;return new ql(i,n)}mergeWith(e,t){return ql.fromChildren(e,[this,t])}toString(){return`${this.size} @ ${this.peak}`}}var zl;!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"}(zl||(zl={}));const Wl=ke.object({B_I:ke.u64,B_L:ke.u64,B_S:ke.u64,C:ke.u16,D:ke.u32,E:ke.u32,G_A:ke.u64,G_I:ke.u64,G_R:ke.u64,G_T:ke.u64,H:ke.u16,I:ke.u16,J:ke.u16,L:ke.u32,O:ke.u16,P:ke.u16,Q:ke.u16,R:ke.u16,S:ke.u16,T:ke.u16,U:ke.u16,V:ke.u16,W_A:ke.u16,W_B:ke.u32,W_C:ke.u32,W_E:ke.u32,W_G:ke.u32,W_M:ke.u32,W_P:ke.u32,W_R:ke.u32,W_T:ke.u32,W_X:ke.u32,Y:ke.u32}),Jl=new Map;class Yl{entropyHash;operands;chainSpec;constructor(e,t,r){this.entropyHash=e,this.operands=t,this.chainSpec=r}constants(){return function(e){const t=Jl.get(e);if(void 0!==t)return t;const r=me.encodeObject(Wl,{B_I:ne(10n),B_L:ne(1n),B_S:ne(100n),C:te(e.coresCount),D:se(e.preimageExpungePeriod),E:se(e.epochLength),G_A:ne(Zl),G_I:ne(5e7),G_R:ne(5e9),G_T:ne(eh),H:te(8),I:te(Dr),J:te(8),L:se(14400),O:te(8),P:te(e.slotDuration),Q:te(80),R:te(0),S:te(1024),T:te(e.rotationPeriod),U:te(5),V:te(0),W_A:te(e.validatorsCount),W_B:se(13794305),W_C:se(4e6),W_E:se(684),W_G:se(4104),W_M:se(3072),W_P:se(6),W_R:se(49152),W_T:se(128),W_X:se(3072),Y:se(e.contestLength)});return Jl.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 A.is(h.V0_6_4)?me.encodeObject(ke.sequenceVarLen(Ml.Codec),this.operands,this.chainSpec):me.encodeObject(ke.sequenceVarLen(Dl.Codec),this.operands,this.chainSpec)}oneOperand(e){if(e>=2n**32n)return null;const t=this.operands[Number(e)];return void 0===t?null:A.isGreaterOrEqual(h.V0_6_5)?me.encodeObject(Dl.Codec,t,this.chainSpec):me.encodeObject(Ml.Codec,t,this.chainSpec)}allTransfers(){return null}oneTransfer(e){return null}}var Xl;!function(e){e[e.NoService=0]="NoService",e[e.NoPreimage=1]="NoPreimage"}(Xl||(Xl={}));const Zl=10000000n,eh=3500000000n,th=Js.new(void 0,"accumulate"),rh=ke.object({slot:ke.u32.asOpaque(),serviceId:ke.u32.asOpaque(),operands:ke.sequenceVarLen(Ml.Codec)}),sh=ke.object({slot:ke.u32.asOpaque(),serviceId:ke.u32.asOpaque(),operands:ke.sequenceVarLen(Dl.Codec)}),ih=ke.object({slot:ke.varU32.asOpaque(),serviceId:ke.varU32.asOpaque(),operands:ke.varU32});class nh{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 o=this.state.getService(t);if(null===o)return th.log(`Service with id ${t} not found.`),T.error(Xl.NoService);const a=o.getInfo().codeHash,c=o.getPreimage(a.asOpaque());if(null===c)return th.log(`Code with hash ${a} not found for service ${t}.`),T.error(Xl.NoPreimage);const l=function({serviceId:e,entropy:t,timeslot:r},s){const i=le(Ge(me.encodeObject(ul,{serviceId:e,entropy:t,timeslot:r},s)).raw.subarray(0,4))>>>0;return vr(i%(2**32-512)+256)}({serviceId:t,entropy:i,timeslot:e},this.chainSpec),u=new ll(this.chainSpec,new cl(this.state,n),t,l,e),d={partialState:u,serviceExternalities:u,fetchExternalities:new Yl(i,r,this.chainSpec)},g=Rl.createAccumulateExecutor(t,c,d,this.chainSpec);let f=D.empty();f=A.is(h.V0_6_4)?me.encodeObject(rh,{slot:e,serviceId:t,operands:r},this.chainSpec):A.is(h.V0_6_5)?me.encodeObject(sh,{slot:e,serviceId:t,operands:r},this.chainSpec):me.encodeObject(ih,{slot:e,serviceId:t,operands:se(r.length)});const p=await g.run(f,yo(s)),[y,m]=u.getStateUpdates();if(p.hasStatus()){const e=p.status;if(e===Yn.OOG||e===Yn.PANIC)return T.ok({stateUpdate:m,consumedGas:wr(p.consumedGas)})}if(p.hasMemorySlice()&&p.memorySlice.length===Ne){const e=M.fromBlob(p.memorySlice,Ne);y.yieldedRoot=e.asOpaque()}return T.ok({stateUpdate:y,consumedGas:wr(p.consumedGas)})}async accumulateSingleService(e,t,r,s,i,n){th.trace(`Accumulating service ${e}, items: ${t.length} at slot: ${s}.`);const o=await this.pvmAccumulateInvocation(s,e,t,r,i,n);return o.isError?(th.trace(`Accumulation failed for ${e}.`),{stateUpdate:null,consumedGas:r}):(th.trace(`Accumulation successful for ${e}.`),o.ok)}async accumulateSequentially(e,t,r,s,i,n){const o=this.findReportCutoffIndex(e,t);if(0===o)return{accumulatedReports:se(0),gasCost:wr(0),yieldedRoots:[],pendingTransfers:[],stateUpdates:[]};const a=t.slice(0,o),c=this.state.privilegedServices.autoAccumulateServices,l=new Ll(a,c),h=t.slice(o),{gasCost:u,yieldedRoots:d,pendingTransfers:g,stateUpdates:f,...p}=await this.accumulateInParallel(l,r,s,i,n);S(p);const y=this.mergeServiceStateUpdates(f);if(y.isError)throw new Error("we should be returning Result here");const{accumulatedReports:m,gasCost:b,yieldedRoots:A,pendingTransfers:I,stateUpdates:v,...w}=await this.accumulateSequentially(wr(e-u),h,r,s,i,y.ok);return S(w),{accumulatedReports:se(o+m),gasCost:wr(u+b),yieldedRoots:d.concat(A),pendingTransfers:g.concat(I),stateUpdates:f.concat(v)}}async accumulateInParallel(e,t,r,s,i){const n=e.getServiceIds(),o=[];let a=wr(0);const c=[],l=[];for(const h of n){const{consumedGas:n,stateUpdate:u}=await this.accumulateSingleService(h,e.getOperands(h),e.getGasCost(h),t,r,al.copyFrom(i));a=wr(a+n);const d=s.get(h)??{count:se(0),gasUsed:wr(0)};d.count=se(d.count+e.getReportsLength(h)),d.gasUsed=wr(d.gasUsed+n),s.set(h,d),null!==u&&(o.push([h,u]),l.push(...u.transfers),null!==u.yieldedRoot&&c.push([h,u.yieldedRoot]))}return{stateUpdates:o,pendingTransfers:l,yieldedRoots:c,gasCost: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,authManager:t,validatorsManager:r,autoAccumulateServices:s}=h.privilegedServices;I(null===i,"Only one service can update privileged services!"),i=fi.create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s})}if(null!==h.authorizationQueues)for(const[e,r]of h.authorizationQueues)l===t[e]&&(n[e]=r,o=!0);l===s&&null!==h.validatorsData&&(I(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===xi.Create){if(h.has(e.serviceId))return T.error("duplicate service created",`duplicate service ${e.serviceId} has been created!`);h.add(e.serviceId)}const u=al.new(l);if(null!==i&&(u.privilegedServices=i),null!==a&&(u.validatorsData=a),o)for(const[e,t]of n.entries())u.authorizationQueues.set(Sr(e),t);return T.ok(u)}getAccumulationStateUpdate(e,t,r){const s=this.chainSpec.epochLength,i=r%s,n=hl(e),o=Array.from(n).sort((e,t)=>di(e,t).value),a=xr(this.state.recentlyAccumulated.slice(1).concat(gt.from(o)),this.chainSpec),c=this.state.accumulationQueue.slice();c[i]=Kl(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]=Kl(c[t],n)}return{recentlyAccumulated:a,accumulationQueue:xr(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=wr(eh>e?eh:e);return wr(t)}async transition({reports:e,slot:t,entropy:r}){const s=new Map,i=new Hl(this.chainSpec,this.state),n=i.getWorkReportsToAccumulateImmediately(e),o=i.getWorkReportsToAccumulateLater(e),a=Kl(i.getQueueFromState(t).concat(o),hl(n)),c=i.enqueueReports(a),l=n.concat(c),h=this.getGasLimit(),{accumulatedReports:u,yieldedRoots:d,gasCost:g,pendingTransfers:f,stateUpdates:p,...y}=await this.accumulateSequentially(h,l,t,r,s,al.empty());S(y);const m=l.slice(0,u),b=this.getAccumulationStateUpdate(m,o,t),A=this.mergeServiceStateUpdates(p);if(A.isError)return A;const I=await async function(e){const t=await ht.create(),r=(s=t,{hashConcat:(e,t=[])=>ut(s,[e,...t].map(D.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 M.zero(Ne).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(D.blobFromString("node").raw,[e(i,r).raw,e(n,r).raw])}(e,t)}(e.sort((e,t)=>e[0]-t[0]).map(([e,t])=>D.blobFromParts([ce(e),t.raw])),r)}(d);return T.ok({root:I,stateUpdate:{...b,...A.ok.services},accumulationStatistics:s,pendingTransfers:f})}}class oh{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}transition(e){const t=this.state.authPools.slice();for(let r=Sr(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]=ft(s)}return{authPools:ai(t,this.chainSpec)}}}class ah{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?jl.fromPeaks(this.hasher,r.mmr):jl.empty(this.hasher);return s.append(e.accumulateRoot),t.push({headerHash:e.headerHash,mmr:s.getPeaks(),postStateRoot:M.zero(Ne).asOpaque(),reported:e.workPackages}),t.length>8&&t.shift(),{recentBlocks:t}}}function ch(e,t,r){return function(e,t,r){const s=lh(Ar(t%r.epochLength),r.rotationPeriod),i=(n=function(e,t){I(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(ce(se(Math.floor(e/8))),32);const t=4*e%32,i=t+4,n=le(Ge(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)=>Sr(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 lh(e,t){return Math.floor(e/t)}const hh=D.blobFromString("jam_guarantee").raw;function uh(e){return D.blobFromParts(hh,e.raw)}const dh=1e7;class gh{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 T.error(zl.OutOfOrderGuarantee,`Core indices of work reports are not unique or in order. Got: ${e}, expected at least: ${s+1}`);if(e>=r)return T.error(zl.BadCoreIndex,`Invalid core index. Got: ${e}, max: ${r}`);s=e}return T.ok(_)}(e.guarantees,this.chainSpec);if(t.isError)return t;const r=function(e){for(const t of e){const e=t.view().report.view(),r=e.context.view().prerequisites.view().length,s=e.segmentRootLookup.view().length;if(r+s>8)return T.error(zl.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 T.error(zl.WorkReportTooBig,`Work report at ${e.coreIndex.materialize()} too big. Got ${i} + ${n}, max: 49152`)}return T.ok(_)}(e.guarantees);if(r.isError)return r;const s=this.workReportHashes(e.guarantees),i=this.verifyCredentials(e,s);if(i.isError)return i;const n=hr(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]=ni.create({workReport:new Me(i,r),timeout:e.slot}),l+=1}return T.ok({stateUpdate:{availabilityAssignment:ai(h,this.chainSpec)},reported:a.ok,reporters:mt.fromArray(q,i.ok.map(e=>e.key)).slice()})}workReportHashes(e){const t=[];for(const r of e)t.push(x(Ge(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<$r[0]||l.length>$r[1])return T.error(zl.InsufficientGuarantees,`Invalid number of credentials. Expected ${$r}, 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 T.error(zl.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 T.error(zl.BadValidatorIndex,`Invalid validator index: ${r}`);if(n.core!==a)return T.error(zl.WrongAssignment,`Invalid core assignment for validator ${r}. Expected: ${n.core}, got: ${a}`);i.push({signature:s,key:n.ed25519,message:uh(c)})}}return T.ok(i)}(e.guarantees,t,e.slot,(t,r)=>this.getGuarantorAssignment(t,r,e.newEntropy))}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 T.error(zl.CoreEngaged,`Report pending availability at core: ${n}`);const o=e.authorizerHash;if(void 0===r[n].find(e=>e.isEqualTo(o)))return T.error(zl.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 T.error(zl.BadServiceId,`No service with id: ${t.serviceId}`);const r=e.getInfo();if(t.gas<r.accumulateMinGas)return T.error(zl.ServiceItemGasTooLow,`Service (${t.serviceId}) gas is less than minimal. Got: ${t.gas}, expected at least: ${r.accumulateMinGas}`)}const a=ae(...e.results.map(e=>e.gas));if(a.overflow||a.value>dh)return T.error(zl.WorkReportGasTooHigh,`Total gas too high. Got: ${a.value} (ovfl: ${a.overflow}), maximal: ${dh}`)}return T.ok(_)}(e,this.state.availabilityAssignment,this.state.authPools,e=>this.state.getService(e))}verifyContextualValidity(e){return function(e,t,r,s){const i=[],n=dt.new(),o=gt.new(),a=gt.new();for(const r of e.guarantees){const e=r.materialize();i.push(e.report.context);const s=Fr.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 T.error(zl.BadServiceId,`No service with id: ${r.serviceId}`);if(!r.codeHash.isEqualTo(e.getInfo().codeHash))return T.error(zl.BadCodeHash,`Service (${r.serviceId}) code hash mismatch. Got: ${r.codeHash}, expected: ${e.getInfo().codeHash}`)}}if(n.size!==e.guarantees.length)return T.error(zl.DuplicatePackage,"Duplicate work package detected.");const c=function(e,t,r,s,i){const n=dt.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 T.error(zl.AnchorNotRecent,`Anchor block ${r.anchor} not found in recent blocks.`);if(!t.postStateRoot.isEqualTo(r.stateRoot))return T.error(zl.BadStateRoot,`Anchor state root mismatch. Got: ${r.stateRoot}, expected: ${t.postStateRoot}.`);const o=jl.fromPeaks(s,t.mmr).getSuperPeakHash();if(!o.isEqualTo(r.beefyRoot))return T.error(zl.BadBeefyMmrRoot,`Invalid BEEFY super peak hash. Got: ${r.beefyRoot}, expected: ${o}. Anchor: ${t.headerHash}`);if(r.lookupAnchorSlot<e)return T.error(zl.SegmentRootLookupInvalid,`Lookup anchor slot's too old. Got: ${r.lookupAnchorSlot}, minimal: ${e}`);if(!i.isInChain(r.lookupAnchor))return T.error(zl.SegmentRootLookupInvalid,`Lookup anchor is not found in chain. Hash: ${r.lookupAnchor} (slot: ${r.lookupAnchorSlot})`)}return T.ok(_)}(Math.max(0,e.slot-14400),i,t,r,s);if(c.isError)return c;const l=function(e,t){const r=gt.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 T.error(zl.DuplicatePackage,`The same work package hash found in the pipeline (workPackageHash: ${e})`);return T.ok(_)}(gt.viewDictionaryKeys(n),t);if(l.isError)return l;const h=dt.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 T.error(s?zl.SegmentRootLookupInvalid:zl.DependencyMissing,`Missing work package ${i} in current extrinsic or recent history.`);return T.ok(_)},n=i(r);if(n.isError)return n;const o=i(s,!0);return o.isError?o:T.ok(_)}({currentWorkPackages:n,recentlyReported:h,prerequisiteHashes:o,segmentRootLookupHashes:a});if(u.isError)return u;for(const t of e.guarantees){const e=t.materialize().report;for(const t of e.segmentRootLookup){let e=n.get(t.workPackageHash);if(void 0===e){const r=h.get(t.workPackageHash);e=void 0!==r?Fr.create({workPackageHash:t.workPackageHash,segmentTreeRoot:r}):void 0}if(void 0===e||!e.segmentTreeRoot.isEqualTo(t.segmentTreeRoot))return T.error(zl.SegmentRootLookupInvalid,`Mismatching segment tree root for package ${t.workPackageHash}. Got: ${t.segmentTreeRoot}, expected: ${e?.segmentTreeRoot}`)}}return T.ok(n)}(e,this.state,this.mmrHasher,this.headerChain)}checkSignatures(e,t){if(t.every(e=>e))return T.ok(_);const r=t.map((t,r)=>t?null:e[r].key).filter(e=>null!==e);return T.error(zl.BadSignature,`Invalid signatures for validators with keys: ${r.join(", ")}`)}getGuarantorAssignment(e,t,r){const s=this.chainSpec.epochLength,i=this.chainSpec.rotationPeriod,n=lh(e,i),o=lh(t,i),a=Math.max(0,n-1)*i;if(t>e)return T.error(zl.FutureReportSlot,`Report slot is in future. Block ${e}, Report: ${t}`);if(t<a)return T.error(zl.ReportEpochBeforeLast,`Report slot is too old. Block ${e}, Report: ${t}`);let c=r[2],l=this.state.currentValidatorData,h=e;n>o&&(h=Ar(e-i),function(e,t,r){const s=Math.floor(t/r);return Math.floor(e/r)!==s}(h,e,s)&&(c=this.state.entropy[3],l=this.state.previousValidatorData));const u=ch(this.chainSpec,c,h);return T.ok((d=l,g=(e,t)=>({core:e,ed25519:t.ed25519}),u.map((e,t)=>g(e,d[t]))));var d,g}}class fh{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=Cr(Array.from({length:this.chainSpec.validatorsCount},()=>Ti.empty()),this.chainSpec);return Li.create({...this.state.statistics,current:t,previous:this.state.statistics.current})}calculateDAScoreCore(e){if(void 0===e)return se(0);let t=0;return t+=e.workPackageSpec.length+4104*Math.ceil(65*e.workPackageSpec.exportsCount/64),se(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:wr(t.gasUsed),exported:te(t.exported),imported:te(t.imported),extrinsicCount:te(t.extrinsicCount),extrinsicSize:se(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:te(t.count),size:se(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;I(void 0!==a[r],"authorIndex is out of bounds");const h=a[r].blocks+1;a[r].blocks=se(h);const u=a[r].tickets+s.tickets.length;a[r].tickets=se(u);const d=a[r].preImages+s.preimages.length;a[r].preImages=se(d);const g=s.preimages.reduce((e,t)=>e+t.blob.length,0),f=a[r].preImagesSize+g;a[r].preImagesSize=se(f);for(const{credentials:e}of s.guarantees)for(const{validatorIndex:t}of e){const e=a[t].guarantees+1;a[t].guarantees=se(e)}for(const{validatorIndex:e}of s.assurances){const t=a[e].assurances+1;a[e].assurances=se(t)}for(let e=0;e<this.chainSpec.coresCount;e++){const t=Sr(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:te(0),extrinsicCount:te(0),extrinsicSize:se(0),exported:te(0),gasUsed:wr(0n)},d=n.find(e=>e.coreIndex===t),g=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=se(r?.workPackageSpec.length??0),c[t].dataAvailabilityLoad=this.calculateDAScoreCore(d),c[t].popularity=te(g)}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:g}=this.calculateProvidedScoreService(u),{count:f,gasUsed:p}=e.accumulationStatistics.get(t)??{count:se(0),gasUsed:wr(0n)},{count:y,gasUsed:m}=e.transferStatistics.get(t)??{count:se(0),gasUsed:wr(0n)},b=Pi.empty();b.refinementCount=se(r.length),b.refinementGasUsed=n,b.imports=o,b.extrinsicCount=a,b.extrinsicSize=c,b.exports=h,b.providedCount=d,b.providedSize=g,b.providedCount=d,b.providedSize=g,b.accumulateCount=f,b.accumulateGasUsed=p,b.onTransfersCount=y,b.onTransfersGasUsed=m,l.set(t,b)}return{statistics:o}}}class ph{blocks;constructor(e){this.blocks=e}isInChain(e){return null!==this.blocks.getHeader(e)}}var yh;!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"}(yh||(yh={}));const mh=(e,t)=>T.taggedError(yh,e,t);class bh{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=zc.new({synchronous:!i});this.statistics=new fh(e,t),this.safrole=new sl(e,t,n),this.safroleSeal=new il(n),this.recentHistory=new ah(s,t),this.disputes=new Uc(e,t),this.reports=new gh(e,t,s,new ph(r)),this.assurances=new Ql(e,t),this.accumulate=new nh(e,t),this.deferredTransfers=new Nl(e,t),this.preimages=new Ic(t),this.authorization=new oh(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=Ge(i.seal).asOpaque()),null===o){const t=await this.verifySeal(n,e);if(t.isError)return mh(yh.SafroleSeal,t);o=t.ok}const a=await this.disputes.transition(e.extrinsic.view().disputes.materialize());if(a.isError)return mh(yh.Disputes,a);const{disputesRecords:c,availabilityAssignment:l,...h}=a.ok.stateUpdate;S(h);const u=await this.safrole.transition({slot:n,entropy:o,extrinsic:e.extrinsic.view().tickets.materialize(),punishSet:c.punishSet});if(u.isError)return mh(yh.Safrole,u);const{timeslot:d,ticketsAccumulator:g,sealingKeySeries:f,epochRoot:p,entropy:y,nextValidatorData:m,currentValidatorData:b,previousValidatorData:A,...I}=u.ok.stateUpdate;S(I);const v=await this.reports.transition({slot:n,guarantees:e.extrinsic.view().guarantees.view(),newEntropy:y});if(v.isError)return mh(yh.Reports,v);const{availabilityAssignment:w,...E}=v.ok.stateUpdate;S(E);const C=await this.assurances.transition({assurances:e.extrinsic.view().assurances.view(),slot:n,parentHash:i.parentHeaderHash});if(C.isError)return mh(yh.Assurances,C);const{availabilityAssignment:k,...x}=C.ok.stateUpdate;S(x);const B=this.preimages.integrate({slot:n,preimages:e.extrinsic.view().preimages.materialize()});if(B.isError)return mh(yh.Preimages,B);const{preimages:_,...R}=B.ok;S(R);const O=await this.accumulate.transition({slot:n,reports:C.ok.availableReports,entropy:y[0]});if(O.isError)return mh(yh.Accumulate,O);const{root:U,stateUpdate:N,accumulationStatistics:D,pendingTransfers:M,...P}=O.ok;S(P);const{privilegedServices:L,authQueues:H,designatedValidatorData:K,timeslot:V,preimages:Q,...F}=N,G=await this.deferredTransfers.transition({pendingTransfers:M,...F,preimages:Q,timeslot:n});if(G.isError)return mh(yh.DeferredTransfers,G);const{servicesUpdates:$,storageUpdates:j,transferStatistics:q,...z}=G.ok;S(z),F.servicesUpdates=$,F.storage.push(...j);const W=this.recentHistory.transition({headerHash:t,priorStateRoot:i.priorStateRoot,accumulateRoot:U,workPackages:v.ok.reported}),{recentBlocks:J,...Y}=W;S(Y);const X=this.authorization.transition({slot:n,used:this.getUsedAuthorizerHashes(e.extrinsic.view().guarantees.view())}),{authPools:Z,...ee}=X;S(ee);const te=e.extrinsic.materialize(),re=this.statistics.transition({slot:n,authorIndex:i.bandersnatchBlockAuthorIndex,extrinsic:te,incomingReports:te.guarantees.map(e=>e.report),availableReports:C.ok.availableReports,accumulationStatistics:D,transferStatistics:q}),{statistics:se,...ie}=re;return S(ie),T.ok({...void 0!==H?{authQueues:H}:{},...void 0!==K?{designatedValidatorData:K}:{},...void 0!==L?{privilegedServices:L}:{},authPools:Z,preimages:_.concat(Q),disputesRecords:c,availabilityAssignment:Ah(this.state.availabilityAssignment,w,l,k),recentBlocks:J,statistics:se,timeslot:d,epochRoot:p,entropy:y,currentValidatorData:b,nextValidatorData:m,previousValidatorData:A,sealingKeySeries:f,ticketsAccumulator:g,...F})}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)??gt.new();i.insert(e.authorizerHash.materialize()),t.set(s,i)}return t}}function Ah(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 Ih;!function(e){e[e.Verifier=0]="Verifier",e[e.Stf=1]="Stf",e[e.Update=2]="Update"}(Ih||(Ih={}));const vh=(e,t)=>T.taggedError(Ih,e,t);class wh{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 bh(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: ${U(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=C("import:verify"),n=await this.verifier.verifyBlock(e);if(s.log(i()),n.isError)return vh(Ih.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=C("import:stf"),l=await this.stf.transition(e,a,t,r);if(s.log(c()),l.isError)return vh(Ih.Stf,l);const h=l.ok,u=C("import:state"),d=await this.states.updateAndSetState(a,this.state,h);if(d.isError)return s.error(`🧱 Unable to update state: ${U(d)}`),vh(Ih.Update,d);const g=this.states.getState(a);if(null===g)throw new Error("Freshly updated state not in the DB?");this.state.updateBackend(g.backend),s.log(u());const f=C("import:db"),p=this.blocks.insertBlock(new Me(a,e)),y=await this.states.getStateRoot(g);s.log(`🧱 Storing post-state-root for ${a}: ${y}.`);const m=this.blocks.setPostStateRoot(a,y);return await Promise.all([p,m]),s.log(f()),await this.blocks.setBestHeaderHash(a),T.ok(new Me(a,e.header.view()))}bestBlockHash(){return this.blocks.getBestHeaderHash()}}const Sh=Js.new(void 0,"importer");class Eh 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=ue.decodeObject(es,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 Ch 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=me.encodeObject(es,t,r.chainSpec).raw;e.sendSignal("bestBlock",s,[s.buffer])}triggerOnBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=ue.decodeObject(is.Codec.View,e,t.chainSpec);this.onBlock.emit(r)}else Sh.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 kh=Js.new(void 0,"importer");if(!Ys.isMainThread){Js.configureAll(process.env.JAM_LOG??"",Qs.LOG);const e=function(){const e=new Kn("ready(importer)",wt.reInit),t=new Ch,r=new Ln;return new Dn("importer",e,[e,t,r])}();On.receiveChannel(e,Ys.parentPort).then(e=>async function(e){kh.info(`📥 Importer starting ${e.currentState()}`);const t=await e.waitForState("ready(importer)"),r=await t.doUntil("finished",async(e,t)=>{kh.info("📥 Importer waiting for blocks.");const r=e.getConfig(),s=new si(r.dbPath),i=new Zs(r.chainSpec,s),n=new Sn(r.chainSpec,s),o=new wh(r.chainSpec,new Ac(r.chainSpec,await xh,new Le),kh,i,n);let a=!1;const c=new vc(r.chainSpec,o);e.onBlock.on(async s=>{const i=c.push(s)??Ar(0);if(kh.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=C("importBlock"),h=await o.importBlock(i,await n,r.omitSealVerification);if(h.isOk){const r=h.ok;e.announce(t,r),kh.info(`🧊 Best block: #${r.data.timeSlotIndex.materialize()} (${r.hash})`)}else kh.log(`❌ Rejected block #${a}: ${U(h)}`);kh.log(l())}}finally{a=!1}}})});kh.info("📥 Importer finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>kh.error(e))}const xh=ht.create(),Bh=t(import.meta.url)("node:timers/promises");class _h{chainSpec;keccakHasher;blocks;states;hashAllocator=new Le;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}=_h.getLastHeaderAndState(r,s);this.lastHeaderHash=i,this.lastHeader=n,this.lastState=o}refreshLastHeaderAndState(){const{lastHeaderHash:e,lastHeader:t,lastState:r}=_h.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 me.encodeObject(is.Codec,e,this.chainSpec)}async nextBlock(){this.refreshLastHeaderAndState();const e=this.lastHeader.timeSlotIndex+1,t=Ir(e%6),r=new Ac(this.chainSpec,this.keccakHasher,this.hashAllocator),s=this.lastHeaderHash,i=this.states.getStateRoot(this.lastState),n=ss.create({tickets:[],preimages:[],guarantees:[],assurances:[],disputes:br.create({verdicts:[],culprits:[],faults:[]})}),o=me.encodeObject(ss.Codec,n,this.chainSpec),a=ue.decodeObject(ss.Codec.View,o,this.chainSpec),c=r.extrinsic(a).hash,l=me.create();l.i32(e),l.i16(t),l.bytes(M.fill(90,0));const h=M.fromBlob(l.viewResult().raw,96),u=Xr.create({parentHeaderHash:s,priorStateRoot:await i,extrinsicHash:c,timeSlotIndex:Ar(e),epochMarker:null,ticketsMarker:null,offendersMarker:[],bandersnatchBlockAuthorIndex:t,entropySource:M.fill(96,42*e%256).asOpaque(),seal:h.asOpaque()}),d=me.encodeObject(Xr.Codec,u,this.chainSpec),g=ue.decodeObject(Xr.Codec.View,d,this.chainSpec);return this.lastHeaderHash=r.header(g).hash,this.lastHeader=u,is.create({header:u,extrinsic:n})}}const Rh=Js.new(void 0,"block-generator");class Oh 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):Rh.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 Uh 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 Th=Js.new(void 0,"block-generator");if(!Ys.isMainThread){Js.configureAll(process.env.JAM_LOG??"",Qs.LOG);const e=function(){const e=new Kn("ready(generator)",wt.reInit),t=new Uh,r=new Ln;return new Dn("block-generator",e,[e,t,r])}();On.receiveChannel(e,Ys.parentPort).then(e=>async function(e){Th.info(`🎁 Block Generator running ${e.currentState()}`);const t=await e.waitForState("ready(generator)"),r=t.currentState().getConfig(),s=new si(r.dbPath),i=new Zs(r.chainSpec,s),n=new Sn(r.chainSpec,s),o=await t.doUntil("finished",async(e,t,s)=>{let o=0;const a=new _h(r.chainSpec,await ht.create(),i,n);for(;!s();){o+=1;const r=await a.nextEncodedBlock();Th.trace(`Sending block ${o}`),e.sendBlock(t,r),await(0,Bh.setTimeout)(3e3)}});Th.info("Block Generator finished. Closing channel."),o.currentState().close(e)}(e)).catch(e=>{Th.error(e),void 0!==e.stack&&Th.error(e.stack),void 0!==e.cause&&Th.error(e.cause)})}const Nh=t(import.meta.url)("dgram");var Dh,Mh;(Mh=Dh||(Dh={}))[Mh.NOTSET=0]="NOTSET",Mh[Mh.DEBUG=1]="DEBUG",Mh[Mh.INFO=2]="INFO",Mh[Mh.WARN=3]="WARN",Mh[Mh.ERROR=4]="ERROR",Mh[Mh.SILENT=100]="SILENT";const Ph="captureStackTrace"in Error,Lh="stackTraceLimit"in Error;function Hh(e){switch(e){case Dh.NOTSET:return"NOTSET";case Dh.DEBUG:return"DEBUG";case Dh.INFO:return"INFO";case Dh.WARN:return"WARN";case Dh.ERROR:return"ERROR";case Dh.SILENT:return"SILENT"}}function Kh(e,t){return"function"==typeof t?t():t}function Vh(e){return JSON.stringify(e,Kh)}const Qh=Symbol("level"),Fh=Symbol("key"),Gh=Symbol("keys"),$h=Symbol("date"),jh=Symbol("msg"),qh=Symbol("stack"),zh=Symbol("data"),Wh=(function(e,...t){return r=>{let s=e[0];for(let i=0;i<t.length;i++){const n=t[i];if(n===Fh)s+=r.key;else if(n===Gh)s+=r.keys;else if(n===$h)s+=r.date().toISOString();else if(n===jh)null!=r.msg&&(s+=r.msg);else if(n===Qh)s+=Hh(r.level);else if(n===zh)s+=Vh(r.data);else if(n===qh){const e=r.stack();""!==e&&(s+="\n"+e)}else s+=n.toString();s+=e[i+1]}return s}})`${Qh}:${Fh}:${jh}`,Jh=class{formatter;constructor(e=Wh){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)}},Yh=class extends Jh{emit(e){console.error(e)}};class Xh{key;level;filter;keys;handlers;parent;_loggers=new Map;loggersRegistry;constructor(e="root",t=Dh.NOTSET,r=[new Yh],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 Xh(e,Dh.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!==Dh.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,{},Dh.DEBUG,t):this.log(e,t,Dh.DEBUG,r)}info(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Dh.INFO,t):this.log(e,t,Dh.INFO,r)}warn(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Dh.WARN,t):this.log(e,t,Dh.WARN,r)}error(e,t,r){return null==t||"function"==typeof t?this.log(e,{},Dh.ERROR,t):this.log(e,t,Dh.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(Ph&&Lh){Error.stackTraceLimit++;const t={};Error.captureStackTrace(t,Xh.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=Xh;t(import.meta.url)("node:process");class eu 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 tu=eu;class ru extends tu{constructor(e){super(ru.name,e,arguments)}}const su=ru;class iu extends tu{constructor(e){super(iu.name,e,arguments)}}const nu=iu;class ou extends tu{constructor(e){super(ou.name,e,arguments)}}const au=ou,cu=Symbol("_eventTarget"),lu=Symbol("eventTarget"),hu=Symbol("_eventHandlers"),uu=Symbol("eventHandlers"),du=Symbol("_eventHandled"),gu=Symbol("eventHandled"),fu=Symbol("_handleEventError"),pu=Symbol("handleEventError");function yu(e){return{capture:!1,once:!1,passive:!1,..."boolean"==typeof e?{capture:e}:"object"==typeof e?e:void 0}}function mu(e,t){return e.capture===t.capture}function bu(){return e=>{const t=class extends e{[cu]=new EventTarget;[hu]=new Map;[du]=new WeakSet;[fu]=e=>{throw e.detail};constructor(...e){super(...e),this[cu].addEventListener(au.name,this[fu])}get[lu](){return this[cu]}get[uu](){return this[hu]}get[gu](){return this[du]}get[pu](){return this[fu]}addEventListener(e,t,r){r=yu(r);const s=this;let i,n,o=!1;if("function"==typeof t||"function"==typeof t?.handleEvent){n=this[hu].get(e),void 0===n&&(n=new Set,this[hu].set(e,n));for(const e of n)if(e.callback===t&&(i=e.handler,mu(e.options,r))){o=!0;break}}"function"==typeof t?null==i?(i=async function(e){let r;s[du].add(e);try{r=t.call(s,e)}catch(e){this.dispatchEvent(new au({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new au({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[du].add(e);try{r=t.handleEvent(e)}catch(e){this.dispatchEvent(new au({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new au({detail:e}))}return r},n.add({callback:t,options:r,handler:i})):o||n.add({callback:t,options:r,handler:i}):i=t,this[cu].addEventListener(e,i,r),e===au.name&&1===n?.size&&this[cu].removeEventListener(au.name,this[fu])}removeEventListener(e,t,r){let s,i,n;if(r=yu(r),null!=t){if(i=this[hu].get(e),void 0===i)return;for(const e of i)if(e.callback===t&&mu(e.options,r)){s=e.handler,n=e;break}if(null==s)return}else s=t;this[cu].removeEventListener(e,s,r),null!=i&&null!=n&&(i.delete(n),e===au.name&&0===i.size&&this[cu].addEventListener(au.name,this[fu]))}dispatchEvent(e){if(Object.defineProperties(e,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),e instanceof au)return this[cu].dispatchEvent(e);{let t=this[cu].dispatchEvent(e);if(t&&!this[du].has(e)){const r=new su({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[cu].dispatchEvent(r)}if(t){const r=new nu({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[cu].dispatchEvent(r)}return t}}};return Object.defineProperty(t,"name",Object.getOwnPropertyDescriptor(e,"name")),t}}async function Au(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*Iu(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 vu extends Promise{static get[Symbol.species](){return Promise}static resolve(e){return e instanceof vu?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=vu.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 wu=vu,Su=t(import.meta.url)("node:perf_hooks");var Eu,Cu=(Eu=function(e,t){return Eu=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])},Eu(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}Eu(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),ku=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 Cu(t,e),t}(Error);const xu=class extends ku{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(Su.performance.timeOrigin+Su.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 Bu(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=Bu(s,t,r);if(e)return e}return Bu(e.cause,t,r)}return e instanceof Error&&Bu(e.cause,t,r)}class _u extends xu{static description="Timer error"}class Ru extends _u{static description="The timer has already ended"}class Ou{_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 wu((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(Su.performance.timeOrigin+Su.performance.now()),this._scheduled=new Date(this.timestamp.getTime()+t)):(this.timeoutRef=setInterval(()=>{},2**31-1),this.timestamp=new Date(Su.performance.timeOrigin+Su.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()-(Su.performance.timeOrigin+Su.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 Ru;return this.reset(this._delay)}reset(e){if(null!=this._status)throw new Ru;clearTimeout(this.timeoutRef),this._delay=e,isFinite(e)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},e),this._scheduled=new Date(Su.performance.timeOrigin+Su.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 Uu=Ou;function Tu(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Nu(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 Uu(()=>{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 Uu&&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 Uu(()=>{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 wu((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 Du extends xu{static description="Async locks error"}class Mu extends Du{static description="Async locks timeout"}const Pu=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}:{},()=>Nu((e,t)=>{this._count++;const{p:r,resolveP:s,rejectP:i}=Tu();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,Mu,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}:{},Nu((e,t)=>{const{p:r,resolveP:s,rejectP:i}=Tu();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,Mu,r,[t])}withF(...e){const t=e.pop();return Au([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return Iu([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()}}},Lu=class{semaphore=new Pu(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 Au([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return Iu([this.lock(...e)],([e])=>t(e))}},Hu=class{readersLock=new Lu;writersLock=new Lu;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}:{},()=>Nu(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,Mu,e,[])}write(e){return e=null!=e?{...e}:{},()=>Nu(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,Mu,e,[])}waitForUnlock(e){const t=this.readersLock.waitForUnlock(e),r=this.writersLock.waitForUnlock(e);return wu.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 Au([this.read(...e)],([e])=>t(e))}withWriteF(...e){const t=e.pop();return Au([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 Iu([this.read(...e)],([e])=>t(e))}withWriteG(...e){const t=e.pop();return Iu([this.write(...e)],([e])=>t(e))}},Ku=Symbol("_running"),Vu=Symbol("running"),Qu=Symbol("_destroyed"),Fu=Symbol("destroyed"),Gu=Symbol("_status"),$u=Symbol("status"),ju=Symbol("_statusP"),qu=Symbol("statusP"),zu=Symbol("resolveStatusP"),Wu=Symbol("initLock"),Ju=(async()=>{}).constructor,Yu=function*(){}.constructor,Xu=async function*(){}.constructor,Zu="captureStackTrace"in Error;function ed(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function td(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 rd extends tu{}class sd extends rd{}class id extends rd{}class nd extends rd{}class od extends rd{}class ad extends rd{}class cd extends rd{}class ld extends xu{static description="Async init error"}class hd extends ld{static description="Async init is not running"}class ud extends ld{static description="Async init is destroyed"}function dd({eventDestroy:e=ad,eventDestroyed:t=cd}={}){return r=>{const{p:s,resolveP:i}=ed(),n=class extends(bu()(r)){[Qu]=!1;[Gu]=null;[ju]=s;[zu]=i;[Wu]=new Hu;get[Fu](){return this[Qu]}get[$u](){return this[Gu]}get[qu](){return this[ju]}async destroy(...r){return this[Wu].withWriteF(async()=>{if(this[Qu])return;this[Gu]="destroying",this[zu]("destroying");const{p:s,resolveP:i}=ed();let n;return this[ju]=s,this[zu]=i,this.dispatchEvent(new e),"function"==typeof super.destroy&&(n=await super.destroy(...r)),this[Qu]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[Gu]=null,this[zu](null);const{p:e,resolveP:t}=ed();this[ju]=e,this[zu]=t})}};return Object.defineProperty(n,"name",Object.getOwnPropertyDescriptor(r,"name")),n}}function gd(e=new ud,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[Wu].isLocked("write")&&null===this[Gu]&&await this[ju],r.includes(this[Gu]))return a.apply(this,s);if(t)return this[Wu].withReadF(async()=>{if(this[Qu])throw td(e,n[o]),e;return a.apply(this,s)});if(this[Wu].isLocked("write")||this[Qu])throw td(e,n[o]),e;return a.apply(this,s)}:a instanceof Yu?function*(...t){if(r.includes(this[Gu]))return yield*a.apply(this,t);if(this[Wu].isLocked("write")&&null!==this[$u]||this[Qu])throw td(e,n[o]),e;return yield*a.apply(this,t)}:a instanceof Xu?async function*(...s){if(this[Wu].isLocked("write")&&null===this[Gu]&&await this[ju],r.includes(this[Gu]))return yield*a.apply(this,s);if(t)return yield*this[Wu].withReadG(()=>{if(this[Qu])throw td(e,n[o]),e;return a.apply(this,s)});if(this[Wu].isLocked("write")||this[Qu])throw td(e,n[o]),e;return yield*a.apply(this,s)}:function(...t){if(r.includes(this[Gu]))return a.apply(this,t);if(this[Wu].isLocked("write")&&null!==this[$u]||this[Qu])throw td(e,n[o]),e;return a.apply(this,t)},Object.defineProperty(n[o],"name",{value:i}),n}}function fd({eventStart:e=sd,eventStarted:t=id,eventStop:r=nd,eventStopped:s=od}={}){return i=>{const{p:n,resolveP:o}=ed(),a=class extends(bu()(i)){[Ku]=!1;[Gu]=null;[ju]=n;[zu]=o;[Wu]=new Hu;get[Vu](){return this[Ku]}get[$u](){return this[Gu]}get[qu](){return this[ju]}async start(...r){return this[Wu].withWriteF(async()=>{if(this[Ku])return;this[Gu]="starting",this[zu]("starting");const{p:s,resolveP:i}=ed();let n;return this[ju]=s,this[zu]=i,this.dispatchEvent(new e),"function"==typeof super.start&&(n=await super.start(...r)),this[Ku]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[Gu]=null,this[zu](null);const{p:e,resolveP:t}=ed();this[ju]=e,this[zu]=t})}async stop(...e){return this[Wu].withWriteF(async()=>{if(!this[Ku])return;this[Gu]="stopping",this[zu]("stopping");const{p:t,resolveP:i}=ed();let n;return this[ju]=t,this[zu]=i,this.dispatchEvent(new r),"function"==typeof super.stop&&(n=await super.stop(...e)),this[Ku]=!1,this.dispatchEvent(new s),n}).finally(()=>{this[Gu]=null,this[zu](null);const{p:e,resolveP:t}=ed();this[ju]=e,this[zu]=t})}};return Object.defineProperty(a,"name",Object.getOwnPropertyDescriptor(i,"name")),a}}function pd(e=new hd,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[Wu].isLocked("write")&&null===this[Gu]&&await this[ju],r.includes(this[Gu]))return a.apply(this,s);if(t)return this[Wu].withReadF(async()=>{if(!this[Ku])throw td(e,n[o]),e;return a.apply(this,s)});if(this[Wu].isLocked("write")||!this[Ku])throw td(e,n[o]),e;return a.apply(this,s)}:a instanceof Yu?function*(...t){if(r.includes(this[Gu]))return yield*a.apply(this,t);if(this[Wu].isLocked("write")&&null!==this[$u]||!this[Ku])throw td(e,n[o]),e;return yield*a.apply(this,t)}:a instanceof Xu?async function*(...s){if(this[Wu].isLocked("write")&&null===this[Gu]&&await this[ju],r.includes(this[Gu]))return yield*a.apply(this,s);if(t)return yield*this[Wu].withReadG(()=>{if(!this[Ku])throw td(e,n[o]),e;return a.apply(this,s)});if(this[Wu].isLocked("write")||!this[Ku])throw td(e,n[o]),e;return yield*a.apply(this,s)}:function(...t){if(r.includes(this[Gu]))return a.apply(this,t);if(this[Wu].isLocked("write")&&null!==this[$u]||!this[Ku])throw td(e,n[o]),e;return a.apply(this,t)},Object.defineProperty(n[o],"name",{value:i}),n}}class yd 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 md=yd;class bd{[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,md.fromString(s),this)}),this._clientConnections.forEach((r,s)=>{e.bind(t)(r,md.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:[md.fromString(e),t]}}const s=t.next();if(!s.done){const[e,t]=s.value;return{done:!1,value:[md.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 Ad=bd,Id="data:application/javascript;base64,aW1wb3J0IHByb2Nlc3MgZnJvbSAncHJvY2Vzcyc7CmltcG9ydCBwYXRoIGZyb20gJ3BhdGgnOwppbXBvcnQgdXJsIGZyb20gJ3VybCc7CmltcG9ydCBNb2R1bGUgZnJvbSAnbm9kZTptb2R1bGUnOwpjb25zdCByZXF1aXJlID0gTW9kdWxlLmNyZWF0ZVJlcXVpcmUoaW1wb3J0Lm1ldGEudXJsKTsKY29uc3QgZGlybmFtZSA9IHVybC5maWxlVVJMVG9QYXRoKG5ldyBVUkwoJy4nLCBpbXBvcnQubWV0YS51cmwpKTsKY29uc3QgcHJvamVjdFJvb3QgPSBwYXRoLmpvaW4oZGlybmFtZSwgJy4uLy4uLycpOwpjb25zdCBwcmVidWlsZFBhdGggPSBwYXRoLmpvaW4ocHJvamVjdFJvb3QsICdwcmVidWlsZCcpOwovKioKICogVHJ5IHJlcXVpcmUgb24gYWxsIHByZWJ1aWxkIHRhcmdldHMgZmlyc3QsIHRoZW4KICogdHJ5IHJlcXVpcmUgb24gYWxsIG5wbSB0YXJnZXRzIHNlY29uZC4KICovCmZ1bmN0aW9uIHJlcXVpcmVCaW5kaW5nKHRhcmdldHMpIHsKICAgIGNvbnN0IHByZWJ1aWxkVGFyZ2V0cyA9IHRhcmdldHMubWFwKCh0YXJnZXQpID0+IHBhdGguam9pbihwcmVidWlsZFBhdGgsIGBxdWljLSR7dGFyZ2V0fS5ub2RlYCkpOwogICAgZm9yIChjb25zdCBwcmVidWlsZFRhcmdldCBvZiBwcmVidWlsZFRhcmdldHMpIHsKICAgICAgICB0cnkgewogICAgICAgICAgICByZXR1cm4gcmVxdWlyZShwcmVidWlsZFRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKHByZWJ1aWxkVGFyZ2V0KS5ocmVmKTsKICAgICAgICB9CiAgICAgICAgY2F0Y2ggKGUpIHsKICAgICAgICAgICAgaWYgKGUuY29kZSAhPT0gJ01PRFVMRV9OT1RfRk9VTkQnKQogICAgICAgICAgICAgICAgdGhyb3cgZTsKICAgICAgICB9CiAgICB9CiAgICBjb25zdCBucG1UYXJnZXRzID0gdGFyZ2V0cy5tYXAoKHRhcmdldCkgPT4gYEBtYXRyaXhhaS9xdWljLSR7dGFyZ2V0fWApOwogICAgZm9yIChjb25zdCBucG1UYXJnZXQgb2YgbnBtVGFyZ2V0cykgewogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKG5wbVRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKG5wbVRhcmdldCkuaHJlZik7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgfQogICAgdGhyb3cgbmV3IEVycm9yKGBGYWlsZWQgcmVxdWlyaW5nIHBvc3NpYmxlIG5hdGl2ZSBiaW5kaW5nczogJHtwcmVidWlsZFRhcmdldHMuY29uY2F0KG5wbVRhcmdldHMpfWApOwp9CmxldCBuYXRpdmVCaW5kaW5nOwovKioKICogRm9yIGRlc2t0b3Agd2Ugb25seSBzdXBwb3J0IHdpbjMyLCBkYXJ3aW4gYW5kIGxpbnV4LgogKiBNb2JpbGUgT1Mgc3VwcG9ydCBpcyBwZW5kaW5nLgogKi8Kc3dpdGNoIChwcm9jZXNzLnBsYXRmb3JtKSB7CiAgICBjYXNlICd3aW4zMic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLXg2NCddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlICdpYTMyJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLWlhMzInXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnd2luMzItYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgICAgIHRocm93IG5ldyBFcnJvcihgVW5zdXBwb3J0ZWQgYXJjaGl0ZWN0dXJlIG9uIFdpbmRvd3M6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGNhc2UgJ2Rhcndpbic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4teDY0K2FybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi11bml2ZXJzYWwnLAogICAgICAgICAgICAgICAgXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQrYXJtNjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4tdW5pdmVyc2FsJywKICAgICAgICAgICAgICAgIF0pOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoYFVuc3VwcG9ydGVkIGFyY2hpdGVjdHVyZSBvbiBtYWNPUzogJHtwcm9jZXNzLmFyY2h9YCk7CiAgICAgICAgfQogICAgICAgIGJyZWFrOwogICAgY2FzZSAnbGludXgnOgogICAgICAgIHN3aXRjaCAocHJvY2Vzcy5hcmNoKSB7CiAgICAgICAgICAgIGNhc2UgJ3g2NCc6CiAgICAgICAgICAgICAgICBuYXRpdmVCaW5kaW5nID0gcmVxdWlyZUJpbmRpbmcoWydsaW51eC14NjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnbGludXgtYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ2xpbnV4LWFybSddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBhcmNoaXRlY3R1cmUgb24gTGludXg6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGRlZmF1bHQ6CiAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBPUzogJHtwcm9jZXNzLnBsYXRmb3JtfSwgYXJjaGl0ZWN0dXJlOiAke3Byb2Nlc3MuYXJjaH1gKTsKfQpleHBvcnQgZGVmYXVsdCBuYXRpdmVCaW5kaW5nOwovLyMgc291cmNlTWFwcGluZ1VSTD1xdWljaGUuanMubWFw",vd=t(import.meta.url)("dns");var wd=o(618);class Sd extends xu{static description="QUIC error"}class Ed extends xu{static description="You should never see this error"}class Cd extends xu{static description="Host provided was not valid"}class kd extends xu{static description="Port provided was not valid"}class xd extends Sd{static description="QUIC config error"}class Bd extends Sd{static description="QUIC Socket error"}class _d extends Bd{static description="QUIC Socket is not running"}class Rd extends Bd{static description="QUIC Socket has active connections"}class Od extends Bd{static description="QUIC Socket cannot bind to the specified address"}class Ud extends Bd{static description="QUIC Socket cannot send to the specified address"}class Td extends Bd{static description="QUIC Socket internal error"}class Nd extends Sd{static description="QUIC Client error"}class Dd extends Nd{static description="QUIC Client is destroyed"}class Md extends Nd{static description="QUIC Client cannot be created with an unstarted shared QUIC socket"}class Pd extends Nd{static description="QUIC Client had a failure relating to an invalid argument"}class Ld extends Nd{static description="QUIC Client cannot be created with the specified host"}class Hd extends Nd{static description="QUIC Client internal error"}class Kd extends Sd{static description="QUIC Server error"}class Vd extends Kd{static description="QUIC Server is not running"}class Qd extends Kd{static description="QUIC Server cannot start with an unstarted shared QUIC socket"}class Fd extends Kd{static description="QUIC Server creating a new connection"}class Gd extends Kd{static description="QUIC Server internal error"}class $d extends Kd{static description="QUIC Server is stopping"}class jd extends Sd{static description="QUIC Connection error"}class qd extends jd{static description="QUIC Connection is stopping"}class zd extends jd{static description="QUIC Connection is not running"}class Wd extends jd{static description="QUIC Connection cannot be restarted because it has already been closed"}class Jd extends Sd{static description="QUIC Connection start requires data when it is a server connection"}class Yd extends jd{static description="QUIC connection invalid configuration"}class Xd extends jd{static description="QUIC Connection local error";constructor(e="",t){super(e,t)}}class Zd extends Xd{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class eg extends jd{static description="QUIC Connection peer error";constructor(e="",t){super(e,t)}}class tg extends Xd{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class rg extends jd{static description="QUIC Connection max idle timeout exhausted"}class sg extends jd{static description="QUIC Connection internal error"}class ig extends Sd{static description="QUIC Stream error"}class ng extends ig{static description="QUIC Stream is destroyed"}class og extends ig{static description="QUIC Stream locally closed readable side";constructor(e="",t){super(e,t)}}class ag extends ig{static description="QUIC Stream locally closed writable side";constructor(e="",t){super(e,t)}}class cg extends ig{static description="QUIC Stream peer closed readable side";constructor(e="",t){super(e,t)}}class lg extends ig{static description="QUIC Stream peer closed writable side";constructor(e="",t){super(e,t)}}class hg extends ig{static description="QUIC Stream internal error"}class ug extends ig{static description="QUIC Stream limit has been reached"}const dg=new TextEncoder,gg=new TextDecoder("utf-8");function fg(e){throw new Ed(e)}function pg(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 yg(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function mg(e){const[t]=wd.Validator.isValidIPv4String(e);return t}function bg(e){const[t]=wd.Validator.isValidIPv6String(e);return!!t||Ag(e)}function Ag(e){if(e.startsWith("::ffff:"))try{return wd.IPv6.fromString(e),!0}catch{if(mg(e.slice(7)))return!0}return!1}function Ig(e){if(!mg(e))throw new TypeError("Invalid IPv4 address");return"::ffff:"+e}function vg(e){const t=e.slice(7);if(mg(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 wg(e){const t=new wd.IPv4("0.0.0.0"),r=new wd.IPv6("::");if(Ag(e)){const r=vg(e);return new wd.IPv4(r).isEquals(t)?Ig("127.0.0.1"):e}return mg(e)&&new wd.IPv4(e).isEquals(t)?"127.0.0.1":bg(e)&&new wd.IPv6(e).isEquals(r)?"::1":e}async function Sg(e){return(await vd.promises.lookup(e,{family:0,all:!1,verbatim:!0})).address}async function Eg(e,t){if(mg(e))return[e,"udp4"];if(bg(e))return[e,"udp6"];try{return Eg(e=await t(e),t)}catch{throw new Cd}}function Cg(e){if(!function(e){return"number"==typeof e&&e>=0&&e<=65535}(e))throw new kd;return e}function kg(e,t=0){let r;return r=mg(e)?`${e}:${t}`:bg(e)?`[${e}]:${t}`:`${e}:${t}`,r}function xg(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=Ag(e),a=Ag(r);if("ipv4&ipv6"===t&&"udp4"===s)return Ig(r);if("ipv4"===t){if(o){if("udp4"===s)return Ig(r);if("udp6"===s&&!a)throw new i(`Invalid target host ${r} from an IPv4 socket`)}else if("udp6"===s){if(a)return vg(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 Bg(e){const t=[];if("string"==typeof e)t.push(e.trim()+"\n");else if(e instanceof Uint8Array)t.push(gg.decode(e).trim()+"\n");else if(Array.isArray(e))for(const r of e)"string"==typeof r?t.push(r.trim()+"\n"):t.push(gg.decode(r).trim()+"\n");return t}function _g(e){const t=e.replace(/-----BEGIN .*-----/,"").replace(/-----END .*-----/,"").replace(/\s+/g,""),r=Buffer.from(t,"base64");return new Uint8Array(r)}function Rg(e){return`${e.name}${"description"in e?`: ${e.description}`:""}${void 0!==e.message?` - ${e.message}`:""}`}function Og(e){let t;return null!=(t=e.message.match(/StreamStopped\((\d{1,16})\)/))&&parseInt(t[1])}function Ug(e){let t;return null!=(t=e.message.match(/StreamReset\((\d{1,16})\)/))&&parseInt(t[1])}function Tg(e,t=1e5){En.setMaxListeners(t,e)}class Ng extends tu{}class Dg extends Ng{}class Mg extends Dg{}class Pg extends Dg{}class Lg extends Dg{}class Hg extends Ng{}class Kg extends Hg{}class Vg extends Dg{}class Qg extends Hg{}class Fg extends Ng{}class Gg extends Fg{}class $g extends Fg{}class jg extends Fg{}class qg extends Ng{}class zg extends qg{}class Wg extends qg{}class Jg extends qg{}class Yg extends qg{}class Xg extends qg{}class Zg extends Ng{}class ef extends Zg{}class tf extends Zg{}class rf extends Zg{}class sf extends Zg{}class nf extends Zg{}var of=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 af=class{connectionMap=new Ad;logger;server;resolveHostname;_host;_port;_type;_closed=!1;_closedP;resolveClosedP;socket;socketBind;socketClose;socketSend;handleEventQUICSocketError=e=>{const t=e.detail;this.logger.debug(Rg(t))};handleEventQUICSocketClose=async()=>{await this.socketClose(),this._closed=!0,this.resolveClosedP(),this[Vu]&&await this.stop({force:!0})};handleSocketMessage=async(e,t)=>{let r;try{r=Id.Header.fromSlice(e,Id.MAX_CONN_ID_LEN)}catch(e){if("BufferTooShort"===e.message||"InvalidPacket"===e.message)return;throw e}const s=new md(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(Bu(e,e=>e instanceof Bd)){const t=new Td("Failed to call accept connection due to socket send",{cause:e});return this.dispatchEvent(new Pg({detail:t})),void this.dispatchEvent(new Lg)}if(e instanceof Fd)return;throw e}}};constructor({resolveHostname:e=Sg,logger:t}){this.logger=t??new Zh(this.constructor.name),this.resolveHostname=e;const{p:r,resolveP:s}=yg();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}={}){Tg(this[cu]);let i=kg(e,t);this.logger.info(`Start ${this.constructor.name} on ${i}`);const[n,o]=await Eg(e,this.resolveHostname),a=Cg(t);this.socket=Nh.createSocket({type:o,reuseAddr:r,ipv6Only:s}),this.socketBind=pg(this.socket.bind).bind(this.socket),this.socketClose=pg(this.socket.close).bind(this.socket),this.socketSend=pg(this.socket.send).bind(this.socket);const{p:c,rejectP:l}=yg();c.catch(()=>{}),this.socket.once("error",l);const h=this.socketBind(a,n);try{await Promise.race([h,c])}catch(t){throw new Od(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||Ag(n)?this._type="ipv4":"udp6"===o&&(this._type="ipv6"):this._type="ipv4&ipv6",this.socket.on("message",this.handleSocketMessage),this.addEventListener(Pg.name,this.handleEventQUICSocketError),this.addEventListener(Lg.name,this.handleEventQUICSocketClose,{once:!0}),this._closed=!1,i=kg(this._host,this._port),this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({force:e=!1}={}){const t=kg(this._host,this._port);if(this.logger.info(`Stop ${this.constructor.name} on ${t}`),!e&&this.connectionMap.size>0)throw new Rd(`Cannot stop QUICSocket with ${this.connectionMap.size} active connection(s)`);this._closed||this.dispatchEvent(new Lg),await this._closedP;const{p:r,resolveP:s}=yg();this._closedP=r,this.resolveClosedP=s,this.removeEventListener(Pg.name,this.handleEventQUICSocketError),this.removeEventListener(Lg.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 Eg(r,this.resolveHostname);return s=wg(s),s=xg(this._host,this._type,s,i,Ud),e[t]=s,this.socketSend(...e)}async send_(...e){return this.socketSend(...e)}setServer(e){this.server=e}unsetServer(){delete this.server}};of([pd(new _d)],af.prototype,"host",null),of([pd(new _d)],af.prototype,"port",null),of([pd(new _d)],af.prototype,"type",null),of([pd(new _d)],af.prototype,"send",null),of([pd(new _d)],af.prototype,"send_",null),af=of([fd({eventStart:class extends Dg{},eventStarted:class extends Dg{},eventStop:class extends Dg{},eventStopped:Mg})],af);const cf=af,lf=new WeakMap;const hf=function(e,t,r){const s=e.name??e.constructor.name,i=e[t];if(lf.has(i))throw new TypeError(`\`${s}.${t.toString()}\` redeclares \`@context\` decorator`);lf.set(i,r)};class uf extends xu{static description="Contexts error"}class df extends uf{static description="Aborted due to timer expiration"}const gf=function(e=!1,t=1/0,r=df){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=lf.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 Uu))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 Uu(()=>{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 Uu&&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 Uu(()=>{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 wu((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}},ff=["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(":"),pf=1/0,yf={sigalgs:ff,verifyPeer:!0,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:Id.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:Id.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:Id.MAX_CONNECTION_WINDOW,maxStreamWindow:Id.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},mf={sigalgs:ff,verifyPeer:!1,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:Id.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:Id.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:Id.MAX_CONNECTION_WINDOW,maxStreamWindow:Id.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},bf=t(import.meta.url)("stream/web");var Af=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 If=Symbol("abort readableP reason");let vf=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(tf.name,a.handleEventQUICStreamError),a.addEventListener(rf.name,a.handleEventQUICStreamCloseRead,{once:!0}),a.addEventListener(sf.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 hg)throw this.logger.debug(Rg(t)),t;t instanceof og||t instanceof cg?this.dispatchEvent(new rf({detail:t})):(t instanceof ag||t instanceof lg)&&this.dispatchEvent(new sf({detail:t}))};handleEventQUICStreamCloseRead=async()=>{this._readClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[Fu]||"destroying"===this[$u]||await this.destroy({force:!1}))};handleEventQUICStreamCloseWrite=async()=>{this._writeClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[Fu]||"destroying"===this[$u]||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}=yg();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 bf.ReadableStream({start:this.readableStart.bind(this)}):this.readable=new bf.ReadableStream({start:this.readableStart.bind(this),pull:this.readablePull.bind(this),cancel:this.readableCancel.bind(this)},new bf.CountQueuingStrategy({highWaterMark:1})),"uni"===this.type&&"peer"===this.initiated)this.writable=new bf.WritableStream({start:this.writableStart.bind(this)});else{this.writable=new bf.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===Og(e)){if("StreamLimit"===e.message){const t="bidi"===this.type?s.initialMaxStreamsBidi:s.initialMaxStreamsUni;throw new ug(`Stream limit of ${t} has been reached`,{cause:e})}throw new hg(`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(tf.name,this.handleEventQUICStreamError),this.removeEventListener(rf.name,this.handleEventQUICStreamCloseRead),this.removeEventListener(sf.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=Ug(e))){const e=this.codeToReason("read",t),r=new cg("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),this.rejectReadableP?.(e),void this.dispatchEvent(new tf({detail:r}))}{const t=new hg("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.rejectReadableP?.(t),this.dispatchEvent(new tf({detail:t})),t}}if(null===e){const e=new hg("Failed `streamRecv` on the readable stream");throw this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new tf({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 rf),void this.rejectReadableP?.(If)}this.resolveReadableP?.()}write(){try{this.connection.conn.streamCapacity(this.streamId)}catch(e){let t;if(!1!==(t=Og(e))){this.connection.conn.streamShutdown(this.streamId,Id.Shutdown.Write,t);const e=this.codeToReason("write",t),r=new lg("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),this.rejectWritableP?.(e),void this.dispatchEvent(new tf({detail:r}))}{const t=new hg("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.rejectWritableP?.(t),this.dispatchEvent(new tf({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}=yg();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=Ug(e))){const e=this.codeToReason("read",t),r=new cg("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),void this.dispatchEvent(new tf({detail:r}))}{const t=new hg("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.dispatchEvent(new tf({detail:t})),t}}if(null===e){const e=new hg("Failed `streamRecv` on the readable stream because it is not readable");throw this.readableController.error(e),this.dispatchEvent(new tf({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 rf)),this.dispatchEvent(new nf)}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=Og(e))){const e=this.codeToReason("write",t),r=new lg("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new tf({detail:r}))}{const t=new hg("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new tf({detail:t})),t}}if(this.dispatchEvent(new nf),t<e.byteLength){e=e.subarray(t,e.byteLength);const{p:r,resolveP:s,rejectP:i}=yg();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=Og(e))){const e=this.codeToReason("write",t),r=new lg("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new tf({detail:r}))}{const t=new hg("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new tf({detail:t})),t}}this.dispatchEvent(new sf),this.dispatchEvent(new nf)}readableCancel(e){if(this._readClosed)return;const t=this.reasonToCode("read",e);try{this.connection.conn.streamShutdown(this.streamId,Id.Shutdown.Read,t)}catch(r){const e=new hg("Local stream readable could not be shutdown",{cause:r});throw this.readableController.error(e),this.dispatchEvent(new tf({detail:e})),e}const r=new og("Closing readable stream locally",{data:{code:t},cause:e});this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new tf({detail:r})),this.dispatchEvent(new nf)}writableAbort(e){if(this._writeClosed)return;const t=this.reasonToCode("write",e);try{this.connection.conn.streamShutdown(this.streamId,Id.Shutdown.Write,t)}catch(r){const e=new hg("Local stream writable could not be shutdown",{cause:r});throw this.writableController.error(e),this.dispatchEvent(new tf({detail:e})),e}const r=new ag("Closing writable stream locally",{data:{code:t},cause:e});this.writableController.error(e),this.rejectWritableP?.(e),this.dispatchEvent(new tf({detail:r})),this.dispatchEvent(new nf)}};Af([gd(new ng)],vf.prototype,"meta",null),Af([gd(new ng,!1,["destroying"])],vf.prototype,"read",null),Af([gd(new ng,!1,["destroying"])],vf.prototype,"write",null),vf=Af([dd({eventDestroy:class extends Zg{},eventDestroyed:ef})],vf);const wf=vf;var Sf,Ef,Cf,kf,xf,Bf;!function(e){e[e.Reno=0]="Reno",e[e.CUBIC=1]="CUBIC",e[e.BBR=2]="BBR"}(Sf||(Sf={})),function(e){e[e.Read=0]="Read",e[e.Write=1]="Write"}(Ef||(Ef={})),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"}(Cf||(Cf={})),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"}(kf||(kf={})),(Bf=xf||(xf={}))[Bf.CloseNotify=256]="CloseNotify",Bf[Bf.UnexpectedMessage=266]="UnexpectedMessage",Bf[Bf.BadRecordMac=276]="BadRecordMac",Bf[Bf.RecordOverflow=278]="RecordOverflow",Bf[Bf.HandshakeFailure=296]="HandshakeFailure",Bf[Bf.BadCertificate=298]="BadCertificate",Bf[Bf.UnsupportedCertificate=299]="UnsupportedCertificate",Bf[Bf.CertificateRevoked=300]="CertificateRevoked",Bf[Bf.CertificateExpired=301]="CertificateExpired",Bf[Bf.CertificateUnknown=302]="CertificateUnknown",Bf[Bf.IllegalParameter=303]="IllegalParameter",Bf[Bf.UnknownCA=304]="UnknownCA",Bf[Bf.AccessDenied=305]="AccessDenied",Bf[Bf.DecodeError=306]="DecodeError",Bf[Bf.DecryptError=307]="DecryptError",Bf[Bf.ProtocolVersion=326]="ProtocolVersion",Bf[Bf.InsufficientSecurity=327]="InsufficientSecurity",Bf[Bf.InternalError=336]="InternalError",Bf[Bf.InappropriateFallback=342]="InappropriateFallback",Bf[Bf.UserCanceled=346]="UserCanceled",Bf[Bf.MissingExtension=365]="MissingExtension",Bf[Bf.UnsupportedExtension=366]="UnsupportedExtension",Bf[Bf.UnrecognizedName=368]="UnrecognizedName",Bf[Bf.BadCertificateStatusResponse=369]="BadCertificateStatusResponse",Bf[Bf.UnknownPSKIdentity=371]="UnknownPSKIdentity",Bf[Bf.CertificateRequired=372]="CertificateRequired",Bf[Bf.NoApplicationProtocol=376]="NoApplicationProtocol";var _f=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 Rf=class{type;closedP;conn;streamMap=new Map;sendId;logger;socket;config;reasonToCode;codeToReason;recvLock=new Lu;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(Rg(t)),t instanceof sg)throw t;this.dispatchEvent(new Jg({detail:t}))};handleEventQUICConnectionClose=async e=>{const t=e.detail;this.secureEstablished||this.rejectSecureEstablishedP(t),t instanceof Xd&&await this.send(),this[Vu]&&"stopping"!==this[$u]&&await this.stop({force:!0})};handleEventQUICStream=e=>{e.detail instanceof tu&&!(e.detail instanceof nf)&&this.dispatchEvent(e.detail.clone())};handleEventQUICStreamSend=async()=>{this[Vu]&&await this.send()};handleEventQUICStreamDestroyed=e=>{const t=e.target;t.removeEventListener(nf.name,this.handleEventQUICStreamSend),t.removeEventListener(nu.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 Yd("`keepAliveIntervalTime` must be less than `maxIdleTimeout`");const h=function(e){if(null!=e.key&&null==e.cert)throw new xd("The cert option must be set when key is set");if(null==e.key&&null!=e.cert)throw new xd("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 xd("The number of keys must match the number of certs");let t,r,s,i;if(null!=e.ca){const r=Bg(e.ca);t=dg.encode(r.join(""))}null!=e.key&&(r=Bg(e.key).map(e=>dg.encode(e))),null!=e.cert&&(s=Bg(e.cert).map(e=>dg.encode(e)));try{i=Id.Config.withBoringSslCtx(e.verifyPeer,null!=e.verifyCallback,t,r,s,e.sigalgs)}catch(e){throw new xd(`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=Id.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=Id.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=Bg(this.config.cert);this.certDERs=e.map(_g)}if(null!=this.config.ca){const e=Bg(this.config.ca);this.caDERs=e.map(_g)}this.reasonToCode=a,this.codeToReason=c,this._remoteHost=i.host,this._remotePort=i.port;const{p:d,resolveP:g,rejectP:f}=yg();d.catch(()=>{}),this.secureEstablishedP=d,this.resolveSecureEstablishedP=()=>{this.secureEstablished=!0,g()},this.rejectSecureEstablishedP=f;const{p,resolveP:y}=yg();this.closedP=p,this.resolveClosedP=y}get connectionId(){const e=this.conn.sourceId();return new md(e.buffer,e.byteOffset,e.byteLength)}get connectionIdPeer(){const e=this.conn.destinationId();return new md(e.buffer,e.byteOffset,e.byteLength)}get connectionIdShared(){const e=this.conn.sourceId(),t=this.conn.destinationId();return Buffer.compare(e,t)<=0?new md(Buffer.concat([e,t])):new md(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 Wd;r.signal.throwIfAborted();const{p:s,rejectP:i}=yg();s.catch(()=>{});const n=()=>{i(r.signal.reason)};if(r.signal.addEventListener("abort",n),this.addEventListener(Wg.name,this.handleEventQUICConnectionError),this.addEventListener(Jg.name,this.handleEventQUICConnectionClose,{once:!0}),"client"===this.type)await this.send();else if("server"===this.type){if(null==e||null==t)throw new Jd("Starting a server connection requires initial data and remote information");await this.recv(e,t)}try{await Promise.race([this.secureEstablishedP,s])}catch(e){if(r.signal.aborted){for(const t of this.conn.readable())this.conn.streamShutdown(t,Id.Shutdown.Read,this.reasonToCode("read",e));for(const t of this.conn.writable())this.conn.streamShutdown(t,Id.Shutdown.Write,this.reasonToCode("write",e));this.conn.close(!1,kf.ApplicationError,Buffer.from(""));const t=this.conn.localError(),r=new Xd("Failed to start QUIC connection due to start timeout",{data:t,cause:e});this.dispatchEvent(new Wg({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 Xd(i,{data:s});this.dispatchEvent(new Wg({detail:n}))}await this.closedP,this.removeEventListener(Wg.name,this.handleEventQUICConnectionError),this.removeEventListener(Jg.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 sg("Failed connection recv due with unknown error",{cause:e});throw this.dispatchEvent(new Wg({detail:t})),t}{let r;return r="TlsFail"===e.message?new Zd("Failed connection due to native TLS verification",{cause:e,data:t}):new Xd("Failed connection due to local error",{cause:e,data:t}),void this.dispatchEvent(new Wg({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 sg("Failed connection send with unknown internal error",{cause:e});throw this.dispatchEvent(new Wg({detail:t})),t}this.dispatchEvent(new Xg({detail:{id:this.sendId,msg:r.subarray(0,e),port:t.to.port,address:t.to.host}}))}if(this.setConnTimeoutTimer(),!this.secureEstablished&&!this.conn.isDraining()&&!this.conn.isClosed()&&this.conn.isEstablished()&&this.config.verifyPeer&&null!=this.config.verifyCallback){const e=this.conn.peerCertChain(),t=await this.config.verifyCallback(e,this.caDERs);if(null!=t){this.conn.close(!1,t,Buffer.from(""));const e=this.conn.localError(),r=new Zd("Failed connection due to custom TLS verification",{data:e});return void this.dispatchEvent(new Wg({detail:r}))}this.resolveSecureEstablishedP(),this.processStreams()}if("stopping"!==this[$u]){const e=this.conn.peerError();if(null!=e){const t=`Peer closed with ${e.isApp?"application":"transport"} code ${e.errorCode}`;return void(e.errorCode>=Id.CRYPTO_ERROR_START&&e.errorCode<=Id.CRYPTO_ERROR_STOP?this.dispatchEvent(new Wg({detail:new tg(t,{data:e})})):this.dispatchEvent(new Wg({detail:new eg(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:fg("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[Vu]||"stopping"===this[$u]){this.conn.streamShutdown(e,Ef.Write,this.reasonToCode("write",qd)),this.conn.streamShutdown(e,Ef.Read,this.reasonToCode("read",qd));continue}this.isStreamUsed(e)&&fg("We should never repeat streamIds when creating streams"),t=wf.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${wf.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(nf.name,this.handleEventQUICStreamSend),t.addEventListener(ef.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(nu.name,this.handleEventQUICStream),this.dispatchEvent(new Yg({detail:t}))}t.read()}for(const e of this.conn.writable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[Vu]||"stopping"===this[$u]){this.conn.streamShutdown(e,Ef.Write,this.reasonToCode("write",qd)),this.conn.streamShutdown(e,Ef.Read,this.reasonToCode("read",qd));continue}if(this.isStreamUsed(e)){try{this.conn.streamSend(e,new Uint8Array,!1)}catch(e){if(!1!==Og(e))continue;if("FinalSize"===e.message)continue;throw e}fg("We never expect a duplicate stream to be readable")}t=wf.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${wf.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(nf.name,this.handleEventQUICStreamSend),t.addEventListener(ef.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(nu.name,this.handleEventQUICStream),this.dispatchEvent(new Yg({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 Wg({detail:new rg})));await this.send();const r=this.conn.timeout();null!=r&&(this.connTimeoutTimer=new Uu({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 Wg({detail:new rg}))));null==this.connTimeoutTimer||"settled"===this.connTimeoutTimer.status?this.connTimeoutTimer=new Uu({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)&&fg("We should never repeat streamIds when creating streams");const r=wf.createQUICStream({initiated:"local",streamId:t,connection:this,config:this.config,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${wf.name} ${t}`)});return this.streamMap.set(r.streamId,r),r.addEventListener(nf.name,this.handleEventQUICStreamSend),r.addEventListener(ef.name,this.handleEventQUICStreamDestroyed,{once:!0}),r.addEventListener(nu.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 Uu({delay:e,handler:t,lazy:!0})))};this.keepAliveIntervalTimer=new Uu({delay:e,handler:t,lazy:!0})}stopKeepAliveIntervalTimer(){this.keepAliveIntervalTimer?.cancel()}};var Of,Uf;_f([pd(new zd)],Rf.prototype,"connectionIdPeer",null),_f([pd(new zd)],Rf.prototype,"connectionIdShared",null),_f([gf(!0,pf,class extends jd{static description="QUIC Connection start timeout"}),(Of=1,Uf=hf,function(e,t){Uf(e,t,Of)})],Rf.prototype,"start",null),_f([pd(new zd,!1,["starting","stopping"])],Rf.prototype,"recv",null),_f([pd(new zd,!1,["starting","stopping"])],Rf.prototype,"send",null),_f([pd(new zd)],Rf.prototype,"newStream",null),Rf=_f([fd({eventStart:class extends qg{},eventStarted:class extends qg{},eventStop:class extends qg{},eventStopped:zg})],Rf);const Tf=Rf;var Nf=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 Df=class{isSocketShared;reasonToCode;codeToReason;minIdleTimeout;logger;socket;crypto;config;_closed=!1;_closedP;resolveClosedP;stopAbortController;handleEventQUICServerError=e=>{const t=e.detail;if(this.logger.info(Rg(t)),t instanceof Gd)throw t;this.dispatchEvent(new jg({detail:t}))};handleEventQUICServerClose=async e=>{const t=e.detail;if(!(t instanceof Qd||this.isSocketShared)){this.socket.removeEventListener(Mg.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new Gd("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new $g({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[Vu]&&"stopping"!==this[$u]&&(void 0!==t?await this.stop({isApp:!1,errorCode:kf.InternalError,reason:Buffer.from(t.description),force:!0}):await this.stop({force:!0}))};handleEventQUICSocket=e=>{e.detail instanceof tu&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new Qd;this.removeEventListener(nu.name,this.handleEventQUICSocket),this.dispatchEvent(new $g({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof tu&&!(e.detail instanceof Xg)&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionSend=async e=>{if(this.socket[Vu]&&"stopping"!==this.socket[$u])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 Vg(`${Vg.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new $g({detail:new Gd("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(Xg.name,this.handleEventQUICConnectionSend),t.removeEventListener(nu.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({crypto:e,config:t,socket:r,resolveHostname:s=Sg,reasonToCode:i,codeToReason:n,minIdleTimeout:o,logger:a}){this.logger=a??new Zh(this.constructor.name),this.crypto=e,null==r?(this.socket=new cf({resolveHostname:s,logger:this.logger.getChild(cf.name)}),this.isSocketShared=!1):(this.socket=r,this.isSocketShared=!0),this.config={...mf,...t},this.reasonToCode=i,this.codeToReason=n,this.minIdleTimeout=o;const{p:c,resolveP:l}=yg();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,Tg(this.stopAbortController.signal),this.isSocketShared){if(!this.socket[Vu])throw new Qd;i=kg(this.socket.host,this.socket.port),this.logger.info(`Start ${this.constructor.name} on ${i}`)}else i=kg(e,t),this.logger.info(`Start ${this.constructor.name} on ${i}`),await this.socket.start({host:e,port:t,reuseAddr:r,ipv6Only:s}),i=kg(this.socket.host,this.socket.port);this.socket.setServer(this),this.addEventListener($g.name,this.handleEventQUICServerError),this.addEventListener(jg.name,this.handleEventQUICServerClose,{once:!0}),this.socket.addEventListener(Mg.name,this.handleEventQUICSocketStopped,{once:!0}),this.isSocketShared||this.socket.addEventListener(nu.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[Vu]&&(i=kg(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 $d),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 jg),await this._closedP;const{p:o,resolveP:a}=yg();this._closedP=o,this.resolveClosedP=a,this.removeEventListener($g.name,this.handleEventQUICServerError),this.removeEventListener(jg.name,this.handleEventQUICServerClose),this.socket.removeEventListener(Mg.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(nu.name,this.handleEventQUICSocket),this.logger.info(`Stopped ${this.constructor.name}${null!=i?` on ${i}`:""}`)}async acceptConnection(e,t,r,s){if(t.ty!==Id.Type.Initial&&t.ty!==Id.Type.ZeroRTT)return;const i=new md(await this.crypto.ops.sign(this.crypto.key,r),0,Id.MAX_CONN_ID_LEN),n=kg(e.host,e.port);if(!Id.versionIsSupported(t.version)){const r=Buffer.allocUnsafe(Id.MAX_DATAGRAM_SIZE),s=Id.negotiateVersion(t.scid,t.dcid,r);try{await this.socket.send_(r,0,s,e.port,e.host)}catch(e){throw new Fd(`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(Id.MAX_DATAGRAM_SIZE),a=Id.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 Fd(`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 md(t.dcid),l=new Tf({type:"server",scid:c,dcid:a,socket:this.socket,remoteInfo:e,config:{...this.config},reasonToCode:this.reasonToCode,codeToReason:this.codeToReason,logger:this.logger.getChild(`${Tf.name} ${i.toString()}`)});this.socket.connectionMap.set(l.connectionId,l),l.addEventListener(Xg.name,this.handleEventQUICConnectionSend),l.addEventListener(zg.name,this.handleEventQUICConnectionStopped,{once:!0}),l.addEventListener(nu.name,this.handleEventQUICConnection);try{await l.start({data:s,remoteInfo:e},{timer:this.minIdleTimeout,signal:this.stopAbortController?.signal})}catch(e){throw l.removeEventListener(Xg.name,this.handleEventQUICConnectionSend),l.removeEventListener(zg.name,this.handleEventQUICConnectionStopped),l.removeEventListener(nu.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(l.connectionId),new Fd("Failed to start accepted connection",{cause:e})}return this.dispatchEvent(new Gg({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?md.fromString(o.dcid):void 0}(e,t,this.crypto)}};Nf([pd(new Vd)],Df.prototype,"host",null),Nf([pd(new Vd)],Df.prototype,"port",null),Nf([pd(new Vd)],Df.prototype,"acceptConnection",null),Df=Nf([fd({eventStart:class extends Fg{},eventStarted:class extends Fg{},eventStop:class extends Fg{},eventStopped:class extends Fg{}})],Df);var Mf=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 Pf=class{static async createQUICClient({host:e,port:t,serverName:r,localHost:s="::",localPort:i=0,socket:n,crypto:o,config:a={},resolveHostname:c=Sg,reuseAddr:l,ipv6Only:h,reasonToCode:u,codeToReason:d,logger:g=new Zh(`${this.name}`)},f){let p=kg(e,t);g.info(`Create ${this.name} to ${p}`);const y={...yf,...a},m=new ArrayBuffer(Id.MAX_CONN_ID_LEN);await o.ops.randomBytes(m);const b=new md(m);let[A,I]=await Eg(e,c);const v=Cg(t);let w,S;if(A=wg(A),null==n){const[e]=await Eg(s,c),t=Cg(i);n=new cf({resolveHostname:c,logger:g.getChild(cf.name)}),w=!1,await n.start({host:e,port:t,reuseAddr:l,ipv6Only:h})}else if(w=!0,!n[Vu])throw new Qd;try{A=xg(n.host,n.type,A,I,Ld)}catch(e){throw w||await n.stop({force:!0}),e}try{S=new Tf({type:"client",scid:b,serverName:r??e,socket:n,remoteInfo:{host:A,port:v},config:y,reasonToCode:u,codeToReason:d,logger:g.getChild(`${Tf.name} ${b.toString()}`)})}catch(e){throw w||await n.stop({force:!0}),e}const E=new this({socket:n,connection:S,isSocketShared:w,logger:g});w||n.addEventListener(nu.name,E.handleEventQUICSocket),n.addEventListener(Mg.name,E.handleEventQUICSocketStopped,{once:!0}),S.addEventListener(nu.name,E.handleEventQUICConnection),S.addEventListener(Wg.name,E.handleEventQUICConnectionError),S.addEventListener(Xg.name,E.handleEventQUICConnectionSend),S.addEventListener(zg.name,E.handleEventQUICConnectionStopped,{once:!0}),E.addEventListener(Kg.name,E.handleEventQUICClientError),E.addEventListener(Qg.name,E.handleEventQUICClientClose,{once:!0}),n.connectionMap.set(S.connectionId,S);const C=new AbortController,k=()=>{C.abort(f.signal.reason)};f.signal.aborted?C.abort(f.signal.reason):f.signal.addEventListener("abort",k);const x=e=>{switch(e.detail.code){case"EINVAL":case"EADDRNOTAVAIL":case"ENETUNREACH":C.abort(new Pd(void 0,{cause:e.detail}))}};E.addEventListener(`${Vg.name}-${S.sendId}`,x);try{await S.start(void 0,{timer:f.timer,signal:C.signal})}catch(e){throw n.connectionMap.delete(S.connectionId),n.removeEventListener(Mg.name,E.handleEventQUICSocketStopped),w||(n.removeEventListener(nu.name,E.handleEventQUICSocket),await n.stop({force:!0})),S.removeEventListener(nu.name,E.handleEventQUICConnection),S.removeEventListener(Wg.name,E.handleEventQUICConnectionError),S.removeEventListener(Xg.name,E.handleEventQUICConnectionSend),S.removeEventListener(zg.name,E.handleEventQUICConnectionStopped),E.removeEventListener(Kg.name,E.handleEventQUICClientError),E.removeEventListener(Qg.name,E.handleEventQUICClientClose),e}finally{f.signal.removeEventListener("abort",k),E.removeEventListener(`${Vg.name}-${S.sendId}`,x)}return p=kg(A,t),g.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(Rg(t)),t instanceof Hd||t instanceof sg)throw t;this.dispatchEvent(new Qg({detail:t}))};handleEventQUICClientClose=async e=>{const t=e.detail;if(this.connection.removeEventListener(Wg.name,this.handleEventQUICConnectionError),await this.connection.stop({isApp:!1,errorCode:kf.InternalError,reason:Buffer.from(t.description),force:!0}),!(t instanceof Md||this.isSocketShared)){this.socket.removeEventListener(Mg.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new Hd("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new Kg({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[Fu]||"destroying"===this[$u]||await this.destroy({force:!0})};handleEventQUICSocket=e=>{e.detail instanceof tu&&!(e.detail instanceof Xg)&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new Md;this.removeEventListener(nu.name,this.handleEventQUICSocket),this.dispatchEvent(new Kg({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof tu&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionError=e=>{const t=e.detail;this.dispatchEvent(new Kg({detail:t}))};handleEventQUICConnectionSend=async e=>{try{if(!this.socket[Vu]||"stopping"===this.socket[$u])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 Vg(`${Vg.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new Kg({detail:new Hd("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(Wg.name,this.handleEventQUICConnectionError),t.removeEventListener(Xg.name,this.handleEventQUICConnectionSend),t.removeEventListener(nu.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}=yg();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[Vu]&&(i=kg(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(Kg.name,this.handleEventQUICClientError),this.removeEventListener(Qg.name,this.handleEventQUICClientClose),this.socket.removeEventListener(Mg.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(nu.name,this.handleEventQUICSocket),this.logger.info(`Destroyed ${this.constructor.name}${null!=i?` to ${i}`:""}`)}};Mf([gd(new Dd)],Pf.prototype,"host",null),Mf([gd(new Dd)],Pf.prototype,"port",null),Mf([gd(new Dd)],Pf.prototype,"localHost",null),Mf([gd(new Dd)],Pf.prototype,"localPort",null),Mf([gf(!0,pf,class extends Nd{static description="QUIC Client create timeout"}),function(e,t){return function(r,s){t(r,s,e)}}(1,hf)],Pf,"createQUICClient",null),Pf=Mf([dd({eventDestroy:class extends Hg{},eventDestroyed:class extends Hg{}})],Pf),t(import.meta.url)("node:crypto");class Lf{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=Lf.toUint8Array(e),s=Lf.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 Hf="string",Kf=/^[0-9a-f\s]+$/i,Vf=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Qf=/^[a-zA-Z0-9-_]+$/;class Ff{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=Lf.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return decodeURIComponent(escape(r))}}class Gf{static toString(e,t=!1){const r=Lf.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 $f{static isHex(e){return typeof e===Hf&&Kf.test(e)}static isBase64(e){return typeof e===Hf&&Vf.test(e)}static isBase64Url(e){return typeof e===Hf&&Qf.test(e)}static ToString(e,t="utf8"){const r=Lf.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 Gf.toString(r,!0);case"utf16":case"utf16be":return Gf.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 Gf.fromString(e,!0);case"utf16":case"utf16be":return Gf.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=Lf.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(!$f.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(!$f.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=$f.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Ff.fromString(e);case"utf16":case"utf16be":return Gf.fromString(e);case"utf16le":case"usc2":return Gf.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=$f.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Ff.toString(e);case"utf16":case"utf16be":return Gf.toString(e);case"utf16le":case"usc2":return Gf.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=Lf.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return r}static ToHex(e){const t=Lf.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(!$f.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 Gf.toString(e,t)}static FromUtf16String(e,t=!1){return Gf.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 jf(...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 qf(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 zf(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 Wf(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 Jf(...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 Yf(){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=zf(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,zf(n,8)-s}function Xf(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 Zf(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function ep(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 tp(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)}$f.DEFAULT_UTF8_ENCODING="utf8",Math.log(2);class rp{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return ep(this.items)}}const sp=[new Uint8Array([1])],ip="0123456789",np="name",op="valueHexView",ap="isHexOnly",cp="idBlock",lp="tagClass",hp="tagNumber",up="isConstructed",dp="fromBER",gp="toBER",fp="local",pp="",yp=new ArrayBuffer(0),mp=new Uint8Array(0),bp="EndOfContent",Ap="OCTET STRING",Ip="BIT STRING";function vp(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?Lf.toUint8Array(r.valueHex):mp}fromBER(e,t,r){const s=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!tp(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",yp)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:$f.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class wp{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=pp,warnings:r=[],valueBeforeDecode:s=mp}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=Lf.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:$f.ToHex(this.valueBeforeDecodeView)}}}wp.NAME="baseBlock";class Sp extends wp{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'")}}Sp.NAME="valueBlock";class Ep extends(vp(wp)){constructor({idBlock:e={}}={}){var t,r,s,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?Lf.toUint8Array(e.valueHex):mp,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",yp}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=Wf(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=Lf.toUint8Array(e);if(!tp(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=zf(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}}}Ep.NAME="identificationBlock";class Cp extends wp{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=Lf.toUint8Array(e);if(!tp(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=zf(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=Wf(this.length,8);if(s.byteLength>127)return this.error="Too big length",yp;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}}}Cp.NAME="lengthBlock";const kp={};class xp extends wp{constructor({name:e=pp,optional:t=!1,primitiveSchema:r,...s}={},i){super(s),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new Ep(s),this.lenBlock=new Cp(s),this.valueBlock=i?new i(s):new Sp(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 rp;t||Bp(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?yp: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():$f.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${$f.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 Bp(e){var t;if(e instanceof kp.Constructed)for(const t of e.valueBlock.value)Bp(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}xp.NAME="BaseBlock";class _p extends xp{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=pp,...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}'`}}_p.NAME="BaseStringBlock";class Rp extends(vp(Sp)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var Op,Up,Tp,Np,Dp,Mp,Pp,Lp,Hp,Kp,Vp,Qp,Fp,Gp,$p,jp,qp,zp,Wp,Jp,Yp,Xp,Zp,ey,ty,ry,sy,iy,ny,oy,ay,cy,ly,hy,uy,dy;Rp.NAME="PrimitiveValueBlock";class gy extends xp{constructor(e={}){super(e,Rp),this.idBlock.isConstructed=!1}}function fy(e,t=0,r=e.length){const s=t;let i=new xp({},Sp);const n=new wp;if(!tp(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=xp;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=kp.EndOfContent;break;case 1:a=kp.Boolean;break;case 2:a=kp.Integer;break;case 3:a=kp.BitString;break;case 4:a=kp.OctetString;break;case 5:a=kp.Null;break;case 6:a=kp.ObjectIdentifier;break;case 10:a=kp.Enumerated;break;case 12:a=kp.Utf8String;break;case 13:a=kp.RelativeObjectIdentifier;break;case 14:a=kp.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:a=kp.Sequence;break;case 17:a=kp.Set;break;case 18:a=kp.NumericString;break;case 19:a=kp.PrintableString;break;case 20:a=kp.TeletexString;break;case 21:a=kp.VideotexString;break;case 22:a=kp.IA5String;break;case 23:a=kp.UTCTime;break;case 24:a=kp.GeneralizedTime;break;case 25:a=kp.GraphicString;break;case 26:a=kp.VisibleString;break;case 27:a=kp.GeneralString;break;case 28:a=kp.UniversalString;break;case 29:a=kp.CharacterString;break;case 30:a=kp.BmpString;break;case 31:a=kp.DATE;break;case 32:a=kp.TimeOfDay;break;case 33:a=kp.DateTime;break;case 34:a=kp.Duration;break;default:{const e=i.idBlock.isConstructed?new kp.Constructed:new kp.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else a=i.idBlock.isConstructed?kp.Constructed:kp.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 py(e){if(!e.byteLength){const e=new xp({},Sp);return e.error="Input buffer has zero length",{offset:-1,result:e}}return fy(Lf.toUint8Array(e).slice(),0,e.byteLength)}function yy(e,t){return e?1:t}Op=gy,kp.Primitive=Op,gy.NAME="PRIMITIVE";class my extends Sp{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const s=Lf.toUint8Array(e);if(!tp(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(;yy(this.isIndefiniteForm,r)>0;){const e=fy(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===bp)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===bp?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){const r=t||new rp;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?yp:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}my.NAME="ConstructedValueBlock";class by extends xp{constructor(e={}){super(e,my),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} :`}}Up=by,kp.Constructed=Up,by.NAME="CONSTRUCTED";class Ay extends Sp{fromBER(e,t,r){return t}toBER(e){return yp}}Ay.override="EndOfContentValueBlock";class Iy extends xp{constructor(e={}){super(e,Ay),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Tp=Iy,kp.EndOfContent=Tp,Iy.NAME=bp;class vy extends xp{constructor(e={}){super(e,Sp),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}`}}Np=vy,kp.Null=Np,vy.NAME="NULL";class wy extends(vp(Sp)){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=Lf.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,r){const s=Lf.toUint8Array(e);return tp(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,Yf.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}wy.NAME="BooleanValueBlock";class Sy extends xp{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,wy),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}Dp=Sy,kp.Boolean=Dp,Sy.NAME="BOOLEAN";class Ey extends(vp(my)){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=my.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===bp){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==Ap)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?my.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Ey.NAME="OctetStringValueBlock";class Cy extends xp{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},Ey),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=fy(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?by.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${$f.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 Mp&&e.push(t.valueBlock.valueHexView);return Lf.concat(e)}}Mp=Cy,kp.OctetString=Mp,Cy.NAME=Ap;class ky extends(vp(my)){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=my.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(const e of this.value){const t=e.constructor.NAME;if(t===bp){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==Ip)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=Lf.toUint8Array(e);if(!tp(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=fy(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 my.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return yp;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}}}ky.NAME="BitStringValueBlock";class xy extends xp{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},ky),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 by.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 By(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=Jf(new Uint8Array([l%10]),n):n[o-h]=l%10;return r[0]>0&&(n=Jf(r,n)),n}function _y(e){if(e>=sp.length)for(let t=sp.length;t<=e;t++){const e=new Uint8Array([0]);let r=sp[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=Jf(e,r)),sp.push(r)}return sp[e]}function Ry(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()}Pp=xy,kp.BitString=Pp,xy.NAME=Ip;class Oy extends(vp(Sp)){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=Yf.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=Wf(r-t,8,s);return new Uint8Array(e)[0]|=128,e}let i=Wf(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=Ry(_y(s),r),n="-"):r=By(r,_y(s))),s++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(o=!0),o&&(n+=ip.charAt(r[e]));return!1===o&&(n+=ip.charAt(0)),n}}Lp=Oy,Oy.NAME="IntegerValueBlock",Object.defineProperty(Lp.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class Uy extends xp{constructor(e={}){super(e,Oy),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Zf(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Zf();const t=BigInt(e),r=new rp,s=t.toString(16).replace(/^-/,""),i=new Uint8Array($f.FromHex(s));if(t<0){const e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;const s=BigInt(`0x${$f.ToHex(e)}`)+t,n=Lf.toUint8Array($f.FromHex(s.toString(16)));n[0]|=128,r.write(n)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);return new Hp({valueHex:r.final()})}convertToDER(){const e=new Hp({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Hp({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}Hp=Uy,kp.Integer=Hp,Uy.NAME="INTEGER";class Ty extends Uy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Kp=Ty,kp.Enumerated=Kp,Ty.NAME="ENUMERATED";class Ny extends(vp(Sp)){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=Lf.toUint8Array(e);if(!tp(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=zf(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Zf();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=Wf(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",yp;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=$f.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}}}Ny.NAME="sidBlock";class Dy extends Sp{constructor({value:e=pp,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new Ny;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,yp;t.push(s)}return ep(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 Ny;if(s>Number.MAX_SAFE_INTEGER){Zf();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}}Dy.NAME="ObjectIdentifierValueBlock";class My extends xp{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Dy),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Vp=My,kp.ObjectIdentifier=Vp,My.NAME="OBJECT IDENTIFIER";class Py extends(vp(wp)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const s=Lf.toUint8Array(e);if(!tp(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=zf(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=Wf(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",yp;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?$f.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Py.NAME="relativeSidBlock";class Ly extends Sp{constructor({value:e=pp,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new Py;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,yp;r.push(s)}return ep(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 Py;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}}Ly.NAME="RelativeObjectIdentifierValueBlock";class Hy extends xp{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Ly),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Qp=Hy,kp.RelativeObjectIdentifier=Qp,Hy.NAME="RelativeObjectIdentifier";class Ky extends by{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}Fp=Ky,kp.Sequence=Fp,Ky.NAME="SEQUENCE";class Vy extends by{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}Gp=Vy,kp.Set=Gp,Vy.NAME="SET";class Qy extends(vp(Sp)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=pp}toJSON(){return{...super.toJSON(),value:this.value}}}Qy.NAME="StringValueBlock";class Fy extends Qy{}Fy.NAME="SimpleStringValueBlock";class Gy extends _p{constructor({...e}={}){super(e,Fy)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,Lf.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}}Gy.NAME="SIMPLE STRING";class $y extends Gy{fromBuffer(e){this.valueBlock.valueHexView=Lf.toUint8Array(e);try{this.valueBlock.value=$f.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=$f.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array($f.FromUtf8String(e)),this.valueBlock.value=e}}$y.NAME="Utf8StringValueBlock";class jy extends $y{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}$p=jy,kp.Utf8String=$p,jy.NAME="UTF8String";class qy extends Gy{fromBuffer(e){this.valueBlock.value=$f.ToUtf16String(e),this.valueBlock.valueHexView=Lf.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array($f.FromUtf16String(e))}}qy.NAME="BmpStringValueBlock";class zy extends qy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}jp=zy,kp.BmpString=jp,zy.NAME="BMPString";class Wy extends Gy{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=Wf(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}}Wy.NAME="UniversalStringValueBlock";class Jy extends Wy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}qp=Jy,kp.UniversalString=qp,Jy.NAME="UniversalString";class Yy extends Gy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}zp=Yy,kp.NumericString=zp,Yy.NAME="NumericString";class Xy extends Gy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}Wp=Xy,kp.PrintableString=Wp,Xy.NAME="PrintableString";class Zy extends Gy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}Jp=Zy,kp.TeletexString=Jp,Zy.NAME="TeletexString";class em extends Gy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Yp=em,kp.VideotexString=Yp,em.NAME="VideotexString";class tm extends Gy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}Xp=tm,kp.IA5String=Xp,tm.NAME="IA5String";class rm extends Gy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}Zp=rm,kp.GraphicString=Zp,rm.NAME="GraphicString";class sm extends Gy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}ey=sm,kp.VisibleString=ey,sm.NAME="VisibleString";class im extends Gy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}ty=im,kp.GeneralString=ty,im.NAME="GeneralString";class nm extends Gy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}ry=nm,kp.CharacterString=ry,nm.NAME="CharacterString";class om extends sm{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,Lf.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]=Xf(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Xf(this.month,2),e[2]=Xf(this.day,2),e[3]=Xf(this.hour,2),e[4]=Xf(this.minute,2),e[5]=Xf(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}}}sy=om,kp.UTCTime=sy,om.NAME="UTCTime";class am extends om{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(Xf(this.year,4)),e.push(Xf(this.month,2)),e.push(Xf(this.day,2)),e.push(Xf(this.hour,2)),e.push(Xf(this.minute,2)),e.push(Xf(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(Xf(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}iy=am,kp.GeneralizedTime=iy,am.NAME="GeneralizedTime";class cm extends jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}ny=cm,kp.DATE=ny,cm.NAME="DATE";class lm extends jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}oy=lm,kp.TimeOfDay=oy,lm.NAME="TimeOfDay";class hm extends jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}ay=hm,kp.DateTime=ay,hm.NAME="DateTime";class um extends jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}cy=um,kp.Duration=cy,um.NAME="Duration";class dm extends jy{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}ly=dm,kp.TIME=ly,dm.NAME="TIME";class gm{constructor({name:e=pp,optional:t=!1}={}){this.name=e,this.optional=t}}class fm extends gm{constructor({value:e=[],...t}={}){super(t),this.value=e}}class pm extends gm{constructor({value:e=new gm,local:t=!1,...r}={}){super(r),this.value=e,this.local=t}}class ym{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=Lf.toUint8Array(e)}constructor({data:e=mp}={}){this.dataView=Lf.toUint8Array(e)}fromBER(e,t,r){const s=t+r;return this.dataView=Lf.toUint8Array(e).subarray(t,s),s}toBER(e){return this.dataView.slice().buffer}}function mm(e,t,r){if(r instanceof fm){for(const s of r.value)if(mm(e,t,s).verified)return{verified:!0,result:e};{const e={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(np)&&(e.name=r.name),e}}if(r instanceof gm)return r.hasOwnProperty(np)&&(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(cp in r==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(dp in r.idBlock==0)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(gp 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(lp))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(hp))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(up))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(ap 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(op 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,pp),r.name&&(e[r.name]=t)),r instanceof kp.Constructed){let s=0,i={verified:!1,result:{error:"Unknown error"}},n=r.valueBlock.value.length;if(n>0&&r.valueBlock.value[0]instanceof pm&&(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,pp),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,pp),r.name&&(delete e[r.name],t.name=r.name)),t}}else if(r.valueBlock.value[0]instanceof pm){if(i=mm(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,pp),r.name&&delete e[r.name]),i;s++}if(np in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let s={};s=fp 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=mm(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,pp),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,pp),r.name&&(delete e[r.name],t.name=r.name)),t}return{verified:!0,result:e}}if(r.primitiveSchema&&op in t.valueBlock){const s=fy(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,pp),r.name&&(delete e[r.name],t.name=r.name)),t}return mm(e,s.result,r.primitiveSchema)}return{verified:!0,result:e}}function bm(e,t){if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=fy(Lf.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:mm(r.result,r.result,t)}(dy=hy||(hy={}))[dy.Sequence=0]="Sequence",dy[dy.Set=1]="Set",dy[dy.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"}(uy||(uy={}));class Am{constructor(e,t=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if("number"==typeof e)this.fromNumber(e);else{if(!Lf.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=Lf.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof xy))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 xy({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new xy({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 Im{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):Lf.isBufferSource(e)?this.buffer=Lf.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Cy))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new Cy({valueHex:this.buffer})}toSchema(e){return new Cy({name:e})}}const vm={fromASN:e=>e instanceof vy?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new vy;const t=py(e);if(t.result.error)throw new Error(t.result.error);return t.result}},wm={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new Uy({value:+e})},Sm={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new Ty({value:e})},Em={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Uy({valueHex:e})},Cm={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new xy({valueHex:e})},km={fromASN:e=>e.valueBlock.toString(),toASN:e=>new My({value:e})},xm={fromASN:e=>e.valueBlock.value,toASN:e=>new Sy({value:e})},Bm={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Cy({valueHex:e})},_m={fromASN:e=>new Im(e.getValue()),toASN:e=>e.toASN()};function Rm(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}const Om=Rm(jy),Um=Rm(zy),Tm=Rm(Jy),Nm=Rm(Yy),Dm=Rm(Xy),Mm=Rm(Zy),Pm=Rm(em),Lm=Rm(tm),Hm=Rm(rm),Km=Rm(sm),Vm=Rm(im),Qm=Rm(nm),Fm={fromASN:e=>e.toDate(),toASN:e=>new om({valueDate:e})},Gm={fromASN:e=>e.toDate(),toASN:e=>new am({valueDate:e})},$m={fromASN:()=>null,toASN:()=>new vy};function jm(e){switch(e){case uy.Any:return vm;case uy.BitString:return Cm;case uy.BmpString:return Um;case uy.Boolean:return xm;case uy.CharacterString:return Qm;case uy.Enumerated:return Sm;case uy.GeneralString:return Vm;case uy.GeneralizedTime:return Gm;case uy.GraphicString:return Hm;case uy.IA5String:return Lm;case uy.Integer:return wm;case uy.Null:return $m;case uy.NumericString:return Nm;case uy.ObjectIdentifier:return km;case uy.OctetString:return Bm;case uy.PrintableString:return Dm;case uy.TeletexString:return Mm;case uy.UTCTime:return Fm;case uy.UniversalString:return Tm;case uy.Utf8String:return Om;case uy.VideotexString:return Pm;case uy.VisibleString:return Km;default:return null}}function qm(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||qm(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function zm(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||zm(r)}return!1}function Wm(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;const r=new Uint8Array(e),s=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(r[t]!==s[t])return!1;return!0}const Jm=new class{constructor(){this.items=new WeakMap}has(e){return this.items.has(e)}get(e,t=!1){const r=this.items.get(e);if(!r)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!r.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return r}cache(e){const t=this.get(e);t.schema||(t.schema=this.create(e,!0))}createDefault(e){const t={type:hy.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=uy[i.type],t=a[e];if(!t)throw new Error(`Cannot get ASN1 class by name '${e}'`);o=new t({name:n})}else qm(i.type)?o=(new i.type).toSchema(n):i.optional?this.get(i.type).type===hy.Choice?o=new gm({name:n}):(o=this.create(i.type,!1),o.name=n):o=new gm({name:n});const c=!!i.optional||void 0!==i.defaultValue;if(i.repeated&&(o.name="",o=new("set"===i.repeated?Vy:Ky)({name:"",value:[new pm({name:n,value:o})]})),null!==i.context&&void 0!==i.context)if(i.implicit)if("number"==typeof i.type||qm(i.type)){const e=i.repeated?by:gy;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 by({name:e?"":n,optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}else s.push(new by({optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:[o]}));else o.optional=c,s.push(o)}switch(r.type){case hy.Sequence:return new Ky({value:s,name:""});case hy.Set:return new Vy({value:s,name:""});case hy.Choice:return new fm({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}},Ym=e=>t=>{let r;Jm.has(t)?r=Jm.get(t):(r=Jm.createDefault(t),Jm.set(t,r)),Object.assign(r,e)},Xm=e=>(t,r)=>{let s;Jm.has(t.constructor)?s=Jm.get(t.constructor):(s=Jm.createDefault(t.constructor),Jm.set(t.constructor,s));const i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){const s=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 Zm extends Error{constructor(){super(...arguments),this.schemas=[]}}class eb{static parse(e,t){const r=py(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(qm(t))return(new t).fromASN(e);const s=Jm.get(t);Jm.cache(t);let i=s.schema;if(e.constructor===by&&s.type!==hy.Choice){i=new by({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:s.schema.valueBlock.value});for(const t in s.items)delete e[t]}const n=mm({},e,i);if(!n.verified)throw new Zm(`Data does not match to ${t.name} ASN1 schema. ${n.result.error}`);const o=new t;if(zm(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||qm(c)){const s=null!==(r=i.converter)&&void 0!==r?r:qm(c)?new c:null;if(!s)throw new Error("Converter is empty");if(i.repeated)if(i.implicit){const r=new("sequence"===i.repeated?Ky:Vy);r.valueBlock=t.valueBlock;const n=py(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(qm(c))e=(new c).toSchema("");else{const t=uy[c],r=a[t];if(!r)throw new Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=r.valueBlock,r=py(e.toBER(!1)).result}o[e]=s.fromASN(r)}}else if(i.repeated){if(!Array.isArray(t))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");o[e]=Array.from(t,e=>this.fromASN(e,c))}else o[e]=this.fromASN(t,c)}return o}catch(e){throw e instanceof Zm&&e.schemas.push(t.name),e}}}class tb{static serialize(e){return e instanceof xp?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&"object"==typeof e&&qm(e))return e.toASN();if(!e||"object"!=typeof e)throw new TypeError("Parameter 1 should be type of Object.");const t=e.constructor,r=Jm.get(t);Jm.cache(t);let s,i=[];if(r.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if("number"==typeof r.itemType){const s=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&&Wm(this.serialize(n.defaultValue),this.serialize(o)))continue;const a=tb.toAsnItem(n,s,t,o);if("number"==typeof n.context)if(n.implicit)if(n.repeated||"number"!=typeof n.type&&!qm(n.type))i.push(new by({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:a.valueBlock.value}));else{const e={};e.valueHex=a instanceof vy?a.valueBeforeDecodeView:a.valueBlock.toBER(),i.push(new gy({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},...e}))}else i.push(new by({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 hy.Sequence:s=new Ky({value:i});break;case hy.Set:s=new Vy({value:i});break;case hy.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 ${uy[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?Ky:Vy)({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?Ky:Vy)({value:t})}else i=this.toASN(s);return i}}class rb extends Array{constructor(e=[]){if("number"==typeof e)super(e);else{super();for(const t of e)this.push(t)}}}class sb{static serialize(e){return tb.serialize(e)}static parse(e,t){return eb.parse(e,t)}static toString(e){const t=py(Lf.isBufferSource(e)?Lf.toArrayBuffer(e):sb.serialize(e));if(-1===t.offset)throw new Error(`Cannot decode ASN.1 data. ${t.result.error}`);return t.result.toString()}}function ib(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 nb extends Error{constructor(e,t){super(t?`${e}. See the inner exception for more details.`:e),this.message=e,this.innerError=t}}class ob extends nb{constructor(e,t,r){super(t,r),this.schema=e}}class ab extends ob{constructor(e,t,r){super(e,`JSON doesn't match to '${e.target.name}' schema. ${t}`,r)}}class cb extends nb{}class lb extends nb{constructor(e,t,r){super(`Cannot serialize by '${e}' schema. ${t}`,r),this.schemaName=e}}class hb extends ab{constructor(e,t,r={}){super(e,"Some keys doesn't match to schema"),this.keys=t,this.errors=r}}var ub;function db(e,t){if(!function(e,t){switch(t){case ub.Boolean:return"boolean"==typeof e;case ub.Number:return"number"==typeof e;case ub.String:return"string"==typeof e}return!0}(e,t))throw new TypeError(`Value must be ${ub[t]}`)}function gb(e){return e&&e.prototype?!(!e.prototype.toJSON||!e.prototype.fromJSON)||gb(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"}(ub||(ub={}));const fb="default",pb=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 yb{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 cb("Incoming value must be string");if(!t.exec(e))throw new cb(`Value doesn't match to pattern '${t.toString()}'`)}}class mb{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(db(e,ub.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 cb(`Value doesn't match to diapason [${e},${t}]`)}}}class bb{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(db(e,ub.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 cb(`Value doesn't match to diapason (${e},${t})`)}}}class Ab{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 cb(`Value length must be more than ${this.minLength}.`);if(void 0!==this.maxLength&&e.length>this.maxLength)throw new cb(`Value length must be less than ${this.maxLength}.`)}else if(e.length!==this.length)throw new cb(`Value length must be exactly ${this.length}.`)}}class Ib{constructor(e){this.enumeration=e}validate(e){if(db(e,ub.String),!this.enumeration.includes(e))throw new cb(`Value must be one of ${this.enumeration.map(e=>`'${e}'`).join(", ")}`)}}class vb{static checkValues(e,t){const r=Array.isArray(e)?e:[e];for(const s of r)for(const r of t.validations)r instanceof Ab&&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)db(e,t.type)}}static getSchemaByName(e,t=fb){return{...e.names[fb],...e.names[t]}}}class wb extends vb{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||fb;if(gb(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&&!pb.has(s))throw new nb("Cannot get schema for `targetSchema` param");if(s=s||e.constructor,pb.has(s)){const t=pb.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 lb(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 lb?e:new lb(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 Sb extends vb{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||fb,i=new r;if(gb(i))return i.fromJSON(e);const n=pb.get(r),o=this.getSchemaByName(n,s),a={};t.strictProperty&&!Array.isArray(e)&&Sb.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 ab(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 ab||(e=new ab(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 hb(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 hb(r,n)}}const Eb=(e={})=>(t,r)=>{const s=`Cannot set type for ${r} property of ${t.constructor.name} schema`;let i;pb.has(t.constructor)?(i=pb.get(t.constructor),i.target!==t.constructor&&(i=pb.create(t.constructor),pb.set(t.constructor,i))):(i=pb.create(t.constructor),pb.set(t.constructor,i));const n={type:ub.Any,validations:[]},o=Object.assign(n,e);if(o.validations=function(e){const t=[];return e.pattern&&t.push(new yb(e.pattern)),e.type!==ub.Number&&e.type!==ub.Any||(void 0===e.minInclusive&&void 0===e.maxInclusive||t.push(new mb(e.minInclusive,e.maxInclusive)),void 0===e.minExclusive&&void 0===e.maxExclusive||t.push(new bb(e.minExclusive,e.maxExclusive)),void 0!==e.enumeration&&t.push(new Ib(e.enumeration))),(e.type===ub.String||e.repeated||e.type===ub.Any)&&(void 0===e.length&&void 0===e.minLength&&void 0===e.maxLength||t.push(new Ab(e.length,e.minLength,e.maxLength))),t}(o),"number"!=typeof o.type&&!pb.has(o.type)&&!gb(o.type))throw new Error(`${s}. Assigning type doesn't have schema.`);let a;a=Array.isArray(e.schema)?e.schema:[e.schema||fb];for(const e of a)i.names[e]||(i.names[e]={}),i.names[e][r]=o};class Cb extends Error{}class kb extends Cb{}class xb extends Cb{constructor(e){super("Unsupported operation: "+(e?`${e}`:""))}}class Bb extends Cb{}class _b extends Cb{constructor(e){super(`${e}: Missing required property`)}}class Rb{static toArrayBuffer(e){const t=e.replace(/-{5}(BEGIN|END) .*-{5}/g,"").replace("\r","").replace("\n","");return $f.FromBase64(t)}static toUint8Array(e){const t=this.toArrayBuffer(e);return new Uint8Array(t)}static fromBufferSource(e,t){const r=$f.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 Ob{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 xb("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 xb("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 xb("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 xb("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 xb("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 xb("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 Bb("length: Is not multiple of 8")}async onDeriveBits(e,t,r,...s){throw new xb("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 Cb("key: Is not extractable")}async onExportKey(e,t,...r){throw new xb("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 xb("importKey")}checkAlgorithmName(e){if(e.name.toLowerCase()!==this.name.toLowerCase())throw new kb("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 Cb("key does not match that of operation")}checkRequiredProperty(e,t){if(!(t in e))throw new _b(t)}checkHashAlgorithm(e,t){for(const r of t)if(r.toLowerCase()===e.name.toLowerCase())return;throw new Bb(`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(!Lf.isBufferSource(t))throw new TypeError("keyData: Is not ArrayBufferView or ArrayBuffer");var r}prepareData(e){return Lf.toArrayBuffer(e)}}class Ub extends Ob{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 Tb extends Ub{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 Nb extends Ub{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 Bb("length: Must be more than 0")}}class Db extends Ub{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 Bb("length: Must be more than 0")}}class Mb extends Ub{constructor(){super(...arguments),this.name="AES-ECB",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}}class Pb extends Ub{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 Bb("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 Bb("tagLength: Must be one of 32, 64, 96, 104, 112, 120 or 128")}}}class Lb extends Ub{constructor(){super(...arguments),this.name="AES-KW",this.usages=["wrapKey","unwrapKey"]}}class Hb extends Ob{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 Bb(`algorithm.length: Must be ${this.keySizeBits}`)}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class Kb extends Ob{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=$f.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 Vb extends Kb{constructor(){super(...arguments),this.name="RSASSA-PKCS1-v1_5",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class Qb extends Kb{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 Fb extends Kb{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 Gb extends Ob{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 Bb(`namedCurve: Must be one of ${this.namedCurves.join(", ")}`)}}class $b extends Gb{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 qb{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 zb extends Gb{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 qb))throw new TypeError("public: Is not a CryptoKey");if("public"!==e.public.type)throw new Bb("public: Is not a public key");if(e.public.algorithm.name!==this.name)throw new Bb(`public: Is not ${this.name} key`)}}class Wb extends zb{constructor(){super(...arguments),this.name="ECDH-ES",this.namedCurves=["X25519","X448"]}}class Jb extends Gb{constructor(){super(...arguments),this.name="EdDSA",this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["Ed25519","Ed448"]}}let Yb=class{constructor(e){e&&(this.value=e)}};ib([Xm({type:uy.ObjectIdentifier})],Yb.prototype,"value",void 0),Yb=ib([Ym({type:hy.Choice})],Yb);class Xb{constructor(e){Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],Xb.prototype,"algorithm",void 0),ib([Xm({type:uy.Any,optional:!0})],Xb.prototype,"parameters",void 0);class Zb{constructor(){this.version=0,this.privateKeyAlgorithm=new Xb,this.privateKey=new ArrayBuffer(0)}}ib([Xm({type:uy.Integer})],Zb.prototype,"version",void 0),ib([Xm({type:Xb})],Zb.prototype,"privateKeyAlgorithm",void 0),ib([Xm({type:uy.OctetString})],Zb.prototype,"privateKey",void 0),ib([Xm({type:uy.Any,optional:!0})],Zb.prototype,"attributes",void 0);class eA{constructor(){this.publicKeyAlgorithm=new Xb,this.publicKey=new ArrayBuffer(0)}}ib([Xm({type:Xb})],eA.prototype,"publicKeyAlgorithm",void 0),ib([Xm({type:uy.BitString})],eA.prototype,"publicKey",void 0);const tA={fromJSON:e=>$f.FromBase64Url(e),toJSON:e=>$f.ToBase64Url(new Uint8Array(e))},rA={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?jf(new Uint8Array([0]).buffer,e):e;return new Uy({valueHex:t})}};class sA{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)}}ib([Xm({type:uy.Integer,converter:wm})],sA.prototype,"version",void 0),ib([Xm({type:uy.Integer,converter:rA}),Eb({name:"n",converter:tA})],sA.prototype,"modulus",void 0),ib([Xm({type:uy.Integer,converter:rA}),Eb({name:"e",converter:tA})],sA.prototype,"publicExponent",void 0),ib([Xm({type:uy.Integer,converter:rA}),Eb({name:"d",converter:tA})],sA.prototype,"privateExponent",void 0),ib([Xm({type:uy.Integer,converter:rA}),Eb({name:"p",converter:tA})],sA.prototype,"prime1",void 0),ib([Xm({type:uy.Integer,converter:rA}),Eb({name:"q",converter:tA})],sA.prototype,"prime2",void 0),ib([Xm({type:uy.Integer,converter:rA}),Eb({name:"dp",converter:tA})],sA.prototype,"exponent1",void 0),ib([Xm({type:uy.Integer,converter:rA}),Eb({name:"dq",converter:tA})],sA.prototype,"exponent2",void 0),ib([Xm({type:uy.Integer,converter:rA}),Eb({name:"qi",converter:tA})],sA.prototype,"coefficient",void 0),ib([Xm({type:uy.Any,optional:!0})],sA.prototype,"otherPrimeInfos",void 0);class iA{constructor(){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0)}}ib([Xm({type:uy.Integer,converter:rA}),Eb({name:"n",converter:tA})],iA.prototype,"modulus",void 0),ib([Xm({type:uy.Integer,converter:rA}),Eb({name:"e",converter:tA})],iA.prototype,"publicExponent",void 0);let nA=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 Cb("Wrong ECPoint. Current version supports only Uncompressed (0x04) point");e=new Uint8Array(this.value.slice(1));const t=e.length/2;return{x:$f.ToBase64Url(e.buffer.slice(0,0+t)),y:$f.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=$f.FromBase64Url(e.x),r=$f.FromBase64Url(e.y),s=jf(new Uint8Array([4]).buffer,t,r);return this.value=new Uint8Array(s).buffer,this}};ib([Xm({type:uy.OctetString})],nA.prototype,"value",void 0),nA=ib([Ym({type:hy.Choice})],nA);class oA{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=$f.FromBase64Url(e.d),"x"in e){const t=new nA;t.fromJSON(e);const r=tb.toASN(t);"valueHex"in r.valueBlock&&(this.publicKey=r.valueBlock.valueHex)}return this}toJSON(){const e={};return e.d=$f.ToBase64Url(this.privateKey),this.publicKey&&Object.assign(e,new nA(this.publicKey).toJSON()),e}}ib([Xm({type:uy.Integer,converter:wm})],oA.prototype,"version",void 0),ib([Xm({type:uy.OctetString})],oA.prototype,"privateKey",void 0),ib([Xm({context:0,type:uy.Any,optional:!0})],oA.prototype,"parameters",void 0),ib([Xm({context:1,type:uy.BitString,optional:!0})],oA.prototype,"publicKey",void 0);const aA={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 Uy({valueHex:e.buffer})}return new Uy({valueHex:e})}};var cA=Object.freeze({__proto__:null,AsnIntegerWithoutPaddingConverter:aA});class lA{static decodePoint(e,t){const r=Lf.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=Lf.toUint8Array(e.x),i=Lf.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=Lf.toUint8Array(e.r),i=Lf.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=Lf.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 hA{constructor(){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0)}static fromWebCryptoSignature(e){const t=e.byteLength/2,r=lA.decodeSignature(e,8*t),s=new hA;return s.r=Lf.toArrayBuffer(r.r),s.s=Lf.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 lA.encodeSignature(this,e).buffer}}ib([Xm({type:uy.Integer,converter:aA})],hA.prototype,"r",void 0),ib([Xm({type:uy.Integer,converter:aA})],hA.prototype,"s",void 0);class uA extends Zb{}ib([Xm({context:1,implicit:!0,type:uy.BitString,optional:!0})],uA.prototype,"publicKey",void 0);let dA=class{constructor(){this.value=new ArrayBuffer(0)}fromJSON(e){if(!e.d)throw new Error("d: Missing required property");return this.value=$f.FromBase64Url(e.d),this}toJSON(){return{d:$f.ToBase64Url(this.value)}}};ib([Xm({type:uy.OctetString})],dA.prototype,"value",void 0),dA=ib([Ym({type:hy.Choice})],dA);let gA=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){return{x:$f.ToBase64Url(this.value)}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");return this.value=$f.FromBase64Url(e.x),this}};ib([Xm({type:uy.BitString})],gA.prototype,"value",void 0),gA=ib([Ym({type:hy.Choice})],gA);let fA=class{};ib([Xm({type:uy.OctetString}),Eb({type:ub.String,converter:tA})],fA.prototype,"d",void 0),fA=ib([Ym({type:hy.Choice})],fA);const pA="1.2.840.10045.3.1.7",yA="1.3.132.0",mA=`${yA}.34`,bA=`${yA}.35`,AA=`${yA}.10`,IA="1.3.36.3.3.2.8.1.1",vA=`${IA}.1`,wA=`${IA}.2`,SA=`${IA}.3`,EA=`${IA}.4`,CA=`${IA}.5`,kA=`${IA}.6`,xA=`${IA}.7`,BA=`${IA}.8`,_A=`${IA}.9`,RA=`${IA}.10`,OA=`${IA}.11`,UA=`${IA}.12`,TA=`${IA}.13`,NA=`${IA}.14`;var DA=Object.freeze({__proto__:null,AlgorithmIdentifier:Xb,get CurvePrivateKey(){return fA},EcDsaSignature:hA,EcPrivateKey:oA,get EcPublicKey(){return nA},get EdPrivateKey(){return dA},get EdPublicKey(){return gA},get ObjectIdentifier(){return Yb},OneAsymmetricKey:uA,PrivateKeyInfo:Zb,PublicKeyInfo:eA,RsaPrivateKey:sA,RsaPublicKey:iA,converters:cA,idBrainpoolP160r1:vA,idBrainpoolP160t1:wA,idBrainpoolP192r1:SA,idBrainpoolP192t1:EA,idBrainpoolP224r1:CA,idBrainpoolP224t1:kA,idBrainpoolP256r1:xA,idBrainpoolP256t1:BA,idBrainpoolP320r1:_A,idBrainpoolP320t1:RA,idBrainpoolP384r1:OA,idBrainpoolP384t1:UA,idBrainpoolP512r1:TA,idBrainpoolP512t1:NA,idEd25519:"1.3.101.112",idEd448:"1.3.101.113",idEllipticCurve:yA,idSecp256k1:AA,idSecp256r1:pA,idSecp384r1:mA,idSecp521r1:bA,idVersionOne:IA,idX25519:"1.3.101.110",idX448:"1.3.101.111"});class MA{constructor(){}static register(e){const t=new Yb;t.value=e.id;const r=sb.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}}MA.items=[],MA.names=[],MA.register({name:"P-256",id:pA,size:256}),MA.register({name:"P-384",id:mA,size:384}),MA.register({name:"P-521",id:bA,size:521}),MA.register({name:"K-256",id:AA,size:256}),MA.register({name:"brainpoolP160r1",id:vA,size:160}),MA.register({name:"brainpoolP160t1",id:wA,size:160}),MA.register({name:"brainpoolP192r1",id:SA,size:192}),MA.register({name:"brainpoolP192t1",id:EA,size:192}),MA.register({name:"brainpoolP224r1",id:CA,size:224}),MA.register({name:"brainpoolP224t1",id:kA,size:224}),MA.register({name:"brainpoolP256r1",id:xA,size:256}),MA.register({name:"brainpoolP256t1",id:BA,size:256}),MA.register({name:"brainpoolP320r1",id:_A,size:320}),MA.register({name:"brainpoolP320t1",id:RA,size:320}),MA.register({name:"brainpoolP384r1",id:OA,size:384}),MA.register({name:"brainpoolP384t1",id:UA,size:384}),MA.register({name:"brainpoolP512r1",id:TA,size:512}),MA.register({name:"brainpoolP512t1",id:NA,size:512});class PA extends Ob{constructor(){super(...arguments),this.name="X25519",this.usages={privateKey:["deriveKey","deriveBits"],publicKey:[]}}checkAlgorithmParams(e){this.checkRequiredProperty(e,"public")}}class LA extends Ob{constructor(){super(...arguments),this.name="Ed25519",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class HA extends Ob{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 KA extends Ob{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 VA extends Ob{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"),!Lf.isBufferSource(e.salt))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"info"),!Lf.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 QA extends Ob{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 FA extends QA{constructor(){super(...arguments),this.name="shake128",this.defaultLength=16}}class GA extends QA{constructor(){super(...arguments),this.name="shake256",this.defaultLength=32}}class $A{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=$f.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 qA={jwk:["private","public","secret"],pkcs8:["private"],spki:["public"],raw:["secret","public"]},zA=["pkcs8","spki","raw"];class WA{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=Lf.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=Lf.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=Lf.toArrayBuffer(i),c=Lf.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=Lf.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=Lf.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),!qA[t])throw new TypeError("Invalid keyFormat argument");if(!qA[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(!zA.includes(t))throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView or JsonWebKey)'");if(!Lf.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=$f.FromUtf8String(e)}const o=this.prepareAlgorithm(s),a=Lf.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=Lf.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($f.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(WA.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 kb("Unrecognized name");return t}checkCryptoKey(e){if(!(e instanceof qb))throw new TypeError("Key is not of type 'CryptoKey'")}}const JA=t(import.meta.url)("buffer"),YA=t(import.meta.url)("crypto");var XA=o.n(YA);const ZA=t(import.meta.url)("process"),eI={fromJSON:e=>JA.Buffer.from($f.FromBase64Url(e)),toJSON:e=>$f.ToBase64Url(e)};class tI extends qb{constructor(){super(...arguments),this.data=JA.Buffer.alloc(0),this.algorithm={name:""},this.extractable=!1,this.type="secret",this.usages=[],this.kty="oct",this.alg=""}}ib([Eb({name:"ext",type:ub.Boolean,optional:!0})],tI.prototype,"extractable",void 0),ib([Eb({name:"key_ops",type:ub.String,repeated:!0,optional:!0})],tI.prototype,"usages",void 0),ib([Eb({type:ub.String})],tI.prototype,"kty",void 0),ib([Eb({type:ub.String,optional:!0})],tI.prototype,"alg",void 0);class rI extends tI{constructor(){super(...arguments),this.kty="oct",this.type="secret"}}class sI extends tI{}class iI extends rI{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 kb("Unsupported algorithm name")}}set alg(e){}}ib([Eb({name:"k",converter:eI})],iI.prototype,"data",void 0);class nI{static async generateKey(e,t,r){const s=new iI;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=XA().randomBytes(e.length>>3),s}static async exportKey(e,t){if(!(t instanceof iI))throw new Error("key: Is not AesCryptoKey");switch(e.toLowerCase()){case"jwk":return wb.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new Bb("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Sb.fromJSON(t,{targetSchema:iI});break;case"raw":n=new iI,n.data=JA.Buffer.from(t);break;default:throw new Bb("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 Bb("keyData: Is wrong key length")}return n}static async encrypt(e,t,r){switch(e.name.toUpperCase()){case"AES-CBC":return this.encryptAesCBC(e,t,JA.Buffer.from(r));case"AES-CTR":return this.encryptAesCTR(e,t,JA.Buffer.from(r));case"AES-GCM":return this.encryptAesGCM(e,t,JA.Buffer.from(r));case"AES-KW":return this.encryptAesKW(e,t,JA.Buffer.from(r));case"AES-ECB":return this.encryptAesECB(e,t,JA.Buffer.from(r));default:throw new Bb("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof iI))throw new Error("key: Is not AesCryptoKey");switch(e.name.toUpperCase()){case"AES-CBC":return this.decryptAesCBC(e,t,JA.Buffer.from(r));case"AES-CTR":return this.decryptAesCTR(e,t,JA.Buffer.from(r));case"AES-GCM":return this.decryptAesGCM(e,t,JA.Buffer.from(r));case"AES-KW":return this.decryptAesKW(e,t,JA.Buffer.from(r));case"AES-ECB":return this.decryptAesECB(e,t,JA.Buffer.from(r));default:throw new Bb("algorithm: Is not recognized")}}static async encryptAesCBC(e,t,r){const s=XA().createCipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=JA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCBC(e,t,r){const s=XA().createDecipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=JA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesCTR(e,t,r){const s=XA().createCipheriv(`aes-${t.algorithm.length}-ctr`,t.data,JA.Buffer.from(e.counter));let i=s.update(r);return i=JA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCTR(e,t,r){const s=XA().createDecipheriv(`aes-${t.algorithm.length}-ctr`,t.data,new Uint8Array(e.counter));let i=s.update(r);return i=JA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesGCM(e,t,r){const s=XA().createCipheriv(`aes-${t.algorithm.length}-gcm`,t.data,JA.Buffer.from(e.iv),{authTagLength:(e.tagLength||128)>>3});e.additionalData&&s.setAAD(JA.Buffer.from(e.additionalData));let i=s.update(r);return i=JA.Buffer.concat([i,s.final(),s.getAuthTag()]),new Uint8Array(i).buffer}static async decryptAesGCM(e,t,r){const s=(e.tagLength||128)>>3,i=XA().createDecipheriv(`aes-${t.algorithm.length}-gcm`,t.data,new Uint8Array(e.iv),{authTagLength:s}),n=r.slice(0,r.length-s),o=r.slice(r.length-s);e.additionalData&&i.setAAD(JA.Buffer.from(e.additionalData)),i.setAuthTag(o);let a=i.update(n);return a=JA.Buffer.concat([a,i.final()]),new Uint8Array(a).buffer}static async encryptAesKW(e,t,r){const s=XA().createCipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=JA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesKW(e,t,r){const s=XA().createDecipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=JA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesECB(e,t,r){const s=XA().createCipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=JA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesECB(e,t,r){const s=XA().createDecipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=JA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}nI.AES_KW_IV=JA.Buffer.from("A6A6A6A6A6A6A6A6","hex");const oI=new WeakMap;function aI(e){const t=oI.get(e);if(!t)throw new Bb("Cannot get CryptoKey from secure storage");return t}function cI(e){const t=qb.create(e.algorithm,e.type,e.extractable,e.usages);return Object.freeze(t),oI.set(t,e),t}class lI extends Tb{async onGenerateKey(e,t,r){return cI(await nI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return nI.encrypt(e,aI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return nI.decrypt(e,aI(t),new Uint8Array(r))}async onExportKey(e,t){return nI.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await nI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(aI(e)instanceof iI))throw new TypeError("key: Is not a AesCryptoKey")}}const hI=JA.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),uI=JA.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,135]),dI=16;function gI(e){const t=JA.Buffer.alloc(e.length),r=e.length-1;for(let s=0;s<r;s++)t[s]=e[s]<<1,128&e[s+1]&&(t[s]+=1);return t[r]=e[r]<<1,t}function fI(e,t){const r=Math.min(e.length,t.length),s=JA.Buffer.alloc(r);for(let i=0;i<r;i++)s[i]=e[i]^t[i];return s}function pI(e,t){const r=XA().createCipheriv("aes"+(e.length<<3),e,hI),s=r.update(t);return r.final(),s}function yI(e,t){const r=JA.Buffer.alloc(dI),s=t*dI,i=s+dI;return e.copy(r,0,s,i),r}class mI extends Nb{async onGenerateKey(e,t,r){return cI(await nI.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=pI(e,hI);let r=gI(t);128&t[0]&&(r=fI(r,uI));let s=gI(r);return 128&r[0]&&(s=fI(s,uI)),{subkey1:r,subkey2:s}}(e);let s,i,n=Math.ceil(t.length/dI);0===n?(n=1,s=!1):s=t.length%dI===0;const o=n-1;i=s?fI(yI(t,o),r.subkey1):fI(function(e,t){const r=JA.Buffer.alloc(dI),s=t*dI,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=hI;for(let r=0;r<o;r++)a=fI(c,yI(t,r)),c=pI(e,a);return a=fI(i,c),pI(e,a)}(aI(t).data,JA.Buffer.from(r));return new Uint8Array(s).buffer}async onVerify(e,t,r,s){const i=await this.sign(e,t,s);return 0===JA.Buffer.from(r).compare(JA.Buffer.from(i))}async onExportKey(e,t){return nI.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await nI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(aI(e)instanceof iI))throw new TypeError("key: Is not a AesCryptoKey")}}class bI extends Db{async onGenerateKey(e,t,r){return cI(await nI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return nI.encrypt(e,aI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return nI.decrypt(e,aI(t),new Uint8Array(r))}async onExportKey(e,t){return nI.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await nI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(aI(e)instanceof iI))throw new TypeError("key: Is not a AesCryptoKey")}}class AI extends Pb{async onGenerateKey(e,t,r){return cI(await nI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return nI.encrypt(e,aI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return nI.decrypt(e,aI(t),new Uint8Array(r))}async onExportKey(e,t){return nI.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await nI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(aI(e)instanceof iI))throw new TypeError("key: Is not a AesCryptoKey")}}class II extends Lb{async onGenerateKey(e,t,r){return cI(await nI.generateKey({name:this.name,length:e.length},t,r))}async onExportKey(e,t){return nI.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await nI.importKey(e,t,{name:r.name},s,i))}async onEncrypt(e,t,r){return nI.encrypt(e,aI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return nI.decrypt(e,aI(t),new Uint8Array(r))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(aI(e)instanceof iI))throw new TypeError("key: Is not a AesCryptoKey")}}class vI extends Mb{async onGenerateKey(e,t,r){return cI(await nI.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return nI.encrypt(e,aI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return nI.decrypt(e,aI(t),new Uint8Array(r))}async onExportKey(e,t){return nI.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await nI.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(aI(e)instanceof iI))throw new TypeError("key: Is not a AesCryptoKey")}}class wI extends rI{get alg(){switch(this.algorithm.name.toUpperCase()){case"DES-CBC":return"DES-CBC";case"DES-EDE3-CBC":return"3DES-CBC";default:throw new kb("Unsupported algorithm name")}}set alg(e){}}ib([Eb({name:"k",converter:eI})],wI.prototype,"data",void 0);class SI{static async generateKey(e,t,r){const s=new wI;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=XA().randomBytes(e.length>>3),s}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return wb.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new Bb("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Sb.fromJSON(t,{targetSchema:wI});break;case"raw":n=new wI,n.data=JA.Buffer.from(t);break;default:throw new Bb("format: Must be 'jwk' or 'raw'")}return n.algorithm=r,n.extractable=s,n.usages=i,n}static async encrypt(e,t,r){switch(e.name.toUpperCase()){case"DES-CBC":return this.encryptDesCBC(e,t,JA.Buffer.from(r));case"DES-EDE3-CBC":return this.encryptDesEDE3CBC(e,t,JA.Buffer.from(r));default:throw new Bb("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof wI))throw new Error("key: Is not DesCryptoKey");switch(e.name.toUpperCase()){case"DES-CBC":return this.decryptDesCBC(e,t,JA.Buffer.from(r));case"DES-EDE3-CBC":return this.decryptDesEDE3CBC(e,t,JA.Buffer.from(r));default:throw new Bb("algorithm: Is not recognized")}}static async encryptDesCBC(e,t,r){const s=XA().createCipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=JA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesCBC(e,t,r){const s=XA().createDecipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=JA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptDesEDE3CBC(e,t,r){const s=XA().createCipheriv("des-ede3-cbc",t.data,JA.Buffer.from(e.iv));let i=s.update(r);return i=JA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesEDE3CBC(e,t,r){const s=XA().createDecipheriv("des-ede3-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=JA.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}class EI extends Hb{constructor(){super(...arguments),this.keySizeBits=64,this.ivSize=8,this.name="DES-CBC"}async onGenerateKey(e,t,r){return cI(await SI.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return SI.encrypt(e,aI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return SI.decrypt(e,aI(t),new Uint8Array(r))}async onExportKey(e,t){return SI.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){const n=await SI.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new Bb("keyData: Wrong key size");return cI(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(aI(e)instanceof wI))throw new TypeError("key: Is not a DesCryptoKey")}}class CI extends Hb{constructor(){super(...arguments),this.keySizeBits=192,this.ivSize=8,this.name="DES-EDE3-CBC"}async onGenerateKey(e,t,r){return cI(await SI.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return SI.encrypt(e,aI(t),new Uint8Array(r))}async onDecrypt(e,t,r){return SI.decrypt(e,aI(t),new Uint8Array(r))}async onExportKey(e,t){return SI.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){const n=await SI.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new Bb("keyData: Wrong key size");return cI(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(aI(e)instanceof wI))throw new TypeError("key: Is not a DesCryptoKey")}}function kI(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 Bb("algorithm: Is not recognized")}}class xI extends sI{constructor(){super(...arguments),this.type="private"}getKey(){const e=eb.parse(this.data,DA.PrivateKeyInfo);return eb.parse(e.privateKey,DA.RsaPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:kI(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,wb.toJSON(e))}fromJSON(e){const t=Sb.fromJSON(e,{targetSchema:DA.RsaPrivateKey}),r=new DA.PrivateKeyInfo;r.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.privateKeyAlgorithm.parameters=null,r.privateKey=tb.serialize(t),this.data=JA.Buffer.from(tb.serialize(r))}}class BI extends sI{constructor(){super(...arguments),this.type="public"}getKey(){const e=eb.parse(this.data,DA.PublicKeyInfo);return eb.parse(e.publicKey,DA.RsaPublicKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:kI(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,wb.toJSON(e))}fromJSON(e){const t=Sb.fromJSON(e,{targetSchema:DA.RsaPublicKey}),r=new DA.PublicKeyInfo;r.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.publicKeyAlgorithm.parameters=null,r.publicKey=tb.serialize(t),this.data=JA.Buffer.from(tb.serialize(r))}}class _I{static async generateKey(e,t,r){const s=new xI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new BI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=JA.Buffer.concat([JA.Buffer.alloc(4-e.publicExponent.byteLength,0),JA.Buffer.from(e.publicExponent)]).readInt32BE(0),o=XA().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 wb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;default:throw new Bb("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=Sb.fromJSON(t,{targetSchema:DA.RsaPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=Sb.fromJSON(t,{targetSchema:DA.RsaPublicKey});return this.importPublicKey(e,r,s,i)}case"spki":{const e=eb.parse(new Uint8Array(t),DA.PublicKeyInfo),n=eb.parse(e.publicKey,DA.RsaPublicKey);return this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=eb.parse(new Uint8Array(t),DA.PrivateKeyInfo),n=eb.parse(e.privateKey,DA.RsaPrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new Bb("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 Bb("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 Bb("algorithm: Is not recognized")}}static async encrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.encryptOAEP(e,t,r);throw new Bb("algorithm: Is not recognized")}static async decrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.decryptOAEP(e,t,r);throw new Bb("algorithm: Is not recognized")}static importPrivateKey(e,t,r,s){const i=new DA.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.privateKeyAlgorithm.parameters=null,i.privateKey=tb.serialize(e);const n=new xI;return n.data=JA.Buffer.from(tb.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 DA.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.publicKeyAlgorithm.parameters=null,i.publicKey=tb.serialize(e);const n=new BI;return n.data=JA.Buffer.from(tb.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 Bb("algorithm.hash: Is not recognized")}}static signRsa(e,t,r){const s=this.getCryptoAlgorithm(t.algorithm),i=XA().createSign(s);i.update(JA.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem};"RSA-PSS"===e.name.toUpperCase()&&(n.padding=XA().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=XA().createVerify(i);n.update(JA.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const o={key:t.pem};return"RSA-PSS"===e.name.toUpperCase()&&(o.padding=XA().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:XA().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(XA().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:XA().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(XA().privateDecrypt(s,r)).buffer}}_I.publicKeyUsages=["verify","encrypt","wrapKey"],_I.privateKeyUsages=["sign","decrypt","unwrapKey"];class RI extends Vb{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 _I.generateKey({...e,name:this.name},t,r);return{privateKey:cI(s.privateKey),publicKey:cI(s.publicKey)}}async onSign(e,t,r){return _I.sign(e,aI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return _I.verify(e,aI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return _I.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await _I.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=aI(e);if(!(r instanceof xI||r instanceof BI))throw new TypeError("key: Is not RSA CryptoKey")}}class OI extends Qb{constructor(){super(...arguments),this.hashAlgorithms=["SHA-1","SHA-256","SHA-384","SHA-512","shake128","shake256","SHA3-256","SHA3-384","SHA3-512"]}async onGenerateKey(e,t,r){const s=await _I.generateKey({...e,name:this.name},t,r);return{privateKey:cI(s.privateKey),publicKey:cI(s.publicKey)}}async onSign(e,t,r){return _I.sign(e,aI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return _I.verify(e,aI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return _I.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await _I.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=aI(e);if(!(r instanceof xI||r instanceof BI))throw new TypeError("key: Is not RSA CryptoKey")}}class UI{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=XA().createHash(r).update(JA.Buffer.from(t)).digest();return new Uint8Array(s).buffer}}class TI extends Fb{async onGenerateKey(e,t,r){const s=await _I.generateKey({...e,name:this.name},t,r);return{privateKey:cI(s.privateKey),publicKey:cI(s.publicKey)}}async onEncrypt(e,t,r){const s=aI(t),i=new Uint8Array(r),n=Math.ceil(s.algorithm.modulusLength>>3),o=UI.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=XA().createHash(s.algorithm.hash.name.replace("-","")).update(Lf.toUint8Array(e.label||new Uint8Array(0))).digest();u.set(d,0),u[o+c]=1,XA().randomFillSync(h);const g=this.mgf1(s.algorithm.hash,h,u.length);for(let e=0;e<u.length;e++)u[e]^=g[e];const f=this.mgf1(s.algorithm.hash,u,h.length);for(let e=0;e<h.length;e++)h[e]^=f[e];s.pem||(s.pem=`-----BEGIN PUBLIC KEY-----\n${s.data.toString("base64")}\n-----END PUBLIC KEY-----`);const p=XA().publicEncrypt({key:s.pem,padding:XA().constants.RSA_NO_PADDING},JA.Buffer.from(l));return new Uint8Array(p).buffer}async onDecrypt(e,t,r){const s=aI(t),i=Math.ceil(s.algorithm.modulusLength>>3),n=UI.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=XA().privateDecrypt({key:s.pem,padding:XA().constants.RSA_NO_PADDING},JA.Buffer.from(r));const a=o[0],c=o.subarray(1,n+1),l=o.subarray(n+1);if(0!==a)throw new Error("Decryption failed");const h=this.mgf1(s.algorithm.hash,l,c.length);for(let e=0;e<c.length;e++)c[e]^=h[e];const u=this.mgf1(s.algorithm.hash,c,l.length);for(let e=0;e<l.length;e++)l[e]^=u[e];const d=XA().createHash(s.algorithm.hash.name.replace("-","")).update(Lf.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 g=n;for(;g<l.length;g++){const e=l[g];if(1===e)break;if(0!==e)throw new Error("Decryption failed")}if(g===l.length)throw new Error("Decryption failed");return o=l.subarray(g+1),new Uint8Array(o).buffer}async onExportKey(e,t){return _I.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await _I.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=aI(e);if(!(r instanceof xI||r instanceof BI))throw new TypeError("key: Is not RSA CryptoKey")}mgf1(e,t,r=0){const s=UI.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=XA().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 NI extends Ob{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 _I.generateKey({...e,name:this.name},t,r);return{privateKey:cI(s.privateKey),publicKey:cI(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=$f.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=XA().publicEncrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onDecrypt(e,t,r){const s=this.toCryptoOptions(t),i=XA().privateDecrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onExportKey(e,t){return _I.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await _I.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=aI(e);if(!(r instanceof xI||r instanceof BI))throw new TypeError("key: Is not RSA CryptoKey")}toCryptoOptions(e){const t=e.type.toUpperCase();return{key:`-----BEGIN ${t} KEY-----\n${aI(e).data.toString("base64")}\n-----END ${t} KEY-----`,padding:XA().constants.RSA_PKCS1_PADDING}}}const DI={"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 MI(e){const t=DI[e];if(!t)throw new Bb(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class PI extends sI{constructor(){super(...arguments),this.type="private"}getKey(){const e=eb.parse(this.data,DA.PrivateKeyInfo);return eb.parse(e.privateKey,DA.EcPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,wb.toJSON(e))}fromJSON(e){if(!e.crv)throw new Bb("Cannot get named curve from JWK. Property 'crv' is required");const t=new DA.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",t.privateKeyAlgorithm.parameters=tb.serialize(new DA.ObjectIdentifier(MI(e.crv)));const r=Sb.fromJSON(e,{targetSchema:DA.EcPrivateKey});return t.privateKey=tb.serialize(r),this.data=JA.Buffer.from(tb.serialize(t)),this}}class LI extends sI{constructor(){super(...arguments),this.type="public"}getKey(){const e=eb.parse(this.data,DA.PublicKeyInfo);return new DA.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,wb.toJSON(e))}fromJSON(e){if(!e.crv)throw new Bb("Cannot get named curve from JWK. Property 'crv' is required");const t=Sb.fromJSON(e,{targetSchema:DA.EcPublicKey}),r=new DA.PublicKeyInfo;return r.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1",r.publicKeyAlgorithm.parameters=tb.serialize(new DA.ObjectIdentifier(MI(e.crv))),r.publicKey=tb.toASN(t).valueHex,this.data=JA.Buffer.from(tb.serialize(r)),this}}class HI extends Ob{constructor(){super(...arguments),this.name="SHA-1",this.usages=[]}async onDigest(e,t){return UI.digest(e,t)}}class KI extends Ob{constructor(){super(...arguments),this.name="SHA-256",this.usages=[]}async onDigest(e,t){return UI.digest(e,t)}}class VI extends Ob{constructor(){super(...arguments),this.name="SHA-384",this.usages=[]}async onDigest(e,t){return UI.digest(e,t)}}class QI extends Ob{constructor(){super(...arguments),this.name="SHA-512",this.usages=[]}async onDigest(e,t){return UI.digest(e,t)}}class FI extends Ob{constructor(){super(...arguments),this.name="SHA3-256",this.usages=[]}async onDigest(e,t){return UI.digest(e,t)}}class GI extends Ob{constructor(){super(...arguments),this.name="SHA3-384",this.usages=[]}async onDigest(e,t){return UI.digest(e,t)}}class $I extends Ob{constructor(){super(...arguments),this.name="SHA3-512",this.usages=[]}async onDigest(e,t){return UI.digest(e,t)}}class jI{static async generateKey(e,t,r){const s=new PI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new LI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=XA().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=UI.getAlgorithmName(e.hash),i=XA().createSign(s);i.update(JA.Buffer.from(r)),t.pem||(t.pem=`-----BEGIN PRIVATE KEY-----\n${t.data.toString("base64")}\n-----END PRIVATE KEY-----`);const n={key:t.pem},o=i.sign(n),a=eb.parse(o,DA.EcDsaSignature);return lA.encodeSignature(a,MA.get(t.algorithm.namedCurve).size).buffer}static async verify(e,t,r,s){const i=UI.getAlgorithmName(e.hash),n=XA().createVerify(i);n.update(JA.Buffer.from(s)),t.pem||(t.pem=`-----BEGIN PUBLIC KEY-----\n${t.data.toString("base64")}\n-----END PUBLIC KEY-----`);const o={key:t.pem},a=new DA.EcDsaSignature,c=MA.get(t.algorithm.namedCurve),l=lA.decodeSignature(r,c.size);a.r=Lf.toArrayBuffer(l.r),a.s=Lf.toArrayBuffer(l.s);const h=JA.Buffer.from(tb.serialize(a));return n.verify(o,h)}static async deriveBits(e,t,r){const s=this.getOpenSSLNamedCurve(t.algorithm.namedCurve),i=XA().createECDH(s),n=eb.parse(t.data,DA.PrivateKeyInfo),o=eb.parse(n.privateKey,DA.EcPrivateKey);i.setPrivateKey(JA.Buffer.from(o.privateKey));const a=eb.parse(e.public.data,DA.PublicKeyInfo),c=i.computeSecret(JA.Buffer.from(a.publicKey));return null===r?c:new Uint8Array(c).buffer.slice(0,r>>3)}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return wb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return eb.parse(t.data,DA.PublicKeyInfo).publicKey;default:throw new Bb("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=Sb.fromJSON(t,{targetSchema:DA.EcPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=Sb.fromJSON(t,{targetSchema:DA.EcPublicKey});return this.importPublicKey(e,r,s,i)}case"raw":{const e=new DA.EcPublicKey(t);return this.importPublicKey(e,r,s,i)}case"spki":{const e=eb.parse(new Uint8Array(t),DA.PublicKeyInfo),n=new DA.EcPublicKey(e.publicKey);return this.assertKeyParameters(e.publicKeyAlgorithm.parameters,r.namedCurve),this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=eb.parse(new Uint8Array(t),DA.PrivateKeyInfo),n=eb.parse(e.privateKey,DA.EcPrivateKey);return this.assertKeyParameters(e.privateKeyAlgorithm.parameters,r.namedCurve),this.importPrivateKey(n,r,s,i)}default:throw new Bb("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static assertKeyParameters(e,t){if(!e)throw new Cb("Key info doesn't have required parameters");let r="";try{r=eb.parse(e,DA.ObjectIdentifier).value}catch(e){throw new Cb("Cannot read key info parameters")}if(MI(t)!==r)throw new Cb("Key info parameter doesn't match to named curve")}static async importPrivateKey(e,t,r,s){const i=new DA.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",i.privateKeyAlgorithm.parameters=tb.serialize(new DA.ObjectIdentifier(MI(t.namedCurve))),i.privateKey=tb.serialize(e);const n=new PI;return n.data=JA.Buffer.from(tb.serialize(i)),n.algorithm=Object.assign({},t),n.extractable=r,n.usages=s,n}static async importPublicKey(e,t,r,s){const i=new DA.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1";const n=MI(t.namedCurve);i.publicKeyAlgorithm.parameters=tb.serialize(new DA.ObjectIdentifier(n)),i.publicKey=e.value;const o=new LI;return o.data=JA.Buffer.from(tb.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}}}jI.publicKeyUsages=["verify"],jI.privateKeyUsages=["sign","deriveKey","deriveBits"];class qI extends $b{constructor(){super(...arguments),this.namedCurves=MA.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 jI.generateKey({...e,name:this.name},t,r);return{privateKey:cI(s.privateKey),publicKey:cI(s.publicKey)}}async onSign(e,t,r){return jI.sign(e,aI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return jI.verify(e,aI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return jI.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await jI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=aI(e);if(!(r instanceof PI||r instanceof LI))throw new TypeError("key: Is not EC CryptoKey")}}class zI extends zb{constructor(){super(...arguments),this.namedCurves=MA.names}async onGenerateKey(e,t,r){const s=await jI.generateKey({...e,name:this.name},t,r);return{privateKey:cI(s.privateKey),publicKey:cI(s.publicKey)}}async onExportKey(e,t){return jI.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await jI.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=aI(e);if(!(r instanceof PI||r instanceof LI))throw new TypeError("key: Is not EC CryptoKey")}async onDeriveBits(e,t,r){return await jI.deriveBits({...e,public:aI(e.public)},aI(t),r)}}const WI={[DA.idEd448]:"Ed448",ed448:DA.idEd448,[DA.idX448]:"X448",x448:DA.idX448,[DA.idEd25519]:"Ed25519",ed25519:DA.idEd25519,[DA.idX25519]:"X25519",x25519:DA.idX25519};function JI(e){const t=WI[e.toLowerCase()];if(!t)throw new Bb(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class YI extends sI{constructor(){super(...arguments),this.type="private"}getKey(){const e=eb.parse(this.data,DA.PrivateKeyInfo);return eb.parse(e.privateKey,DA.CurvePrivateKey)}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,wb.toJSON(e))}fromJSON(e){if(!e.crv)throw new Bb("Cannot get named curve from JWK. Property 'crv' is required");const t=new DA.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm=JI(e.crv);const r=Sb.fromJSON(e,{targetSchema:DA.CurvePrivateKey});return t.privateKey=tb.serialize(r),this.data=JA.Buffer.from(tb.serialize(t)),this}}class XI extends sI{constructor(){super(...arguments),this.type="public"}getKey(){return eb.parse(this.data,DA.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:$f.ToBase64Url(e)})}fromJSON(e){if(!e.crv)throw new Bb("Cannot get named curve from JWK. Property 'crv' is required");if(!e.x)throw new Bb("Cannot get property from JWK. Property 'x' is required");const t=new DA.PublicKeyInfo;return t.publicKeyAlgorithm.algorithm=JI(e.crv),t.publicKey=$f.FromBase64Url(e.x),this.data=JA.Buffer.from(tb.serialize(t)),this}}class ZI{static async generateKey(e,t,r){const s=new YI;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new XI;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=e.namedCurve.toLowerCase(),o=XA().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=XA().sign(null,JA.Buffer.from(r),s);return Lf.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 XA().verify(null,JA.Buffer.from(s),i,JA.Buffer.from(r))}static async deriveBits(e,t,r){const s=XA().createPublicKey({key:e.public.data,format:"der",type:"spki"}),i=XA().createPrivateKey({key:t.data,format:"der",type:"pkcs8"}),n=XA().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 wb.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return eb.parse(t.data,DA.PublicKeyInfo).publicKey;default:throw new Bb("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=Sb.fromJSON(t,{targetSchema:DA.CurvePrivateKey});return this.importPrivateKey(e,r,s,i)}if(!e.x)throw new TypeError("keyData: Cannot get required 'x' filed");return this.importPublicKey($f.FromBase64Url(e.x),r,s,i)}case"raw":return this.importPublicKey(t,r,s,i);case"spki":{const e=eb.parse(new Uint8Array(t),DA.PublicKeyInfo);return this.importPublicKey(e.publicKey,r,s,i)}case"pkcs8":{const e=eb.parse(new Uint8Array(t),DA.PrivateKeyInfo),n=eb.parse(e.privateKey,DA.CurvePrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new Bb("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static importPrivateKey(e,t,r,s){const i=new YI;return i.fromJSON({crv:t.namedCurve,d:$f.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 XI;return i.fromJSON({crv:t.namedCurve,x:$f.ToBase64Url(e)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}}ZI.publicKeyUsages=["verify"],ZI.privateKeyUsages=["sign","deriveKey","deriveBits"];class ev extends Jb{async onGenerateKey(e,t,r){const s=await ZI.generateKey({name:this.name,namedCurve:e.namedCurve.replace(/^ed/i,"Ed")},t,r);return{privateKey:cI(s.privateKey),publicKey:cI(s.publicKey)}}async onSign(e,t,r){return ZI.sign(e,aI(t),new Uint8Array(r))}async onVerify(e,t,r,s){return ZI.verify(e,aI(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return ZI.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await ZI.importKey(e,t,{...r,name:this.name},s,i))}}class tv extends Wb{async onGenerateKey(e,t,r){const s=await ZI.generateKey({name:this.name,namedCurve:e.namedCurve.toUpperCase()},t,r);return{privateKey:cI(s.privateKey),publicKey:cI(s.publicKey)}}async onDeriveBits(e,t,r){return await ZI.deriveBits({...e,public:aI(e.public)},aI(t),r)}async onExportKey(e,t){return ZI.exportKey(e,aI(t))}async onImportKey(e,t,r,s,i){return cI(await ZI.importKey(e,t,{...r,name:this.name},s,i))}}class rv extends tI{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 sv extends rv{constructor(){super(...arguments),this.type="private"}toJWK(){const e=XA().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"}),t=Rb.toUint8Array(this.data.toString()),r=sb.parse(t,DA.PrivateKeyInfo),s=sb.parse(r.privateKey,DA.EdPrivateKey).value;return{...super.toJWK(),...e,d:Buffer.from(new Uint8Array(s)).toString("base64url")}}}class iv extends rv{constructor(){super(...arguments),this.type="public"}toJWK(){const e=XA().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"});return{...super.toJWK(),...e}}}class nv{static async generateKey(e,t,r){const s=e.name.toLowerCase(),i=XA().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 sv(n,t,o,i.privateKey),publicKey:new iv(n,!0,a,i.publicKey)}}static async sign(e,t,r){const s=XA().sign(null,Buffer.from(r),t.data);return Lf.toArrayBuffer(s)}static async verify(e,t,r,s){return XA().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 Rb.toArrayBuffer(t.data.toString());case"raw":{const e=t.toJWK();return $f.FromBase64Url(e.x)}default:return Promise.reject(new Bb("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 DA.EdPrivateKey;t.value=Lf.toArrayBuffer(Buffer.from(e.d,"base64url"));const n=new DA.PrivateKeyInfo;n.privateKeyAlgorithm.algorithm="ed25519"===r.name.toLowerCase()?DA.idEd25519:DA.idX25519,n.privateKey=sb.serialize(t);const o=sb.serialize(n),a=Rb.fromBufferSource(o,"PRIVATE KEY");return new sv(r,s,i,a)}if(e.x){const t=XA().createPublicKey({format:"jwk",key:e}).export({format:"pem",type:"spki"});return new iv(r,s,i,t)}throw new Bb("keyData: Cannot import JWK. 'd' or 'x' must be presented")}case"pkcs8":{const e=Rb.fromBufferSource(t,"PRIVATE KEY");return new sv(r,s,i,e)}case"spki":{const e=Rb.fromBufferSource(t,"PUBLIC KEY");return new iv(r,s,i,e)}case"raw":{const e=t,n=XA().createPublicKey({format:"jwk",key:{kty:"OKP",crv:"ed25519"===r.name.toLowerCase()?"Ed25519":"X25519",x:$f.ToBase64Url(e)}}).export({format:"pem",type:"spki"});return new iv(r,s,i,n)}default:return Promise.reject(new Bb("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}}nv.privateKeyUsages=["sign","deriveBits","deriveKey"],nv.publicKeyUsages=["verify"];class ov extends LA{async onGenerateKey(e,t,r){const s=await nv.generateKey(e,t,r);return{privateKey:cI(s.privateKey),publicKey:cI(s.publicKey)}}async onSign(e,t,r){const s=aI(t);return nv.sign(e,s,new Uint8Array(r))}onVerify(e,t,r,s){const i=aI(t);return nv.verify(e,i,new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){const r=aI(t);return nv.exportKey(e,r)}async onImportKey(e,t,r,s,i){return cI(await nv.importKey(e,t,r,s,i))}}class av extends PA{async onGenerateKey(e,t,r){const s=await nv.generateKey(e,t,r);return{privateKey:cI(s.privateKey),publicKey:cI(s.publicKey)}}async onDeriveBits(e,t,r){const s=aI(t),i=aI(e.public),n=XA().createPublicKey({key:i.data.toString(),format:"pem",type:"spki"}),o=XA().createPrivateKey({key:s.data.toString(),format:"pem",type:"pkcs8"}),a=XA().diffieHellman({publicKey:n,privateKey:o});return new Uint8Array(a).buffer.slice(0,r>>3)}async onExportKey(e,t){const r=aI(t);return nv.exportKey(e,r)}async onImportKey(e,t,r,s,i){return cI(await nv.importKey(e,t,r,s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(aI(e)instanceof rv))throw new TypeError("key: Is not a Ed25519CryptoKey")}}class cv extends tI{}class lv extends KA{async onDeriveBits(e,t,r){return new Promise((s,i)=>{const n=Lf.toArrayBuffer(e.salt),o=e.hash.name.replace("-","");XA().pbkdf2(aI(t).data,JA.Buffer.from(n),e.iterations,r>>3,o,(e,t)=>{e?i(e):s(new Uint8Array(t).buffer)})})}async onImportKey(e,t,r,s,i){if("raw"===e){const e=new cv;return e.data=JA.Buffer.from(t),e.algorithm={name:this.name},e.extractable=!1,e.usages=i,cI(e)}throw new Bb("format: Must be 'raw'")}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(aI(e)instanceof cv))throw new TypeError("key: Is not PBKDF CryptoKey")}}class hv extends tI{get alg(){return`HS${this.algorithm.hash.name.toUpperCase().replace("SHA-","")}`}set alg(e){}}ib([Eb({name:"k",converter:eI})],hv.prototype,"data",void 0);class uv extends HA{async onGenerateKey(e,t,r){const s=(e.length||this.getDefaultLength(e.hash.name))>>3<<3,i=new hv;return i.algorithm={...e,length:s,name:this.name},i.extractable=t,i.usages=r,i.data=XA().randomBytes(s>>3),cI(i)}async onSign(e,t,r){const s=UI.getAlgorithmName(t.algorithm.hash),i=XA().createHmac(s,aI(t).data).update(JA.Buffer.from(r)).digest();return new Uint8Array(i).buffer}async onVerify(e,t,r,s){const i=UI.getAlgorithmName(t.algorithm.hash);return 0===XA().createHmac(i,aI(t).data).update(JA.Buffer.from(s)).digest().compare(JA.Buffer.from(r))}async onImportKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=Sb.fromJSON(t,{targetSchema:hv});break;case"raw":n=new hv,n.data=JA.Buffer.from(t);break;default:throw new Bb("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,cI(n)}async onExportKey(e,t){switch(e.toLowerCase()){case"jwk":return wb.toJSON(aI(t));case"raw":return new Uint8Array(aI(t).data).buffer;default:throw new Bb("format: Must be 'jwk' or 'raw'")}}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(aI(e)instanceof hv))throw new TypeError("key: Is not HMAC CryptoKey")}}class dv extends tI{}class gv extends VA{async onImportKey(e,t,r,s,i){if("raw"!==e.toLowerCase())throw new Bb("Operation not supported");const n=new dv;return n.data=JA.Buffer.from(t),n.algorithm={name:this.name},n.extractable=s,n.usages=i,cI(n)}async onDeriveBits(e,t,r){const s=e.hash.name.replace("-",""),i=XA().createHash(s).digest().length,n=r/8,o=Lf.toUint8Array(e.info),a=XA().createHmac(s,Lf.toUint8Array(e.salt)).update(Lf.toUint8Array(aI(t).data)).digest(),c=[JA.Buffer.alloc(0)],l=Math.ceil(n/i)+1;for(let e=1;e<l;++e)c.push(XA().createHmac(s,a).update(JA.Buffer.concat([c[e-1],o,JA.Buffer.from([e])])).digest());return JA.Buffer.concat(c).slice(0,n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(aI(e)instanceof dv))throw new TypeError("key: Is not HKDF CryptoKey")}}class fv{static digest(e,t){const r=XA().createHash(e.name.toLowerCase(),{outputLength:e.length}).update(JA.Buffer.from(t)).digest();return new Uint8Array(r).buffer}}class pv extends FA{async onDigest(e,t){return fv.digest(e,t)}}class yv extends GA{async onDigest(e,t){return fv.digest(e,t)}}class mv extends WA{constructor(){var e;super(),this.providers.set(new lI),this.providers.set(new bI),this.providers.set(new AI),this.providers.set(new mI),this.providers.set(new II),this.providers.set(new vI),XA().getCiphers().includes("des-cbc")&&this.providers.set(new EI),this.providers.set(new CI),this.providers.set(new RI),this.providers.set(new OI),this.providers.set(new TI),this.providers.set(new NI),this.providers.set(new qI),this.providers.set(new zI),this.providers.set(new HI),this.providers.set(new KI),this.providers.set(new VI),this.providers.set(new QI),this.providers.set(new lv),this.providers.set(new uv),this.providers.set(new gv);const t=null===(e=/^v(\d+)/.exec(ZA.version))||void 0===e?void 0:e[1];t&&parseInt(t,10)>=12&&(this.providers.set(new pv),this.providers.set(new yv));const r=XA().getHashes();r.includes("sha3-256")&&this.providers.set(new FI),r.includes("sha3-384")&&this.providers.set(new GI),r.includes("sha3-512")&&this.providers.set(new $I),t&&parseInt(t,10)>=14&&(this.providers.set(new ev),this.providers.set(new tv),this.providers.set(new ov),this.providers.set(new av))}}var bv,Av,Iv;o(909);class vv{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($f.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 wv=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};ib([Xm({type:uy.TeletexString})],wv.prototype,"teletexString",void 0),ib([Xm({type:uy.PrintableString})],wv.prototype,"printableString",void 0),ib([Xm({type:uy.UniversalString})],wv.prototype,"universalString",void 0),ib([Xm({type:uy.Utf8String})],wv.prototype,"utf8String",void 0),ib([Xm({type:uy.BmpString})],wv.prototype,"bmpString",void 0),wv=ib([Ym({type:hy.Choice})],wv);let Sv=class extends wv{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?$f.ToHex(this.anyValue):super.toString())}};ib([Xm({type:uy.IA5String})],Sv.prototype,"ia5String",void 0),ib([Xm({type:uy.Any})],Sv.prototype,"anyValue",void 0),Sv=ib([Ym({type:hy.Choice})],Sv);class Ev{constructor(e={}){this.type="",this.value=new Sv,Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],Ev.prototype,"type",void 0),ib([Xm({type:Sv})],Ev.prototype,"value",void 0);let Cv=bv=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,bv.prototype)}};Cv=bv=ib([Ym({type:hy.Set,itemType:Ev})],Cv);let kv=Av=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,Av.prototype)}};kv=Av=ib([Ym({type:hy.Sequence,itemType:Cv})],kv);let xv=Iv=class extends kv{constructor(e){super(e),Object.setPrototypeOf(this,Iv.prototype)}};xv=Iv=ib([Ym({type:hy.Sequence})],xv);const Bv={fromASN:e=>vv.toString(Bm.fromASN(e)),toASN:e=>Bm.toASN(vv.fromString(e))};class _v{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],_v.prototype,"typeId",void 0),ib([Xm({type:uy.Any,context:0})],_v.prototype,"value",void 0);class Rv{constructor(e={}){this.partyName=new wv,Object.assign(this,e)}}ib([Xm({type:wv,optional:!0,context:0,implicit:!0})],Rv.prototype,"nameAssigner",void 0),ib([Xm({type:wv,context:1,implicit:!0})],Rv.prototype,"partyName",void 0);let Ov=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:_v,context:0,implicit:!0})],Ov.prototype,"otherName",void 0),ib([Xm({type:uy.IA5String,context:1,implicit:!0})],Ov.prototype,"rfc822Name",void 0),ib([Xm({type:uy.IA5String,context:2,implicit:!0})],Ov.prototype,"dNSName",void 0),ib([Xm({type:uy.Any,context:3,implicit:!0})],Ov.prototype,"x400Address",void 0),ib([Xm({type:xv,context:4,implicit:!1})],Ov.prototype,"directoryName",void 0),ib([Xm({type:Rv,context:5})],Ov.prototype,"ediPartyName",void 0),ib([Xm({type:uy.IA5String,context:6,implicit:!0})],Ov.prototype,"uniformResourceIdentifier",void 0),ib([Xm({type:uy.OctetString,context:7,implicit:!0,converter:Bv})],Ov.prototype,"iPAddress",void 0),ib([Xm({type:uy.ObjectIdentifier,context:8,implicit:!0})],Ov.prototype,"registeredID",void 0),Ov=ib([Ym({type:hy.Choice})],Ov);const Uv="1.3.6.1.5.5.7",Tv=`${Uv}.3`,Nv=`${Uv}.48`,Dv=`${Nv}.1`,Mv=`${Nv}.2`,Pv=`${Nv}.3`,Lv=`${Nv}.5`,Hv="2.5.29";var Kv;const Vv=`${Uv}.1.1`;class Qv{constructor(e={}){this.accessMethod="",this.accessLocation=new Ov,Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],Qv.prototype,"accessMethod",void 0),ib([Xm({type:Ov})],Qv.prototype,"accessLocation",void 0);let Fv=Kv=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,Kv.prototype)}};Fv=Kv=ib([Ym({type:hy.Sequence,itemType:Qv})],Fv);const Gv=`${Hv}.35`;class $v extends Im{}class jv{constructor(e={}){e&&Object.assign(this,e)}}ib([Xm({type:$v,context:0,optional:!0,implicit:!0})],jv.prototype,"keyIdentifier",void 0),ib([Xm({type:Ov,context:1,optional:!0,implicit:!0,repeated:"sequence"})],jv.prototype,"authorityCertIssuer",void 0),ib([Xm({type:uy.Integer,context:2,optional:!0,implicit:!0,converter:Em})],jv.prototype,"authorityCertSerialNumber",void 0);const qv=`${Hv}.19`;class zv{constructor(e={}){this.cA=!1,Object.assign(this,e)}}var Wv;ib([Xm({type:uy.Boolean,defaultValue:!1})],zv.prototype,"cA",void 0),ib([Xm({type:uy.Integer,optional:!0})],zv.prototype,"pathLenConstraint",void 0);let Jv=Wv=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,Wv.prototype)}};var Yv;Jv=Wv=ib([Ym({type:hy.Sequence,itemType:Ov})],Jv);let Xv=Yv=class extends Jv{constructor(e){super(e),Object.setPrototypeOf(this,Yv.prototype)}};var Zv;Xv=Yv=ib([Ym({type:hy.Sequence})],Xv);const ew=`${Hv}.32`;let tw=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};ib([Xm({type:uy.IA5String})],tw.prototype,"ia5String",void 0),ib([Xm({type:uy.VisibleString})],tw.prototype,"visibleString",void 0),ib([Xm({type:uy.BmpString})],tw.prototype,"bmpString",void 0),ib([Xm({type:uy.Utf8String})],tw.prototype,"utf8String",void 0),tw=ib([Ym({type:hy.Choice})],tw);class rw{constructor(e={}){this.organization=new tw,this.noticeNumbers=[],Object.assign(this,e)}}ib([Xm({type:tw})],rw.prototype,"organization",void 0),ib([Xm({type:uy.Integer,repeated:"sequence"})],rw.prototype,"noticeNumbers",void 0);class sw{constructor(e={}){Object.assign(this,e)}}ib([Xm({type:rw,optional:!0})],sw.prototype,"noticeRef",void 0),ib([Xm({type:tw,optional:!0})],sw.prototype,"explicitText",void 0);let iw=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:uy.IA5String})],iw.prototype,"cPSuri",void 0),ib([Xm({type:sw})],iw.prototype,"userNotice",void 0),iw=ib([Ym({type:hy.Choice})],iw);class nw{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],nw.prototype,"policyQualifierId",void 0),ib([Xm({type:uy.Any})],nw.prototype,"qualifier",void 0);class ow{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],ow.prototype,"policyIdentifier",void 0),ib([Xm({type:nw,repeated:"sequence",optional:!0})],ow.prototype,"policyQualifiers",void 0);let aw=Zv=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,Zv.prototype)}};aw=Zv=ib([Ym({type:hy.Sequence,itemType:ow})],aw);let cw=class{constructor(e=0){this.value=e}};ib([Xm({type:uy.Integer})],cw.prototype,"value",void 0),cw=ib([Ym({type:hy.Choice})],cw);let lw=class extends cw{};var hw;lw=ib([Ym({type:hy.Choice})],lw);const uw=`${Hv}.31`;var dw;!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"}(dw||(dw={}));class gw extends Am{toJSON(){const e=[],t=this.toNumber();return t&dw.aACompromise&&e.push("aACompromise"),t&dw.affiliationChanged&&e.push("affiliationChanged"),t&dw.cACompromise&&e.push("cACompromise"),t&dw.certificateHold&&e.push("certificateHold"),t&dw.cessationOfOperation&&e.push("cessationOfOperation"),t&dw.keyCompromise&&e.push("keyCompromise"),t&dw.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&dw.superseded&&e.push("superseded"),t&dw.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let fw=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:Ov,context:0,repeated:"sequence",implicit:!0})],fw.prototype,"fullName",void 0),ib([Xm({type:Cv,context:1,implicit:!0})],fw.prototype,"nameRelativeToCRLIssuer",void 0),fw=ib([Ym({type:hy.Choice})],fw);class pw{constructor(e={}){Object.assign(this,e)}}ib([Xm({type:fw,context:0,optional:!0})],pw.prototype,"distributionPoint",void 0),ib([Xm({type:gw,context:1,optional:!0,implicit:!0})],pw.prototype,"reasons",void 0),ib([Xm({type:Ov,context:2,optional:!0,repeated:"sequence",implicit:!0})],pw.prototype,"cRLIssuer",void 0);let yw=hw=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,hw.prototype)}};var mw;yw=hw=ib([Ym({type:hy.Sequence,itemType:pw})],yw);let bw=mw=class extends yw{constructor(e){super(e),Object.setPrototypeOf(this,mw.prototype)}};bw=mw=ib([Ym({type:hy.Sequence,itemType:pw})],bw);class Aw{constructor(e={}){this.onlyContainsUserCerts=Aw.ONLY,this.onlyContainsCACerts=Aw.ONLY,this.indirectCRL=Aw.ONLY,this.onlyContainsAttributeCerts=Aw.ONLY,Object.assign(this,e)}}var Iw;Aw.ONLY=!1,ib([Xm({type:fw,context:0,optional:!0})],Aw.prototype,"distributionPoint",void 0),ib([Xm({type:uy.Boolean,context:1,defaultValue:Aw.ONLY,implicit:!0})],Aw.prototype,"onlyContainsUserCerts",void 0),ib([Xm({type:uy.Boolean,context:2,defaultValue:Aw.ONLY,implicit:!0})],Aw.prototype,"onlyContainsCACerts",void 0),ib([Xm({type:gw,context:3,optional:!0,implicit:!0})],Aw.prototype,"onlySomeReasons",void 0),ib([Xm({type:uy.Boolean,context:4,defaultValue:Aw.ONLY,implicit:!0})],Aw.prototype,"indirectCRL",void 0),ib([Xm({type:uy.Boolean,context:5,defaultValue:Aw.ONLY,implicit:!0})],Aw.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"}(Iw||(Iw={}));let vw=class{constructor(e=Iw.unspecified){this.reason=Iw.unspecified,this.reason=e}toJSON(){return Iw[this.reason]}toString(){return this.toJSON()}};var ww;ib([Xm({type:uy.Enumerated})],vw.prototype,"reason",void 0),vw=ib([Ym({type:hy.Choice})],vw);const Sw=`${Hv}.37`;let Ew=ww=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,ww.prototype)}};Ew=ww=ib([Ym({type:hy.Sequence,itemType:uy.ObjectIdentifier})],Ew);const Cw=`${Tv}.1`,kw=`${Tv}.2`,xw=`${Tv}.3`,Bw=`${Tv}.4`,_w=`${Tv}.8`,Rw=`${Tv}.9`;let Ow=class{constructor(e=new ArrayBuffer(0)){this.value=e}};ib([Xm({type:uy.Integer,converter:Em})],Ow.prototype,"value",void 0),Ow=ib([Ym({type:hy.Choice})],Ow);let Uw=class{constructor(e){this.value=new Date,e&&(this.value=e)}};var Tw;ib([Xm({type:uy.GeneralizedTime})],Uw.prototype,"value",void 0),Uw=ib([Ym({type:hy.Choice})],Uw);let Nw=Tw=class extends Jv{constructor(e){super(e),Object.setPrototypeOf(this,Tw.prototype)}};Nw=Tw=ib([Ym({type:hy.Sequence})],Nw);const Dw=`${Hv}.15`;var Mw,Pw;!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 Lw extends Am{toJSON(){const e=this.toNumber(),t=[];return e&Mw.cRLSign&&t.push("crlSign"),e&Mw.dataEncipherment&&t.push("dataEncipherment"),e&Mw.decipherOnly&&t.push("decipherOnly"),e&Mw.digitalSignature&&t.push("digitalSignature"),e&Mw.encipherOnly&&t.push("encipherOnly"),e&Mw.keyAgreement&&t.push("keyAgreement"),e&Mw.keyCertSign&&t.push("keyCertSign"),e&Mw.keyEncipherment&&t.push("keyEncipherment"),e&Mw.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}}class Hw{constructor(e={}){this.base=new Ov,this.minimum=0,Object.assign(this,e)}}ib([Xm({type:Ov})],Hw.prototype,"base",void 0),ib([Xm({type:uy.Integer,context:0,defaultValue:0,implicit:!0})],Hw.prototype,"minimum",void 0),ib([Xm({type:uy.Integer,context:1,optional:!0,implicit:!0})],Hw.prototype,"maximum",void 0);let Kw=Pw=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,Pw.prototype)}};Kw=Pw=ib([Ym({type:hy.Sequence,itemType:Hw})],Kw);class Vw{constructor(e={}){Object.assign(this,e)}}ib([Xm({type:Kw,context:0,optional:!0,implicit:!0})],Vw.prototype,"permittedSubtrees",void 0),ib([Xm({type:Kw,context:1,optional:!0,implicit:!0})],Vw.prototype,"excludedSubtrees",void 0);class Qw{constructor(e={}){Object.assign(this,e)}}var Fw;ib([Xm({type:uy.Integer,context:0,implicit:!0,optional:!0,converter:Em})],Qw.prototype,"requireExplicitPolicy",void 0),ib([Xm({type:uy.Integer,context:1,implicit:!0,optional:!0,converter:Em})],Qw.prototype,"inhibitPolicyMapping",void 0);class Gw{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],Gw.prototype,"issuerDomainPolicy",void 0),ib([Xm({type:uy.ObjectIdentifier})],Gw.prototype,"subjectDomainPolicy",void 0);let $w=Fw=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,Fw.prototype)}};var jw;$w=Fw=ib([Ym({type:hy.Sequence,itemType:Gw})],$w);const qw=`${Hv}.17`;let zw=jw=class extends Jv{constructor(e){super(e),Object.setPrototypeOf(this,jw.prototype)}};zw=jw=ib([Ym({type:hy.Sequence})],zw);class Ww{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}}var Jw;ib([Xm({type:uy.ObjectIdentifier})],Ww.prototype,"type",void 0),ib([Xm({type:uy.Any,repeated:"set"})],Ww.prototype,"values",void 0);let Yw=Jw=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,Jw.prototype)}};Yw=Jw=ib([Ym({type:hy.Sequence,itemType:Ww})],Yw);const Xw=`${Hv}.14`;class Zw extends $v{}class eS{constructor(e={}){Object.assign(this,e)}}var tS,rS;ib([Xm({type:uy.GeneralizedTime,context:0,implicit:!0,optional:!0})],eS.prototype,"notBefore",void 0),ib([Xm({type:uy.GeneralizedTime,context:1,implicit:!0,optional:!0})],eS.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(tS||(tS={}));class sS extends Am{toJSON(){const e=[],t=this.toNumber();return t&tS.pKIXCertificate&&e.push("pKIXCertificate"),t&tS.newExtensions&&e.push("newExtensions"),t&tS.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class iS{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new sS,Object.assign(this,e)}}ib([Xm({type:uy.GeneralString})],iS.prototype,"entrustVers",void 0),ib([Xm({type:sS})],iS.prototype,"entrustInfoFlags",void 0);let nS=rS=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,rS.prototype)}};nS=rS=ib([Ym({type:hy.Sequence,itemType:Qv})],nS);class oS{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof oS&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&qf(e.parameters,this.parameters)||e.parameters===this.parameters)}}ib([Xm({type:uy.ObjectIdentifier})],oS.prototype,"algorithm",void 0),ib([Xm({type:uy.Any,optional:!0})],oS.prototype,"parameters",void 0);class aS{constructor(e={}){this.algorithm=new oS,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:oS})],aS.prototype,"algorithm",void 0),ib([Xm({type:uy.BitString})],aS.prototype,"subjectPublicKey",void 0);let cS=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}};ib([Xm({type:uy.UTCTime})],cS.prototype,"utcTime",void 0),ib([Xm({type:uy.GeneralizedTime})],cS.prototype,"generalTime",void 0),cS=ib([Ym({type:hy.Choice})],cS);class lS{constructor(e){this.notBefore=new cS(new Date),this.notAfter=new cS(new Date),e&&(this.notBefore=new cS(e.notBefore),this.notAfter=new cS(e.notAfter))}}var hS;ib([Xm({type:cS})],lS.prototype,"notBefore",void 0),ib([Xm({type:cS})],lS.prototype,"notAfter",void 0);class uS{constructor(e={}){this.extnID="",this.critical=uS.CRITICAL,this.extnValue=new Im,Object.assign(this,e)}}uS.CRITICAL=!1,ib([Xm({type:uy.ObjectIdentifier})],uS.prototype,"extnID",void 0),ib([Xm({type:uy.Boolean,defaultValue:uS.CRITICAL})],uS.prototype,"critical",void 0),ib([Xm({type:Im})],uS.prototype,"extnValue",void 0);let dS=hS=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,hS.prototype)}};var gS;dS=hS=ib([Ym({type:hy.Sequence,itemType:uS})],dS),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(gS||(gS={}));class fS{constructor(e={}){this.version=gS.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new oS,this.issuer=new xv,this.validity=new lS,this.subject=new xv,this.subjectPublicKeyInfo=new aS,Object.assign(this,e)}}ib([Xm({type:uy.Integer,context:0,defaultValue:gS.v1})],fS.prototype,"version",void 0),ib([Xm({type:uy.Integer,converter:Em})],fS.prototype,"serialNumber",void 0),ib([Xm({type:oS})],fS.prototype,"signature",void 0),ib([Xm({type:xv})],fS.prototype,"issuer",void 0),ib([Xm({type:lS})],fS.prototype,"validity",void 0),ib([Xm({type:xv})],fS.prototype,"subject",void 0),ib([Xm({type:aS})],fS.prototype,"subjectPublicKeyInfo",void 0),ib([Xm({type:uy.BitString,context:1,implicit:!0,optional:!0})],fS.prototype,"issuerUniqueID",void 0),ib([Xm({type:uy.BitString,context:2,implicit:!0,optional:!0})],fS.prototype,"subjectUniqueID",void 0),ib([Xm({type:dS,context:3,optional:!0})],fS.prototype,"extensions",void 0);class pS{constructor(e={}){this.tbsCertificate=new fS,this.signatureAlgorithm=new oS,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:fS})],pS.prototype,"tbsCertificate",void 0),ib([Xm({type:oS})],pS.prototype,"signatureAlgorithm",void 0),ib([Xm({type:uy.BitString})],pS.prototype,"signatureValue",void 0);class yS{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new cS,Object.assign(this,e)}}ib([Xm({type:uy.Integer,converter:Em})],yS.prototype,"userCertificate",void 0),ib([Xm({type:cS})],yS.prototype,"revocationDate",void 0),ib([Xm({type:uS,optional:!0,repeated:"sequence"})],yS.prototype,"crlEntryExtensions",void 0);class mS{constructor(e={}){this.signature=new oS,this.issuer=new xv,this.thisUpdate=new cS,Object.assign(this,e)}}ib([Xm({type:uy.Integer,optional:!0})],mS.prototype,"version",void 0),ib([Xm({type:oS})],mS.prototype,"signature",void 0),ib([Xm({type:xv})],mS.prototype,"issuer",void 0),ib([Xm({type:cS})],mS.prototype,"thisUpdate",void 0),ib([Xm({type:cS,optional:!0})],mS.prototype,"nextUpdate",void 0),ib([Xm({type:yS,repeated:"sequence",optional:!0})],mS.prototype,"revokedCertificates",void 0),ib([Xm({type:uS,optional:!0,context:0,repeated:"sequence"})],mS.prototype,"crlExtensions",void 0);class bS{constructor(e={}){this.tbsCertList=new mS,this.signatureAlgorithm=new oS,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:mS})],bS.prototype,"tbsCertList",void 0),ib([Xm({type:oS})],bS.prototype,"signatureAlgorithm",void 0),ib([Xm({type:uy.BitString})],bS.prototype,"signature",void 0);class AS{constructor(e={}){this.issuer=new xv,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:xv})],AS.prototype,"issuer",void 0),ib([Xm({type:uy.Integer,converter:Em})],AS.prototype,"serialNumber",void 0);let IS=class{constructor(e={}){Object.assign(this,e)}};var vS;ib([Xm({type:Zw,context:0,implicit:!0})],IS.prototype,"subjectKeyIdentifier",void 0),ib([Xm({type:AS})],IS.prototype,"issuerAndSerialNumber",void 0),IS=ib([Ym({type:hy.Choice})],IS),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"}(vS||(vS={}));let wS=class extends oS{};wS=ib([Ym({type:hy.Sequence})],wS);let SS=class extends oS{};SS=ib([Ym({type:hy.Sequence})],SS);let ES=class extends oS{};ES=ib([Ym({type:hy.Sequence})],ES);let CS=class extends oS{};CS=ib([Ym({type:hy.Sequence})],CS);let kS=class extends oS{};kS=ib([Ym({type:hy.Sequence})],kS);let xS=class extends oS{};xS=ib([Ym({type:hy.Sequence})],xS);class BS{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}}var _S;ib([Xm({type:uy.ObjectIdentifier})],BS.prototype,"attrType",void 0),ib([Xm({type:uy.Any,repeated:"set"})],BS.prototype,"attrValues",void 0);class RS{constructor(e={}){this.version=vS.v0,this.sid=new IS,this.digestAlgorithm=new wS,this.signatureAlgorithm=new SS,this.signature=new Im,Object.assign(this,e)}}ib([Xm({type:uy.Integer})],RS.prototype,"version",void 0),ib([Xm({type:IS})],RS.prototype,"sid",void 0),ib([Xm({type:wS})],RS.prototype,"digestAlgorithm",void 0),ib([Xm({type:BS,repeated:"set",context:0,implicit:!0,optional:!0})],RS.prototype,"signedAttrs",void 0),ib([Xm({type:SS})],RS.prototype,"signatureAlgorithm",void 0),ib([Xm({type:Im})],RS.prototype,"signature",void 0),ib([Xm({type:BS,repeated:"set",context:1,implicit:!0,optional:!0})],RS.prototype,"unsignedAttrs",void 0);let OS=_S=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,_S.prototype)}};OS=_S=ib([Ym({type:hy.Set,itemType:RS})],OS);let US=class extends cS{};US=ib([Ym({type:hy.Choice})],US);let TS=class extends RS{};TS=ib([Ym({type:hy.Sequence})],TS);class NS{constructor(e={}){this.acIssuer=new Ov,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}var DS;ib([Xm({type:Ov})],NS.prototype,"acIssuer",void 0),ib([Xm({type:uy.Integer})],NS.prototype,"acSerial",void 0),ib([Xm({type:Ww,repeated:"sequence"})],NS.prototype,"attrs",void 0);let MS=DS=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,DS.prototype)}};MS=DS=ib([Ym({type:hy.Sequence,itemType:uy.ObjectIdentifier})],MS);class PS{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}}ib([Xm({type:uy.Integer,optional:!0})],PS.prototype,"pathLenConstraint",void 0),ib([Xm({type:MS,implicit:!0,context:0,optional:!0})],PS.prototype,"permittedAttrs",void 0),ib([Xm({type:MS,implicit:!0,context:1,optional:!0})],PS.prototype,"excludedAttrs",void 0),ib([Xm({type:uy.Boolean,defaultValue:!0})],PS.prototype,"permitUnSpecified",void 0);class LS{constructor(e={}){this.issuer=new Jv,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}var HS;ib([Xm({type:Jv})],LS.prototype,"issuer",void 0),ib([Xm({type:uy.Integer,converter:Em})],LS.prototype,"serial",void 0),ib([Xm({type:uy.BitString,optional:!0})],LS.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}(HS||(HS={}));class KS{constructor(e={}){this.digestedObjectType=HS.publicKey,this.digestAlgorithm=new oS,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.Enumerated})],KS.prototype,"digestedObjectType",void 0),ib([Xm({type:uy.ObjectIdentifier,optional:!0})],KS.prototype,"otherObjectTypeID",void 0),ib([Xm({type:oS})],KS.prototype,"digestAlgorithm",void 0),ib([Xm({type:uy.BitString})],KS.prototype,"objectDigest",void 0);class VS{constructor(e={}){Object.assign(this,e)}}ib([Xm({type:Jv,optional:!0})],VS.prototype,"issuerName",void 0),ib([Xm({type:LS,context:0,implicit:!0,optional:!0})],VS.prototype,"baseCertificateID",void 0),ib([Xm({type:KS,context:1,implicit:!0,optional:!0})],VS.prototype,"objectDigestInfo",void 0);let QS=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:Ov,repeated:"sequence"})],QS.prototype,"v1Form",void 0),ib([Xm({type:VS,context:0,implicit:!0})],QS.prototype,"v2Form",void 0),QS=ib([Ym({type:hy.Choice})],QS);class FS{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}ib([Xm({type:uy.GeneralizedTime})],FS.prototype,"notBeforeTime",void 0),ib([Xm({type:uy.GeneralizedTime})],FS.prototype,"notAfterTime",void 0);class GS{constructor(e={}){Object.assign(this,e)}}var $S,jS,qS;ib([Xm({type:LS,implicit:!0,context:0,optional:!0})],GS.prototype,"baseCertificateID",void 0),ib([Xm({type:Jv,implicit:!0,context:1,optional:!0})],GS.prototype,"entityName",void 0),ib([Xm({type:KS,implicit:!0,context:2,optional:!0})],GS.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}($S||($S={}));class zS{constructor(e={}){this.version=$S.v2,this.holder=new GS,this.issuer=new QS,this.signature=new oS,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new FS,this.attributes=[],Object.assign(this,e)}}ib([Xm({type:uy.Integer})],zS.prototype,"version",void 0),ib([Xm({type:GS})],zS.prototype,"holder",void 0),ib([Xm({type:QS})],zS.prototype,"issuer",void 0),ib([Xm({type:oS})],zS.prototype,"signature",void 0),ib([Xm({type:uy.Integer,converter:Em})],zS.prototype,"serialNumber",void 0),ib([Xm({type:FS})],zS.prototype,"attrCertValidityPeriod",void 0),ib([Xm({type:Ww,repeated:"sequence"})],zS.prototype,"attributes",void 0),ib([Xm({type:uy.BitString,optional:!0})],zS.prototype,"issuerUniqueID",void 0),ib([Xm({type:dS,optional:!0})],zS.prototype,"extensions",void 0);class WS{constructor(e={}){this.acinfo=new zS,this.signatureAlgorithm=new oS,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:zS})],WS.prototype,"acinfo",void 0),ib([Xm({type:oS})],WS.prototype,"signatureAlgorithm",void 0),ib([Xm({type:uy.BitString})],WS.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"}(jS||(jS={}));class JS extends Am{}class YS{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier,implicit:!0,context:0})],YS.prototype,"type",void 0),ib([Xm({type:uy.Any,implicit:!0,context:1})],YS.prototype,"value",void 0);class XS{constructor(e={}){this.policyId="",this.classList=new JS(jS.unclassified),Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],XS.prototype,"policyId",void 0),ib([Xm({type:JS,defaultValue:new JS(jS.unclassified)})],XS.prototype,"classList",void 0),ib([Xm({type:YS,repeated:"set"})],XS.prototype,"securityCategories",void 0);class ZS{constructor(e={}){Object.assign(this,e)}}ib([Xm({type:Im})],ZS.prototype,"cotets",void 0),ib([Xm({type:uy.ObjectIdentifier})],ZS.prototype,"oid",void 0),ib([Xm({type:uy.Utf8String})],ZS.prototype,"string",void 0);class eE{constructor(e={}){this.values=[],Object.assign(this,e)}}ib([Xm({type:Jv,implicit:!0,context:0,optional:!0})],eE.prototype,"policyAuthority",void 0),ib([Xm({type:ZS,repeated:"sequence"})],eE.prototype,"values",void 0);class tE{constructor(e={}){this.targetCertificate=new LS,Object.assign(this,e)}}ib([Xm({type:LS})],tE.prototype,"targetCertificate",void 0),ib([Xm({type:Ov,optional:!0})],tE.prototype,"targetName",void 0),ib([Xm({type:KS,optional:!0})],tE.prototype,"certDigestInfo",void 0);let rE=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:Ov,context:0,implicit:!0})],rE.prototype,"targetName",void 0),ib([Xm({type:Ov,context:1,implicit:!0})],rE.prototype,"targetGroup",void 0),ib([Xm({type:tE,context:2,implicit:!0})],rE.prototype,"targetCert",void 0),rE=ib([Ym({type:hy.Choice})],rE);let sE=qS=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,qS.prototype)}};var iE;sE=qS=ib([Ym({type:hy.Sequence,itemType:rE})],sE);let nE=iE=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,iE.prototype)}};nE=iE=ib([Ym({type:hy.Sequence,itemType:sE})],nE);class oE{constructor(e={}){Object.assign(this,e)}}ib([Xm({type:Jv,implicit:!0,context:0,optional:!0})],oE.prototype,"roleAuthority",void 0),ib([Xm({type:Ov,implicit:!0,context:1})],oE.prototype,"roleName",void 0);class aE{constructor(e={}){this.service=new Ov,this.ident=new Ov,Object.assign(this,e)}}var cE;ib([Xm({type:Ov})],aE.prototype,"service",void 0),ib([Xm({type:Ov})],aE.prototype,"ident",void 0),ib([Xm({type:Im,optional:!0})],aE.prototype,"authInfo",void 0);class lE{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],lE.prototype,"otherCertFormat",void 0),ib([Xm({type:uy.Any})],lE.prototype,"otherCert",void 0);let hE=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:pS})],hE.prototype,"certificate",void 0),ib([Xm({type:WS,context:2,implicit:!0})],hE.prototype,"v2AttrCert",void 0),ib([Xm({type:lE,context:3,implicit:!0})],hE.prototype,"other",void 0),hE=ib([Ym({type:hy.Choice})],hE);let uE=cE=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,cE.prototype)}};uE=cE=ib([Ym({type:hy.Set,itemType:hE})],uE);class dE{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],dE.prototype,"contentType",void 0),ib([Xm({type:uy.Any,context:0})],dE.prototype,"content",void 0);let gE=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:Im})],gE.prototype,"single",void 0),ib([Xm({type:uy.Any})],gE.prototype,"any",void 0),gE=ib([Ym({type:hy.Choice})],gE);class fE{constructor(e={}){this.eContentType="",Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],fE.prototype,"eContentType",void 0),ib([Xm({type:gE,context:0,optional:!0})],fE.prototype,"eContent",void 0);let pE=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:Im,context:0,implicit:!0,optional:!0})],pE.prototype,"value",void 0),ib([Xm({type:Im,converter:_m,context:0,implicit:!0,optional:!0,repeated:"sequence"})],pE.prototype,"constructedValue",void 0),pE=ib([Ym({type:hy.Choice})],pE);class yE{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new CS,Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],yE.prototype,"contentType",void 0),ib([Xm({type:CS})],yE.prototype,"contentEncryptionAlgorithm",void 0),ib([Xm({type:pE,optional:!0})],yE.prototype,"encryptedContent",void 0);class mE{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}}var bE;ib([Xm({type:uy.ObjectIdentifier})],mE.prototype,"keyAttrId",void 0),ib([Xm({type:uy.Any,optional:!0})],mE.prototype,"keyAttr",void 0);class AE{constructor(e={}){this.subjectKeyIdentifier=new Zw,Object.assign(this,e)}}ib([Xm({type:Zw})],AE.prototype,"subjectKeyIdentifier",void 0),ib([Xm({type:uy.GeneralizedTime,optional:!0})],AE.prototype,"date",void 0),ib([Xm({type:mE,optional:!0})],AE.prototype,"other",void 0);let IE=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:AE,context:0,implicit:!0,optional:!0})],IE.prototype,"rKeyId",void 0),ib([Xm({type:AS,optional:!0})],IE.prototype,"issuerAndSerialNumber",void 0),IE=ib([Ym({type:hy.Choice})],IE);class vE{constructor(e={}){this.rid=new IE,this.encryptedKey=new Im,Object.assign(this,e)}}ib([Xm({type:IE})],vE.prototype,"rid",void 0),ib([Xm({type:Im})],vE.prototype,"encryptedKey",void 0);let wE=bE=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,bE.prototype)}};wE=bE=ib([Ym({type:hy.Sequence,itemType:vE})],wE);class SE{constructor(e={}){this.algorithm=new oS,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:oS})],SE.prototype,"algorithm",void 0),ib([Xm({type:uy.BitString})],SE.prototype,"publicKey",void 0);let EE=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:Zw,context:0,implicit:!0,optional:!0})],EE.prototype,"subjectKeyIdentifier",void 0),ib([Xm({type:SE,context:1,implicit:!0,optional:!0})],EE.prototype,"originatorKey",void 0),ib([Xm({type:AS,optional:!0})],EE.prototype,"issuerAndSerialNumber",void 0),EE=ib([Ym({type:hy.Choice})],EE);class CE{constructor(e={}){this.version=vS.v3,this.originator=new EE,this.keyEncryptionAlgorithm=new ES,this.recipientEncryptedKeys=new wE,Object.assign(this,e)}}ib([Xm({type:uy.Integer})],CE.prototype,"version",void 0),ib([Xm({type:EE,context:0})],CE.prototype,"originator",void 0),ib([Xm({type:Im,context:1,optional:!0})],CE.prototype,"ukm",void 0),ib([Xm({type:ES})],CE.prototype,"keyEncryptionAlgorithm",void 0),ib([Xm({type:wE})],CE.prototype,"recipientEncryptedKeys",void 0);let kE=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:Zw,context:0,implicit:!0})],kE.prototype,"subjectKeyIdentifier",void 0),ib([Xm({type:AS})],kE.prototype,"issuerAndSerialNumber",void 0),kE=ib([Ym({type:hy.Choice})],kE);class xE{constructor(e={}){this.version=vS.v0,this.rid=new kE,this.keyEncryptionAlgorithm=new ES,this.encryptedKey=new Im,Object.assign(this,e)}}ib([Xm({type:uy.Integer})],xE.prototype,"version",void 0),ib([Xm({type:kE})],xE.prototype,"rid",void 0),ib([Xm({type:ES})],xE.prototype,"keyEncryptionAlgorithm",void 0),ib([Xm({type:Im})],xE.prototype,"encryptedKey",void 0);class BE{constructor(e={}){this.keyIdentifier=new Im,Object.assign(this,e)}}ib([Xm({type:Im})],BE.prototype,"keyIdentifier",void 0),ib([Xm({type:uy.GeneralizedTime,optional:!0})],BE.prototype,"date",void 0),ib([Xm({type:mE,optional:!0})],BE.prototype,"other",void 0);class _E{constructor(e={}){this.version=vS.v4,this.kekid=new BE,this.keyEncryptionAlgorithm=new ES,this.encryptedKey=new Im,Object.assign(this,e)}}ib([Xm({type:uy.Integer})],_E.prototype,"version",void 0),ib([Xm({type:BE})],_E.prototype,"kekid",void 0),ib([Xm({type:ES})],_E.prototype,"keyEncryptionAlgorithm",void 0),ib([Xm({type:Im})],_E.prototype,"encryptedKey",void 0);class RE{constructor(e={}){this.version=vS.v0,this.keyEncryptionAlgorithm=new ES,this.encryptedKey=new Im,Object.assign(this,e)}}ib([Xm({type:uy.Integer})],RE.prototype,"version",void 0),ib([Xm({type:xS,context:0,optional:!0})],RE.prototype,"keyDerivationAlgorithm",void 0),ib([Xm({type:ES})],RE.prototype,"keyEncryptionAlgorithm",void 0),ib([Xm({type:Im})],RE.prototype,"encryptedKey",void 0);class OE{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],OE.prototype,"oriType",void 0),ib([Xm({type:uy.Any})],OE.prototype,"oriValue",void 0);let UE=class{constructor(e={}){Object.assign(this,e)}};var TE;ib([Xm({type:xE,optional:!0})],UE.prototype,"ktri",void 0),ib([Xm({type:CE,context:1,implicit:!0,optional:!0})],UE.prototype,"kari",void 0),ib([Xm({type:_E,context:2,implicit:!0,optional:!0})],UE.prototype,"kekri",void 0),ib([Xm({type:RE,context:3,implicit:!0,optional:!0})],UE.prototype,"pwri",void 0),ib([Xm({type:OE,context:4,implicit:!0,optional:!0})],UE.prototype,"ori",void 0),UE=ib([Ym({type:hy.Choice})],UE);let NE=TE=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,TE.prototype)}};var DE;NE=TE=ib([Ym({type:hy.Set,itemType:UE})],NE);class ME{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],ME.prototype,"otherRevInfoFormat",void 0),ib([Xm({type:uy.Any})],ME.prototype,"otherRevInfo",void 0);let PE=class{constructor(e={}){this.other=new ME,Object.assign(this,e)}};ib([Xm({type:ME,context:1,implicit:!0})],PE.prototype,"other",void 0),PE=ib([Ym({type:hy.Choice})],PE);let LE=DE=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,DE.prototype)}};LE=DE=ib([Ym({type:hy.Set,itemType:PE})],LE);class HE{constructor(e={}){Object.assign(this,e)}}var KE;ib([Xm({type:uE,context:0,implicit:!0,optional:!0})],HE.prototype,"certs",void 0),ib([Xm({type:LE,context:1,implicit:!0,optional:!0})],HE.prototype,"crls",void 0);let VE=KE=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,KE.prototype)}};VE=KE=ib([Ym({type:hy.Set,itemType:BS})],VE);class QE{constructor(e={}){this.version=vS.v0,this.recipientInfos=new NE,this.encryptedContentInfo=new yE,Object.assign(this,e)}}ib([Xm({type:uy.Integer})],QE.prototype,"version",void 0),ib([Xm({type:HE,context:0,implicit:!0,optional:!0})],QE.prototype,"originatorInfo",void 0),ib([Xm({type:NE})],QE.prototype,"recipientInfos",void 0),ib([Xm({type:yE})],QE.prototype,"encryptedContentInfo",void 0),ib([Xm({type:VE,context:1,implicit:!0,optional:!0})],QE.prototype,"unprotectedAttrs",void 0);const FE="1.2.840.113549.1.7.2";var GE;let $E=GE=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,GE.prototype)}};$E=GE=ib([Ym({type:hy.Set,itemType:wS})],$E);class jE{constructor(e={}){this.version=vS.v0,this.digestAlgorithms=new $E,this.encapContentInfo=new fE,this.signerInfos=new OS,Object.assign(this,e)}}ib([Xm({type:uy.Integer})],jE.prototype,"version",void 0),ib([Xm({type:$E})],jE.prototype,"digestAlgorithms",void 0),ib([Xm({type:fE})],jE.prototype,"encapContentInfo",void 0),ib([Xm({type:uE,context:0,implicit:!0,optional:!0})],jE.prototype,"certificates",void 0),ib([Xm({type:LE,context:1,implicit:!0,optional:!0})],jE.prototype,"crls",void 0),ib([Xm({type:OS})],jE.prototype,"signerInfos",void 0);const qE="1.2.840.10045.2.1",zE="1.2.840.10045.4.1",WE="1.2.840.10045.4.3.1",JE="1.2.840.10045.4.3.2",YE="1.2.840.10045.4.3.3",XE="1.2.840.10045.4.3.4",ZE="1.2.840.10045.3.1.7",eC="1.3.132.0.34",tC="1.3.132.0.35";function rC(e){return new oS({algorithm:e})}const sC=rC(zE),iC=(rC(WE),rC(JE)),nC=rC(YE),oC=rC(XE);let aC=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:uy.ObjectIdentifier})],aC.prototype,"fieldType",void 0),ib([Xm({type:uy.Any})],aC.prototype,"parameters",void 0),aC=ib([Ym({type:hy.Sequence})],aC);let cC=class{constructor(e={}){Object.assign(this,e)}};var lC;ib([Xm({type:uy.OctetString})],cC.prototype,"a",void 0),ib([Xm({type:uy.OctetString})],cC.prototype,"b",void 0),ib([Xm({type:uy.BitString,optional:!0})],cC.prototype,"seed",void 0),cC=ib([Ym({type:hy.Sequence})],cC),function(e){e[e.ecpVer1=1]="ecpVer1"}(lC||(lC={}));let hC=class{constructor(e={}){this.version=lC.ecpVer1,Object.assign(this,e)}};ib([Xm({type:uy.Integer})],hC.prototype,"version",void 0),ib([Xm({type:aC})],hC.prototype,"fieldID",void 0),ib([Xm({type:cC})],hC.prototype,"curve",void 0),ib([Xm({type:class extends Im{}})],hC.prototype,"base",void 0),ib([Xm({type:uy.Integer,converter:Em})],hC.prototype,"order",void 0),ib([Xm({type:uy.Integer,optional:!0})],hC.prototype,"cofactor",void 0),hC=ib([Ym({type:hy.Sequence})],hC);let uC=class{constructor(e={}){Object.assign(this,e)}};ib([Xm({type:uy.ObjectIdentifier})],uC.prototype,"namedCurve",void 0),ib([Xm({type:uy.Null})],uC.prototype,"implicitCurve",void 0),ib([Xm({type:hC})],uC.prototype,"specifiedCurve",void 0),uC=ib([Ym({type:hy.Choice})],uC);class dC{constructor(e={}){this.version=1,this.privateKey=new Im,Object.assign(this,e)}}ib([Xm({type:uy.Integer})],dC.prototype,"version",void 0),ib([Xm({type:Im})],dC.prototype,"privateKey",void 0),ib([Xm({type:uC,context:0,optional:!0})],dC.prototype,"parameters",void 0),ib([Xm({type:uy.BitString,context:1,optional:!0})],dC.prototype,"publicKey",void 0);class gC{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.Integer,converter:Em})],gC.prototype,"r",void 0),ib([Xm({type:uy.Integer,converter:Em})],gC.prototype,"s",void 0);const fC="1.2.840.113549.1.1",pC=`${fC}.1`,yC=`${fC}.7`,mC=`${fC}.9`,bC=`${fC}.10`,AC=`${fC}.2`,IC=`${fC}.4`,vC=`${fC}.5`,wC=`${fC}.14`,SC=`${fC}.11`,EC=`${fC}.12`,CC=`${fC}.13`,kC=`${fC}.15`,xC=`${fC}.16`,BC="1.3.14.3.2.26",_C="2.16.840.1.101.3.4.2.4",RC="2.16.840.1.101.3.4.2.1",OC="2.16.840.1.101.3.4.2.2",UC="2.16.840.1.101.3.4.2.3",TC=`${fC}.8`;function NC(e){return new oS({algorithm:e,parameters:null})}NC("1.2.840.113549.2.2"),NC("1.2.840.113549.2.5");const DC=NC(BC),MC=(NC(_C),NC(RC),NC(OC),NC(UC),NC("2.16.840.1.101.3.4.2.5"),NC("2.16.840.1.101.3.4.2.6"),new oS({algorithm:TC,parameters:sb.serialize(DC)})),PC=new oS({algorithm:mC,parameters:sb.serialize(Bm.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});NC(pC),NC(AC),NC(IC),NC(vC),NC(kC),NC(xC),NC(EC),NC(CC),NC(kC),NC(xC);class LC{constructor(e={}){this.hashAlgorithm=new oS(DC),this.maskGenAlgorithm=new oS({algorithm:TC,parameters:sb.serialize(DC)}),this.pSourceAlgorithm=new oS(PC),Object.assign(this,e)}}ib([Xm({type:oS,context:0,defaultValue:DC})],LC.prototype,"hashAlgorithm",void 0),ib([Xm({type:oS,context:1,defaultValue:MC})],LC.prototype,"maskGenAlgorithm",void 0),ib([Xm({type:oS,context:2,defaultValue:PC})],LC.prototype,"pSourceAlgorithm",void 0),new oS({algorithm:yC,parameters:sb.serialize(new LC)});class HC{constructor(e={}){this.hashAlgorithm=new oS(DC),this.maskGenAlgorithm=new oS({algorithm:TC,parameters:sb.serialize(DC)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}ib([Xm({type:oS,context:0,defaultValue:DC})],HC.prototype,"hashAlgorithm",void 0),ib([Xm({type:oS,context:1,defaultValue:MC})],HC.prototype,"maskGenAlgorithm",void 0),ib([Xm({type:uy.Integer,context:2,defaultValue:20})],HC.prototype,"saltLength",void 0),ib([Xm({type:uy.Integer,context:3,defaultValue:1})],HC.prototype,"trailerField",void 0),new oS({algorithm:bC,parameters:sb.serialize(new HC)});class KC{constructor(e={}){this.digestAlgorithm=new oS,this.digest=new Im,Object.assign(this,e)}}var VC;ib([Xm({type:oS})],KC.prototype,"digestAlgorithm",void 0),ib([Xm({type:Im})],KC.prototype,"digest",void 0);class QC{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.Integer,converter:Em})],QC.prototype,"prime",void 0),ib([Xm({type:uy.Integer,converter:Em})],QC.prototype,"exponent",void 0),ib([Xm({type:uy.Integer,converter:Em})],QC.prototype,"coefficient",void 0);let FC=VC=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,VC.prototype)}};FC=VC=ib([Ym({type:hy.Sequence,itemType:QC})],FC);class GC{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)}}ib([Xm({type:uy.Integer})],GC.prototype,"version",void 0),ib([Xm({type:uy.Integer,converter:Em})],GC.prototype,"modulus",void 0),ib([Xm({type:uy.Integer,converter:Em})],GC.prototype,"publicExponent",void 0),ib([Xm({type:uy.Integer,converter:Em})],GC.prototype,"privateExponent",void 0),ib([Xm({type:uy.Integer,converter:Em})],GC.prototype,"prime1",void 0),ib([Xm({type:uy.Integer,converter:Em})],GC.prototype,"prime2",void 0),ib([Xm({type:uy.Integer,converter:Em})],GC.prototype,"exponent1",void 0),ib([Xm({type:uy.Integer,converter:Em})],GC.prototype,"exponent2",void 0),ib([Xm({type:uy.Integer,converter:Em})],GC.prototype,"coefficient",void 0),ib([Xm({type:FC,optional:!0})],GC.prototype,"otherPrimeInfos",void 0);class $C{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}var jC;ib([Xm({type:uy.Integer,converter:Em})],$C.prototype,"modulus",void 0),ib([Xm({type:uy.Integer,converter:Em})],$C.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"}(jC||(jC={}));const qC=jC;var zC=function(e,t){return zC=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},zC(e,t)};function WC(e,t){function r(){this.constructor=e}zC(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function JC(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 YC(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 XC(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(YC(arguments[t]));return e}function ZC(e){return!!e.useClass}function ek(e){return!!e.useFactory}var tk=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,XC(t))}}),t},e}();function rk(e){return"string"==typeof e||"symbol"==typeof e}function sk(e){return"object"==typeof e&&"token"in e&&"transform"in e}function ik(e){return!!e.useToken}function nk(e){return null!=e.useValue}var ok=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 ak=ok,ck=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return WC(t,e),t}(ak),lk=function(){this.scopedResolutions=new Map};var hk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return WC(t,e),t}(ak),uk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return WC(t,e),t}(ak);const dk=function(){this.preResolution=new hk,this.postResolution=new uk};var gk=new Map,fk=function(){function e(e){this.parent=e,this._registry=new ck,this.interceptors=new dk,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var s;if(void 0===r&&(r={lifecycle:qC.Transient}),this.ensureNotDisposed(),s=function(e){return ZC(e)||nk(e)||ik(e)||ek(e)}(t)?t:{useClass:t},ik(s))for(var i=[e],n=s;null!=n;){var o=n.useToken;if(i.includes(o))throw new Error("Token registration cycle detected! "+XC(i,[o]).join(" -> "));i.push(o);var a=this._registry.get(o);n=a&&ik(a.provider)?a.provider:null}if((r.lifecycle===qC.Singleton||r.lifecycle==qC.ContainerScoped||r.lifecycle==qC.ResolutionScoped)&&(nk(s)||ek(s)))throw new Error('Cannot use lifecycle "'+qC[r.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:s,options:r}),this},e.prototype.registerType=function(e,t){return this.ensureNotDisposed(),rk(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(),rk(e)){if(rk(t))return this.register(e,{useToken:t},{lifecycle:qC.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:qC.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!rk(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:qC.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new lk),void 0===r&&(r=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&rk(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 tk}(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=JC(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=JC(this.interceptors.postResolution.getAll(e)),a=o.next();!a.done;a=o.next()){var c=a.value;"Once"!=c.options.frequency&&n.push(c),c.callback(e,t,r)}}catch(e){s={error:e}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(s)throw s.error}}this.interceptors.postResolution.setAll(e,n)}},e.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===qC.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,s=e.options.lifecycle===qC.Singleton,i=e.options.lifecycle===qC.ContainerScoped,n=s||i;return r=nk(e.provider)?e.provider.useValue:ik(e.provider)?n?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):ZC(e.provider)?n?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):ek(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===qC.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var s=this;void 0===t&&(t=new lk),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&rk(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=JC(this._registry.entries()),s=r.next();!s.done;s=r.next()){var i=YC(s.value,2),n=i[0],o=i[1];this._registry.setAll(n,o.filter(function(e){return!nk(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=JC(this._registry.entries()),n=i.next();!n.done;n=i.next()){var o=YC(n.value,2),a=o[0],c=o[1];c.some(function(e){return e.options.lifecycle===qC.ContainerScoped})&&s._registry.setAll(a,c.map(function(e){return e.options.lifecycle===qC.ContainerScoped?{provider:e.provider,options:e.options}:e}))}}catch(e){t={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return s},e.prototype.beforeResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:t,options:r})},e.prototype.afterResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:t,options:r})},e.prototype.dispose=function(){return function(e,t,r,s){return new(r||(r=Promise))(function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((s=s.apply(e,t||[])).next())})}(this,void 0,void 0,function(){var e;return function(e,t){var r,s,i,n,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return n={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function a(n){return function(a){return function(n){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,s&&(i=2&n[0]?s.return:n[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,n[1])).done)return i;switch(s=0,i&&(n=[2&n[0],i.value]),n[0]){case 0:case 1:i=n;break;case 4:return o.label++,{value:n[1],done:!1};case 5:o.label++,s=n[1],n=[0];continue;case 7:n=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==n[0]&&2!==n[0])){o=0;continue}if(3===n[0]&&(!i||n[1]>i[0]&&n[1]<i[3])){o.label=n[1];break}if(6===n[0]&&o.label<i[1]){o.label=i[1],i=n;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(n);break}i[2]&&o.ops.pop(),o.trys.pop();continue}n=t.call(e,o)}catch(e){n=[6,e],s=0}finally{r=i=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}([n,a])}}}(this,function(t){switch(t.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(t){var r=t.dispose();r&&e.push(r)}),[4,Promise.all(e)];case 1:return t.sent(),[2]}})})},e.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},e.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},e.prototype.construct=function(e,t){var r=this;if(e instanceof tk)return e.createProxy(function(e){return r.resolve(e,t)});var s,i=function(){var s=gk.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,XC([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?sk(s)?s.multiple?(n=r.resolve(s.transform)).transform.apply(n,XC([r.resolveAll(s.token,new lk,s.isOptional)],s.transformArgs)):(o=r.resolve(s.transform)).transform.apply(o,XC([r.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?r.resolveAll(s.token,new lk,s.isOptional):r.resolve(s.token,e,s.isOptional):sk(s)?(a=r.resolve(s.transform,e)).transform.apply(a,XC([r.resolve(s.token,e)],s.transformArgs)):r.resolve(s,e)}catch(e){throw new Error(function(e,t,r){var s,i,n=YC(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return function(e,t,r){return void 0===r&&(r=" "),XC([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}(),pk=new fk;const yk=function(e){return function(t){gk.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){pk.register(e,t)}):pk.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 mk;class bk{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}}ib([Xm({type:uy.ObjectIdentifier})],bk.prototype,"attrId",void 0),ib([Xm({type:uy.Any,repeated:"set"})],bk.prototype,"attrValues",void 0);let Ak=mk=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,mk.prototype)}};var Ik;Ak=mk=ib([Ym({type:hy.Sequence,itemType:bk})],Ak);let vk=Ik=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,Ik.prototype)}};vk=Ik=ib([Ym({type:hy.Sequence,itemType:dE})],vk);class wk{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],wk.prototype,"certId",void 0),ib([Xm({type:uy.Any,context:0})],wk.prototype,"certValue",void 0);class Sk{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],Sk.prototype,"crlId",void 0),ib([Xm({type:uy.Any,context:0})],Sk.prototype,"crltValue",void 0);class Ek extends Im{}class Ck{constructor(e={}){this.encryptionAlgorithm=new oS,this.encryptedData=new Ek,Object.assign(this,e)}}var kk,xk;ib([Xm({type:oS})],Ck.prototype,"encryptionAlgorithm",void 0),ib([Xm({type:Ek})],Ck.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(xk||(xk={}));class Bk extends Im{}let _k=kk=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,kk.prototype)}};_k=kk=ib([Ym({type:hy.Sequence,itemType:Ww})],_k);class Rk{constructor(e={}){this.version=xk.v1,this.privateKeyAlgorithm=new oS,this.privateKey=new Bk,Object.assign(this,e)}}ib([Xm({type:uy.Integer})],Rk.prototype,"version",void 0),ib([Xm({type:oS})],Rk.prototype,"privateKeyAlgorithm",void 0),ib([Xm({type:Bk})],Rk.prototype,"privateKey",void 0),ib([Xm({type:_k,implicit:!0,context:0,optional:!0})],Rk.prototype,"attributes",void 0);let Ok=class extends Rk{};Ok=ib([Ym({type:hy.Sequence})],Ok);let Uk=class extends Ck{};Uk=ib([Ym({type:hy.Sequence})],Uk);class Tk{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],Tk.prototype,"secretTypeId",void 0),ib([Xm({type:uy.Any,context:0})],Tk.prototype,"secretValue",void 0);class Nk{constructor(e={}){this.mac=new KC,this.macSalt=new Im,this.iterations=1,Object.assign(this,e)}}ib([Xm({type:KC})],Nk.prototype,"mac",void 0),ib([Xm({type:Im})],Nk.prototype,"macSalt",void 0),ib([Xm({type:uy.Integer,defaultValue:1})],Nk.prototype,"iterations",void 0);class Dk{constructor(e={}){this.version=3,this.authSafe=new dE,this.macData=new Nk,Object.assign(this,e)}}var Mk;ib([Xm({type:uy.Integer})],Dk.prototype,"version",void 0),ib([Xm({type:dE})],Dk.prototype,"authSafe",void 0),ib([Xm({type:Nk,optional:!0})],Dk.prototype,"macData",void 0);class Pk{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:uy.ObjectIdentifier})],Pk.prototype,"bagId",void 0),ib([Xm({type:uy.Any,context:0})],Pk.prototype,"bagValue",void 0),ib([Xm({type:bk,repeated:"set",optional:!0})],Pk.prototype,"bagAttributes",void 0);let Lk=Mk=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,Mk.prototype)}};var Hk,Kk,Vk;Lk=Mk=ib([Ym({type:hy.Sequence,itemType:Pk})],Lk);const Qk="1.2.840.113549.1.9",Fk=`${Qk}.7`,Gk=`${Qk}.14`;let $k=class extends wv{constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};ib([Xm({type:uy.IA5String})],$k.prototype,"ia5String",void 0),$k=ib([Ym({type:hy.Choice})],$k);let jk=class extends dE{};jk=ib([Ym({type:hy.Sequence})],jk);let qk=class extends Dk{};qk=ib([Ym({type:hy.Sequence})],qk);let zk=class extends Ck{};zk=ib([Ym({type:hy.Sequence})],zk);let Wk=class{constructor(e=""){this.value=e}toString(){return this.value}};ib([Xm({type:uy.IA5String})],Wk.prototype,"value",void 0),Wk=ib([Ym({type:hy.Choice})],Wk);let Jk=class extends $k{};Jk=ib([Ym({type:hy.Choice})],Jk);let Yk=class extends wv{};Yk=ib([Ym({type:hy.Choice})],Yk);let Xk=class{constructor(e=new Date){this.value=e}};ib([Xm({type:uy.GeneralizedTime})],Xk.prototype,"value",void 0),Xk=ib([Ym({type:hy.Choice})],Xk);let Zk=class extends wv{};Zk=ib([Ym({type:hy.Choice})],Zk);let ex=class{constructor(e="M"){this.value=e}toString(){return this.value}};ib([Xm({type:uy.PrintableString})],ex.prototype,"value",void 0),ex=ib([Ym({type:hy.Choice})],ex);let tx=class{constructor(e=""){this.value=e}toString(){return this.value}};ib([Xm({type:uy.PrintableString})],tx.prototype,"value",void 0),tx=ib([Ym({type:hy.Choice})],tx);let rx=class extends tx{};rx=ib([Ym({type:hy.Choice})],rx);let sx=class extends wv{};sx=ib([Ym({type:hy.Choice})],sx);let ix=class{constructor(e=""){this.value=e}toString(){return this.value}};ib([Xm({type:uy.ObjectIdentifier})],ix.prototype,"value",void 0),ix=ib([Ym({type:hy.Choice})],ix);let nx=class extends cS{};nx=ib([Ym({type:hy.Choice})],nx);let ox=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};ib([Xm({type:uy.Integer})],ox.prototype,"value",void 0),ox=ib([Ym({type:hy.Choice})],ox);let ax=class extends RS{};ax=ib([Ym({type:hy.Sequence})],ax);let cx=class extends wv{};cx=ib([Ym({type:hy.Choice})],cx);let lx=Hk=class extends dS{constructor(e){super(e),Object.setPrototypeOf(this,Hk.prototype)}};lx=Hk=ib([Ym({type:hy.Sequence})],lx);let hx=Kk=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,Kk.prototype)}};hx=Kk=ib([Ym({type:hy.Set,itemType:BS})],hx);let ux=class{constructor(e=""){this.value=e}toString(){return this.value}};ib([Xm({type:uy.BmpString})],ux.prototype,"value",void 0),ux=ib([Ym({type:hy.Choice})],ux);let dx=class extends oS{};dx=ib([Ym({type:hy.Sequence})],dx);let gx=Vk=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,Vk.prototype)}};var fx;gx=Vk=ib([Ym({type:hy.Sequence,itemType:dx})],gx);let px=fx=class extends rb{constructor(e){super(e),Object.setPrototypeOf(this,fx.prototype)}};px=fx=ib([Ym({type:hy.Sequence,itemType:Ww})],px);class yx{constructor(e={}){this.version=0,this.subject=new xv,this.subjectPKInfo=new aS,this.attributes=new px,Object.assign(this,e)}}ib([Xm({type:uy.Integer})],yx.prototype,"version",void 0),ib([Xm({type:xv})],yx.prototype,"subject",void 0),ib([Xm({type:aS})],yx.prototype,"subjectPKInfo",void 0),ib([Xm({type:px,implicit:!0,context:0})],yx.prototype,"attributes",void 0);class mx{constructor(e={}){this.certificationRequestInfo=new yx,this.signatureAlgorithm=new oS,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}ib([Xm({type:yx})],mx.prototype,"certificationRequestInfo",void 0),ib([Xm({type:oS})],mx.prototype,"signatureAlgorithm",void 0),ib([Xm({type:uy.BitString})],mx.prototype,"signature",void 0);const bx="crypto.algorithm",Ax="crypto.algorithmProvider";var Ix;pk.registerSingleton(Ax,class{getAlgorithms(){return pk.resolveAll(bx)}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 oS({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 vx="1.3.36.3.3.2.8.1.1",wx=`${vx}.1`,Sx=`${vx}.2`,Ex=`${vx}.3`,Cx=`${vx}.4`,kx=`${vx}.5`,xx=`${vx}.6`,Bx=`${vx}.7`,_x=`${vx}.8`,Rx=`${vx}.9`,Ox=`${vx}.10`,Ux=`${vx}.11`,Tx=`${vx}.12`,Nx=`${vx}.13`,Dx=`${vx}.14`,Mx="brainpoolP160r1",Px="brainpoolP160t1",Lx="brainpoolP192r1",Hx="brainpoolP192t1",Kx="brainpoolP224r1",Vx="brainpoolP224t1",Qx="brainpoolP256r1",Fx="brainpoolP256t1",Gx="brainpoolP320r1",$x="brainpoolP320t1",jx="brainpoolP384r1",qx="brainpoolP384t1",zx="brainpoolP512r1",Wx="brainpoolP512t1",Jx="ECDSA";let Yx=Ix=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===Jx.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return sC;case"sha-256":return iC;case"sha-384":return nC;case"sha-512":return oC}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=ZE;break;case"K-256":t=Ix.SECP256K1;break;case"P-384":t=eC;break;case"P-521":t=tC;break;case Mx:t=wx;break;case Px:t=Sx;break;case Lx:t=Ex;break;case Hx:t=Cx;break;case Kx:t=kx;break;case Vx:t=xx;break;case Qx:t=Bx;break;case Fx:t=_x;break;case Gx:t=Rx;break;case $x:t=Ox;break;case jx:t=Ux;break;case qx:t=Tx;break;case zx:t=Nx;break;case Wx:t=Dx}if(t)return new oS({algorithm:qE,parameters:sb.serialize(new uC({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case zE:return{name:Jx,hash:{name:"SHA-1"}};case JE:return{name:Jx,hash:{name:"SHA-256"}};case YE:return{name:Jx,hash:{name:"SHA-384"}};case XE:return{name:Jx,hash:{name:"SHA-512"}};case qE:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(sb.parse(e.parameters,uC).namedCurve){case ZE:return{name:Jx,namedCurve:"P-256"};case Ix.SECP256K1:return{name:Jx,namedCurve:"K-256"};case eC:return{name:Jx,namedCurve:"P-384"};case tC:return{name:Jx,namedCurve:"P-521"};case wx:return{name:Jx,namedCurve:Mx};case Sx:return{name:Jx,namedCurve:Px};case Ex:return{name:Jx,namedCurve:Lx};case Cx:return{name:Jx,namedCurve:Hx};case kx:return{name:Jx,namedCurve:Kx};case xx:return{name:Jx,namedCurve:Vx};case Bx:return{name:Jx,namedCurve:Qx};case _x:return{name:Jx,namedCurve:Fx};case Rx:return{name:Jx,namedCurve:Gx};case Ox:return{name:Jx,namedCurve:$x};case Ux:return{name:Jx,namedCurve:jx};case Tx:return{name:Jx,namedCurve:qx};case Nx:return{name:Jx,namedCurve:zx};case Dx:return{name:Jx,namedCurve:Wx}}}return null}};Yx.SECP256K1="1.3.132.0.10",Yx=Ix=ib([yk()],Yx),pk.registerSingleton(bx,Yx);const Xx=Symbol("name"),Zx=Symbol("value");class eB{constructor(e,t={},r=""){this[Xx]=e,this[Zx]=r;for(const e in t)this[e]=t[e]}}eB.NAME=Xx,eB.VALUE=Zx;class tB{static toString(e){return this.items[e]||e}}tB.items={[BC]:"sha1",[_C]:"sha224",[RC]:"sha256",[OC]:"sha384",[UC]:"sha512",[pC]:"rsaEncryption",[vC]:"sha1WithRSAEncryption",[wC]:"sha224WithRSAEncryption",[SC]:"sha256WithRSAEncryption",[EC]:"sha384WithRSAEncryption",[CC]:"sha512WithRSAEncryption",[qE]:"ecPublicKey",[zE]:"ecdsaWithSHA1",[WE]:"ecdsaWithSHA224",[JE]:"ecdsaWithSHA256",[YE]:"ecdsaWithSHA384",[XE]:"ecdsaWithSHA512",[Cw]:"TLS WWW server authentication",[kw]:"TLS WWW client authentication",[xw]:"Code Signing",[Bw]:"E-mail Protection",[_w]:"Time Stamping",[Rw]:"OCSP Signing",[FE]:"Signed Data"};class rB{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[eB.VALUE];n&&(i=` ${n}`),r.push(`${s}${e[eB.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[eB.NAME]=i,r.push(...this.serializeObj(e,t));else if(n instanceof eB)n[eB.NAME]=i,r.push(...this.serializeObj(n,t));else if(Lf.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[eB.NAME]=i,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),s=Lf.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)}}rB.oidSerializer=tB,rB.algorithmSerializer=class{static toTextObject(e){const t=new eB("Algorithm Identifier",{},tB.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case qE:{const r=(new Yx).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class sB{constructor(...e){if(1===e.length){const t=e[0];this.rawData=sb.serialize(t),this.onInit(t)}else{const t=sb.parse(e[0],e[1]);this.rawData=Lf.toArrayBuffer(e[0]),this.onInit(t)}}equal(e){return e instanceof sB&&qf(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return sb.toString(this.rawData);case"text":return rB.serialize(this.toTextObject());case"hex":return $f.ToHex(this.rawData);case"base64":return $f.ToBase64(this.rawData);case"base64url":return $f.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 eB(this.getTextName(),{},e)}}sB.NAME="ASN";class iB extends sB{constructor(...e){let t;t=Lf.isBufferSource(e[0])?Lf.toArrayBuffer(e[0]):sb.serialize(new uS({extnID:e[0],critical:e[1],extnValue:new Im(Lf.toArrayBuffer(e[2]))})),super(t,uS)}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[eB.NAME]===iB.NAME&&(e[eB.NAME]=tB.toString(this.type)),e}}var nB;class oB{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[nB]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(oB.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(oB.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=oB.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(oB.DEFAULT,e);return this}}nB=Symbol.toStringTag,oB.DEFAULT="default";const aB=new oB,cB=/^[0-2](?:\.[1-9][0-9]*)+$/;class lB{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(cB).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const hB=new lB;function uB(e,t){return`\\${$f.ToHex($f.FromUtf8String(t)).toUpperCase()}`}hB.register("CN","2.5.4.3"),hB.register("L","2.5.4.7"),hB.register("ST","2.5.4.8"),hB.register("O","2.5.4.10"),hB.register("OU","2.5.4.11"),hB.register("C","2.5.4.6"),hB.register("DC","0.9.2342.19200300.100.1.25"),hB.register("E","1.2.840.113549.1.9.1"),hB.register("G","2.5.4.42"),hB.register("I","2.5.4.43"),hB.register("SN","2.5.4.4"),hB.register("T","2.5.4.12");class dB{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 lB,this.asn=new xv;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 xv?this.asn=e:Lf.isBufferSource(e)?this.asn=sb.parse(e,xv):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||hB.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)||hB.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${$f.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,uB)}`).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?`#${$f.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(s)}return t}fromString(e){const t=new xv,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 Cv([a])),i=o}return t}fromJSON(e){const t=new xv;for(const r of e){const e=new Cv;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 Ev({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=$f.FromHex(t.slice(1));else{const s=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=s:dB.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 sb.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]||aB.get()):r=e[0]||aB.get(),await r.subtle.digest(s,this.toArrayBuffer())}}const gB="Cannot initialize GeneralName from ASN.1 data.",fB=`${gB} Unsupported string format in use.`,pB=`${gB} Value doesn't match to GUID regular expression.`,yB=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,mB="1.3.6.1.4.1.311.25.1",bB="1.3.6.1.4.1.311.20.2.3",AB="dns",IB="dn",vB="email",wB="ip",SB="url",EB="guid",CB="upn",kB="id";class xB extends sB{constructor(...e){let t;if(2===e.length)switch(e[0]){case IB:{const r=new dB(e[1]).toArrayBuffer(),s=sb.parse(r,xv);t=new Ov({directoryName:s});break}case AB:t=new Ov({dNSName:e[1]});break;case vB:t=new Ov({rfc822Name:e[1]});break;case EB:{const r=new RegExp(yB,"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?$f.ToHex(new Uint8Array($f.FromHex(e)).reverse()):e).join("");t=new Ov({otherName:new _v({typeId:mB,value:sb.serialize(new Im($f.FromHex(s)))})});break}case wB:t=new Ov({iPAddress:e[1]});break;case kB:t=new Ov({registeredID:e[1]});break;case CB:t=new Ov({otherName:new _v({typeId:bB,value:sb.serialize(Om.toASN(e[1]))})});break;case SB:t=new Ov({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=Lf.isBufferSource(e[0])?sb.parse(e[0],Ov):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=AB,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=vB,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=wB,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=SB,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=kB,this.value=e.registeredID;else if(null!=e.directoryName)this.type=IB,this.value=new dB(e.directoryName).toString();else{if(null==e.otherName)throw new Error(fB);if(e.otherName.typeId===mB){this.type=EB;const t=sb.parse(e.otherName.value,Im),r=new RegExp(yB,"i").exec($f.ToHex(t));if(!r)throw new Error(pB);this.value=r.slice(1).map((e,t)=>t<3?$f.ToHex(new Uint8Array($f.FromHex(e)).reverse()):e).join("-")}else{if(e.otherName.typeId!==bB)throw new Error(fB);this.type=CB,this.value=sb.parse(e.otherName.value,wv).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case IB:case AB:case EB:case wB:case kB:case CB:case SB:e=this.type.toUpperCase();break;case vB:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===kB&&(t=tB.toString(t)),new eB(e,void 0,t)}}class BB extends sB{constructor(e){let t;if(e instanceof Jv)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof Ov)r.push(t);else{const e=sb.parse(new xB(t.type,t.value).rawData,Ov);r.push(e)}t=new Jv(r)}else{if(!Lf.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=sb.parse(e,Jv)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new xB(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[eB.NAME]];Array.isArray(s)||(s=[],e[r[eB.NAME]]=s),s.push(r)}return e}}BB.NAME="GeneralNames";const _B="-{5}",RB="\\n",OB="\\n",UB=`${_B}BEGIN ([^${RB}]+(?=${_B}))${_B}${OB}(?:((?:[^:${RB}]+: (?:[^${RB}]+${OB}(?: +[^${RB}]+${OB})*))+))?${OB}?((?:[a-zA-Z0-9=+/]+${OB})+)${_B}END \\1${_B}`;class TB{static isPem(e){return"string"==typeof e&&new RegExp(UB,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(UB,"g"),r=[];let s=null;for(;s=t.exec(e);){const e=s[3].replace(new RegExp(`[${RB}]+`,"g"),""),t={type:s[1],headers:[],rawData:$f.FromBase64(e)},i=s[2];if(i){const e=i.split(new RegExp(OB,"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(!Lf.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:Lf.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:Lf.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=$f.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")}}TB.CertificateTag="CERTIFICATE",TB.CrlTag="CRL",TB.CertificateRequestTag="CERTIFICATE REQUEST",TB.PublicKeyTag="PUBLIC KEY",TB.PrivateKeyTag="PRIVATE KEY";class NB extends sB{static isAsnEncoded(e){return Lf.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(TB.isPem(e))return TB.decode(e)[0];if($f.isHex(e))return $f.FromHex(e);if($f.isBase64(e))return $f.FromBase64(e);if($f.isBase64Url(e))return $f.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=$f.ToBinary(e);return TB.isPem(t)?TB.decode(t)[0]:$f.isHex(t)?$f.FromHex(t):$f.isBase64(t)?$f.FromBase64(t):$f.isBase64Url(t)?$f.FromBase64Url(t):Lf.toArrayBuffer(e)}}constructor(...e){NB.isAsnEncoded(e[0])?super(NB.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?TB.encode(this.rawData,this.tag):super.toString(e)}}class DB extends NB{static async create(e,t=aB.get()){if(e instanceof DB)return e;if(oB.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new DB(r)}if(e.publicKey)return e.publicKey;if(Lf.isBufferSource(e))return new DB(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){NB.isAsnEncoded(e)?super(e,aS):super(e),this.tag=TB.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]||aB.get()):t=e[0]||aB.get();let i=this.rawData;const n=sb.parse(this.rawData,aS);return n.algorithm.algorithm===bC&&(i=function(e){return e.algorithm=new oS({algorithm:pC,parameters:null}),sb.serialize(e)}(n)),t.subtle.importKey("spki",i,s,!0,r)}onInit(e){const t=pk.resolve(Ax),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case pC:{const t=sb.parse(e.subjectPublicKey,$C),s=Lf.toUint8Array(t.modulus);r.publicExponent=Lf.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]||aB.get()):r=e[0]||aB.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=aB.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=aB.get();const s=sb.parse(this.rawData,aS);return await t.subtle.digest(r,s.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=sb.parse(this.rawData,aS);return e.Algorithm=rB.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===qE?e["EC Point"]=t.subjectPublicKey:e["Raw Data"]=t.subjectPublicKey,e}}class MB extends iB{static async create(e,t=!1,r=aB.get()){if("name"in e&&"serialNumber"in e)return new MB(e,t);const s=await DB.create(e,r),i=await s.getKeyIdentifier(r);return new MB($f.ToHex(i),t)}constructor(...e){if(Lf.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new jv({keyIdentifier:new $v($f.FromHex(e[0]))});super(Gv,e[1],sb.serialize(t))}else{const t=e[0],r=t.name instanceof BB?sb.parse(t.name.rawData,Jv):t.name,s=new jv({authorityCertIssuer:r,authorityCertSerialNumber:$f.FromHex(t.serialNumber)});super(Gv,e[1],sb.serialize(s))}}onInit(e){super.onInit(e);const t=sb.parse(e.extnValue,jv);t.keyIdentifier&&(this.keyId=$f.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?$f.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=sb.parse(this.value,jv);return t.authorityCertIssuer&&(e["Authority Issuer"]=new BB(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}MB.NAME="Authority Key Identifier";class PB extends iB{constructor(...e){if(Lf.isBufferSource(e[0])){super(e[0]);const t=sb.parse(this.value,zv);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new zv({cA:e[0],pathLenConstraint:e[1]});super(qv,e[2],sb.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 LB,HB;PB.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"}(LB||(LB={}));class KB extends iB{constructor(...e){if(Lf.isBufferSource(e[0])){super(e[0]);const t=sb.parse(this.value,Ew);this.usages=t.map(e=>e)}else{const t=new Ew(e[0]);super(Sw,e[1],sb.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(e=>tB.toString(e)).join(", "),e}}KB.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"}(HB||(HB={}));class VB extends iB{constructor(...e){if(Lf.isBufferSource(e[0])){super(e[0]);const t=sb.parse(this.value,Lw);this.usages=t.toNumber()}else{const t=new Lw(e[0]);super(Dw,e[1],sb.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=sb.parse(this.value,Lw);return e[""]=t.toJSON().join(", "),e}}VB.NAME="Key Usages";class QB extends iB{static async create(e,t=!1,r=aB.get()){const s=await DB.create(e,r),i=await s.getKeyIdentifier(r);return new QB($f.ToHex(i),t)}constructor(...e){if(Lf.isBufferSource(e[0])){super(e[0]);const t=sb.parse(this.value,Zw);this.keyId=$f.ToHex(t)}else{const t="string"==typeof e[0]?$f.FromHex(e[0]):e[0],r=new Zw(t);super(Xw,e[1],sb.serialize(r)),this.keyId=$f.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=sb.parse(this.value,Zw);return e[""]=t,e}}QB.NAME="Subject Key Identifier";class FB extends iB{constructor(...e){Lf.isBufferSource(e[0])?super(e[0]):super(qw,e[1],new BB(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=sb.parse(e.extnValue,zw);this.names=new BB(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}FB.NAME="Subject Alternative Name";class GB{static register(e,t){this.items.set(e,t)}static create(e){const t=new iB(e),r=this.items.get(t.type);return r?new r(e):t}}GB.items=new Map;class $B extends iB{constructor(...e){var t;if(Lf.isBufferSource(e[0])){super(e[0]);const t=sb.parse(this.value,aw);this.policies=t.map(e=>e.policyIdentifier)}else{const r=e[0],s=null!==(t=e[1])&&void 0!==t&&t,i=new aw(r.map(e=>new ow({policyIdentifier:e})));super(ew,s,sb.serialize(i)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new eB("",{},tB.toString(e))),e}}$B.NAME="Certificate Policies",GB.register(ew,$B);class jB extends iB{constructor(...e){var t;if(Lf.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map(e=>new pw({distributionPoint:new fw({fullName:[new Ov({uniformResourceIdentifier:e})]})})),r=new yw(t);super(uw,e[1],sb.serialize(r))}else{const t=new yw(e[0]);super(uw,e[1],sb.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=sb.parse(e.extnValue,yw);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 xB(e).toString()).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map(e=>e.toString()).join(", ")),r}),e}}jB.NAME="CRL Distribution Points";class qB extends iB{constructor(...e){var t,r,s,i;if(Lf.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Fv){const t=new Fv(e[0]);super(Vv,e[1],sb.serialize(t))}else{const t=e[0],r=new Fv;WB(r,t,Dv,"ocsp"),WB(r,t,Mv,"caIssuers"),WB(r,t,Pv,"timeStamping"),WB(r,t,Lv,"caRepository"),super(Vv,e[1],sb.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=[],sb.parse(e.extnValue,Fv).forEach(e=>{switch(e.accessMethod){case Dv:this.ocsp.push(new xB(e.accessLocation));break;case Mv:this.caIssuers.push(new xB(e.accessLocation));break;case Pv:this.timeStamping.push(new xB(e.accessLocation));break;case Lv:this.caRepository.push(new xB(e.accessLocation))}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&zB(e,"OCSP",this.ocsp),this.caIssuers.length&&zB(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&zB(e,"Time Stamping",this.timeStamping),this.caRepository.length&&zB(e,"CA Repository",this.caRepository),e}}function zB(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const s=new eB("");r.forEach((e,t)=>{const r=e.toTextObject(),i=`${r[eB.NAME]} ${t+1}`;let n=s[i];Array.isArray(n)||(n=[],s[i]=n),n.push(r)}),e[t]=s}}function WB(e,t,r,s){const i=t[s];i&&(Array.isArray(i)?i:[i]).forEach(t=>{"string"==typeof t&&(t=new xB("url",t)),e.push(new Qv({accessMethod:r,accessLocation:sb.parse(t.rawData,Ov)}))})}qB.NAME="Authority Info Access";class JB extends sB{constructor(...e){let t;if(Lf.isBufferSource(e[0]))t=Lf.toArrayBuffer(e[0]);else{const r=e[0],s=Array.isArray(e[1])?e[1].map(e=>Lf.toArrayBuffer(e)):[];t=sb.serialize(new Ww({type:r,values:s}))}super(t,Ww)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new eB("",{"":e})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[eB.NAME]===JB.NAME&&(e[eB.NAME]=tB.toString(this.type)),e}}JB.NAME="Attribute";class YB extends JB{constructor(...e){var t;if(Lf.isBufferSource(e[0]))super(e[0]);else{const t=new cx({printableString:e[0]});super(Fk,[sb.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=sb.parse(this.values[0],cx);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[eB.VALUE]=this.password,e}}YB.NAME="Challenge Password";class XB extends JB{constructor(...e){var t;if(Lf.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new dS;for(const e of t)r.push(sb.parse(e.rawData,uS));super(Gk,[sb.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=sb.parse(this.values[0],dS);this.items=e.map(e=>GB.create(sb.serialize(e)))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(const r of t)e[r[eB.NAME]]=r;return e}}XB.NAME="Extensions";class ZB{static register(e,t){this.items.set(e,t)}static create(e){const t=new JB(e),r=this.items.get(t.type);return r?new r(e):t}}ZB.items=new Map;const e_="crypto.signatureFormatter";var t_;let r_=t_=class{static createPssParams(e,t){const r=t_.getHashAlgorithm(e);return r?new HC({hashAlgorithm:r,maskGenAlgorithm:new oS({algorithm:TC,parameters:sb.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=pk.resolve(Ax);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 oS({algorithm:pC,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 oS({algorithm:vC,parameters:null});case"sha-256":return new oS({algorithm:SC,parameters:null});case"sha-384":return new oS({algorithm:EC,parameters:null});case"sha-512":return new oS({algorithm:CC,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=t_.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new oS({algorithm:bC,parameters:sb.serialize(t)})}return new oS({algorithm:bC,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case pC:return{name:"RSASSA-PKCS1-v1_5"};case vC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case SC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case EC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case CC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case bC:if(e.parameters){const t=sb.parse(e.parameters,HC);return{name:"RSA-PSS",hash:pk.resolve(Ax).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};r_=t_=ib([yk()],r_),pk.registerSingleton(bx,r_);let s_=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new oS({algorithm:BC});case"sha-256":return new oS({algorithm:RC});case"sha-384":return new oS({algorithm:OC});case"sha-512":return new oS({algorithm:UC})}return null}toWebAlgorithm(e){switch(e.algorithm){case BC:return{name:"SHA-1"};case RC:return{name:"SHA-256"};case OC:return{name:"SHA-384"};case UC:return{name:"SHA-512"}}return null}};s_=ib([yk()],s_),pk.registerSingleton(bx,s_);class i_{addPadding(e,t){const r=Lf.toUint8Array(t),s=new Uint8Array(e);return s.set(r,e-r.length),s}removePadding(e,t=!1){let r=Lf.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=i_.namedCurveSize.get(r)||i_.defaultNamedCurveSize,i=new gC,n=Lf.toUint8Array(t);return i.r=this.removePadding(n.slice(0,s),!0),i.s=this.removePadding(n.slice(s,s+s),!0),sb.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=sb.parse(t,gC),s=e.namedCurve,i=i_.namedCurveSize.get(s)||i_.defaultNamedCurveSize;return jf(this.addPadding(i,this.removePadding(r.r)),this.addPadding(i,this.removePadding(r.s)))}return null}}i_.namedCurveSize=new Map,i_.defaultNamedCurveSize=32;const n_="1.3.101.110",o_="1.3.101.111",a_="1.3.101.112",c_="1.3.101.113";let l_=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=a_;break;case"x25519":t=n_;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=a_;break;case"ed448":t=c_}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=n_;break;case"x448":t=o_}}return t?new oS({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case a_:return{name:"Ed25519"};case c_:return{name:"EdDSA",namedCurve:"Ed448"};case n_:return{name:"X25519"};case o_:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};l_=ib([yk()],l_),pk.registerSingleton(bx,l_);(class extends NB{constructor(e){NB.isAsnEncoded(e)?super(e,mx):super(e),this.tag=TB.CertificateRequestTag}onInit(e){this.tbs=sb.serialize(e.certificationRequestInfo),this.publicKey=new DB(e.certificationRequestInfo.subjectPKInfo);const t=pk.resolve(Ax);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>ZB.create(sb.serialize(e)));const r=this.getAttribute(Gk);this.extensions=[],r instanceof XB&&(this.extensions=r.items),this.subjectName=new dB(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=aB.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),s=pk.resolveAll(e_).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=sb.parse(this.rawData,mx),r=t.certificationRequestInfo,s=new eB("",{Version:`${gS[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new eB("");for(const t of this.attributes){const r=t.toTextObject();e[r[eB.NAME]]=r}s.Attributes=e}return e.Data=s,e.Signature=new eB("",{Algorithm:rB.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";var h_;(class extends NB{constructor(e){NB.isAsnEncoded(e)?super(e,pS):super(e),this.tag=TB.CertificateTag}onInit(e){const t=e.tbsCertificate;this.tbs=sb.serialize(t),this.serialNumber=$f.ToHex(t.serialNumber),this.subjectName=new dB(t.subject),this.subject=new dB(t.subject).toString(),this.issuerName=new dB(t.issuer),this.issuer=this.issuerName.toString();const r=pk.resolve(Ax);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=>GB.create(sb.serialize(e)))),this.publicKey=new DB(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=aB.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 DB)r={...i.algorithm,...this.signatureAlgorithm},s=await i.export(r,["verify"],t);else if(Lf.isBufferSource(i)){const e=new DB(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=pk.resolveAll(e_).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=aB.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=aB.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=sb.parse(this.rawData,pS),r=t.tbsCertificate,s=new eB("",{Version:`${gS[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":rB.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new eB("",{"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 eB("");for(const t of this.extensions){const r=t.toTextObject();e[r[eB.NAME]]=r}s.Extensions=e}return e.Data=s,e.Signature=new eB("",{Algorithm:rB.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"}(h_||(h_={})),GB.register(qv,PB),GB.register(Sw,KB),GB.register(Dw,VB),GB.register(Xw,QB),GB.register(Gv,MB),GB.register(qw,FB),GB.register(uw,jB),GB.register(Vv,qB),ZB.register(Fk,YB),ZB.register(Gk,XB),pk.registerSingleton(e_,class{toAsnSignature(e,t){return Lf.toArrayBuffer(t)}toWebSignature(e,t){return Lf.toArrayBuffer(t)}}),pk.registerSingleton(e_,i_),i_.namedCurveSize.set("P-256",32),i_.namedCurveSize.set("K-256",32),i_.namedCurveSize.set("P-384",48),i_.namedCurveSize.set("P-521",66),Js.new(void 0,"networking");const u_=new class extends $A{constructor(){super(...arguments),this.subtle=new mv}getRandomValues(e){if(!ArrayBuffer.isView(e))throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'");const t=JA.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return XA().randomFillSync(t),e}};var d_,g_,f_;function p_(e){return Z(e)}aB.set(u_),(f_=d_||(d_={}))[f_.NoCertificate=0]="NoCertificate",f_[f_.NotEd25519=1]="NotEd25519",f_[f_.PublicKeyTypeMismatch=2]="PublicKeyTypeMismatch",f_[f_.AltNameMismatch=3]="AltNameMismatch",f_[f_.IncorrectSignature=4]="IncorrectSignature",function(e){e[e.Public=0]="Public",e[e.Private=1]="Private"}(g_||(g_={})),Js.new(void 0,"net:peers"),Js.new(void 0,"net"),Js.new(void 0,"net"),Js.new(void 0,"net"),Js.new(void 0,"jamnps");const y_=p_(0);class m_ extends k{hash;slot;static Codec=ke.Class(m_,{hash:ke.bytes(Ne).asOpaque(),slot:ke.u32.asOpaque()});static create({hash:e,slot:t}){return new m_(e,t)}constructor(e,t){super(),this.hash=e,this.slot=t}}class b_{final;leafs;static Codec=ke.Class(b_,{final:m_.Codec,leafs:ke.sequenceVarLen(m_.Codec)});static create({final:e,leafs:t}){return new b_(e,t)}constructor(e,t){this.final=e,this.leafs=t}}class A_ extends k{header;final;static Codec=ke.Class(A_,{header:Xr.Codec,final:m_.Codec});static create({header:e,final:t}){return new A_(e,t)}constructor(e,t){super(),this.header=e,this.final=t}}const I_=Js.new(void 0,"protocol/up-0");class v_{getHandshake;onAnnouncement;kind=y_;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=ue.decodeObject(b_.Codec,t);return this.handshakes.set(r,s),void(this.pendingHandshakes.delete(r)||(I_.log(`[${r}] <-- responding with a handshake.`),e.bufferAndSend(me.encodeObject(b_.Codec,this.getHandshake()))))}const s=ue.decodeObject(A_.Codec,t);I_.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(me.encodeObject(b_.Codec,t))}sendAnnouncement(e,t){this.handshakes.has(e.streamId)?e.bufferAndSend(me.encodeObject(A_.Codec,t)):I_.warn(`[${e.streamId}] no handshake yet, skipping announcement.`)}}var w_;p_(128),function(e){e[e.AscExcl=0]="AscExcl",e[e.DescIncl=1]="DescIncl"}(w_||(w_={}));class S_ extends k{headerHash;direction;maxBlocks;static Codec=ke.Class(S_,{headerHash:ke.bytes(Ne).asOpaque(),direction:ke.u8.convert(e=>Z(e),e=>{switch(e){case w_.AscExcl:return w_.AscExcl;case w_.DescIncl:return w_.DescIncl;default:throw new Error(`Invalid 'Direction' value: ${e}`)}}),maxBlocks:ke.u32});static create({headerHash:e,direction:t,maxBlocks:r}){return new S_(e,t,r)}constructor(e,t,r){super(),this.headerHash=e,this.direction=t,this.maxBlocks=r}}Js.new(void 0,"protocol/ce-128");const E_=p_(129),C_=ke.bytes(64).convert(e=>M.fromBlob(e.raw,64),e=>new tn(e.raw));class k_ extends k{key;value;static Codec=ke.Class(k_,{key:ke.bytes(Zi),value:ke.blob});static create({key:e,value:t}){return new k_(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}class x_ extends k{keyValuePairs;static Codec=ke.Class(x_,{keyValuePairs:ke.sequenceVarLen(k_.Codec)});static create({keyValuePairs:e}){return new x_(e)}constructor(e){super(),this.keyValuePairs=e}}class B_ extends k{headerHash;startKey;endKey;maximumSize;static Codec=ke.Class(B_,{headerHash:ke.bytes(Ne).asOpaque(),startKey:ke.bytes(Zi),endKey:ke.bytes(Zi),maximumSize:ke.u32});static create({headerHash:e,startKey:t,endKey:r,maximumSize:s}){return new B_(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.startKey=t,this.endKey=r,this.maximumSize=s}}const __=Js.new(void 0,"protocol/ce-129");class R_{isServer;getBoundaryNodes;getKeyValuePairs;kind=E_;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(__.info(`[${e.streamId}][server]: Received request.`),void 0===this.getBoundaryNodes||void 0===this.getKeyValuePairs)return;const r=ue.decodeObject(B_.Codec,t),s=this.getBoundaryNodes(r.headerHash,r.startKey,r.endKey),i=this.getKeyValuePairs(r.headerHash,r.startKey,r.endKey);return __.info(`[${e.streamId}][server]: <-- responding with boundary nodes and key value pairs.`),e.bufferAndSend(me.encodeObject(ke.sequenceVarLen(C_),s)),e.bufferAndSend(me.encodeObject(x_.Codec,x_.create({keyValuePairs:i}))),void e.close()}if(!this.boundaryNodes.has(e.streamId))return this.boundaryNodes.set(e.streamId,ue.decodeObject(ke.sequenceVarLen(C_),t)),void __.info(`[${e.streamId}][client]: Received boundary nodes.`);this.onResponse.get(e.streamId)?.(ue.decodeObject(x_.Codec,t)),__.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(me.encodeObject(B_.Codec,B_.create({headerHash:t,startKey:r,endKey:r,maximumSize:se(4096)}))),e.close()}}p_(131),p_(132);class O_ extends k{epochIndex;ticket;static Codec=ke.Class(O_,{epochIndex:ke.u32.asOpaque(),ticket:xt.Codec});static create({epochIndex:e,ticket:t}){return new O_(e,t)}constructor(e,t){super(),this.epochIndex=e,this.ticket=t}}Js.new(void 0,"protocol/ce-131-ce-132"),p_(133);class U_ extends k{coreIndex;workPackage;static Codec=ke.Class(U_,{coreIndex:ke.u16.asOpaque(),workPackage:Mr.Codec});static create({coreIndex:e,workPackage:t}){return new U_(e,t)}constructor(e,t){super(),this.coreIndex=e,this.workPackage=t}}Js.new(void 0,"protocol/ce-133"),ke.blob,p_(134);class T_ extends k{coreIndex;segmentsRootMappings;static Codec=ke.Class(T_,{coreIndex:ke.u16.asOpaque(),segmentsRootMappings:ke.sequenceVarLen(Fr.Codec)});static create({coreIndex:e,segmentsRootMappings:t}){return new T_(e,t)}constructor(e,t){super(),this.coreIndex=e,this.segmentsRootMappings=t}}class N_ extends k{workReportHash;signature;static Codec=ke.Class(N_,{workReportHash:ke.bytes(Ne).asOpaque(),signature:ke.bytes(lr).asOpaque()});static create({workReportHash:e,signature:t}){return new N_(e,t)}constructor(e,t){super(),this.workReportHash=e,this.signature=t}}Js.new(void 0,"protocol/ce-134"),p_(135);class D_ extends k{report;slot;signatures;static Codec=ke.Class(D_,{report:Gr.Codec,slot:ke.u32.asOpaque(),signatures:St(e=>Et(jr.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2}))});static create({report:e,slot:t,signatures:r}){return new D_(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.signatures=r}}Js.new(void 0,"protocol/ce-135");const M_=t(import.meta.url)("node:net"),P_=t(import.meta.url)("node:path"),L_=t(import.meta.url)("node:buffer");var H_;!function(e){e[e.Msg=0]="Msg",e[e.Open=1]="Open",e[e.Close=2]="Close"}(H_||(H_={}));class K_{streamId;type;data;static Codec=ke.Class(K_,{streamId:ke.u32,type:ke.u8.convert(e=>Z(e),e=>{switch(e){case H_.Msg:return H_.Msg;case H_.Open:return H_.Open;case H_.Close:return H_.Close;default:throw new Error(`Invalid 'StreamEnvelopeType' value: ${e}`)}}),data:ke.blob});static create({streamId:e,type:t,data:r}){return new K_(e,t,r)}constructor(e,t,r){this.streamId=e,this.type=t,this.data=r}}class V_{streamByte;static Codec=ke.Class(V_,{streamByte:ke.u8});static create({streamByte:e}){return new V_(e)}constructor(e){this.streamByte=e}}const Q_=Js.new(void 0,"ext-ipc");class F_{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 $_(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 G_(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 G_(i,this.sender);n.open(V_.create({streamByte:e})),t(r,n)}onSocketMessage(e){const t=ue.decodeObject(K_.Codec,e),r=t.streamId;Q_.log(`[${r}] incoming message: ${t.type} ${t.data}`);const s=this.streams.get(r),i=new G_(r,this.sender);if(void 0===s){if(t.type!==H_.Open)return void Q_.warn(`[${r}] (unknown) got invalid type ${t.type}.`);const e=ue.decodeObject(V_.Codec,t.data),s=this.streamHandlers.get(e.streamByte);return void 0!==s?(Q_.log(`[${r}] new stream for ${s.kind}`),this.streams.set(r,s),void i.open(e)):void i.close()}if(t.type===H_.Close){const e=this.streams.get(r);return e?.onClose(r,!1),void this.streams.delete(r)}t.type===H_.Msg?s.onStreamMessage(i,t.data):this.pendingStreams.delete(r)||Q_.warn(`[${r}] got invalid type ${t.type}.`)}onClose({error:e}){Q_.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 Q_.log("Waiting for the handler to be closed."),this.onEnd.listen}}class G_{streamId;sender;constructor(e,t){this.streamId=e,this.sender=t}open(e){const t=me.encodeObject(V_.Codec,e);this.sender.send(me.encodeObject(K_.Codec,K_.create({streamId:this.streamId,type:H_.Open,data:t})))}bufferAndSend(e){return this.sender.send(me.encodeObject(K_.Codec,K_.create({streamId:this.streamId,type:H_.Msg,data:e}))),!0}close(){this.sender.send(me.encodeObject(K_.Codec,K_.create({streamId:this.streamId,type:H_.Close,data:D.blobFromNumbers([])})))}}class $_{socket;constructor(e){this.socket=e}send(e){!function(e,t){const r=new Uint8Array(j_);me.create({destination:r}).i32(t.length),e.write(r),e.write(t)}(this.socket,e.raw)}close(){this.socket.end()}}const j_=4;function q_(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=m_.create({hash:i,slot:s.timeSlotIndex});r=n,t.emit("announcement",A_.create({header:s,final:n}))}),function(e,t,r,s){const i="win32"===Ts.platform()?"\\\\.\\pipe\\typeberry":P_.join(Ts.tmpdir(),"typeberry.ipc"),n=Js.new(void 0,"ext-ipc"),o=(0,M_.createServer)(i=>{n.log("Client connected");const o=new F_(i);o.registerHandlers(new v_(t,()=>{})),o.registerHandlers(new R_(!0,r,s));const a=e=>{if(!(e instanceof A_))throw new Error(`Invalid annoncement received: ${e}`);o.withStreamOfKind(y_,(t,r)=>{t.sendAnnouncement(r,e)})};e.on("announcement",a),i.on("data",function(e){let t=L_.Buffer.alloc(0),r=-1;return s=>{t=L_.Buffer.concat([t,s]);do{if(-1===r){if(t.length<j_)break;r=t.readUint32LE(),t=t.subarray(j_)}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{Os.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??m_.create({hash:M.zero(Ne).asOpaque(),slot:Ar(0)});return b_.create({final:e,leafs:[]})},()=>[],(e,t)=>{let r=D.blobFromNumbers([255,255,0,0]);return M.fromBlob($e("0x83bd3bde264a79a2e67c487696c1d7f0b549da89").raw.subarray(0,De),De).isEqualTo(t)&&(r=D.blobFromNumbers([255,255,255,0])),[new k_(t,r)]})}(e);return()=>{t()}}const z_=e=>e.endsWith(".json");function W_(e,t){const r=Us().readFileSync(e),s=D.blobFrom(new Uint8Array(r));return ue.decodeObject(is.Codec.View,s,t)}function J_(e,t){const r=Us().readFileSync(e,"utf-8"),s=J(JSON.parse(r),(i=t,X.object({header:Bs,extrinsic:(n=i,X.object({tickets:Ss,preimages:vs,guarantees:As,assurances:gr(n),disputes:ls},({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})=>ss.create({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})))},({header:e,extrinsic:t})=>is.create({header:e,extrinsic:t}))));var i,n;const o=me.encodeObject(is.Codec,s,t);return ue.decodeObject(is.Codec.View,o,t)}const Y_={genesisPath:"",timeSlot:Ar(0),validatorIndex:Ir(0)};class X_{isAuthoring;blocksToImport;nodeName;node;dev;static new({isAuthoring:e,blockToImport:t,nodeName:r,nodeConfig:s,devConfig:i,seedConfig:n}){let o=i??{...Y_};return void 0!==n&&(o={...o,...n}),new X_(e??!1,t??[],r,s,o)}constructor(e,t,r,s,i){this.isAuthoring=e,this.blocksToImport=t,this.nodeName=r,this.node=s,this.dev=i}}const Z_=Js.new(void 0,"jam");var eR;async function tR(e,t){if(!Ys.isMainThread)return void Z_.error("The main binary cannot be running as a Worker!");const r=iR(e.node.flavor),{rootDb:s,dbPath:i,genesisHeaderHash:n}=function(e,t,r,{readOnly:s=!1}={}){const i=$e(e).toString().substring(2,10),n=Ge(t).asOpaque(),o=`${r}/${i}/${n.toString().substring(2,10)}`;Z_.info(`🛢️ Opening database at ${o}`);try{return{dbPath:o,rootDb:new si(o,s),genesisHeaderHash:n}}catch(e){throw new Error(`Unable to open database at ${o}: ${e}`)}}(e.nodeName,e.node.chainSpec.genesisHeader,t(e.node.databaseBasePath));await async function(e,t,r,s){const i=new Zs(e,r),n=new Sn(e,r),o=i.getBestHeaderHash(),a=i.getPostStateRoot(o);if(Z_.log(`🛢️ Best header hash: ${o}`),Z_.log(`🛢️ Best state root: ${a}`),null!==a&&!a.isEqualTo(M.zero(Ne))&&!o.isEqualTo(M.zero(Ne)))return void await r.db.close();Z_.log("🛢️ Database looks fresh. Initializing.");const c=ue.decodeObject(Xr.Codec,s.genesisHeader,e),l=is.create({header:Xr.empty(),extrinsic:ss.create({tickets:[],preimages:[],assurances:[],guarantees:[],disputes:{verdicts:[],culprits:[],faults:[]}})}).extrinsic,h=is.create({header:c,extrinsic:l}),u=ue.decodeObject(is.Codec.View,me.encodeObject(is.Codec,h,e),e);Z_.log(`🧬 Writing genesis block #${c.timeSlotIndex}: ${t}`);const{genesisStateSerialized:d,genesisStateRootHash:g}=function(e,t){const r=bt.fromEntries(Array.from(t.entries())),s=gn.fromTruncatedDictionaryUnsafe(r),i=Yi.fromStateEntries(e,s),n=s.getRootHash();return Z_.info(`🧬 Genesis state root: ${n}`),{genesisState:i,genesisStateSerialized:s,genesisStateRootHash:n}}(e,s.genesisState);await i.insertBlock(new Me(t,u)),await n.insertState(t,d),await i.setPostStateRoot(t,g),await i.setBestHeaderHash(t),await r.db.close()}(r,n,s,e.node.chainSpec);const o=await async function(){const e=kh,t=new Eh;return Vn(new URL("./bootstrap.mjs","file:///home/runner/work/typeberry/typeberry/workers/importer/index.ts"),e,"ready(main)",t)}(),a=q_({bestHeader:o.getState("ready(main)").onBestBlock}),c=new wt(r,i,e.node.authorship.omitSealVerification),l=o.transition((e,t)=>e.sendConfig(t,c)),h=sR(l,r,e.blocksToImport),u=await rR(e.isAuthoring,c,l);Z_.info("[main]⌛ waiting for importer to finish");const d=await h;Z_.log("[main] ☠️ Closing the extensions"),a(),Z_.log("[main]⌛ waiting for tasks to finish"),await d.currentState().waitForWorkerToFinish(),Z_.log("[main] ☠️ Closing the authorship module"),u(),Z_.info("[main] ✅ Done.")}!function(e){e[e.InMemory=0]="InMemory",e[e.Lmdb=1]="Lmdb"}(eR||(eR={}));const rR=async(e,t,r)=>{if(!e)return()=>Promise.resolve();Z_.info("✍️ Starting block generator.");const{generator:s,finish:i}=await async function(e){const t=(await async function(){const e=Th,t=new Oh;return Vn(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=>{Z_.log(`✍️ Produced block. Size: [${r.length}]`),e.sendBlock(t,r)})}),i},sR=async(e,t,r)=>null===r?e.waitForState("finished"):(Z_.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=z_(r)?J_(r,t):W_(r,t);yield e}}({files:r,chainSpec:t});for(const t of i)Z_.log(`📖 Importing block: #${t.header.view().timeSlotIndex.materialize()}`),e.sendBlock(s,t.encoded().raw);return Z_.info("All blocks scheduled to be imported."),e.finish(s)})),iR=e=>{if(e===Hs.Full)return vt;if(e===Hs.Tiny)return It;throw new Error(`Unknown chain spec: ${e}. Possible options: ${[Hs.Full,Hs.Tiny]}`)},nR=(e=>{var t={};return o.d(t,e),t})({default:()=>s.default}),oR=`\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: ${Ls.name}]\n --config Path to a config file or '${Ps}'.\n [default: ${Ls.config}]\n`;var aR;function cR(e,t){const{name:r}=hR(e,"name",e=>e,Ls.name),{config:s}=hR(e,"config",e=>e===Ps?Ps:t(e),Ls.config);return{nodeName:r,configPath:s}}function lR(e,t){const r=(0,nR.default)(e),s=r._.shift()??aR.Run;switch(s){case aR.Run:{const e=cR(r,t);return uR(r),{command:aR.Run,args:e}}case aR.Import:{const e=cR(r,t),s=r._.map(e=>t(e));return r._=[],uR(r),{command:aR.Import,args:{...e,files:s}}}default:r._.unshift(s),uR(r)}throw new Error(`Invalid arguments: ${JSON.stringify(r)}`)}function hR(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 uR(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"}(aR||(aR={}));const dR=e=>{const t=e.command===aR.Import?e.args.files:[],r=function(e){if(e===Ps)return J(Ds,Vs.fromJson);try{const t=Us().readFileSync(e,"utf8");return J(JSON.parse(t),Vs.fromJson)}catch(t){throw new Error(`Unable to load config file from ${e}: ${t}`)}}(e.args.configPath);return X_.new({isAuthoring:!1,blockToImport:t,nodeName:e.args.nodeName,nodeConfig:r})};if("file:///home/runner/work/typeberry/typeberry/bin/jam/index.ts"===(0,c.pathToFileURL)(process.argv[1]).href){Js.configureAll(process.env.JAM_LOG??"",Qs.LOG);const e="undefined/../..",t=t=>t.startsWith("/")?t:`${e}/${t}`;let r;try{r=lR(process.argv.slice(2),t)}catch(e){console.error(`\n${e}\n`),console.info(oR),process.exit(1)}tR(dR(r),t).catch(e=>{console.error(`${e}`),process.exit(-1)})}let gR;Js.configureAll(process.env.JAM_LOG??"",Qs.LOG);try{gR=lR(process.argv.slice(2),fR)}catch(e){console.error(`\n${e}\n`),console.info(oR),process.exit(1)}function fR(e){return e}tR(dR(gR),fR).catch(e=>{console.error(`${e}`),process.exit(-1)});export{aR as Command,oR as HELP,lR as parseArgs,dR as prepareConfigFile};
|
|
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:()=>Gd,BaseBlock:()=>nl,BaseStringBlock:()=>ol,BitString:()=>nd,BmpString:()=>kd,Boolean:()=>td,CharacterString:()=>Pd,Choice:()=>jd,Constructed:()=>Jl,DATE:()=>Vd,DateTime:()=>Qd,Duration:()=>$d,EndOfContent:()=>Xl,Enumerated:()=>ud,GeneralString:()=>Md,GeneralizedTime:()=>Hd,GraphicString:()=>Nd,HexBlock:()=>Zc,IA5String:()=>Td,Integer:()=>dd,Null:()=>Zl,NumericString:()=>_d,ObjectIdentifier:()=>gd,OctetString:()=>sd,Primitive:()=>Gl,PrintableString:()=>Rd,RawData:()=>zd,RelativeObjectIdentifier:()=>md,Repeated:()=>qd,Sequence:()=>yd,Set:()=>Ad,TIME:()=>Fd,TeletexString:()=>Od,TimeOfDay:()=>Kd,UTCTime:()=>Ld,UniversalString:()=>Bd,Utf8String:()=>Ed,ValueBlock:()=>tl,VideotexString:()=>Ud,ViewWriter:()=>Nc,VisibleString:()=>Dd,compareSchema:()=>Wd,fromBER:()=>ql,verifySchema:()=>Jd});var c={};a.r(c),a.d(c,{Announcement:()=>HS,Handler:()=>KS,Handshake:()=>LS,HashAndSlot:()=>PS,STREAM_KIND:()=>MS});var l={};a.r(l),a.d(l,{Handler:()=>ZS,KeyValuePair:()=>WS,STREAM_KIND:()=>qS,StateRequest:()=>YS,StateResponse:()=>JS});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)??y,I=function(e){if(void 0===e)return;const t=e;if(!Object.values(f).includes(t))throw new Error(`Configured environment variable TEST_SUITE is unknown: '${e}'. Use one of: ${Object.values(f)}`);return t}(m.TEST_SUITE)??p;class v{static override(e){A=e??y}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)}`:"symbol"==typeof e?e.toString():`${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 z(this.raw)}toStringTruncated(){return this.raw.length>32?`${z(this.raw.subarray(0,16))}...${z(this.raw.subarray(this.raw.length-16)).substring(2)} (${this.raw.length} bytes)`:this.toString()}toJSON(){return this.toString()}asText(){return(new TextDecoder).decode(this.raw)}isEqualTo(e){return this.length===e.length&&W(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!"),W(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".charCodeAt(0),F="A".charCodeAt(0),G="F".charCodeAt(0),j=10;function q(e){if(e>=V&&e<=K)return e-V;if(e>=Q&&e<=$)return e-Q+j;if(e>=F&&e<=G)return e-F+j;throw new Error(`Invalid characters in hex byte string: ${String.fromCharCode(e)}`)}function z(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}function W(e,t){for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}const J=(e,t)=>e.compare(t);class Y{data;bitLength;static fromBlob(e,t){return new Y(e,t)}static fromBytes(e,t){return new Y(e.raw,t)}static empty(e){const t=new Uint8Array(Math.ceil(e/8));return new Y(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 X=Symbol("no key");function Z(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]=Z(t,s,`${r}.${e}`);return n}if("optional"===s)return null==e?e:Z(e,t[1],r);if("object"===s)return ee(t[1],e,r);if("string"===s)return ee(t[1],Z(e,s,r),r);if("number"===s){const s=t[0];return ee(t[1],Z(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]=Z(t,a[e],`${r}.${e}`)}else Array.isArray(a[e])&&"optional"===a[e][0]&&(i[e]=X);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]===X&&delete i[e];return i}function ee(e,t,r){try{return e(t,r)}catch(e){throw new Error(`[${r}] Error while parsing the value: ${e}`)}}var te;!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]=Z(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(Z(n,e,`${s}.key`),Z(a,t,`${s}.value`));return i})},e.object=function(e,t){return r((r,s)=>{const i=Z(r,e,s);return t(i)})}}(te||(te={}));const re=e=>S(e,se(e),`input must have one-byte representation, got ${e}`),se=e=>(255&e)===e,ie=e=>S(e,ne(e),`input must have two-byte representation, got ${e}`),ne=e=>(65535&e)===e,ae=e=>S(e,oe(e),`input must have four-byte representation, got ${e}`),oe=e=>(4294967295&e)>>>0===e,ce=e=>{const t=BigInt(e);return S(t,le(t),`input must have eight-byte representation, got ${e}`)},le=e=>(18446744073709551615n&e)===e;function de(...e){let t=0n;for(const r of e)t+=r;const r=!le(t);return t&=0xffffffffffffffffn,{overflow:r,value:ce(t)}}function ue(e){return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}function he(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 fe=(e,...t)=>t.reduce((e,t)=>t>e?e:t,e);class ge{source;offset;context;static fromBytesBlob(e,t){return new ge(e.raw,t)}static fromBlob(e){return new ge(e)}static decodeObject(e,t,r){const s=t instanceof P?ge.fromBytesBlob(t):ge.fromBlob(t);s.attachContext(r);const i=s.object(e);return s.finish(),i}static decodeSequence(e,t,r){const s=t instanceof P?ge.fromBytesBlob(t):ge.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 ge(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=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 ce(e);if(this.ensureHasBytes(t),this.offset+=t,8===t)return ce(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 ce(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 Y.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 Y.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 pe=[255,254,252,248,240,224,192,128];function be(e){w(e>=0&&e<256,`Incorrect byte value: ${e}`);for(let t=0;t<pe.length;t++)if(e>=pe[t])return 8-t;return 0}function me(e){return w(e.isExact,"The value is not exact size estimation!"),e.bytes}function ye(e,t){return{bytes:e.bytes+t.bytes,isExact:e.isExact&&t.isExact}}const Ae=10485760;class Ie{destination;buffer;static create(e){if(void 0!==e&&"destination"in e)return new Ie(e.destination);const t=e?.expectedLength??512,r=new ArrayBuffer(Math.min(Ae,t),{maxByteLength:Ae}),s=new Uint8Array(r);return new Ie(s,r)}static encodeObject(e,t,r){const s=Ie.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(ae(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(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(L.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){w(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}){w(e>=0,"Negative length given");const r=this.offset+e;if(r>Ae){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(Ae,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 ve{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 we(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 Se{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 Ee{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 ve(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 Se(()=>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 Ce{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 ve(this.decoder);for(let s=this.lastDecodedIdx+1;s<=e;s++){const e=r.decoder.clone(),i=this.descriptor;t=new Se(()=>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 ke{name;sizeHint;encode;decode;skip;View;static withView(e,t,r,s,i,n){return new ke(e,t,r,s,i,n)}static new(e,t,r,s,i){return new ke(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 ve(e));const r=e.bytesRead();return P.blobFrom(e.source.subarray(t,r))}convert(e,t){return new ke(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 xe(e){return e.convert(e=>(w(Array.isArray(e),`Non-arrays are not supported as 'readonly': got ${typeof e}, ${e}`),e),e=>e)}function Be(e){return{bytes:e,isExact:!0}}var _e,Re;function Oe(e,t){for(const r in e)if("string"==typeof r&&r in e){const s=r;try{t(s,e[s])}catch(e){throw new Error(`${r}: ${e}`)}}}function Ue(e){return e.View!==e}(Re=_e||(_e={})).bytes=(()=>{const e=new Map;return t=>{let r=e.get(t);return void 0===r&&(r=ke.new(`Bytes<${t}>`,Be(t),(e,t)=>e.bytes(t),e=>e.bytes(t),e=>e.bytes(t)),e.set(t,r)),r}})(),Re.varU32=ke.new("var_u32",{bytes:4,isExact:!1},(e,t)=>e.varU32(t),e=>e.varU32(),e=>e.varU32()),Re.varU64=ke.new("var_u64",{bytes:8,isExact:!1},(e,t)=>e.varU64(t),e=>e.varU64(),e=>e.varU64()),Re.u64=ke.withView("u64",Be(8),(e,t)=>e.i64(t),e=>e.u64(),e=>e.u64(),Re.bytes(8)),Re.u32=ke.withView("u32",Be(4),(e,t)=>e.i32(t),e=>e.u32(),e=>e.u32(),Re.bytes(4)),Re.u24=ke.withView("u24",Be(3),(e,t)=>e.i24(t),e=>e.u24(),e=>e.u24(),Re.bytes(3)),Re.u16=ke.withView("u16",Be(2),(e,t)=>e.i16(t),e=>e.u16(),e=>e.u16(),Re.bytes(2)),Re.u8=ke.new("u8",Be(1),(e,t)=>e.i8(t),e=>e.u8(),e=>e.u8()),Re.i64=ke.withView("u64",Be(8),(e,t)=>e.i64(t),e=>e.i64(),e=>e.u64(),Re.bytes(8)),Re.i32=ke.withView("i32",Be(4),(e,t)=>e.i32(t),e=>e.i32(),e=>e.u32(),Re.bytes(4)),Re.i24=ke.withView("i24",Be(3),(e,t)=>e.i24(t),e=>e.i24(),e=>e.u24(),Re.bytes(3)),Re.i16=ke.withView("i16",Be(2),(e,t)=>e.i16(t),e=>e.i16(),e=>e.u16(),Re.bytes(2)),Re.i8=ke.new("i8",Be(1),(e,t)=>e.i8(t),e=>e.i8(),e=>e.u8()),Re.bool=ke.new("bool",Be(1),(e,t)=>e.bool(t),e=>e.bool(),e=>e.bool()),Re.blob=ke.new("BytesBlob",{bytes:64,isExact:!1},(e,t)=>e.bytesBlob(t),e=>e.bytesBlob(),e=>e.bytesBlob()),Re.string=ke.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(),Re.blob),Re.bitVecVarLen=ke.new("BitVec[?]",{bytes:8,isExact:!1},(e,t)=>e.bitVecVarLen(t),e=>e.bitVecVarLen(),e=>e.bitVecVarLen()),Re.bitVecFixLen=e=>ke.new(`BitVec[${e}]`,Be(e>>>3),(e,t)=>e.bitVecFixLen(t),t=>t.bitVecFixLen(e),t=>t.bitVecFixLen(e)),Re.optional=e=>{const t=ke.new(`Optional<${e.name}>`,ye({bytes:1,isExact:!1},e.sizeHint),(t,r)=>t.optional(e,r),t=>t.optional(e),t=>t.optional(e));return Ue(e)?ke.withView(t.name,t.sizeHint,t.encode,t.decode,t.skip,Re.optional(e.View)):t},Re.sequenceVarLen=(e,t={minLength:0,maxLength:2**32-1})=>{const r=`Sequence<${e.name}>[?]`,s=t.typicalLength??64;return ke.withView(r,{bytes:s*e.sizeHint.bytes,isExact:!1},(s,i)=>{we(t,i.length,r),s.sequenceVarLen(e,i)},s=>{const i=s.varU32();return we(t,i,r),s.sequenceFixLen(e,i)},s=>{const i=s.decoder.varU32();return we(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 we(t,s,i),r.sequenceFixLen(e,s)};return ke.new(i,r,(e,r)=>{we(t,r.length,i);const s=r.encoded();e.bytes(L.fromBlob(s.raw,s.length))},t=>{const r=new Ce(t.clone(),e);return n(new ve(t)),r},n)}(e,t))},Re.sequenceFixLen=(e,t)=>ke.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 ke.new(n,r,(e,t)=>{const r=t.encoded();e.bytes(L.fromBlob(r.raw,r.length))},r=>{const i=new Ce(r.clone(),e,t);return s(new ve(r)),i},s)}(e,{fixedLength:t})),Re.dictionary=(e,t,{sortKeys:r,fixedLength:s})=>{const i=ke.new(`Dictionary<${e.name}, ${t.name}>[${s??"?"}]`,{bytes:void 0!==s?s*ye(e.sizeHint,t.sizeHint).bytes:32*(ye(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(ae(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 Ue(t)?ke.withView(i.name,i.sizeHint,i.encode,i.decode,i.skip,Re.dictionary(e,t.View,{sortKeys:r,fixedLength:s})):i},Re.pair=(e,t)=>{const r=ke.new(`Pair<${e.name}, ${t.name}>`,ye(e.sizeHint,t.sizeHint),(r,s)=>{e.encode(r,s[0]),t.encode(r,s[1])},r=>[e.decode(r),t.decode(r)],r=>{e.skip(r),t.skip(r)});return Ue(e)&&Ue(t)?ke.withView(r.name,r.sizeHint,r.encode,r.decode,r.skip,Re.pair(e.View,t.View)):r},Re.custom=({name:e,sizeHint:t={bytes:0,isExact:!1}},r,s,i)=>ke.new(e,t,r,s,i),Re.select=({name:e,sizeHint:t},r)=>ke.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),Re.object=(e,t="object",r=e=>e)=>Re.Class({name:t,create:r},e),Re.Class=(e,t)=>{let r=Be(0);Oe(t,(e,t)=>{r=ye(r,t.sizeHint)});const s=e=>{if(r.isExact)return e.decoder.skip(r.bytes);Oe(t,(t,r)=>{r.skip(e)})},i=function(e,t,r,s){class i extends Ee{constructor(r){super(r,e,t)}}return Oe(t,e=>{"string"==typeof e&&Object.defineProperty(i.prototype,e,{get:function(){return this.get(e)}})}),ke.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 ve(e)),t},s)}(e,t,r,s);return ke.withView(e.name,r,(e,r)=>{Oe(t,(t,s)=>{const i=r[t];s.encode(e,i)})},r=>{const s={};return Oe(t,(e,t)=>{const i=t.decode(r);s[e]=i}),e.create(s)},s,i)};var Te=a(239);const Ne=32,De=96,Me=144,Pe=144,Le=32,He=31;class Ve extends B{hash;data;constructor(e,t){super(),this.hash=e,this.data=t}}class Ke extends Ve{encoded;constructor(e,t,r){super(e,t),this.encoded=r}}class Qe{emptyHash(){return L.zero(Le)}}const $e=new Qe;var Fe,Ge=a(675),je=a.n(Ge);function qe(e,t=$e){const r=t.emptyHash();if(0===e.length)return r.asOpaque();const s=je()(Le);for(const t of e)s?.update(t instanceof P?t.raw:t);return s?.digest(r.raw),r.asOpaque()}function ze(e,t=$e){const r=je()(Le),s=e instanceof P?e.raw:e;r?.update(s);const i=t.emptyHash();return r?.digest(i.raw),i}function We(e,t=$e){return ze(P.blobFromString(e),t)}function Je(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 Ye{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 Je(this,void 0,void 0,function*(){const t=yield this.lock();try{return yield Promise.resolve(e())}finally{t()}})}}const Xe="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Ze=null!==(Fe=Xe.Buffer)&&void 0!==Fe?Fe:null,et=Xe.TextEncoder?new Xe.TextEncoder:null;function tt(e,t){return(15&e)+(e>>6|e>>3&8)<<4|(15&t)+(t>>6|t>>3&8)}const rt="a".charCodeAt(0)-10,st="0".charCodeAt(0);function it(e,t,r){let s=0;for(let i=0;i<r;i++){let r=t[i]>>>4;e[s++]=r>9?r+rt:r+st,r=15&t[i],e[s++]=r>9?r+rt:r+st}return String.fromCharCode.apply(null,e)}const nt=null!==Ze?e=>{if("string"==typeof e){const t=Ze.from(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.length)}if(Ze.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 et.encode(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")},at=new Uint8Array(256);for(let e=0;e<64;e++)at["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;function ot(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=at[e.charCodeAt(t)],n=at[e.charCodeAt(t+1)],a=at[e.charCodeAt(t+2)],o=at[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 ct=16384,lt=new Ye,dt=new Map;function ut(e,t){return Je(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=lt.dispatch(()=>Je(this,void 0,void 0,function*(){if(!dt.has(e.name)){const t=ot(e.data),r=WebAssembly.compile(t);dt.set(e.name,r)}const t=yield dt.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+ct);t+=i.length,s.set(i),r.exports.Hash_Update(i.length)}})(nt(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):it(l,s,t)},u=e=>"string"==typeof e?e.length<4096:e.byteLength<ct;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(()=>Je(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,ct)}))(),{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]=tt(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]!==tt(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=nt(e);return s.set(a),r.exports.Hash_Calculate(a.length,i,n),it(l,s,t)},hashLength:t}})}new Ye,new Ye,new DataView(new ArrayBuffer(4)),new Ye,new Ye,new Ye,new Ye,new Uint8Array(8),new Ye,new Ye,new Ye;var ht={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 ft(e){return[224,256,384,512].includes(e)?null:new Error("Invalid variant! Valid values: 224, 256, 384, 512")}new Ye,new Ye,new Ye,new Ye,new Ye,new Ye,new Ye,new Ye,new Uint8Array(8),new Ye,new Uint8Array(8),new Ye,new Uint8Array(8),new Ye,new Ye,new Ye;class gt{hasher;static async create(){return new gt(await function(e=512){if(ft(e))return Promise.reject(ft(e));const t=e/8;return ut(ht,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 pt(e,t){e.hasher.init();for(const r of t)e.hasher.update(r.raw);return L.fromBlob(e.hasher.digest("binary"),Le)}class bt{map=new Map;constructor(){}static new(){return new bt}static fromEntries(e){const t=new bt;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 mt{map;static viewDictionaryKeys(e){return new mt(e)}static from(e){const t=mt.new();return t.insertAll(e),t}static new(){return new mt}constructor(e=bt.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 yt(e){return e}class At 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 At(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 At.new(r,t)}toString(){return k(Array.from(this))}}class It{array;comparator;static fromArray(e,t=[]){const r=t.slice();return r.sort((t,r)=>e(t,r).value),new It(r,e)}static fromSortedArray(e,t=[]){const r=t.length;if(0===r)return new It([],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 It(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 It.fromSortedArray(r,o)}*[Symbol.iterator](){for(const e of this.array)yield e}}class vt extends It{static fromArray(e,t=[]){if(0===t.length)return new vt([],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 vt(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 vt(r,e)}static fromSortedArray(e,t=[]){if(0===t.length)return new vt([],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 vt(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 vt.fromSortedArray(r,t.array);if(0===t.length)return vt.fromSortedArray(r,e.array);const s=It.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,vt.fromSortedArray(r,s)}}class wt{dict;static fromEntries(e){const t=Array.from(e).map(([e,t])=>{const r=L.zero(Le).asOpaque();return r.raw.set(e.raw.subarray(0,He)),[r,t]});return new wt(bt.fromEntries(t))}truncatedKey=L.zero(Le).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,He)),this.dict.get(this.truncatedKey)}has(e){return this.truncatedKey.raw.set(e.raw.subarray(0,He)),this.dict.has(this.truncatedKey)}set(e,t){const r=L.zero(Le);r.raw.set(e.raw.subarray(0,He)),this.dict.set(r.asOpaque(),t)}delete(e){this.truncatedKey.raw.set(e.raw.subarray(0,He)),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,He),He).asOpaque(),t]}[Symbol.iterator](){return this.entries()}}class St 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=ie(Math.floor(e.validatorsCount/3)),this.validatorsSuperMajority=ie(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=ae(4104/e.numberECPiecesPerSegment),this.maxBlockGas=e.maxBlockGas,this.maxRefineGas=e.maxRefineGas}}const Et=new St({validatorsCount:ie(6),coresCount:ie(2),epochLength:ae(12),contestLength:ae(10),maxTicketsPerExtrinsic:re(3),rotationPeriod:ie(4),slotDuration:ie(6),ticketsPerValidator:re(3),numberECPiecesPerSegment:ae(1026),preimageExpungePeriod:ae(32),maxBlockGas:ce(2e7),maxRefineGas:ce(1e9)}),Ct=new St({validatorsCount:ie(1023),coresCount:ie(341),epochLength:ae(600),contestLength:ae(500),maxTicketsPerExtrinsic:re(16),rotationPeriod:ie(10),slotDuration:ie(6),ticketsPerValidator:re(2),numberECPiecesPerSegment:ae(6),preimageExpungePeriod:ae(19200),maxBlockGas:ce(35e8),maxRefineGas:ce(5e9)});class kt{chainSpec;dbPath;omitSealVerification;static reInit(e){const{chainSpec:t,dbPath:r,omitSealVerification:s}=e;return new kt(new St(t),r,s)}constructor(e,t,r=!1){this.chainSpec=e,this.dbPath=t,this.omitSealVerification=r}}function xt(e){const t=Ct,{name:r,sizeHint:s}=e(t),i=new Map;return _e.select({name:r,sizeHint:{bytes:s.bytes,isExact:!1}},s=>{if(s instanceof St){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 Bt=(e,t,r)=>"fixedLength"in t?xe(_e.sequenceFixLen(e,t.fixedLength)).convert(R,yt):xe(_e.sequenceVarLen(e,t)).convert(R,yt),_t=(e,t)=>{const r=r=>{if(t!==r)throw new Error(`[${e.name}] Invalid size of fixed-size array. Got ${r}, expected: ${t}`)};return _e.sequenceFixLen(e,t).convert(e=>(r(e.length),e),e=>(r(e.length),At.new(e,t)))},Rt=(e,t,{typicalLength:r=32,compare:s=(e,r)=>t(e).compare(t(r))}={})=>ke.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=bt.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 Ot extends B{attempt;signature;static Codec=_e.Class(Ot,{attempt:_e.u8.asOpaque(),signature:_e.bytes(784).asOpaque()});static create({attempt:e,signature:t}){return new Ot(e,t)}constructor(e,t){super(),this.attempt=e,this.signature=t}}class Ut extends B{id;attempt;static Codec=_e.Class(Ut,{id:_e.bytes(Le),attempt:_e.u8.asOpaque()});static create({id:e,attempt:t}){return new Ut(e,t)}constructor(e,t){super(),this.id=e,this.attempt=t}}const Tt=Bt(Ot.Codec,{minLength:0,maxLength:16,typicalLength:16});var Nt;!function(e){e.bytesN=e=>te.fromString(t=>L.parseBytes(t,e).asOpaque()),e.bytesNNoPrefix=e=>te.fromString(t=>L.parseBytesNoPrefix(t,e).asOpaque()),e.bytes32=()=>te.fromString(e=>L.parseBytes(e,32).asOpaque()),e.bytes32NoPrefix=()=>te.fromString(e=>L.parseBytesNoPrefix(e,32).asOpaque()),e.bytesBlob=te.fromString(P.parseBlob),e.bytesBlobNoPrefix=te.fromString(P.parseBlobNoPrefix),e.ed25519Signature=te.fromString(e=>L.parseBytes(e,64).asOpaque()),e.ticketAttempt=te.fromNumber(e=>{if(0!==e&&1!==e&&2!==e)throw new Error("Invalid TicketAttempt value.");return re(e)}),e.uint8Array=te.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=te.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=te.fromAny(e=>BigInt(e))}(Nt||(Nt={}));const Dt=2n**255n-19n,Mt=2n**252n+27742317777372353535851937790883648493n,Pt=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Lt=0x6666666666666666666666666666666666666666666666666666666666666658n,Ht={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Dt,n:Mt,h:8,Gx:Pt,Gy:Lt},Vt=(e="")=>{throw new Error(e)},Kt=e=>"string"==typeof e,Qt=(e,t)=>!(e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name)(e)||"number"==typeof t&&t>0&&e.length!==t?Vt("Uint8Array of valid length expected"):e,$t=e=>new Uint8Array(e),Ft=(e,t)=>Qt(Kt(e)?Zt(e):$t(Qt(e)),t),Gt=(e,t=Dt)=>{let r=e%t;return r>=0n?r:t+r},jt=e=>e instanceof qt?e:Vt("Point expected");class qt{constructor(e,t,r,s){this.ex=e,this.ey=t,this.ez=r,this.et=s}static fromAffine(e){return new qt(e.x,e.y,1n,Gt(e.x*e.y))}static fromHex(e,t=!1){const{d:r}=Ht,s=(e=Ft(e,32)).slice(),i=e[31];s[31]=-129&i;const n=tr(s);!t||0n<=n&&n<2n**256n||Vt("bad y coord 1"),t||0n<=n&&n<Dt||Vt("bad y coord 2");const a=Gt(n*n),o=Gt(a-1n),c=Gt(r*a+1n);let{isValid:l,value:d}=ar(o,c);l||Vt("bad y coordinate 3");const u=1n==(1n&d),h=!!(128&i);return!t&&0n===d&&h&&Vt("bad y coord 3"),h!==u&&(d=Gt(-d)),new qt(d,n,1n,Gt(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}=jt(e),o=Gt(t*a),c=Gt(i*s),l=Gt(r*a),d=Gt(n*s);return o===c&&l===d}is0(){return this.equals(Wt)}negate(){return new qt(Gt(-this.ex),this.ey,this.ez,Gt(-this.et))}double(){const{ex:e,ey:t,ez:r}=this,{a:s}=Ht,i=Gt(e*e),n=Gt(t*t),a=Gt(2n*Gt(r*r)),o=Gt(s*i),c=e+t,l=Gt(Gt(c*c)-i-n),d=o+n,u=d-a,h=o-n,f=Gt(l*u),g=Gt(d*h),p=Gt(l*h),b=Gt(u*d);return new qt(f,g,b,p)}add(e){const{ex:t,ey:r,ez:s,et:i}=this,{ex:n,ey:a,ez:o,et:c}=jt(e),{a:l,d}=Ht,u=Gt(t*n),h=Gt(r*a),f=Gt(i*d*c),g=Gt(s*o),p=Gt((t+r)*(n+a)-u-h),b=Gt(g-f),m=Gt(g+f),y=Gt(h-l*u),A=Gt(p*b),I=Gt(m*y),v=Gt(p*y),w=Gt(b*m);return new qt(A,I,w,v)}mul(e,t=!0){if(0n===e)return!0===t?Vt("cannot multiply by 0"):Wt;if("bigint"==typeof e&&0n<e&&e<Mt||Vt("invalid scalar, must be < L"),!t&&this.is0()||1n===e)return this;if(this.equals(zt))return br(e).p;let r=Wt,s=zt;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(Ht.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(Mt/2n,!1).double();return e=e.add(this),e.is0()}toAffine(){const{ex:e,ey:t,ez:r}=this;if(this.equals(Wt))return{x:0n,y:1n};const s=sr(r,Dt);return 1n!==Gt(r*s)&&Vt("invalid inverse"),{x:Gt(e*s),y:Gt(t*s)}}toRawBytes(){const{x:e,y:t}=this.toAffine(),r=er(t);return r[31]|=1n&e?128:0,r}toHex(){return Yt(this.toRawBytes())}}qt.BASE=new qt(Pt,Lt,1n,Gt(Pt*Lt)),qt.ZERO=new qt(0n,1n,1n,0n);const{BASE:zt,ZERO:Wt}=qt,Jt=(e,t)=>e.toString(16).padStart(t,"0"),Yt=e=>Array.from(Qt(e)).map(e=>Jt(e,2)).join(""),Xt=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0,Zt=e=>{const t="hex invalid";if(!Kt(e))return Vt(t);const r=e.length,s=r/2;if(r%2)return Vt(t);const i=$t(s);for(let r=0,n=0;r<s;r++,n+=2){const s=Xt(e.charCodeAt(n)),a=Xt(e.charCodeAt(n+1));if(void 0===s||void 0===a)return Vt(t);i[r]=16*s+a}return i},er=e=>Zt(Jt(e,64)).reverse(),tr=e=>BigInt("0x"+Yt($t(Qt(e)).reverse())),rr=(...e)=>{const t=$t(e.reduce((e,t)=>e+Qt(t).length,0));let r=0;return e.forEach(e=>{t.set(e,r),r+=e.length}),t},sr=(e,t)=>{(0n===e||t<=0n)&&Vt("no inverse n="+e+" mod="+t);let r=Gt(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?Gt(i,t):Vt("no inverse")},ir=(e,t)=>{let r=e;for(;t-- >0n;)r*=r,r%=Dt;return r},nr=19681161376707505956807079304988542015446066515923890162744021073123829784752n,ar=(e,t)=>{const r=Gt(t*t*t),s=(e=>{const t=e*e%Dt*e%Dt,r=ir(t,2n)*t%Dt,s=ir(r,1n)*e%Dt,i=ir(s,5n)*s%Dt,n=ir(i,10n)*i%Dt,a=ir(n,20n)*n%Dt,o=ir(a,40n)*a%Dt,c=ir(o,80n)*o%Dt,l=ir(c,80n)*o%Dt,d=ir(l,10n)*i%Dt;return{pow_p_5_8:ir(d,2n)*e%Dt,b2:t}})(e*Gt(r*r*t)).pow_p_5_8;let i=Gt(e*r*s);const n=Gt(t*i*i),a=i,o=Gt(i*nr),c=n===e,l=n===Gt(-e),d=n===Gt(-e*nr);return c&&(i=a),(l||d)&&(i=o),1n==(1n&Gt(i))&&(i=Gt(-i)),{isValid:c||l,value:i}},or=e=>Gt(tr(e),Mt);let cr;const lr=(...e)=>gr.sha512Async(...e),dr=e=>{const t=e.slice(0,32);t[0]&=248,t[31]&=127,t[31]|=64;const r=e.slice(32,64),s=or(t),i=zt.mul(s),n=i.toRawBytes();return{head:t,prefix:r,scalar:s,point:i,pointBytes:n}},ur=e=>lr(Ft(e,32)).then(dr);function hr(e,t){return e?lr(t.hashable).then(t.finish):t.finish(((...e)=>"function"==typeof cr?cr(...e):Vt("etc.sha512Sync not set"))(t.hashable))}const fr=()=>"object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,gr={bytesToHex:Yt,hexToBytes:Zt,concatBytes:rr,mod:Gt,invert:sr,randomBytes:(e=32)=>{const t=fr();return t&&t.getRandomValues||Vt("crypto.getRandomValues must be defined"),t.getRandomValues($t(e))},sha512Async:async(...e)=>{const t=fr(),r=t&&t.subtle;r||Vt("etc.sha512Async or crypto.subtle must be defined");const s=rr(...e);return $t(await r.digest("SHA-512",s.buffer))},sha512Sync:void 0};let pr;Object.defineProperties(gr,{sha512Sync:{configurable:!1,get:()=>cr,set(e){cr||(cr=e)}}});const br=e=>{const t=pr||(pr=(()=>{const e=[];let t=zt,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=Wt,i=zt;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 mr=a(625);const yr=32,Ar=64;class Ir{pubKey;_privKey;constructor(e,t){this.pubKey=e,this._privKey=t}}async function vr(e){const t=await(r=e.raw,ur(r).then(e=>e.pointBytes));var r;return new Ir(L.fromBlob(t,yr).asOpaque(),e.asOpaque())}async function wr(e,t){const r=await(async(e,t)=>{const r=Ft(e),s=await ur(t);return hr(!0,((e,t,r)=>{const{pointBytes:s,scalar:i}=e,n=or(t),a=zt.mul(n).toRawBytes();return{hashable:rr(a,s,r),finish:e=>{const t=Gt(n+or(e)*i,Mt);return Qt(rr(a,er(t)),64)}}})(s,await lr(s.prefix,r),r))})(t.raw,e._privKey.raw);return L.fromBlob(r,Ar).asOpaque()}async function Sr(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+=yr,r.set(n.raw,s),s+=Ar;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,mr.verify_ed25519)(r)).map(e=>1===e);return Promise.resolve(i)}const Er=L.blobFromString("jam_val_key_ed25519");L.blobFromString("jam_val_key_bandersnatch");class Cr extends B{anchor;bitfield;validatorIndex;signature;static Codec=_e.Class(Cr,{anchor:_e.bytes(Le).asOpaque(),bitfield:xt(e=>_e.bitVecFixLen(e.coresCount)),validatorIndex:_e.u16.asOpaque(),signature:_e.bytes(Ar).asOpaque()});static create({anchor:e,bitfield:t,validatorIndex:r,signature:s}){return new Cr(e,t,r,s)}constructor(e,t,r,s){super(),this.anchor=e,this.bitfield=t,this.validatorIndex=r,this.signature=s}}const kr=xt(e=>Bt(Cr.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2})),xr=e=>te.array((e=>te.object({anchor:Nt.bytes32(),bitfield:te.fromString(t=>{const r=Math.ceil(e.coresCount/8);return Y.fromBytes(L.parseBytes(t,r),e.coresCount)}),validator_index:"number",signature:Nt.ed25519Signature},({anchor:e,bitfield:t,validator_index:r,signature:s})=>Cr.create({anchor:e,bitfield:t,validatorIndex:r,signature:s})))(e));class Br extends B{workReportHash;wasConsideredValid;key;signature;static Codec=_e.Class(Br,{workReportHash:_e.bytes(Le).asOpaque(),wasConsideredValid:_e.bool,key:_e.bytes(yr).asOpaque(),signature:_e.bytes(Ar).asOpaque()});static create({workReportHash:e,wasConsideredValid:t,key:r,signature:s}){return new Br(e,t,r,s)}constructor(e,t,r,s){super(),this.workReportHash=e,this.wasConsideredValid=t,this.key=r,this.signature=s}}class _r extends B{workReportHash;key;signature;static Codec=_e.Class(_r,{workReportHash:_e.bytes(Le).asOpaque(),key:_e.bytes(yr).asOpaque(),signature:_e.bytes(Ar).asOpaque()});static create({workReportHash:e,key:t,signature:r}){return new _r(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.key=t,this.signature=r}}class Rr extends B{isWorkReportValid;index;signature;static Codec=_e.Class(Rr,{isWorkReportValid:_e.bool,index:_e.u16.asOpaque(),signature:_e.bytes(Ar).asOpaque()});static create({isWorkReportValid:e,index:t,signature:r}){return new Rr(e,t,r)}constructor(e,t,r){super(),this.isWorkReportValid=e,this.index=t,this.signature=r}}class Or extends B{workReportHash;votesEpoch;votes;static Codec=_e.Class(Or,{workReportHash:_e.bytes(Le).asOpaque(),votesEpoch:_e.u32.asOpaque(),votes:xt(e=>xe(_e.sequenceFixLen(Rr.Codec,e.validatorsSuperMajority)).convert(R,yt))});static create({workReportHash:e,votesEpoch:t,votes:r}){return new Or(e,t,r)}constructor(e,t,r){super(),this.workReportHash=e,this.votesEpoch=t,this.votes=r}}class Ur extends B{verdicts;culprits;faults;static Codec=_e.Class(Ur,{verdicts:_e.sequenceVarLen(Or.Codec),culprits:_e.sequenceVarLen(_r.Codec),faults:_e.sequenceVarLen(Br.Codec)});static create({verdicts:e,culprits:t,faults:r}){return new Ur(e,t,r)}constructor(e,t,r){super(),this.verdicts=e,this.culprits=t,this.faults=r}}const Tr=e=>ae(e),Nr=e=>ie(e),Dr=e=>ae(e),Mr=e=>ce(e),Pr=e=>ie(e),Lr=e=>ae(e);function Hr(e,t){return w(e.length===t.validatorsCount,`Invalid per-validator array length. Expected ${t.validatorsCount}, got: ${e.length}`),e}const Vr=e=>xt(t=>Bt(e,{fixedLength:t.validatorsCount}));function Kr(e,t){return w(e.length===t.epochLength,`Invalid per-epoch-block array length. Expected ${t.epochLength}, got: ${e.length}`),e}const Qr=e=>xt(t=>Bt(e,{fixedLength:t.epochLength}));class $r extends B{anchor;stateRoot;beefyRoot;lookupAnchor;lookupAnchorSlot;prerequisites;static Codec=_e.Class($r,{anchor:_e.bytes(Le).asOpaque(),stateRoot:_e.bytes(Le).asOpaque(),beefyRoot:_e.bytes(Le).asOpaque(),lookupAnchor:_e.bytes(Le).asOpaque(),lookupAnchorSlot:_e.u32.asOpaque(),prerequisites:_e.sequenceVarLen(_e.bytes(Le).asOpaque())});static create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n}){return new $r(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 Gr extends B{treeRoot;index;static Codec=_e.Class(Gr,{treeRoot:_e.bytes(Le),index:_e.u16.asOpaque()});static create({treeRoot:e,index:t}){return new Gr(e,t)}constructor(e,t){super(),this.treeRoot=e,this.index=t}}class jr extends B{hash;len;static Codec=_e.Class(jr,{hash:_e.bytes(Le).asOpaque(),len:_e.u32});static create({hash:e,len:t}){return new jr(e,t)}constructor(e,t){super(),this.hash=e,this.len=t}}class qr extends B{service;codeHash;payload;refineGasLimit;accumulateGasLimit;importSegments;extrinsic;exportCount;static Codec=v.isGreaterOrEqual(h.V0_7_0)?_e.Class(qr,{service:_e.u32.asOpaque(),codeHash:_e.bytes(Le).asOpaque(),refineGasLimit:_e.u64.asOpaque(),accumulateGasLimit:_e.u64.asOpaque(),exportCount:_e.u16,payload:_e.blob,importSegments:Bt(Gr.Codec,{minLength:0,maxLength:Fr,typicalLength:Fr}),extrinsic:_e.sequenceVarLen(jr.Codec)}):_e.Class(qr,{service:_e.u32.asOpaque(),codeHash:_e.bytes(Le).asOpaque(),payload:_e.blob,refineGasLimit:_e.u64.asOpaque(),accumulateGasLimit:_e.u64.asOpaque(),importSegments:Bt(Gr.Codec,{minLength:0,maxLength:Fr,typicalLength:Fr}),extrinsic:_e.sequenceVarLen(jr.Codec),exportCount:_e.u16});static create({service:e,codeHash:t,payload:r,refineGasLimit:s,accumulateGasLimit:i,importSegments:n,extrinsic:a,exportCount:o}){return new qr(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 zr(e){return S(e,e>=Wr&&e<=Jr,`WorkItemsCount: Expected '${Wr} <= count <= ${Jr}' got ${e}`)}const Wr=1,Jr=16;class Yr extends B{authorization;authCodeHost;authCodeHash;parametrization;context;items;static Codec=v.isGreaterOrEqual(h.V0_7_0)?_e.Class(Yr,{authCodeHost:_e.u32.asOpaque(),authCodeHash:_e.bytes(Le).asOpaque(),context:$r.Codec,authorization:_e.blob,parametrization:_e.blob,items:_e.sequenceVarLen(qr.Codec).convert(e=>e,e=>At.new(e,zr(e.length)))}):_e.Class(Yr,{authorization:_e.blob,authCodeHost:_e.u32.asOpaque(),authCodeHash:_e.bytes(Le).asOpaque(),parametrization:_e.blob,context:$r.Codec,items:_e.sequenceVarLen(qr.Codec).convert(e=>e,e=>At.new(e,zr(e.length)))});static create({authorization:e,authCodeHost:t,authCodeHash:r,parametrization:s,context:i,items:n}){return new Yr(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 Xr,Zr;(Zr=Xr||(Xr={}))[Zr.ok=0]="ok",Zr[Zr.outOfGas=1]="outOfGas",Zr[Zr.panic=2]="panic",Zr[Zr.incorrectNumberOfExports=v.isGreaterOrEqual(h.V0_6_7)?3:-1]="incorrectNumberOfExports",Zr[Zr.digestTooBig=v.isGreaterOrEqual(h.V0_6_7)?4:-1]="digestTooBig",Zr[Zr.badCode=v.isGreaterOrEqual(h.V0_6_7)?5:3]="badCode",Zr[Zr.codeOversize=v.isGreaterOrEqual(h.V0_6_7)?6:4]="codeOversize";class es extends B{kind;okBlob;static Codec=_e.custom({name:"WorkExecResult",sizeHint:{bytes:1,isExact:!1}},(e,t)=>{e.varU32(ae(t.kind)),t.kind===Xr.ok&&null!==t.okBlob&&e.bytesBlob(t.okBlob)},e=>{const t=e.varU32();if(t===Xr.ok){const r=e.bytesBlob();return new es(t,r)}if(t>Xr.codeOversize)throw new Error(`Invalid WorkExecResultKind: ${t}`);return new es(t)},e=>{e.decoder.varU32()===Xr.ok&&e.bytesBlob()});constructor(e,t=null){super(),this.kind=e,this.okBlob=t}}class ts extends B{gasUsed;importedSegments;extrinsicCount;extrinsicSize;exportedSegments;static Codec=_e.Class(ts,{gasUsed:_e.varU64.asOpaque(),importedSegments:_e.varU32,extrinsicCount:_e.varU32,extrinsicSize:_e.varU32,exportedSegments:_e.varU32});static create({gasUsed:e,importedSegments:t,extrinsicCount:r,extrinsicSize:s,exportedSegments:i}){return new ts(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 rs{serviceId;codeHash;payloadHash;gas;result;load;static Codec=_e.Class(rs,{serviceId:_e.u32.asOpaque(),codeHash:_e.bytes(Le).asOpaque(),payloadHash:_e.bytes(Le),gas:_e.u64.asOpaque(),result:es.Codec,load:ts.Codec});static create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n}){return new rs(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 ss extends B{hash;length;erasureRoot;exportsRoot;exportsCount;static Codec=_e.Class(ss,{hash:_e.bytes(Le).asOpaque(),length:_e.u32,erasureRoot:_e.bytes(Le),exportsRoot:_e.bytes(Le).asOpaque(),exportsCount:_e.u16});static create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i}){return new ss(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 is extends B{workPackageHash;segmentTreeRoot;static Codec=_e.Class(is,{workPackageHash:_e.bytes(Le).asOpaque(),segmentTreeRoot:_e.bytes(Le).asOpaque()});constructor(e,t){super(),this.workPackageHash=e,this.segmentTreeRoot=t}static create({workPackageHash:e,segmentTreeRoot:t}){return new is(e,t)}}class ns 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 ns(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 as=_e.Class(ns,{workPackageSpec:ss.Codec,context:$r.Codec,coreIndex:_e.varU32.convert(e=>ae(e),e=>{if(!ne(e))throw new Error(`Core index exceeds U16: ${e}`);return Pr(e)}),authorizerHash:_e.bytes(Le).asOpaque(),authorizationGasUsed:_e.varU64.asOpaque(),authorizationOutput:_e.blob,segmentRootLookup:xe(_e.sequenceVarLen(is.Codec)),results:_e.sequenceVarLen(rs.Codec).convert(e=>e,e=>At.new(e,zr(e.length)))}),os=_e.Class(ns,{workPackageSpec:ss.Codec,context:$r.Codec,coreIndex:v.isGreaterOrEqual(h.V0_6_5)&&!v.isSuite(f.JAMDUNA,h.V0_6_5)?_e.varU32.convert(e=>ae(e),e=>{if(!ne(e))throw new Error(`Core index exceeds U16: ${e}`);return Pr(e)}):_e.u16.asOpaque(),authorizerHash:_e.bytes(Le).asOpaque(),authorizationOutput:_e.blob,segmentRootLookup:xe(_e.sequenceVarLen(is.Codec)),results:_e.sequenceVarLen(rs.Codec).convert(e=>e,e=>At.new(e,zr(e.length))),authorizationGasUsed:_e.varU64.asOpaque()});ns.Codec=v.isGreaterOrEqual(h.V0_7_0)?as:os;const cs=[2,3];class ls extends B{validatorIndex;signature;static Codec=_e.Class(ls,{validatorIndex:_e.u16.asOpaque(),signature:_e.bytes(Ar).asOpaque()});static create({validatorIndex:e,signature:t}){return new ls(e,t)}constructor(e,t){super(),this.validatorIndex=e,this.signature=t}}class ds extends B{report;slot;credentials;static Codec=_e.Class(ds,{report:ns.Codec,slot:_e.u32.asOpaque(),credentials:Bt(ls.Codec,{minLength:cs[0],maxLength:cs[1],typicalLength:cs[1]})});static create({report:e,slot:t,credentials:r}){return new ds(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.credentials=r}}const us=xt(e=>Bt(ds.Codec,{minLength:0,maxLength:e.coresCount,typicalLength:e.coresCount}));class hs extends B{bandersnatch;ed25519;static Codec=_e.Class(hs,{bandersnatch:_e.bytes(Ne).asOpaque(),ed25519:_e.bytes(yr).asOpaque()});static create({bandersnatch:e,ed25519:t}){return new hs(e,t)}constructor(e,t){super(),this.bandersnatch=e,this.ed25519=t}}class fs extends B{entropy;ticketsEntropy;validators;static Codec=_e.Class(fs,{entropy:_e.bytes(Le).asOpaque(),ticketsEntropy:_e.bytes(Le).asOpaque(),validators:Vr(hs.Codec)});static create({entropy:e,ticketsEntropy:t,validators:r}){return new fs(e,t,r)}constructor(e,t,r){super(),this.entropy=e,this.ticketsEntropy=t,this.validators=r}}const gs=e=>{const t=e.encoded().raw,r=t.length-De;return P.blobFrom(t.subarray(0,r))},ps={parentHeaderHash:_e.bytes(Le).asOpaque(),priorStateRoot:_e.bytes(Le).asOpaque(),extrinsicHash:_e.bytes(Le).asOpaque(),timeSlotIndex:_e.u32.asOpaque(),epochMarker:_e.optional(fs.Codec),ticketsMarker:_e.optional(Qr(Ut.Codec)),offendersMarker:_e.sequenceVarLen(_e.bytes(yr).asOpaque()),bandersnatchBlockAuthorIndex:_e.u16.asOpaque(),entropySource:_e.bytes(De).asOpaque(),seal:_e.bytes(De).asOpaque()};class bs extends B{static Codec=_e.Class(bs,v.isLessThan(h.V0_7_0)?ps:{parentHeaderHash:_e.bytes(Le).asOpaque(),priorStateRoot:_e.bytes(Le).asOpaque(),extrinsicHash:_e.bytes(Le).asOpaque(),timeSlotIndex:_e.u32.asOpaque(),epochMarker:_e.optional(fs.Codec),ticketsMarker:_e.optional(Qr(Ut.Codec)),bandersnatchBlockAuthorIndex:_e.u16.asOpaque(),entropySource:_e.bytes(De).asOpaque(),offendersMarker:_e.sequenceVarLen(_e.bytes(yr).asOpaque()),seal:_e.bytes(De).asOpaque()});static create(e){return Object.assign(bs.empty(),e)}parentHeaderHash=L.zero(Le).asOpaque();priorStateRoot=L.zero(Le).asOpaque();extrinsicHash=L.zero(Le).asOpaque();timeSlotIndex=Tr(0);epochMarker=null;ticketsMarker=null;bandersnatchBlockAuthorIndex=Nr(0);entropySource=L.zero(De).asOpaque();offendersMarker=[];seal=L.zero(De).asOpaque();constructor(){super()}static empty(){return new bs}}class ms extends Ve{static Codec=_e.Class(ms,{hash:_e.bytes(Le).asOpaque(),data:bs.Codec.View});static create({hash:e,data:t}){return new Ve(e,t)}}const ys=ms.Codec;class As extends B{requester;blob;static Codec=_e.Class(As,{requester:_e.u32.asOpaque(),blob:_e.blob});static create({requester:e,blob:t}){return new As(e,t)}constructor(e,t){super(),this.requester=e,this.blob=t}}const Is=_e.sequenceVarLen(As.Codec);class vs extends B{tickets;preimages;guarantees;assurances;disputes;static Codec=_e.Class(vs,{tickets:Tt,preimages:Is,guarantees:us,assurances:kr,disputes:Ur.Codec});static create({tickets:e,preimages:t,assurances:r,disputes:s,guarantees:i}){return new vs(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 ws extends B{header;extrinsic;static Codec=_e.Class(ws,{header:bs.Codec,extrinsic:vs.Codec});static create({header:e,extrinsic:t}){return new ws(e,t)}constructor(e,t){super(),this.header=e,this.extrinsic=t}}const Ss=te.object({target:Nt.bytes32(),vote:"boolean",key:Nt.bytes32(),signature:Nt.ed25519Signature},({target:e,vote:t,key:r,signature:s})=>Br.create({workReportHash:e,wasConsideredValid:t,key:r,signature:s})),Es=te.object({target:Nt.bytes32(),key:Nt.bytes32(),signature:Nt.ed25519Signature},({target:e,key:t,signature:r})=>_r.create({workReportHash:e,key:t,signature:r})),Cs=te.object({vote:"boolean",index:"number",signature:Nt.ed25519Signature},({vote:e,index:t,signature:r})=>Rr.create({isWorkReportValid:e,index:t,signature:r})),ks=te.object({target:Nt.bytes32(),age:"number",votes:te.array(Cs)},({target:e,age:t,votes:r})=>Or.create({workReportHash:e,votesEpoch:t,votes:r})),xs=te.object({verdicts:te.array(ks),culprits:te.array(Es),faults:te.array(Ss)},({verdicts:e,culprits:t,faults:r})=>Ur.create({verdicts:e,culprits:t,faults:r})),Bs=te.object({anchor:Nt.bytes32(),state_root:Nt.bytes32(),beefy_root:Nt.bytes32(),lookup_anchor:Nt.bytes32(),lookup_anchor_slot:"number",prerequisites:te.array(Nt.bytes32())},({anchor:e,state_root:t,beefy_root:r,lookup_anchor:s,lookup_anchor_slot:i,prerequisites:n})=>$r.create({anchor:e,stateRoot:t,beefyRoot:r,lookupAnchor:s,lookupAnchorSlot:i,prerequisites:n})),_s=te.object({ok:te.optional(te.fromString(P.parseBlob)),out_of_gas:te.optional(te.fromAny(()=>null)),panic:te.optional(te.fromAny(()=>null)),bad_code:te.optional(te.fromAny(()=>null)),code_oversize:te.optional(te.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 es(ae(Xr.ok),t);if(null===r)return new es(ae(Xr.outOfGas));if(null===s)return new es(ae(Xr.panic));if(null===i)return new es(ae(Xr.badCode));if(null===n)return new es(ae(Xr.codeOversize));throw new Error("Invalid WorkExecResult")}),Rs=te.object({gas_used:te.fromNumber(e=>Mr(e)),imports:"number",extrinsic_count:"number",extrinsic_size:"number",exports:"number"},({gas_used:e,imports:t,extrinsic_count:r,extrinsic_size:s,exports:i})=>ts.create({gasUsed:Mr(e),importedSegments:ae(t),extrinsicCount:ae(r),extrinsicSize:ae(s),exportedSegments:ae(i)})),Os=te.object({service_id:"number",code_hash:Nt.bytes32(),payload_hash:Nt.bytes32(),accumulate_gas:te.fromNumber(e=>Mr(e)),result:_s,refine_load:Rs},({service_id:e,code_hash:t,payload_hash:r,accumulate_gas:s,result:i,refine_load:n})=>rs.create({serviceId:e,codeHash:t,payloadHash:r,gas:s,result:i,load:n})),Us=te.object({hash:Nt.bytes32(),length:"number",erasure_root:Nt.bytes32(),exports_root:Nt.bytes32(),exports_count:"number"},({hash:e,length:t,erasure_root:r,exports_root:s,exports_count:i})=>ss.create({hash:e,length:t,erasureRoot:r,exportsRoot:s,exportsCount:i})),Ts=te.object({work_package_hash:Nt.bytes32(),segment_tree_root:Nt.bytes32()},({work_package_hash:e,segment_tree_root:t})=>is.create({workPackageHash:e,segmentTreeRoot:t})),Ns=te.object({package_spec:Us,context:Bs,core_index:"number",authorizer_hash:Nt.bytes32(),auth_output:te.fromString(P.parseBlob),segment_root_lookup:te.array(Ts),results:te.array(Os),auth_gas_used:te.fromNumber(e=>Mr(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=At.new(n,zr(n.length));return ns.create({workPackageSpec:e,context:t,coreIndex:r,authorizerHash:s,authorizationOutput:i,segmentRootLookup:a,results:c,authorizationGasUsed:o})}),Ds=te.object({validator_index:"number",signature:Nt.ed25519Signature},({validator_index:e,signature:t})=>ls.create({validatorIndex:e,signature:t})),Ms=te.object({report:Ns,slot:"number",signatures:te.array(Ds)},({report:e,slot:t,signatures:r})=>ds.create({report:e,slot:t,credentials:r})),Ps=te.array(Ms),Ls=te.object({requester:"number",blob:te.fromString(P.parseBlob)},({requester:e,blob:t})=>As.create({requester:e,blob:t})),Hs=te.array(Ls),Vs=te.object({attempt:Nt.ticketAttempt,signature:te.fromString(e=>L.parseBytes(e,784).asOpaque())},e=>Ot.create({attempt:e.attempt,signature:e.signature})),Ks=te.array(Vs),Qs=te.fromString(e=>L.parseBytes(e,96).asOpaque()),$s=te.object({bandersnatch:Nt.bytes32(),ed25519:Nt.bytes32()},hs.create),Fs=te.object({entropy:Nt.bytes32(),tickets_entropy:Nt.bytes32(),validators:te.array($s)},e=>fs.create({entropy:e.entropy,ticketsEntropy:e.tickets_entropy,validators:e.validators})),Gs=te.object({id:Nt.bytes32(),attempt:Nt.ticketAttempt},e=>Ut.create({id:e.id,attempt:e.attempt})),js=te.object({parent:Nt.bytes32(),parent_state_root:Nt.bytes32(),extrinsic_hash:Nt.bytes32(),slot:"number",epoch_mark:te.optional(Fs),tickets_mark:te.optional(te.array(Gs)),offenders_mark:te.array(Nt.bytes32()),author_index:"number",entropy_source:Qs,seal:Qs},({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=bs.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}),qs=t(import.meta.url)("node:timers/promises");var zs;function Ws(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 Js(e){const t="debug"===e?"LOG":e.toUpperCase();if(void 0===zs[t])throw new Error(`Unknown logging level: "${e}". Use one of "trace", "debug", "log","info", "warn", "error"`);return zs[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"}(zs||(zs={}));class Ys{options;static create(e,t){return e===zs.TRACE?new Xs(t):e===zs.LOG?new Zs(t):e===zs.INFO?new ei(t):new Ys(t)}constructor(e){this.options=e}trace(e,t,r){}log(e,t,r){}info(e,t,r){}warn(e,t,r){this.push(zs.WARN,e,t,r)}error(e,t,r){this.push(zs.ERROR,e,t,r)}push(e,t,r,s){const i=r.replace(this.options.workingDir,""),n=t.replace(this.options.workingDir,""),a=Ws(this.options,t),o=zs[e].padEnd(5);if(e<a)return;const c=`${o} [${n}] ${s}\n\t@ ${i}`;e===zs.WARN?console.warn(c):e===zs.ERROR?console.error(c):console.info(c)}}class Xs extends Ys{trace(e,t,r){this.push(zs.TRACE,e,t,r)}log(e,t,r){this.push(zs.LOG,e,t,r)}info(e,t,r){this.push(zs.INFO,e,t,r)}}class Zs extends Ys{trace(e,t,r){}log(e,t,r){this.push(zs.LOG,e,t,r)}info(e,t,r){this.push(zs.INFO,e,t,r)}}class ei extends Ys{trace(e,t,r){}log(e,t,r){}info(e,t,r){this.push(zs.INFO,e,t,r)}}const ti={workingDir:"",defaultLevel:zs.LOG,modules:new Map},ri={options:ti,transport:Ys.create(ti.defaultLevel,ti)};class si{moduleName;fileName;config;static new(e,t){const r=e??"unknown";return new si(t??r,r,ri)}static getLevel(e){return Ws(ri.options,e)}static configureAllFromOptions(e){const t=Array.from(e.modules.values()).reduce((e,t)=>e<t?e:t,e.defaultLevel),r=Ys.create(t,e);ri.options=e,ri.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(),Js(r.trim()))}else n=Js(t)}const a="".split("/");return a.pop(),a.pop(),{defaultLevel:n,modules:s,workingDir:r??a.join("/")}}(e,t,r);si.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 ii;!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"}(ii||(ii={}));const ni="captureStackTrace"in Error,ai="stackTraceLimit"in Error;function oi(e){switch(e){case ii.NOTSET:return"NOTSET";case ii.DEBUG:return"DEBUG";case ii.INFO:return"INFO";case ii.WARN:return"WARN";case ii.ERROR:return"ERROR";case ii.SILENT:return"SILENT"}}function ci(e,t){return"function"==typeof t?t():t}function li(e){return JSON.stringify(e,ci)}const di=Symbol("level"),ui=Symbol("key"),hi=Symbol("keys"),fi=Symbol("date"),gi=Symbol("msg"),pi=Symbol("stack"),bi=Symbol("data");function mi(e,...t){return r=>{let s=e[0];for(let i=0;i<t.length;i++){const n=t[i];if(n===ui)s+=r.key;else if(n===hi)s+=r.keys;else if(n===fi)s+=r.date().toISOString();else if(n===gi)null!=r.msg&&(s+=r.msg);else if(n===di)s+=oi(r.level);else if(n===bi)s+=li(r.data);else if(n===pi){const e=r.stack();""!==e&&(s+="\n"+e)}else s+=n.toString();s+=e[i+1]}return s}}const yi=mi`${di}:${ui}:${gi}`,Ai=class{formatter;constructor(e=yi){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)}},Ii=class extends Ai{emit(e){console.error(e)}};class vi{key;level;filter;keys;handlers;parent;_loggers=new Map;loggersRegistry;constructor(e="root",t=ii.NOTSET,r=[new Ii],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 vi(e,ii.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!==ii.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,{},ii.DEBUG,t):this.log(e,t,ii.DEBUG,r)}info(e,t,r){return null==t||"function"==typeof t?this.log(e,{},ii.INFO,t):this.log(e,t,ii.INFO,r)}warn(e,t,r){return null==t||"function"==typeof t?this.log(e,{},ii.WARN,t):this.log(e,t,ii.WARN,r)}error(e,t,r){return null==t||"function"==typeof t?this.log(e,{},ii.ERROR,t):this.log(e,t,ii.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(ni&&ai){Error.stackTraceLimit++;const t={};Error.captureStackTrace(t,vi.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 wi=vi,Si=t(import.meta.url)("node:process"),Ei=class extends Ai{emit(e){Si.stderr.write(e+"\n")}},Ci=t(import.meta.url)("dgram");class ki 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 xi=ki;class Bi extends xi{constructor(e){super(Bi.name,e,arguments)}}const _i=Bi;class Ri extends xi{constructor(e){super(Ri.name,e,arguments)}}const Oi=Ri;class Ui extends xi{constructor(e){super(Ui.name,e,arguments)}}const Ti=Ui,Ni=Symbol("_eventTarget"),Di=Symbol("eventTarget"),Mi=Symbol("_eventHandlers"),Pi=Symbol("eventHandlers"),Li=Symbol("_eventHandled"),Hi=Symbol("eventHandled"),Vi=Symbol("_handleEventError"),Ki=Symbol("handleEventError");function Qi(e){return{capture:!1,once:!1,passive:!1,..."boolean"==typeof e?{capture:e}:"object"==typeof e?e:void 0}}function $i(e,t){return e.capture===t.capture}function Fi(){return e=>{const t=class extends e{[Ni]=new EventTarget;[Mi]=new Map;[Li]=new WeakSet;[Vi]=e=>{throw e.detail};constructor(...e){super(...e),this[Ni].addEventListener(Ti.name,this[Vi])}get[Di](){return this[Ni]}get[Pi](){return this[Mi]}get[Hi](){return this[Li]}get[Ki](){return this[Vi]}addEventListener(e,t,r){r=Qi(r);const s=this;let i,n,a=!1;if("function"==typeof t||"function"==typeof t?.handleEvent){n=this[Mi].get(e),void 0===n&&(n=new Set,this[Mi].set(e,n));for(const e of n)if(e.callback===t&&(i=e.handler,$i(e.options,r))){a=!0;break}}"function"==typeof t?null==i?(i=async function(e){let r;s[Li].add(e);try{r=t.call(s,e)}catch(e){this.dispatchEvent(new Ti({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new Ti({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[Li].add(e);try{r=t.handleEvent(e)}catch(e){this.dispatchEvent(new Ti({detail:e}))}if("function"==typeof r?.then)try{await r}catch(e){this.dispatchEvent(new Ti({detail:e}))}return r},n.add({callback:t,options:r,handler:i})):a||n.add({callback:t,options:r,handler:i}):i=t,this[Ni].addEventListener(e,i,r),e===Ti.name&&1===n?.size&&this[Ni].removeEventListener(Ti.name,this[Vi])}removeEventListener(e,t,r){let s,i,n;if(r=Qi(r),null!=t){if(i=this[Mi].get(e),void 0===i)return;for(const e of i)if(e.callback===t&&$i(e.options,r)){s=e.handler,n=e;break}if(null==s)return}else s=t;this[Ni].removeEventListener(e,s,r),null!=i&&null!=n&&(i.delete(n),e===Ti.name&&0===i.size&&this[Ni].addEventListener(Ti.name,this[Vi]))}dispatchEvent(e){if(Object.defineProperties(e,{target:{value:this,writable:!1},currentTarget:{value:this,writable:!1}}),e instanceof Ti)return this[Ni].dispatchEvent(e);{let t=this[Ni].dispatchEvent(e);if(t&&!this[Li].has(e)){const r=new _i({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[Ni].dispatchEvent(r)}if(t){const r=new Oi({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[Ni].dispatchEvent(r)}return t}}};return Object.defineProperty(t,"name",Object.getOwnPropertyDescriptor(e,"name")),t}}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 await t(s)}catch(e){throw i=e,e}finally{r.reverse();for(const e of r)await e(i)}}async function*ji(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 qi extends Promise{static get[Symbol.species](){return Promise}static resolve(e){return e instanceof qi?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=qi.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 zi=qi,Wi=t(import.meta.url)("node:perf_hooks");var Ji,Yi=(Ji=function(e,t){return Ji=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])},Ji(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}Ji(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),Xi=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 Yi(t,e),t}(Error);const Zi=class extends Xi{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(Wi.performance.timeOrigin+Wi.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 en(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=en(s,t,r);if(e)return e}return en(e.cause,t,r)}return e instanceof Error&&en(e.cause,t,r)}class tn extends Zi{static description="Timer error"}class rn extends tn{static description="The timer has already ended"}class sn{_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 zi((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(Wi.performance.timeOrigin+Wi.performance.now()),this._scheduled=new Date(this.timestamp.getTime()+t)):(this.timeoutRef=setInterval(()=>{},2**31-1),this.timestamp=new Date(Wi.performance.timeOrigin+Wi.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()-(Wi.performance.timeOrigin+Wi.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 rn;return this.reset(this._delay)}reset(e){if(null!=this._status)throw new rn;clearTimeout(this.timeoutRef),this._delay=e,isFinite(e)?(this.timeoutRef=setTimeout(()=>{this.fulfill()},e),this._scheduled=new Date(Wi.performance.timeOrigin+Wi.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 nn=sn;function an(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function on(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 nn(()=>{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 nn&&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 nn(()=>{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 zi((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 cn extends Zi{static description="Async locks error"}class ln extends cn{static description="Async locks timeout"}const dn=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}:{},()=>on((e,t)=>{this._count++;const{p:r,resolveP:s,rejectP:i}=an();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,ln,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}:{},on((e,t)=>{const{p:r,resolveP:s,rejectP:i}=an();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,ln,r,[t])}withF(...e){const t=e.pop();return Gi([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return ji([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()}}},un=class{semaphore=new dn(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 Gi([this.lock(...e)],([e])=>t(e))}withG(...e){const t=e.pop();return ji([this.lock(...e)],([e])=>t(e))}},hn=class{readersLock=new un;writersLock=new un;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}:{},()=>on(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,ln,e,[])}write(e){return e=null!=e?{...e}:{},()=>on(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,ln,e,[])}waitForUnlock(e){const t=this.readersLock.waitForUnlock(e),r=this.writersLock.waitForUnlock(e);return zi.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 Gi([this.read(...e)],([e])=>t(e))}withWriteF(...e){const t=e.pop();return Gi([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 ji([this.read(...e)],([e])=>t(e))}withWriteG(...e){const t=e.pop();return ji([this.write(...e)],([e])=>t(e))}},fn=Symbol("_running"),gn=Symbol("running"),pn=Symbol("_destroyed"),bn=Symbol("destroyed"),mn=Symbol("_status"),yn=Symbol("status"),An=Symbol("_statusP"),In=Symbol("statusP"),vn=Symbol("resolveStatusP"),wn=Symbol("initLock"),Sn=(async()=>{}).constructor,En=function*(){}.constructor,Cn=async function*(){}.constructor,kn="captureStackTrace"in Error;function xn(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function Bn(e,t){if(null!=e.stack){const r=e.stack.slice(0,e.stack.indexOf("\n")+1);kn?Error.captureStackTrace(e,t):e.stack=(new Error).stack??"",e.stack=e.stack.replace(/[^\n]+\n/,r)}}class _n extends xi{}class Rn extends _n{}class On extends _n{}class Un extends _n{}class Tn extends _n{}class Nn extends _n{}class Dn extends _n{}class Mn extends Zi{static description="Async init error"}class Pn extends Mn{static description="Async init is not running"}class Ln extends Mn{static description="Async init is destroyed"}function Hn({eventDestroy:e=Nn,eventDestroyed:t=Dn}={}){return r=>{const{p:s,resolveP:i}=xn(),n=class extends(Fi()(r)){[pn]=!1;[mn]=null;[An]=s;[vn]=i;[wn]=new hn;get[bn](){return this[pn]}get[yn](){return this[mn]}get[In](){return this[An]}async destroy(...r){return this[wn].withWriteF(async()=>{if(this[pn])return;this[mn]="destroying",this[vn]("destroying");const{p:s,resolveP:i}=xn();let n;return this[An]=s,this[vn]=i,this.dispatchEvent(new e),"function"==typeof super.destroy&&(n=await super.destroy(...r)),this[pn]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[mn]=null,this[vn](null);const{p:e,resolveP:t}=xn();this[An]=e,this[vn]=t})}};return Object.defineProperty(n,"name",Object.getOwnPropertyDescriptor(r,"name")),n}}function Vn(e=new Ln,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 Sn?async function(...s){if(this[wn].isLocked("write")&&null===this[mn]&&await this[An],r.includes(this[mn]))return o.apply(this,s);if(t)return this[wn].withReadF(async()=>{if(this[pn])throw Bn(e,n[a]),e;return o.apply(this,s)});if(this[wn].isLocked("write")||this[pn])throw Bn(e,n[a]),e;return o.apply(this,s)}:o instanceof En?function*(...t){if(r.includes(this[mn]))return yield*o.apply(this,t);if(this[wn].isLocked("write")&&null!==this[yn]||this[pn])throw Bn(e,n[a]),e;return yield*o.apply(this,t)}:o instanceof Cn?async function*(...s){if(this[wn].isLocked("write")&&null===this[mn]&&await this[An],r.includes(this[mn]))return yield*o.apply(this,s);if(t)return yield*this[wn].withReadG(()=>{if(this[pn])throw Bn(e,n[a]),e;return o.apply(this,s)});if(this[wn].isLocked("write")||this[pn])throw Bn(e,n[a]),e;return yield*o.apply(this,s)}:function(...t){if(r.includes(this[mn]))return o.apply(this,t);if(this[wn].isLocked("write")&&null!==this[yn]||this[pn])throw Bn(e,n[a]),e;return o.apply(this,t)},Object.defineProperty(n[a],"name",{value:i}),n}}function Kn({eventStart:e=Rn,eventStarted:t=On,eventStop:r=Un,eventStopped:s=Tn}={}){return i=>{const{p:n,resolveP:a}=xn(),o=class extends(Fi()(i)){[fn]=!1;[mn]=null;[An]=n;[vn]=a;[wn]=new hn;get[gn](){return this[fn]}get[yn](){return this[mn]}get[In](){return this[An]}async start(...r){return this[wn].withWriteF(async()=>{if(this[fn])return;this[mn]="starting",this[vn]("starting");const{p:s,resolveP:i}=xn();let n;return this[An]=s,this[vn]=i,this.dispatchEvent(new e),"function"==typeof super.start&&(n=await super.start(...r)),this[fn]=!0,this.dispatchEvent(new t),n}).finally(()=>{this[mn]=null,this[vn](null);const{p:e,resolveP:t}=xn();this[An]=e,this[vn]=t})}async stop(...e){return this[wn].withWriteF(async()=>{if(!this[fn])return;this[mn]="stopping",this[vn]("stopping");const{p:t,resolveP:i}=xn();let n;return this[An]=t,this[vn]=i,this.dispatchEvent(new r),"function"==typeof super.stop&&(n=await super.stop(...e)),this[fn]=!1,this.dispatchEvent(new s),n}).finally(()=>{this[mn]=null,this[vn](null);const{p:e,resolveP:t}=xn();this[An]=e,this[vn]=t})}};return Object.defineProperty(o,"name",Object.getOwnPropertyDescriptor(i,"name")),o}}function Qn(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 Sn?async function(...s){if(this[wn].isLocked("write")&&null===this[mn]&&await this[An],r.includes(this[mn]))return o.apply(this,s);if(t)return this[wn].withReadF(async()=>{if(!this[fn])throw Bn(e,n[a]),e;return o.apply(this,s)});if(this[wn].isLocked("write")||!this[fn])throw Bn(e,n[a]),e;return o.apply(this,s)}:o instanceof En?function*(...t){if(r.includes(this[mn]))return yield*o.apply(this,t);if(this[wn].isLocked("write")&&null!==this[yn]||!this[fn])throw Bn(e,n[a]),e;return yield*o.apply(this,t)}:o instanceof Cn?async function*(...s){if(this[wn].isLocked("write")&&null===this[mn]&&await this[An],r.includes(this[mn]))return yield*o.apply(this,s);if(t)return yield*this[wn].withReadG(()=>{if(!this[fn])throw Bn(e,n[a]),e;return o.apply(this,s)});if(this[wn].isLocked("write")||!this[fn])throw Bn(e,n[a]),e;return yield*o.apply(this,s)}:function(...t){if(r.includes(this[mn]))return o.apply(this,t);if(this[wn].isLocked("write")&&null!==this[yn]||!this[fn])throw Bn(e,n[a]),e;return o.apply(this,t)},Object.defineProperty(n[a],"name",{value:i}),n}}class $n 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=$n;class Gn{[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 jn=Gn,qn="data:application/javascript;base64,aW1wb3J0IHByb2Nlc3MgZnJvbSAncHJvY2Vzcyc7CmltcG9ydCBwYXRoIGZyb20gJ3BhdGgnOwppbXBvcnQgdXJsIGZyb20gJ3VybCc7CmltcG9ydCBNb2R1bGUgZnJvbSAnbm9kZTptb2R1bGUnOwpjb25zdCByZXF1aXJlID0gTW9kdWxlLmNyZWF0ZVJlcXVpcmUoaW1wb3J0Lm1ldGEudXJsKTsKY29uc3QgZGlybmFtZSA9IHVybC5maWxlVVJMVG9QYXRoKG5ldyBVUkwoJy4nLCBpbXBvcnQubWV0YS51cmwpKTsKY29uc3QgcHJvamVjdFJvb3QgPSBwYXRoLmpvaW4oZGlybmFtZSwgJy4uLy4uLycpOwpjb25zdCBwcmVidWlsZFBhdGggPSBwYXRoLmpvaW4ocHJvamVjdFJvb3QsICdwcmVidWlsZCcpOwovKioKICogVHJ5IHJlcXVpcmUgb24gYWxsIHByZWJ1aWxkIHRhcmdldHMgZmlyc3QsIHRoZW4KICogdHJ5IHJlcXVpcmUgb24gYWxsIG5wbSB0YXJnZXRzIHNlY29uZC4KICovCmZ1bmN0aW9uIHJlcXVpcmVCaW5kaW5nKHRhcmdldHMpIHsKICAgIGNvbnN0IHByZWJ1aWxkVGFyZ2V0cyA9IHRhcmdldHMubWFwKCh0YXJnZXQpID0+IHBhdGguam9pbihwcmVidWlsZFBhdGgsIGBxdWljLSR7dGFyZ2V0fS5ub2RlYCkpOwogICAgZm9yIChjb25zdCBwcmVidWlsZFRhcmdldCBvZiBwcmVidWlsZFRhcmdldHMpIHsKICAgICAgICB0cnkgewogICAgICAgICAgICByZXR1cm4gcmVxdWlyZShwcmVidWlsZFRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKHByZWJ1aWxkVGFyZ2V0KS5ocmVmKTsKICAgICAgICB9CiAgICAgICAgY2F0Y2ggKGUpIHsKICAgICAgICAgICAgaWYgKGUuY29kZSAhPT0gJ01PRFVMRV9OT1RfRk9VTkQnKQogICAgICAgICAgICAgICAgdGhyb3cgZTsKICAgICAgICB9CiAgICB9CiAgICBjb25zdCBucG1UYXJnZXRzID0gdGFyZ2V0cy5tYXAoKHRhcmdldCkgPT4gYEBtYXRyaXhhaS9xdWljLSR7dGFyZ2V0fWApOwogICAgZm9yIChjb25zdCBucG1UYXJnZXQgb2YgbnBtVGFyZ2V0cykgewogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKG5wbVRhcmdldCk7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgICAgIHRyeSB7CiAgICAgICAgICAgIHJldHVybiByZXF1aXJlKHVybC5wYXRoVG9GaWxlVVJMKG5wbVRhcmdldCkuaHJlZik7CiAgICAgICAgfQogICAgICAgIGNhdGNoIChlKSB7CiAgICAgICAgICAgIGlmIChlLmNvZGUgIT09ICdNT0RVTEVfTk9UX0ZPVU5EJykKICAgICAgICAgICAgICAgIHRocm93IGU7CiAgICAgICAgfQogICAgfQogICAgdGhyb3cgbmV3IEVycm9yKGBGYWlsZWQgcmVxdWlyaW5nIHBvc3NpYmxlIG5hdGl2ZSBiaW5kaW5nczogJHtwcmVidWlsZFRhcmdldHMuY29uY2F0KG5wbVRhcmdldHMpfWApOwp9CmxldCBuYXRpdmVCaW5kaW5nOwovKioKICogRm9yIGRlc2t0b3Agd2Ugb25seSBzdXBwb3J0IHdpbjMyLCBkYXJ3aW4gYW5kIGxpbnV4LgogKiBNb2JpbGUgT1Mgc3VwcG9ydCBpcyBwZW5kaW5nLgogKi8Kc3dpdGNoIChwcm9jZXNzLnBsYXRmb3JtKSB7CiAgICBjYXNlICd3aW4zMic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLXg2NCddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlICdpYTMyJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ3dpbjMyLWlhMzInXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnd2luMzItYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgICAgIHRocm93IG5ldyBFcnJvcihgVW5zdXBwb3J0ZWQgYXJjaGl0ZWN0dXJlIG9uIFdpbmRvd3M6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGNhc2UgJ2Rhcndpbic6CiAgICAgICAgc3dpdGNoIChwcm9jZXNzLmFyY2gpIHsKICAgICAgICAgICAgY2FzZSAneDY0JzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4teDY0K2FybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi11bml2ZXJzYWwnLAogICAgICAgICAgICAgICAgXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0JywKICAgICAgICAgICAgICAgICAgICAnZGFyd2luLWFybTY0K3g2NCcsCiAgICAgICAgICAgICAgICAgICAgJ2Rhcndpbi14NjQrYXJtNjQnLAogICAgICAgICAgICAgICAgICAgICdkYXJ3aW4tdW5pdmVyc2FsJywKICAgICAgICAgICAgICAgIF0pOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoYFVuc3VwcG9ydGVkIGFyY2hpdGVjdHVyZSBvbiBtYWNPUzogJHtwcm9jZXNzLmFyY2h9YCk7CiAgICAgICAgfQogICAgICAgIGJyZWFrOwogICAgY2FzZSAnbGludXgnOgogICAgICAgIHN3aXRjaCAocHJvY2Vzcy5hcmNoKSB7CiAgICAgICAgICAgIGNhc2UgJ3g2NCc6CiAgICAgICAgICAgICAgICBuYXRpdmVCaW5kaW5nID0gcmVxdWlyZUJpbmRpbmcoWydsaW51eC14NjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtNjQnOgogICAgICAgICAgICAgICAgbmF0aXZlQmluZGluZyA9IHJlcXVpcmVCaW5kaW5nKFsnbGludXgtYXJtNjQnXSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXJtJzoKICAgICAgICAgICAgICAgIG5hdGl2ZUJpbmRpbmcgPSByZXF1aXJlQmluZGluZyhbJ2xpbnV4LWFybSddKTsKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBhcmNoaXRlY3R1cmUgb24gTGludXg6ICR7cHJvY2Vzcy5hcmNofWApOwogICAgICAgIH0KICAgICAgICBicmVhazsKICAgIGRlZmF1bHQ6CiAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbnN1cHBvcnRlZCBPUzogJHtwcm9jZXNzLnBsYXRmb3JtfSwgYXJjaGl0ZWN0dXJlOiAke3Byb2Nlc3MuYXJjaH1gKTsKfQpleHBvcnQgZGVmYXVsdCBuYXRpdmVCaW5kaW5nOwovLyMgc291cmNlTWFwcGluZ1VSTD1xdWljaGUuanMubWFw",zn=t(import.meta.url)("dns"),Wn=t(import.meta.url)("node:events");var Jn=a.n(Wn),Yn=a(618);class Xn extends Zi{static description="QUIC error"}class Zn extends Zi{static description="You should never see this error"}class ea extends Zi{static description="Host provided was not valid"}class ta extends Zi{static description="Port provided was not valid"}class ra extends Xn{static description="QUIC config error"}class sa extends Xn{static description="QUIC Socket error"}class ia extends sa{static description="QUIC Socket is not running"}class na extends sa{static description="QUIC Socket has active connections"}class aa extends sa{static description="QUIC Socket cannot bind to the specified address"}class oa extends sa{static description="QUIC Socket cannot send to the specified address"}class ca extends sa{static description="QUIC Socket internal error"}class la extends Xn{static description="QUIC Client error"}class da extends la{static description="QUIC Client is destroyed"}class ua extends la{static description="QUIC Client cannot be created with an unstarted shared QUIC socket"}class ha extends la{static description="QUIC Client had a failure relating to an invalid argument"}class fa extends la{static description="QUIC Client cannot be created with the specified host"}class ga extends la{static description="QUIC Client internal error"}class pa extends Xn{static description="QUIC Server error"}class ba extends pa{static description="QUIC Server is not running"}class ma extends pa{static description="QUIC Server cannot start with an unstarted shared QUIC socket"}class ya extends pa{static description="QUIC Server creating a new connection"}class Aa extends pa{static description="QUIC Server internal error"}class Ia extends pa{static description="QUIC Server is stopping"}class va extends Xn{static description="QUIC Connection error"}class wa extends va{static description="QUIC Connection is stopping"}class Sa extends va{static description="QUIC Connection is not running"}class Ea extends va{static description="QUIC Connection cannot be restarted because it has already been closed"}class Ca extends Xn{static description="QUIC Connection start requires data when it is a server connection"}class ka extends va{static description="QUIC connection invalid configuration"}class xa extends va{static description="QUIC Connection local error";constructor(e="",t){super(e,t)}}class Ba extends xa{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class _a extends va{static description="QUIC Connection peer error";constructor(e="",t){super(e,t)}}class Ra extends xa{static description="QUIC Connection local TLS error";constructor(e="",t){super(e,t)}}class Oa extends va{static description="QUIC Connection max idle timeout exhausted"}class Ua extends va{static description="QUIC Connection internal error"}class Ta extends Xn{static description="QUIC Stream error"}class Na extends Ta{static description="QUIC Stream is destroyed"}class Da extends Ta{static description="QUIC Stream locally closed readable side";constructor(e="",t){super(e,t)}}class Ma extends Ta{static description="QUIC Stream locally closed writable side";constructor(e="",t){super(e,t)}}class Pa extends Ta{static description="QUIC Stream peer closed readable side";constructor(e="",t){super(e,t)}}class La extends Ta{static description="QUIC Stream peer closed writable side";constructor(e="",t){super(e,t)}}class Ha extends Ta{static description="QUIC Stream internal error"}class Va extends Ta{static description="QUIC Stream limit has been reached"}const Ka=new TextEncoder,Qa=new TextDecoder("utf-8");function $a(e){throw new Zn(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 Ga(){let e,t;return{p:new Promise((r,s)=>{e=r,t=s}),resolveP:e,rejectP:t}}function ja(e){const[t]=Yn.Validator.isValidIPv4String(e);return t}function qa(e){const[t]=Yn.Validator.isValidIPv6String(e);return!!t||za(e)}function za(e){if(e.startsWith("::ffff:"))try{return Yn.IPv6.fromString(e),!0}catch{if(ja(e.slice(7)))return!0}return!1}function Wa(e){if(!ja(e))throw new TypeError("Invalid IPv4 address");return"::ffff:"+e}function Ja(e){const t=e.slice(7);if(ja(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 Ya(e){const t=new Yn.IPv4("0.0.0.0"),r=new Yn.IPv6("::");if(za(e)){const r=Ja(e);return new Yn.IPv4(r).isEquals(t)?Wa("127.0.0.1"):e}return ja(e)&&new Yn.IPv4(e).isEquals(t)?"127.0.0.1":qa(e)&&new Yn.IPv6(e).isEquals(r)?"::1":e}async function Xa(e){return(await zn.promises.lookup(e,{family:0,all:!1,verbatim:!0})).address}async function Za(e,t){if(ja(e))return[e,"udp4"];if(qa(e))return[e,"udp6"];try{return Za(e=await t(e),t)}catch{throw new ea}}function eo(e){if(!function(e){return"number"==typeof e&&e>=0&&e<=65535}(e))throw new ta;return e}function to(e,t=0){let r;return r=ja(e)?`${e}:${t}`:qa(e)?`[${e}]:${t}`:`${e}:${t}`,r}function ro(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=za(e),o=za(r);if("ipv4&ipv6"===t&&"udp4"===s)return Wa(r);if("ipv4"===t){if(a){if("udp4"===s)return Wa(r);if("udp6"===s&&!o)throw new i(`Invalid target host ${r} from an IPv4 socket`)}else if("udp6"===s){if(o)return Ja(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 so(e){const t=[];if("string"==typeof e)t.push(e.trim()+"\n");else if(e instanceof Uint8Array)t.push(Qa.decode(e).trim()+"\n");else if(Array.isArray(e))for(const r of e)"string"==typeof r?t.push(r.trim()+"\n"):t.push(Qa.decode(r).trim()+"\n");return t}function io(e){const t=e.replace(/-----BEGIN .*-----/,"").replace(/-----END .*-----/,"").replace(/\s+/g,""),r=Buffer.from(t,"base64");return new Uint8Array(r)}function no(e){return`${e.name}${"description"in e?`: ${e.description}`:""}${void 0!==e.message?` - ${e.message}`:""}`}function ao(e){let t;return null!=(t=e.message.match(/StreamStopped\((\d{1,16})\)/))&&parseInt(t[1])}function oo(e){let t;return null!=(t=e.message.match(/StreamReset\((\d{1,16})\)/))&&parseInt(t[1])}function co(e,t=1e5){Wn.setMaxListeners(t,e)}class lo extends xi{}class uo extends lo{}class ho extends uo{}class fo extends uo{}class go extends uo{}class po extends lo{}class bo extends po{}class mo extends uo{}class yo extends po{}class Ao extends lo{}class Io extends Ao{}class vo extends Ao{}class wo extends Ao{}class So extends lo{}class Eo extends So{}class Co extends So{}class ko extends So{}class xo extends So{}class Bo extends So{}class _o extends lo{}class Ro extends _o{}class Oo extends _o{}class Uo extends _o{}class To extends _o{}class No extends _o{}var Do=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 Mo=class{connectionMap=new jn;logger;server;resolveHostname;_host;_port;_type;_closed=!1;_closedP;resolveClosedP;socket;socketBind;socketClose;socketSend;handleEventQUICSocketError=e=>{const t=e.detail;this.logger.debug(no(t))};handleEventQUICSocketClose=async()=>{await this.socketClose(),this._closed=!0,this.resolveClosedP(),this[gn]&&await this.stop({force:!0})};handleSocketMessage=async(e,t)=>{let r;try{r=qn.Header.fromSlice(e,qn.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(en(e,e=>e instanceof sa)){const t=new ca("Failed to call accept connection due to socket send",{cause:e});return this.dispatchEvent(new fo({detail:t})),void this.dispatchEvent(new go)}if(e instanceof ya)return;throw e}}};constructor({resolveHostname:e=Xa,logger:t}){this.logger=t??new wi(this.constructor.name),this.resolveHostname=e;const{p:r,resolveP:s}=Ga();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}={}){co(this[Ni]);let i=to(e,t);this.logger.info(`Start ${this.constructor.name} on ${i}`);const[n,a]=await Za(e,this.resolveHostname),o=eo(t);this.socket=Ci.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}=Ga();c.catch(()=>{}),this.socket.once("error",l);const d=this.socketBind(o,n);try{await Promise.race([d,c])}catch(t){throw new aa(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||za(n)?this._type="ipv4":"udp6"===a&&(this._type="ipv6"):this._type="ipv4&ipv6",this.socket.on("message",this.handleSocketMessage),this.addEventListener(fo.name,this.handleEventQUICSocketError),this.addEventListener(go.name,this.handleEventQUICSocketClose,{once:!0}),this._closed=!1,i=to(this._host,this._port),this.logger.info(`Started ${this.constructor.name} on ${i}`)}async stop({force:e=!1}={}){const t=to(this._host,this._port);if(this.logger.info(`Stop ${this.constructor.name} on ${t}`),!e&&this.connectionMap.size>0)throw new na(`Cannot stop QUICSocket with ${this.connectionMap.size} active connection(s)`);this._closed||this.dispatchEvent(new go),await this._closedP;const{p:r,resolveP:s}=Ga();this._closedP=r,this.resolveClosedP=s,this.removeEventListener(fo.name,this.handleEventQUICSocketError),this.removeEventListener(go.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 Za(r,this.resolveHostname);return s=Ya(s),s=ro(this._host,this._type,s,i,oa),e[t]=s,this.socketSend(...e)}async send_(...e){return this.socketSend(...e)}setServer(e){this.server=e}unsetServer(){delete this.server}};Do([Qn(new ia)],Mo.prototype,"host",null),Do([Qn(new ia)],Mo.prototype,"port",null),Do([Qn(new ia)],Mo.prototype,"type",null),Do([Qn(new ia)],Mo.prototype,"send",null),Do([Qn(new ia)],Mo.prototype,"send_",null),Mo=Do([Kn({eventStart:class extends uo{},eventStarted:class extends uo{},eventStop:class extends uo{},eventStopped:ho})],Mo);const Po=Mo,Lo=new WeakMap;const Ho=function(e,t,r){const s=e.name??e.constructor.name,i=e[t];if(Lo.has(i))throw new TypeError(`\`${s}.${t.toString()}\` redeclares \`@context\` decorator`);Lo.set(i,r)};class Vo extends Zi{static description="Contexts error"}class Ko extends Vo{static description="Aborted due to timer expiration"}const Qo=function(e=!1,t=1/0,r=Ko){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=Lo.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 nn))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 nn(()=>{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 nn&&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 nn(()=>{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 zi((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}},$o=["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,Go={sigalgs:$o,verifyPeer:!0,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:qn.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:qn.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:qn.MAX_CONNECTION_WINDOW,maxStreamWindow:qn.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},jo={sigalgs:$o,verifyPeer:!1,grease:!0,keepAliveIntervalTime:void 0,maxIdleTimeout:0,maxRecvUdpPayloadSize:qn.MAX_DATAGRAM_SIZE,maxSendUdpPayloadSize:qn.MAX_DATAGRAM_SIZE,initialMaxData:10485760,initialMaxStreamDataBidiLocal:1048576,initialMaxStreamDataBidiRemote:1048576,initialMaxStreamDataUni:1048576,initialMaxStreamsBidi:100,initialMaxStreamsUni:100,maxConnectionWindow:qn.MAX_CONNECTION_WINDOW,maxStreamWindow:qn.MAX_STREAM_WINDOW,enableDgram:[!1,0,0],disableActiveMigration:!0,applicationProtos:["quic"],enableEarlyData:!0,readableChunkSize:4096},qo=t(import.meta.url)("stream/web");var zo=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 Wo=Symbol("abort readableP reason");let Jo=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 wi(`${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(Oo.name,o.handleEventQUICStreamError),o.addEventListener(Uo.name,o.handleEventQUICStreamCloseRead,{once:!0}),o.addEventListener(To.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 Ha)throw this.logger.debug(no(t)),t;t instanceof Da||t instanceof Pa?this.dispatchEvent(new Uo({detail:t})):(t instanceof Ma||t instanceof La)&&this.dispatchEvent(new To({detail:t}))};handleEventQUICStreamCloseRead=async()=>{this._readClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[bn]||"destroying"===this[yn]||await this.destroy({force:!1}))};handleEventQUICStreamCloseWrite=async()=>{this._writeClosed=!0,this._readClosed&&this._writeClosed&&(this.resolveClosedP(),this[bn]||"destroying"===this[yn]||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}=Ga();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 qo.ReadableStream({start:this.readableStart.bind(this)}):this.readable=new qo.ReadableStream({start:this.readableStart.bind(this),pull:this.readablePull.bind(this),cancel:this.readableCancel.bind(this)},new qo.CountQueuingStrategy({highWaterMark:1})),"uni"===this.type&&"peer"===this.initiated)this.writable=new qo.WritableStream({start:this.writableStart.bind(this)});else{this.writable=new qo.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===ao(e)){if("StreamLimit"===e.message){const t="bidi"===this.type?s.initialMaxStreamsBidi:s.initialMaxStreamsUni;throw new Va(`Stream limit of ${t} has been reached`,{cause:e})}throw new Ha(`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(Oo.name,this.handleEventQUICStreamError),this.removeEventListener(Uo.name,this.handleEventQUICStreamCloseRead),this.removeEventListener(To.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=oo(e))){const e=this.codeToReason("read",t),r=new Pa("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),this.rejectReadableP?.(e),void this.dispatchEvent(new Oo({detail:r}))}{const t=new Ha("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.rejectReadableP?.(t),this.dispatchEvent(new Oo({detail:t})),t}}if(null===e){const e=new Ha("Failed `streamRecv` on the readable stream");throw this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new Oo({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 Uo),void this.rejectReadableP?.(Wo)}this.resolveReadableP?.()}write(){try{this.connection.conn.streamCapacity(this.streamId)}catch(e){let t;if(!1!==(t=ao(e))){this.connection.conn.streamShutdown(this.streamId,qn.Shutdown.Write,t);const e=this.codeToReason("write",t),r=new La("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),this.rejectWritableP?.(e),void this.dispatchEvent(new Oo({detail:r}))}{const t=new Ha("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.rejectWritableP?.(t),this.dispatchEvent(new Oo({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}=Ga();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=oo(e))){const e=this.codeToReason("read",t),r=new Pa("Peer reset the readable stream",{data:{code:t},cause:e});return this.readableController.error(e),void this.dispatchEvent(new Oo({detail:r}))}{const t=new Ha("Failed `streamRecv` on the readable stream",{cause:e});throw this.readableController.error(t),this.dispatchEvent(new Oo({detail:t})),t}}if(null===e){const e=new Ha("Failed `streamRecv` on the readable stream because it is not readable");throw this.readableController.error(e),this.dispatchEvent(new Oo({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 Uo)),this.dispatchEvent(new No)}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=ao(e))){const e=this.codeToReason("write",t),r=new La("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new Oo({detail:r}))}{const t=new Ha("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new Oo({detail:t})),t}}if(this.dispatchEvent(new No),t<e.byteLength){e=e.subarray(t,e.byteLength);const{p:r,resolveP:s,rejectP:i}=Ga();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=ao(e))){const e=this.codeToReason("write",t),r=new La("Peer stopped the writable stream",{data:{code:t},cause:e});return this.writableController.error(e),void this.dispatchEvent(new Oo({detail:r}))}{const t=new Ha("Local stream writable could not `streamSend`",{cause:e});throw this.writableController.error(t),this.dispatchEvent(new Oo({detail:t})),t}}this.dispatchEvent(new To),this.dispatchEvent(new No)}readableCancel(e){if(this._readClosed)return;const t=this.reasonToCode("read",e);try{this.connection.conn.streamShutdown(this.streamId,qn.Shutdown.Read,t)}catch(r){const e=new Ha("Local stream readable could not be shutdown",{cause:r});throw this.readableController.error(e),this.dispatchEvent(new Oo({detail:e})),e}const r=new Da("Closing readable stream locally",{data:{code:t},cause:e});this.readableController.error(e),this.rejectReadableP?.(e),this.dispatchEvent(new Oo({detail:r})),this.dispatchEvent(new No)}writableAbort(e){if(this._writeClosed)return;const t=this.reasonToCode("write",e);try{this.connection.conn.streamShutdown(this.streamId,qn.Shutdown.Write,t)}catch(r){const e=new Ha("Local stream writable could not be shutdown",{cause:r});throw this.writableController.error(e),this.dispatchEvent(new Oo({detail:e})),e}const r=new Ma("Closing writable stream locally",{data:{code:t},cause:e});this.writableController.error(e),this.rejectWritableP?.(e),this.dispatchEvent(new Oo({detail:r})),this.dispatchEvent(new No)}};zo([Vn(new Na)],Jo.prototype,"meta",null),zo([Vn(new Na,!1,["destroying"])],Jo.prototype,"read",null),zo([Vn(new Na,!1,["destroying"])],Jo.prototype,"write",null),Jo=zo([Hn({eventDestroy:class extends _o{},eventDestroyed:Ro})],Jo);const Yo=Jo;var Xo,Zo,ec,tc,rc;!function(e){e[e.Reno=0]="Reno",e[e.CUBIC=1]="CUBIC",e[e.BBR=2]="BBR"}(Xo||(Xo={})),function(e){e[e.Read=0]="Read",e[e.Write=1]="Write"}(Zo||(Zo={})),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"}(ec||(ec={})),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"}(tc||(tc={})),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"}(rc||(rc={}));var sc=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 ic=class{type;closedP;conn;streamMap=new Map;sendId;logger;socket;config;reasonToCode;codeToReason;recvLock=new un;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(no(t)),t instanceof Ua)throw t;this.dispatchEvent(new ko({detail:t}))};handleEventQUICConnectionClose=async e=>{const t=e.detail;this.secureEstablished||this.rejectSecureEstablishedP(t),t instanceof xa&&await this.send(),this[gn]&&"stopping"!==this[yn]&&await this.stop({force:!0})};handleEventQUICStream=e=>{e.detail instanceof xi&&!(e.detail instanceof No)&&this.dispatchEvent(e.detail.clone())};handleEventQUICStreamSend=async()=>{this[gn]&&await this.send()};handleEventQUICStreamDestroyed=e=>{const t=e.target;t.removeEventListener(No.name,this.handleEventQUICStreamSend),t.removeEventListener(Oi.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 wi(`${this.constructor.name} ${t}`),this.sendId=t.toString(),null!=n.keepAliveIntervalTime&&0!==n.maxIdleTimeout&&n.keepAliveIntervalTime>=n.maxIdleTimeout)throw new ka("`keepAliveIntervalTime` must be less than `maxIdleTimeout`");const d=function(e){if(null!=e.key&&null==e.cert)throw new ra("The cert option must be set when key is set");if(null==e.key&&null!=e.cert)throw new ra("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 ra("The number of keys must match the number of certs");let t,r,s,i;if(null!=e.ca){const r=so(e.ca);t=Ka.encode(r.join(""))}null!=e.key&&(r=so(e.key).map(e=>Ka.encode(e))),null!=e.cert&&(s=so(e.cert).map(e=>Ka.encode(e)));try{i=qn.Config.withBoringSslCtx(e.verifyPeer,null!=e.verifyCallback,t,r,s,e.sigalgs)}catch(e){throw new ra(`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=qn.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=qn.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=so(this.config.cert);this.certDERs=e.map(io)}if(null!=this.config.ca){const e=so(this.config.ca);this.caDERs=e.map(io)}this.reasonToCode=o,this.codeToReason=c,this._remoteHost=i.host,this._remotePort=i.port;const{p:h,resolveP:f,rejectP:g}=Ga();h.catch(()=>{}),this.secureEstablishedP=h,this.resolveSecureEstablishedP=()=>{this.secureEstablished=!0,f()},this.rejectSecureEstablishedP=g;const{p,resolveP:b}=Ga();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 Ea;r.signal.throwIfAborted();const{p:s,rejectP:i}=Ga();s.catch(()=>{});const n=()=>{i(r.signal.reason)};if(r.signal.addEventListener("abort",n),this.addEventListener(Co.name,this.handleEventQUICConnectionError),this.addEventListener(ko.name,this.handleEventQUICConnectionClose,{once:!0}),"client"===this.type)await this.send();else if("server"===this.type){if(null==e||null==t)throw new Ca("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,qn.Shutdown.Read,this.reasonToCode("read",e));for(const t of this.conn.writable())this.conn.streamShutdown(t,qn.Shutdown.Write,this.reasonToCode("write",e));this.conn.close(!1,tc.ApplicationError,Buffer.from(""));const t=this.conn.localError(),r=new xa("Failed to start QUIC connection due to start timeout",{data:t,cause:e});this.dispatchEvent(new Co({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 xa(i,{data:s});this.dispatchEvent(new Co({detail:n}))}await this.closedP,this.removeEventListener(Co.name,this.handleEventQUICConnectionError),this.removeEventListener(ko.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 Ua("Failed connection recv due with unknown error",{cause:e});throw this.dispatchEvent(new Co({detail:t})),t}{let r;return r="TlsFail"===e.message?new Ba("Failed connection due to native TLS verification",{cause:e,data:t}):new xa("Failed connection due to local error",{cause:e,data:t}),void this.dispatchEvent(new Co({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 Ua("Failed connection send with unknown internal error",{cause:e});throw this.dispatchEvent(new Co({detail:t})),t}this.dispatchEvent(new Bo({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 Ba("Failed connection due to custom TLS verification",{data:e});return void this.dispatchEvent(new Co({detail:r}))}this.resolveSecureEstablishedP(),this.processStreams()}if("stopping"!==this[yn]){const e=this.conn.peerError();if(null!=e){const t=`Peer closed with ${e.isApp?"application":"transport"} code ${e.errorCode}`;return void(e.errorCode>=qn.CRYPTO_ERROR_START&&e.errorCode<=qn.CRYPTO_ERROR_STOP?this.dispatchEvent(new Co({detail:new Ra(t,{data:e})})):this.dispatchEvent(new Co({detail:new _a(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:$a("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[gn]||"stopping"===this[yn]){this.conn.streamShutdown(e,Zo.Write,this.reasonToCode("write",wa)),this.conn.streamShutdown(e,Zo.Read,this.reasonToCode("read",wa));continue}this.isStreamUsed(e)&&$a("We should never repeat streamIds when creating streams"),t=Yo.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${Yo.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(No.name,this.handleEventQUICStreamSend),t.addEventListener(Ro.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(Oi.name,this.handleEventQUICStream),this.dispatchEvent(new xo({detail:t}))}t.read()}for(const e of this.conn.writable()){let t=this.streamMap.get(e);if(null==t){if(!1===this[gn]||"stopping"===this[yn]){this.conn.streamShutdown(e,Zo.Write,this.reasonToCode("write",wa)),this.conn.streamShutdown(e,Zo.Read,this.reasonToCode("read",wa));continue}if(this.isStreamUsed(e)){try{this.conn.streamSend(e,new Uint8Array,!1)}catch(e){if(!1!==ao(e))continue;if("FinalSize"===e.message)continue;throw e}$a("We never expect a duplicate stream to be readable")}t=Yo.createQUICStream({initiated:"peer",streamId:e,config:this.config,connection:this,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${Yo.name} ${e}`)}),this.streamMap.set(t.streamId,t),t.addEventListener(No.name,this.handleEventQUICStreamSend),t.addEventListener(Ro.name,this.handleEventQUICStreamDestroyed,{once:!0}),t.addEventListener(Oi.name,this.handleEventQUICStream),this.dispatchEvent(new xo({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 Co({detail:new Oa})));await this.send();const r=this.conn.timeout();null!=r&&(this.connTimeoutTimer=new nn({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 Co({detail:new Oa}))));null==this.connTimeoutTimer||"settled"===this.connTimeoutTimer.status?this.connTimeoutTimer=new nn({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)&&$a("We should never repeat streamIds when creating streams");const r=Yo.createQUICStream({initiated:"local",streamId:t,connection:this,config:this.config,codeToReason:this.codeToReason,reasonToCode:this.reasonToCode,logger:this.logger.getChild(`${Yo.name} ${t}`)});return this.streamMap.set(r.streamId,r),r.addEventListener(No.name,this.handleEventQUICStreamSend),r.addEventListener(Ro.name,this.handleEventQUICStreamDestroyed,{once:!0}),r.addEventListener(Oi.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 nn({delay:e,handler:t,lazy:!0})))};this.keepAliveIntervalTimer=new nn({delay:e,handler:t,lazy:!0})}stopKeepAliveIntervalTimer(){this.keepAliveIntervalTimer?.cancel()}};var nc,ac;sc([Qn(new Sa)],ic.prototype,"connectionIdPeer",null),sc([Qn(new Sa)],ic.prototype,"connectionIdShared",null),sc([Qo(!0,Fo,class extends va{static description="QUIC Connection start timeout"}),(nc=1,ac=Ho,function(e,t){ac(e,t,nc)})],ic.prototype,"start",null),sc([Qn(new Sa,!1,["starting","stopping"])],ic.prototype,"recv",null),sc([Qn(new Sa,!1,["starting","stopping"])],ic.prototype,"send",null),sc([Qn(new Sa)],ic.prototype,"newStream",null),ic=sc([Kn({eventStart:class extends So{},eventStarted:class extends So{},eventStop:class extends So{},eventStopped:Eo})],ic);const oc=ic;var cc=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 lc=class{isSocketShared;reasonToCode;codeToReason;minIdleTimeout;logger;socket;crypto;config;_closed=!1;_closedP;resolveClosedP;stopAbortController;handleEventQUICServerError=e=>{const t=e.detail;if(this.logger.info(no(t)),t instanceof Aa)throw t;this.dispatchEvent(new wo({detail:t}))};handleEventQUICServerClose=async e=>{const t=e.detail;if(!(t instanceof ma||this.isSocketShared)){this.socket.removeEventListener(ho.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new Aa("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new vo({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[gn]&&"stopping"!==this[yn]&&(void 0!==t?await this.stop({isApp:!1,errorCode:tc.InternalError,reason:Buffer.from(t.description),force:!0}):await this.stop({force:!0}))};handleEventQUICSocket=e=>{e.detail instanceof xi&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new ma;this.removeEventListener(Oi.name,this.handleEventQUICSocket),this.dispatchEvent(new vo({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof xi&&!(e.detail instanceof Bo)&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionSend=async e=>{if(this.socket[gn]&&"stopping"!==this.socket[yn])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 mo(`${mo.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new vo({detail:new Aa("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(Bo.name,this.handleEventQUICConnectionSend),t.removeEventListener(Oi.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(t.connectionId)};constructor({crypto:e,config:t,socket:r,resolveHostname:s=Xa,reasonToCode:i,codeToReason:n,minIdleTimeout:a,logger:o}){this.logger=o??new wi(this.constructor.name),this.crypto=e,null==r?(this.socket=new Po({resolveHostname:s,logger:this.logger.getChild(Po.name)}),this.isSocketShared=!1):(this.socket=r,this.isSocketShared=!0),this.config={...jo,...t},this.reasonToCode=i,this.codeToReason=n,this.minIdleTimeout=a;const{p:c,resolveP:l}=Ga();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,co(this.stopAbortController.signal),this.isSocketShared){if(!this.socket[gn])throw new ma;i=to(this.socket.host,this.socket.port),this.logger.info(`Start ${this.constructor.name} on ${i}`)}else i=to(e,t),this.logger.info(`Start ${this.constructor.name} on ${i}`),await this.socket.start({host:e,port:t,reuseAddr:r,ipv6Only:s}),i=to(this.socket.host,this.socket.port);this.socket.setServer(this),this.addEventListener(vo.name,this.handleEventQUICServerError),this.addEventListener(wo.name,this.handleEventQUICServerClose,{once:!0}),this.socket.addEventListener(ho.name,this.handleEventQUICSocketStopped,{once:!0}),this.isSocketShared||this.socket.addEventListener(Oi.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[gn]&&(i=to(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 Ia),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 wo),await this._closedP;const{p:a,resolveP:o}=Ga();this._closedP=a,this.resolveClosedP=o,this.removeEventListener(vo.name,this.handleEventQUICServerError),this.removeEventListener(wo.name,this.handleEventQUICServerClose),this.socket.removeEventListener(ho.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(Oi.name,this.handleEventQUICSocket),this.logger.info(`Stopped ${this.constructor.name}${null!=i?` on ${i}`:""}`)}async acceptConnection(e,t,r,s){if(t.ty!==qn.Type.Initial&&t.ty!==qn.Type.ZeroRTT)return;const i=new Fn(await this.crypto.ops.sign(this.crypto.key,r),0,qn.MAX_CONN_ID_LEN),n=to(e.host,e.port);if(!qn.versionIsSupported(t.version)){const r=Buffer.allocUnsafe(qn.MAX_DATAGRAM_SIZE),s=qn.negotiateVersion(t.scid,t.dcid,r);try{await this.socket.send_(r,0,s,e.port,e.host)}catch(e){throw new ya(`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(qn.MAX_DATAGRAM_SIZE),o=qn.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 ya(`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 oc({type:"server",scid:c,dcid:o,socket:this.socket,remoteInfo:e,config:{...this.config},reasonToCode:this.reasonToCode,codeToReason:this.codeToReason,logger:this.logger.getChild(`${oc.name} ${i.toString()}`)});this.socket.connectionMap.set(l.connectionId,l),l.addEventListener(Bo.name,this.handleEventQUICConnectionSend),l.addEventListener(Eo.name,this.handleEventQUICConnectionStopped,{once:!0}),l.addEventListener(Oi.name,this.handleEventQUICConnection);try{await l.start({data:s,remoteInfo:e},{timer:this.minIdleTimeout,signal:this.stopAbortController?.signal})}catch(e){throw l.removeEventListener(Bo.name,this.handleEventQUICConnectionSend),l.removeEventListener(Eo.name,this.handleEventQUICConnectionStopped),l.removeEventListener(Oi.name,this.handleEventQUICConnection),this.socket.connectionMap.delete(l.connectionId),new ya("Failed to start accepted connection",{cause:e})}return this.dispatchEvent(new Io({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)}};cc([Qn(new ba)],lc.prototype,"host",null),cc([Qn(new ba)],lc.prototype,"port",null),cc([Qn(new ba)],lc.prototype,"acceptConnection",null),lc=cc([Kn({eventStart:class extends Ao{},eventStarted:class extends Ao{},eventStop:class extends Ao{},eventStopped:class extends Ao{}})],lc);const dc=lc;var uc=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 hc=class{static async createQUICClient({host:e,port:t,serverName:r,localHost:s="::",localPort:i=0,socket:n,crypto:a,config:o={},resolveHostname:c=Xa,reuseAddr:l,ipv6Only:d,reasonToCode:u,codeToReason:h,logger:f=new wi(`${this.name}`)},g){let p=to(e,t);f.info(`Create ${this.name} to ${p}`);const b={...Go,...o},m=new ArrayBuffer(qn.MAX_CONN_ID_LEN);await a.ops.randomBytes(m);const y=new Fn(m);let[A,I]=await Za(e,c);const v=eo(t);let w,S;if(A=Ya(A),null==n){const[e]=await Za(s,c),t=eo(i);n=new Po({resolveHostname:c,logger:f.getChild(Po.name)}),w=!1,await n.start({host:e,port:t,reuseAddr:l,ipv6Only:d})}else if(w=!0,!n[gn])throw new ma;try{A=ro(n.host,n.type,A,I,fa)}catch(e){throw w||await n.stop({force:!0}),e}try{S=new oc({type:"client",scid:y,serverName:r??e,socket:n,remoteInfo:{host:A,port:v},config:b,reasonToCode:u,codeToReason:h,logger:f.getChild(`${oc.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(Oi.name,E.handleEventQUICSocket),n.addEventListener(ho.name,E.handleEventQUICSocketStopped,{once:!0}),S.addEventListener(Oi.name,E.handleEventQUICConnection),S.addEventListener(Co.name,E.handleEventQUICConnectionError),S.addEventListener(Bo.name,E.handleEventQUICConnectionSend),S.addEventListener(Eo.name,E.handleEventQUICConnectionStopped,{once:!0}),E.addEventListener(bo.name,E.handleEventQUICClientError),E.addEventListener(yo.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 ha(void 0,{cause:e.detail}))}};E.addEventListener(`${mo.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(ho.name,E.handleEventQUICSocketStopped),w||(n.removeEventListener(Oi.name,E.handleEventQUICSocket),await n.stop({force:!0})),S.removeEventListener(Oi.name,E.handleEventQUICConnection),S.removeEventListener(Co.name,E.handleEventQUICConnectionError),S.removeEventListener(Bo.name,E.handleEventQUICConnectionSend),S.removeEventListener(Eo.name,E.handleEventQUICConnectionStopped),E.removeEventListener(bo.name,E.handleEventQUICClientError),E.removeEventListener(yo.name,E.handleEventQUICClientClose),e}finally{g.signal.removeEventListener("abort",k),E.removeEventListener(`${mo.name}-${S.sendId}`,x)}return p=to(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(no(t)),t instanceof ga||t instanceof Ua)throw t;this.dispatchEvent(new yo({detail:t}))};handleEventQUICClientClose=async e=>{const t=e.detail;if(this.connection.removeEventListener(Co.name,this.handleEventQUICConnectionError),await this.connection.stop({isApp:!1,errorCode:tc.InternalError,reason:Buffer.from(t.description),force:!0}),!(t instanceof ua||this.isSocketShared)){this.socket.removeEventListener(ho.name,this.handleEventQUICSocketStopped);try{await this.socket.stop({force:!0})}catch(e){const t=new ga("Failed to stop QUICSocket",{cause:e});this.dispatchEvent(new bo({detail:t}))}}this._closed=!0,this.resolveClosedP(),this[bn]||"destroying"===this[yn]||await this.destroy({force:!0})};handleEventQUICSocket=e=>{e.detail instanceof xi&&!(e.detail instanceof Bo)&&this.dispatchEvent(e.detail.clone())};handleEventQUICSocketStopped=()=>{const e=new ua;this.removeEventListener(Oi.name,this.handleEventQUICSocket),this.dispatchEvent(new bo({detail:e}))};handleEventQUICConnection=e=>{e.detail instanceof xi&&this.dispatchEvent(e.detail.clone())};handleEventQUICConnectionError=e=>{const t=e.detail;this.dispatchEvent(new bo({detail:t}))};handleEventQUICConnectionSend=async e=>{try{if(!this.socket[gn]||"stopping"===this.socket[yn])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 mo(`${mo.name}-${e.detail.id}`,{detail:t}));break;default:this.dispatchEvent(new bo({detail:new ga("Failed to send data on the QUICSocket",{data:e.detail,cause:t})}))}}};handleEventQUICConnectionStopped=e=>{const t=e.target;t.removeEventListener(Co.name,this.handleEventQUICConnectionError),t.removeEventListener(Bo.name,this.handleEventQUICConnectionSend),t.removeEventListener(Oi.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}=Ga();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[gn]&&(i=to(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(bo.name,this.handleEventQUICClientError),this.removeEventListener(yo.name,this.handleEventQUICClientClose),this.socket.removeEventListener(ho.name,this.handleEventQUICSocketStopped),this.isSocketShared||this.socket.removeEventListener(Oi.name,this.handleEventQUICSocket),this.logger.info(`Destroyed ${this.constructor.name}${null!=i?` to ${i}`:""}`)}};uc([Vn(new da)],hc.prototype,"host",null),uc([Vn(new da)],hc.prototype,"port",null),uc([Vn(new da)],hc.prototype,"localHost",null),uc([Vn(new da)],hc.prototype,"localPort",null),uc([Qo(!0,Fo,class extends la{static description="QUIC Client create timeout"}),function(e,t){return function(r,s){t(r,s,e)}}(1,Ho)],hc,"createQUICClient",null),hc=uc([Hn({eventDestroy:class extends po{},eventDestroyed:class extends po{}})],hc);const fc=hc,gc=t(import.meta.url)("node:crypto");var pc=a.n(gc);class bc{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=bc.toUint8Array(e),s=bc.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 mc="string",yc=/^[0-9a-f\s]+$/i,Ac=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Ic=/^[a-zA-Z0-9-_]+$/;class vc{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=bc.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return decodeURIComponent(escape(r))}}class wc{static toString(e,t=!1){const r=bc.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 Sc{static isHex(e){return typeof e===mc&&yc.test(e)}static isBase64(e){return typeof e===mc&&Ac.test(e)}static isBase64Url(e){return typeof e===mc&&Ic.test(e)}static ToString(e,t="utf8"){const r=bc.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 wc.toString(r,!0);case"utf16":case"utf16be":return wc.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 wc.fromString(e,!0);case"utf16":case"utf16be":return wc.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){const t=bc.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(!Sc.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(!Sc.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=Sc.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return vc.fromString(e);case"utf16":case"utf16be":return wc.fromString(e);case"utf16le":case"usc2":return wc.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=Sc.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return vc.toString(e);case"utf16":case"utf16be":return wc.toString(e);case"utf16le":case"usc2":return wc.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=bc.toUint8Array(e);let r="";for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return r}static ToHex(e){const t=bc.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(!Sc.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 wc.toString(e,t)}static FromUtf16String(e,t=!1){return wc.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 Ec(...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 Cc(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 kc(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 xc(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 Bc(...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 _c(){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=kc(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,kc(n,8)-s}function Rc(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 Oc(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Uc(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 Tc(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)}Sc.DEFAULT_UTF8_ENCODING="utf8",Math.log(2);class Nc{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Uc(this.items)}}const Dc=[new Uint8Array([1])],Mc="0123456789",Pc="name",Lc="valueHexView",Hc="isHexOnly",Vc="idBlock",Kc="tagClass",Qc="tagNumber",$c="isConstructed",Fc="fromBER",Gc="toBER",jc="local",qc="",zc=new ArrayBuffer(0),Wc=new Uint8Array(0),Jc="EndOfContent",Yc="OCTET STRING",Xc="BIT STRING";function Zc(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?bc.toUint8Array(r.valueHex):Wc}fromBER(e,t,r){const s=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!Tc(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",zc)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Sc.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class el{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=qc,warnings:r=[],valueBeforeDecode:s=Wc}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=bc.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Sc.ToHex(this.valueBeforeDecodeView)}}}el.NAME="baseBlock";class tl extends el{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'")}}tl.NAME="valueBlock";class rl extends(Zc(el)){constructor({idBlock:e={}}={}){var t,r,s,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?bc.toUint8Array(e.valueHex):Wc,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",zc}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=xc(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=bc.toUint8Array(e);if(!Tc(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=kc(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}}}rl.NAME="identificationBlock";class sl extends el{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=bc.toUint8Array(e);if(!Tc(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=kc(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=xc(this.length,8);if(s.byteLength>127)return this.error="Too big length",zc;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}}}sl.NAME="lengthBlock";const il={};class nl extends el{constructor({name:e=qc,optional:t=!1,primitiveSchema:r,...s}={},i){super(s),this.name=e,this.optional=t,r&&(this.primitiveSchema=r),this.idBlock=new rl(s),this.lenBlock=new sl(s),this.valueBlock=i?new i(s):new tl(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 Nc;t||al(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?zc: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():Sc.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${Sc.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 al(e){var t;if(e instanceof il.Constructed)for(const t of e.valueBlock.value)al(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}nl.NAME="BaseBlock";class ol extends nl{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=qc,...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}'`}}ol.NAME="BaseStringBlock";class cl extends(Zc(tl)){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}}var 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,$l,Fl;cl.NAME="PrimitiveValueBlock";class Gl extends nl{constructor(e={}){super(e,cl),this.idBlock.isConstructed=!1}}function jl(e,t=0,r=e.length){const s=t;let i=new nl({},tl);const n=new el;if(!Tc(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=nl;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=il.EndOfContent;break;case 1:o=il.Boolean;break;case 2:o=il.Integer;break;case 3:o=il.BitString;break;case 4:o=il.OctetString;break;case 5:o=il.Null;break;case 6:o=il.ObjectIdentifier;break;case 10:o=il.Enumerated;break;case 12:o=il.Utf8String;break;case 13:o=il.RelativeObjectIdentifier;break;case 14:o=il.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:o=il.Sequence;break;case 17:o=il.Set;break;case 18:o=il.NumericString;break;case 19:o=il.PrintableString;break;case 20:o=il.TeletexString;break;case 21:o=il.VideotexString;break;case 22:o=il.IA5String;break;case 23:o=il.UTCTime;break;case 24:o=il.GeneralizedTime;break;case 25:o=il.GraphicString;break;case 26:o=il.VisibleString;break;case 27:o=il.GeneralString;break;case 28:o=il.UniversalString;break;case 29:o=il.CharacterString;break;case 30:o=il.BmpString;break;case 31:o=il.DATE;break;case 32:o=il.TimeOfDay;break;case 33:o=il.DateTime;break;case 34:o=il.Duration;break;default:{const e=i.idBlock.isConstructed?new il.Constructed:new il.Primitive;e.idBlock=i.idBlock,e.lenBlock=i.lenBlock,e.warnings=i.warnings,i=e}}}else o=i.idBlock.isConstructed?il.Constructed:il.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 ql(e){if(!e.byteLength){const e=new nl({},tl);return e.error="Input buffer has zero length",{offset:-1,result:e}}return jl(bc.toUint8Array(e).slice(),0,e.byteLength)}function zl(e,t){return e?1:t}ll=Gl,il.Primitive=ll,Gl.NAME="PRIMITIVE";class Wl extends tl{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const s=bc.toUint8Array(e);if(!Tc(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(;zl(this.isIndefiniteForm,r)>0;){const e=jl(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===Jc)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Jc?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){const r=t||new Nc;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,r);return t?zc:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const t of this.value)e.value.push(t.toJSON());return e}}Wl.NAME="ConstructedValueBlock";class Jl extends nl{constructor(e={}){super(e,Wl),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} :`}}dl=Jl,il.Constructed=dl,Jl.NAME="CONSTRUCTED";class Yl extends tl{fromBER(e,t,r){return t}toBER(e){return zc}}Yl.override="EndOfContentValueBlock";class Xl extends nl{constructor(e={}){super(e,Yl),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}ul=Xl,il.EndOfContent=ul,Xl.NAME=Jc;class Zl extends nl{constructor(e={}){super(e,tl),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}`}}hl=Zl,il.Null=hl,Zl.NAME="NULL";class ed extends(Zc(tl)){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=bc.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,r){const s=bc.toUint8Array(e);return Tc(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,_c.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}ed.NAME="BooleanValueBlock";class td extends nl{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,ed),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}fl=td,il.Boolean=fl,td.NAME="BOOLEAN";class rd extends(Zc(Wl)){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=Wl.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===Jc){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(t!==Yc)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?Wl.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}rd.NAME="OctetStringValueBlock";class sd extends nl{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},rd),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=jl(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?Jl.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${Sc.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 gl&&e.push(t.valueBlock.valueHexView);return bc.concat(e)}}gl=sd,il.OctetString=gl,sd.NAME=Yc;class id extends(Zc(Wl)){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=Wl.prototype.fromBER.call(this,e,t,r),-1===s)return s;for(const e of this.value){const t=e.constructor.NAME;if(t===Jc){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(t!==Xc)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=bc.toUint8Array(e);if(!Tc(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=jl(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 Wl.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return zc;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}}}id.NAME="BitStringValueBlock";class nd extends nl{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},id),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 Jl.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 ad(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=Bc(new Uint8Array([l%10]),n):n[a-d]=l%10;return r[0]>0&&(n=Bc(r,n)),n}function od(e){if(e>=Dc.length)for(let t=Dc.length;t<=e;t++){const e=new Uint8Array([0]);let r=Dc[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=Bc(e,r)),Dc.push(r)}return Dc[e]}function cd(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()}pl=nd,il.BitString=pl,nd.NAME=Xc;class ld extends(Zc(tl)){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=_c.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=xc(r-t,8,s);return new Uint8Array(e)[0]|=128,e}let i=xc(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=cd(od(s),r),n="-"):r=ad(r,od(s))),s++,t>>=1}for(let e=0;e<r.length;e++)r[e]&&(a=!0),a&&(n+=Mc.charAt(r[e]));return!1===a&&(n+=Mc.charAt(0)),n}}bl=ld,ld.NAME="IntegerValueBlock",Object.defineProperty(bl.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class dd extends nl{constructor(e={}){super(e,ld),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Oc(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Oc();const t=BigInt(e),r=new Nc,s=t.toString(16).replace(/^-/,""),i=new Uint8Array(Sc.FromHex(s));if(t<0){const e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;const s=BigInt(`0x${Sc.ToHex(e)}`)+t,n=bc.toUint8Array(Sc.FromHex(s.toString(16)));n[0]|=128,r.write(n)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);return new ml({valueHex:r.final()})}convertToDER(){const e=new ml({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new ml({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}ml=dd,il.Integer=ml,dd.NAME="INTEGER";class ud extends dd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}yl=ud,il.Enumerated=yl,ud.NAME="ENUMERATED";class hd extends(Zc(tl)){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=bc.toUint8Array(e);if(!Tc(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=kc(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Oc();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=xc(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",zc;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=Sc.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}}}hd.NAME="sidBlock";class fd extends tl{constructor({value:e=qc,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new hd;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,zc;t.push(s)}return Uc(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 hd;if(s>Number.MAX_SAFE_INTEGER){Oc();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}}fd.NAME="ObjectIdentifierValueBlock";class gd extends nl{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,fd),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Al=gd,il.ObjectIdentifier=Al,gd.NAME="OBJECT IDENTIFIER";class pd extends(Zc(el)){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,r){if(0===r)return t;const s=bc.toUint8Array(e);if(!Tc(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=kc(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=xc(this.valueDec,7);if(0===t.byteLength)return this.error="Error during encoding SID value",zc;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?Sc.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}pd.NAME="relativeSidBlock";class bd extends tl{constructor({value:e=qc,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,r){let s=t;for(;r>0;){const t=new pd;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,zc;r.push(s)}return Uc(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 pd;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}}bd.NAME="RelativeObjectIdentifierValueBlock";class md extends nl{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,bd),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Il=md,il.RelativeObjectIdentifier=Il,md.NAME="RelativeObjectIdentifier";class yd extends Jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}vl=yd,il.Sequence=vl,yd.NAME="SEQUENCE";class Ad extends Jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}wl=Ad,il.Set=wl,Ad.NAME="SET";class Id extends(Zc(tl)){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=qc}toJSON(){return{...super.toJSON(),value:this.value}}}Id.NAME="StringValueBlock";class vd extends Id{}vd.NAME="SimpleStringValueBlock";class wd extends ol{constructor({...e}={}){super(e,vd)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,bc.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}}wd.NAME="SIMPLE STRING";class Sd extends wd{fromBuffer(e){this.valueBlock.valueHexView=bc.toUint8Array(e);try{this.valueBlock.value=Sc.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=Sc.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Sc.FromUtf8String(e)),this.valueBlock.value=e}}Sd.NAME="Utf8StringValueBlock";class Ed extends Sd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}Sl=Ed,il.Utf8String=Sl,Ed.NAME="UTF8String";class Cd extends wd{fromBuffer(e){this.valueBlock.value=Sc.ToUtf16String(e),this.valueBlock.valueHexView=bc.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Sc.FromUtf16String(e))}}Cd.NAME="BmpStringValueBlock";class kd extends Cd{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}El=kd,il.BmpString=El,kd.NAME="BMPString";class xd extends wd{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=xc(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}}xd.NAME="UniversalStringValueBlock";class Bd extends xd{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Cl=Bd,il.UniversalString=Cl,Bd.NAME="UniversalString";class _d extends wd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}kl=_d,il.NumericString=kl,_d.NAME="NumericString";class Rd extends wd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}xl=Rd,il.PrintableString=xl,Rd.NAME="PrintableString";class Od extends wd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}Bl=Od,il.TeletexString=Bl,Od.NAME="TeletexString";class Ud extends wd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}_l=Ud,il.VideotexString=_l,Ud.NAME="VideotexString";class Td extends wd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}Rl=Td,il.IA5String=Rl,Td.NAME="IA5String";class Nd extends wd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}Ol=Nd,il.GraphicString=Ol,Nd.NAME="GraphicString";class Dd extends wd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}Ul=Dd,il.VisibleString=Ul,Dd.NAME="VisibleString";class Md extends wd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}Tl=Md,il.GeneralString=Tl,Md.NAME="GeneralString";class Pd extends wd{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}Nl=Pd,il.CharacterString=Nl,Pd.NAME="CharacterString";class Ld extends Dd{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,bc.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]=Rc(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Rc(this.month,2),e[2]=Rc(this.day,2),e[3]=Rc(this.hour,2),e[4]=Rc(this.minute,2),e[5]=Rc(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}}}Dl=Ld,il.UTCTime=Dl,Ld.NAME="UTCTime";class Hd extends Ld{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(Rc(this.year,4)),e.push(Rc(this.month,2)),e.push(Rc(this.day,2)),e.push(Rc(this.hour,2)),e.push(Rc(this.minute,2)),e.push(Rc(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(Rc(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}Ml=Hd,il.GeneralizedTime=Ml,Hd.NAME="GeneralizedTime";class Vd extends Ed{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}Pl=Vd,il.DATE=Pl,Vd.NAME="DATE";class Kd extends Ed{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}Ll=Kd,il.TimeOfDay=Ll,Kd.NAME="TimeOfDay";class Qd extends Ed{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}Hl=Qd,il.DateTime=Hl,Qd.NAME="DateTime";class $d extends Ed{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}Vl=$d,il.Duration=Vl,$d.NAME="Duration";class Fd extends Ed{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}Kl=Fd,il.TIME=Kl,Fd.NAME="TIME";class Gd{constructor({name:e=qc,optional:t=!1}={}){this.name=e,this.optional=t}}class jd extends Gd{constructor({value:e=[],...t}={}){super(t),this.value=e}}class qd extends Gd{constructor({value:e=new Gd,local:t=!1,...r}={}){super(r),this.value=e,this.local=t}}class zd{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=bc.toUint8Array(e)}constructor({data:e=Wc}={}){this.dataView=bc.toUint8Array(e)}fromBER(e,t,r){const s=t+r;return this.dataView=bc.toUint8Array(e).subarray(t,s),s}toBER(e){return this.dataView.slice().buffer}}function Wd(e,t,r){if(r instanceof jd){for(const s of r.value)if(Wd(e,t,s).verified)return{verified:!0,result:e};{const e={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(Pc)&&(e.name=r.name),e}}if(r instanceof Gd)return r.hasOwnProperty(Pc)&&(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(Vc 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(Gc 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(Kc))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(Qc))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($c))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(Hc 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(Lc 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,qc),r.name&&(e[r.name]=t)),r instanceof il.Constructed){let s=0,i={verified:!1,result:{error:"Unknown error"}},n=r.valueBlock.value.length;if(n>0&&r.valueBlock.value[0]instanceof qd&&(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,qc),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,qc),r.name&&(delete e[r.name],t.name=r.name)),t}}else if(r.valueBlock.value[0]instanceof qd){if(i=Wd(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,qc),r.name&&delete e[r.name]),i;s++}if(Pc in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let s={};s=jc 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=Wd(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,qc),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,qc),r.name&&(delete e[r.name],t.name=r.name)),t}return{verified:!0,result:e}}if(r.primitiveSchema&&Lc in t.valueBlock){const s=jl(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,qc),r.name&&(delete e[r.name],t.name=r.name)),t}return Wd(e,s.result,r.primitiveSchema)}return{verified:!0,result:e}}function Jd(e,t){if(t instanceof Object==0)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=jl(bc.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:Wd(r.result,r.result,t)}(Fl=Ql||(Ql={}))[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"}($l||($l={}));class Yd{constructor(e,t=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if("number"==typeof e)this.fromNumber(e);else{if(!bc.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=bc.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof nd))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 nd({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new nd({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 Xd{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):bc.isBufferSource(e)?this.buffer=bc.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof sd))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new sd({valueHex:this.buffer})}toSchema(e){return new sd({name:e})}}const Zd={fromASN:e=>e instanceof Zl?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new Zl;const t=ql(e);if(t.result.error)throw new Error(t.result.error);return t.result}},eu={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new dd({value:+e})},tu={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new ud({value:e})},ru={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new dd({valueHex:e})},su={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new nd({valueHex:e})},iu={fromASN:e=>e.valueBlock.toString(),toASN:e=>new gd({value:e})},nu={fromASN:e=>e.valueBlock.value,toASN:e=>new td({value:e})},au={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new sd({valueHex:e})},ou={fromASN:e=>new Xd(e.getValue()),toASN:e=>e.toASN()};function cu(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}const lu=cu(Ed),du=cu(kd),uu=cu(Bd),hu=cu(_d),fu=cu(Rd),gu=cu(Od),pu=cu(Ud),bu=cu(Td),mu=cu(Nd),yu=cu(Dd),Au=cu(Md),Iu=cu(Pd),vu={fromASN:e=>e.toDate(),toASN:e=>new Ld({valueDate:e})},wu={fromASN:e=>e.toDate(),toASN:e=>new Hd({valueDate:e})},Su={fromASN:()=>null,toASN:()=>new Zl};function Eu(e){switch(e){case $l.Any:return Zd;case $l.BitString:return su;case $l.BmpString:return du;case $l.Boolean:return nu;case $l.CharacterString:return Iu;case $l.Enumerated:return tu;case $l.GeneralString:return Au;case $l.GeneralizedTime:return wu;case $l.GraphicString:return mu;case $l.IA5String:return bu;case $l.Integer:return eu;case $l.Null:return Su;case $l.NumericString:return hu;case $l.ObjectIdentifier:return iu;case $l.OctetString:return au;case $l.PrintableString:return fu;case $l.TeletexString:return gu;case $l.UTCTime:return vu;case $l.UniversalString:return uu;case $l.Utf8String:return lu;case $l.VideotexString:return pu;case $l.VisibleString:return yu;default:return null}}function Cu(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||Cu(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function ku(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||ku(r)}return!1}function xu(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 Bu=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:Ql.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=$l[i.type],t=o[e];if(!t)throw new Error(`Cannot get ASN1 class by name '${e}'`);a=new t({name:n})}else Cu(i.type)?a=(new i.type).toSchema(n):i.optional?this.get(i.type).type===Ql.Choice?a=new Gd({name:n}):(a=this.create(i.type,!1),a.name=n):a=new Gd({name:n});const c=!!i.optional||void 0!==i.defaultValue;if(i.repeated&&(a.name="",a=new("set"===i.repeated?Ad:yd)({name:"",value:[new qd({name:n,value:a})]})),null!==i.context&&void 0!==i.context)if(i.implicit)if("number"==typeof i.type||Cu(i.type)){const e=i.repeated?Jl:Gl;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 Jl({name:e?"":n,optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:t}))}else s.push(new Jl({optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:[a]}));else a.optional=c,s.push(a)}switch(r.type){case Ql.Sequence:return new yd({value:s,name:""});case Ql.Set:return new Ad({value:s,name:""});case Ql.Choice:return new jd({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}},_u=e=>t=>{let r;Bu.has(t)?r=Bu.get(t):(r=Bu.createDefault(t),Bu.set(t,r)),Object.assign(r,e)},Ru=e=>(t,r)=>{let s;Bu.has(t.constructor)?s=Bu.get(t.constructor):(s=Bu.createDefault(t.constructor),Bu.set(t.constructor,s));const i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){const s=Eu(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 Ou extends Error{constructor(){super(...arguments),this.schemas=[]}}class Uu{static parse(e,t){const r=ql(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(Cu(t))return(new t).fromASN(e);const s=Bu.get(t);Bu.cache(t);let i=s.schema;if(e.constructor===Jl&&s.type!==Ql.Choice){i=new Jl({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:s.schema.valueBlock.value});for(const t in s.items)delete e[t]}const n=Wd({},e,i);if(!n.verified)throw new Ou(`Data does not match to ${t.name} ASN1 schema. ${n.result.error}`);const a=new t;if(ku(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=Eu(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||Cu(c)){const s=null!==(r=i.converter)&&void 0!==r?r:Cu(c)?new c:null;if(!s)throw new Error("Converter is empty");if(i.repeated)if(i.implicit){const r=new("sequence"===i.repeated?yd:Ad);r.valueBlock=t.valueBlock;const n=ql(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(Cu(c))e=(new c).toSchema("");else{const t=$l[c],r=o[t];if(!r)throw new Error(`Cannot get '${t}' class from asn1js module`);e=new r}e.valueBlock=r.valueBlock,r=ql(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 Ou&&e.schemas.push(t.name),e}}}class Tu{static serialize(e){return e instanceof nl?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&"object"==typeof e&&Cu(e))return e.toASN();if(!e||"object"!=typeof e)throw new TypeError("Parameter 1 should be type of Object.");const t=e.constructor,r=Bu.get(t);Bu.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=Eu(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&&xu(this.serialize(n.defaultValue),this.serialize(a)))continue;const o=Tu.toAsnItem(n,s,t,a);if("number"==typeof n.context)if(n.implicit)if(n.repeated||"number"!=typeof n.type&&!Cu(n.type))i.push(new Jl({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:o.valueBlock.value}));else{const e={};e.valueHex=o instanceof Zl?o.valueBeforeDecodeView:o.valueBlock.toBER(),i.push(new Gl({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},...e}))}else i.push(new Jl({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 Ql.Sequence:s=new yd({value:i});break;case Ql.Set:s=new Ad({value:i});break;case Ql.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 ${$l[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?yd:Ad)({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?yd:Ad)({value:t})}else i=this.toASN(s);return i}}class Nu extends Array{constructor(e=[]){if("number"==typeof e)super(e);else{super();for(const t of e)this.push(t)}}}class Du{static serialize(e){return Tu.serialize(e)}static parse(e,t){return Uu.parse(e,t)}static toString(e){const t=ql(bc.isBufferSource(e)?bc.toArrayBuffer(e):Du.serialize(e));if(-1===t.offset)throw new Error(`Cannot decode ASN.1 data. ${t.result.error}`);return t.result.toString()}}function Mu(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 Pu extends Error{constructor(e,t){super(t?`${e}. See the inner exception for more details.`:e),this.message=e,this.innerError=t}}class Lu extends Pu{constructor(e,t,r){super(t,r),this.schema=e}}class Hu extends Lu{constructor(e,t,r){super(e,`JSON doesn't match to '${e.target.name}' schema. ${t}`,r)}}class Vu extends Pu{}class Ku extends Pu{constructor(e,t,r){super(`Cannot serialize by '${e}' schema. ${t}`,r),this.schemaName=e}}class Qu extends Hu{constructor(e,t,r={}){super(e,"Some keys doesn't match to schema"),this.keys=t,this.errors=r}}var $u;function Fu(e,t){if(!function(e,t){switch(t){case $u.Boolean:return"boolean"==typeof e;case $u.Number:return"number"==typeof e;case $u.String:return"string"==typeof e}return!0}(e,t))throw new TypeError(`Value must be ${$u[t]}`)}function Gu(e){return e&&e.prototype?!(!e.prototype.toJSON||!e.prototype.fromJSON)||Gu(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"}($u||($u={}));const ju="default",qu=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 zu{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 Vu("Incoming value must be string");if(!t.exec(e))throw new Vu(`Value doesn't match to pattern '${t.toString()}'`)}}class Wu{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(Fu(e,$u.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 Vu(`Value doesn't match to diapason [${e},${t}]`)}}}class Ju{constructor(e=Number.MIN_VALUE,t=Number.MAX_VALUE){this.min=e,this.max=t}validate(e){if(Fu(e,$u.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 Vu(`Value doesn't match to diapason (${e},${t})`)}}}class Yu{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 Vu(`Value length must be more than ${this.minLength}.`);if(void 0!==this.maxLength&&e.length>this.maxLength)throw new Vu(`Value length must be less than ${this.maxLength}.`)}else if(e.length!==this.length)throw new Vu(`Value length must be exactly ${this.length}.`)}}class Xu{constructor(e){this.enumeration=e}validate(e){if(Fu(e,$u.String),!this.enumeration.includes(e))throw new Vu(`Value must be one of ${this.enumeration.map(e=>`'${e}'`).join(", ")}`)}}class Zu{static checkValues(e,t){const r=Array.isArray(e)?e:[e];for(const s of r)for(const r of t.validations)r instanceof Yu&&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=ju){return{...e.names[ju],...e.names[t]}}}class eh extends Zu{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||ju;if(Gu(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&&!qu.has(s))throw new Pu("Cannot get schema for `targetSchema` param");if(s=s||e.constructor,qu.has(s)){const t=qu.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 Ku(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 Ku?e:new Ku(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 th extends Zu{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||ju,i=new r;if(Gu(i))return i.fromJSON(e);const n=qu.get(r),a=this.getSchemaByName(n,s),o={};t.strictProperty&&!Array.isArray(e)&&th.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 Hu(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 Hu||(e=new Hu(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 Qu(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 Qu(r,n)}}const rh=(e={})=>(t,r)=>{const s=`Cannot set type for ${r} property of ${t.constructor.name} schema`;let i;qu.has(t.constructor)?(i=qu.get(t.constructor),i.target!==t.constructor&&(i=qu.create(t.constructor),qu.set(t.constructor,i))):(i=qu.create(t.constructor),qu.set(t.constructor,i));const n={type:$u.Any,validations:[]},a=Object.assign(n,e);if(a.validations=function(e){const t=[];return e.pattern&&t.push(new zu(e.pattern)),e.type!==$u.Number&&e.type!==$u.Any||(void 0===e.minInclusive&&void 0===e.maxInclusive||t.push(new Wu(e.minInclusive,e.maxInclusive)),void 0===e.minExclusive&&void 0===e.maxExclusive||t.push(new Ju(e.minExclusive,e.maxExclusive)),void 0!==e.enumeration&&t.push(new Xu(e.enumeration))),(e.type===$u.String||e.repeated||e.type===$u.Any)&&(void 0===e.length&&void 0===e.minLength&&void 0===e.maxLength||t.push(new Yu(e.length,e.minLength,e.maxLength))),t}(a),"number"!=typeof a.type&&!qu.has(a.type)&&!Gu(a.type))throw new Error(`${s}. Assigning type doesn't have schema.`);let o;o=Array.isArray(e.schema)?e.schema:[e.schema||ju];for(const e of o)i.names[e]||(i.names[e]={}),i.names[e][r]=a};class sh extends Error{}class ih extends sh{}class nh extends sh{constructor(e){super("Unsupported operation: "+(e?`${e}`:""))}}class ah extends sh{}class oh extends sh{constructor(e){super(`${e}: Missing required property`)}}class ch{static toArrayBuffer(e){const t=e.replace(/-{5}(BEGIN|END) .*-{5}/g,"").replace("\r","").replace("\n","");return Sc.FromBase64(t)}static toUint8Array(e){const t=this.toArrayBuffer(e);return new Uint8Array(t)}static fromBufferSource(e,t){const r=Sc.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 lh{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 nh("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 nh("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 nh("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 nh("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 nh("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 nh("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 ah("length: Is not multiple of 8")}async onDeriveBits(e,t,r,...s){throw new nh("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 sh("key: Is not extractable")}async onExportKey(e,t,...r){throw new nh("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 nh("importKey")}checkAlgorithmName(e){if(e.name.toLowerCase()!==this.name.toLowerCase())throw new ih("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 sh("key does not match that of operation")}checkRequiredProperty(e,t){if(!(t in e))throw new oh(t)}checkHashAlgorithm(e,t){for(const r of t)if(r.toLowerCase()===e.name.toLowerCase())return;throw new ah(`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(!bc.isBufferSource(t))throw new TypeError("keyData: Is not ArrayBufferView or ArrayBuffer");var r}prepareData(e){return bc.toArrayBuffer(e)}}class dh extends lh{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 uh extends dh{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 hh extends dh{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 ah("length: Must be more than 0")}}class fh extends dh{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 ah("length: Must be more than 0")}}class gh extends dh{constructor(){super(...arguments),this.name="AES-ECB",this.usages=["encrypt","decrypt","wrapKey","unwrapKey"]}}class ph extends dh{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 ah("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 ah("tagLength: Must be one of 32, 64, 96, 104, 112, 120 or 128")}}}class bh extends dh{constructor(){super(...arguments),this.name="AES-KW",this.usages=["wrapKey","unwrapKey"]}}class mh extends lh{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 ah(`algorithm.length: Must be ${this.keySizeBits}`)}checkDerivedKeyParams(e){this.checkGenerateKeyParams(e)}}class yh extends lh{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=Sc.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 Ah extends yh{constructor(){super(...arguments),this.name="RSASSA-PKCS1-v1_5",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class Ih extends yh{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 vh extends yh{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 wh extends lh{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 ah(`namedCurve: Must be one of ${this.namedCurves.join(", ")}`)}}class Sh extends wh{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 Eh=["secret","private","public"];class Ch{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!==Eh.indexOf(e)}get[Symbol.toStringTag](){return"CryptoKey"}}class kh extends wh{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 Ch))throw new TypeError("public: Is not a CryptoKey");if("public"!==e.public.type)throw new ah("public: Is not a public key");if(e.public.algorithm.name!==this.name)throw new ah(`public: Is not ${this.name} key`)}}class xh extends kh{constructor(){super(...arguments),this.name="ECDH-ES",this.namedCurves=["X25519","X448"]}}class Bh extends wh{constructor(){super(...arguments),this.name="EdDSA",this.usages={privateKey:["sign"],publicKey:["verify"]},this.namedCurves=["Ed25519","Ed448"]}}let _h=class{constructor(e){e&&(this.value=e)}};Mu([Ru({type:$l.ObjectIdentifier})],_h.prototype,"value",void 0),_h=Mu([_u({type:Ql.Choice})],_h);class Rh{constructor(e){Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],Rh.prototype,"algorithm",void 0),Mu([Ru({type:$l.Any,optional:!0})],Rh.prototype,"parameters",void 0);class Oh{constructor(){this.version=0,this.privateKeyAlgorithm=new Rh,this.privateKey=new ArrayBuffer(0)}}Mu([Ru({type:$l.Integer})],Oh.prototype,"version",void 0),Mu([Ru({type:Rh})],Oh.prototype,"privateKeyAlgorithm",void 0),Mu([Ru({type:$l.OctetString})],Oh.prototype,"privateKey",void 0),Mu([Ru({type:$l.Any,optional:!0})],Oh.prototype,"attributes",void 0);class Uh{constructor(){this.publicKeyAlgorithm=new Rh,this.publicKey=new ArrayBuffer(0)}}Mu([Ru({type:Rh})],Uh.prototype,"publicKeyAlgorithm",void 0),Mu([Ru({type:$l.BitString})],Uh.prototype,"publicKey",void 0);const Th={fromJSON:e=>Sc.FromBase64Url(e),toJSON:e=>Sc.ToBase64Url(new Uint8Array(e))},Nh={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?Ec(new Uint8Array([0]).buffer,e):e;return new dd({valueHex:t})}};class Dh{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)}}Mu([Ru({type:$l.Integer,converter:eu})],Dh.prototype,"version",void 0),Mu([Ru({type:$l.Integer,converter:Nh}),rh({name:"n",converter:Th})],Dh.prototype,"modulus",void 0),Mu([Ru({type:$l.Integer,converter:Nh}),rh({name:"e",converter:Th})],Dh.prototype,"publicExponent",void 0),Mu([Ru({type:$l.Integer,converter:Nh}),rh({name:"d",converter:Th})],Dh.prototype,"privateExponent",void 0),Mu([Ru({type:$l.Integer,converter:Nh}),rh({name:"p",converter:Th})],Dh.prototype,"prime1",void 0),Mu([Ru({type:$l.Integer,converter:Nh}),rh({name:"q",converter:Th})],Dh.prototype,"prime2",void 0),Mu([Ru({type:$l.Integer,converter:Nh}),rh({name:"dp",converter:Th})],Dh.prototype,"exponent1",void 0),Mu([Ru({type:$l.Integer,converter:Nh}),rh({name:"dq",converter:Th})],Dh.prototype,"exponent2",void 0),Mu([Ru({type:$l.Integer,converter:Nh}),rh({name:"qi",converter:Th})],Dh.prototype,"coefficient",void 0),Mu([Ru({type:$l.Any,optional:!0})],Dh.prototype,"otherPrimeInfos",void 0);class Mh{constructor(){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0)}}Mu([Ru({type:$l.Integer,converter:Nh}),rh({name:"n",converter:Th})],Mh.prototype,"modulus",void 0),Mu([Ru({type:$l.Integer,converter:Nh}),rh({name:"e",converter:Th})],Mh.prototype,"publicExponent",void 0);let Ph=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 sh("Wrong ECPoint. Current version supports only Uncompressed (0x04) point");e=new Uint8Array(this.value.slice(1));const t=e.length/2;return{x:Sc.ToBase64Url(e.buffer.slice(0,0+t)),y:Sc.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=Sc.FromBase64Url(e.x),r=Sc.FromBase64Url(e.y),s=Ec(new Uint8Array([4]).buffer,t,r);return this.value=new Uint8Array(s).buffer,this}};Mu([Ru({type:$l.OctetString})],Ph.prototype,"value",void 0),Ph=Mu([_u({type:Ql.Choice})],Ph);class Lh{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=Sc.FromBase64Url(e.d),"x"in e){const t=new Ph;t.fromJSON(e);const r=Tu.toASN(t);"valueHex"in r.valueBlock&&(this.publicKey=r.valueBlock.valueHex)}return this}toJSON(){const e={};return e.d=Sc.ToBase64Url(this.privateKey),this.publicKey&&Object.assign(e,new Ph(this.publicKey).toJSON()),e}}Mu([Ru({type:$l.Integer,converter:eu})],Lh.prototype,"version",void 0),Mu([Ru({type:$l.OctetString})],Lh.prototype,"privateKey",void 0),Mu([Ru({context:0,type:$l.Any,optional:!0})],Lh.prototype,"parameters",void 0),Mu([Ru({context:1,type:$l.BitString,optional:!0})],Lh.prototype,"publicKey",void 0);const Hh={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 dd({valueHex:e.buffer})}return new dd({valueHex:e})}};var Vh=Object.freeze({__proto__:null,AsnIntegerWithoutPaddingConverter:Hh});class Kh{static decodePoint(e,t){const r=bc.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=bc.toUint8Array(e.x),i=bc.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=bc.toUint8Array(e.r),i=bc.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=bc.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 Qh{constructor(){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0)}static fromWebCryptoSignature(e){const t=e.byteLength/2,r=Kh.decodeSignature(e,8*t),s=new Qh;return s.r=bc.toArrayBuffer(r.r),s.s=bc.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 Kh.encodeSignature(this,e).buffer}}Mu([Ru({type:$l.Integer,converter:Hh})],Qh.prototype,"r",void 0),Mu([Ru({type:$l.Integer,converter:Hh})],Qh.prototype,"s",void 0);class $h extends Oh{}Mu([Ru({context:1,implicit:!0,type:$l.BitString,optional:!0})],$h.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=Sc.FromBase64Url(e.d),this}toJSON(){return{d:Sc.ToBase64Url(this.value)}}};Mu([Ru({type:$l.OctetString})],Fh.prototype,"value",void 0),Fh=Mu([_u({type:Ql.Choice})],Fh);let Gh=class{constructor(e){this.value=new ArrayBuffer(0),e&&(this.value=e)}toJSON(){return{x:Sc.ToBase64Url(this.value)}}fromJSON(e){if(!("x"in e))throw new Error("x: Missing required property");return this.value=Sc.FromBase64Url(e.x),this}};Mu([Ru({type:$l.BitString})],Gh.prototype,"value",void 0),Gh=Mu([_u({type:Ql.Choice})],Gh);let jh=class{};Mu([Ru({type:$l.OctetString}),rh({type:$u.String,converter:Th})],jh.prototype,"d",void 0),jh=Mu([_u({type:Ql.Choice})],jh);const qh="1.2.840.10045.3.1.7",zh="1.3.132.0",Wh=`${zh}.34`,Jh=`${zh}.35`,Yh=`${zh}.10`,Xh="1.3.36.3.3.2.8.1.1",Zh=`${Xh}.1`,ef=`${Xh}.2`,tf=`${Xh}.3`,rf=`${Xh}.4`,sf=`${Xh}.5`,nf=`${Xh}.6`,af=`${Xh}.7`,of=`${Xh}.8`,cf=`${Xh}.9`,lf=`${Xh}.10`,df=`${Xh}.11`,uf=`${Xh}.12`,hf=`${Xh}.13`,ff=`${Xh}.14`;var gf=Object.freeze({__proto__:null,AlgorithmIdentifier:Rh,get CurvePrivateKey(){return jh},EcDsaSignature:Qh,EcPrivateKey:Lh,get EcPublicKey(){return Ph},get EdPrivateKey(){return Fh},get EdPublicKey(){return Gh},get ObjectIdentifier(){return _h},OneAsymmetricKey:$h,PrivateKeyInfo:Oh,PublicKeyInfo:Uh,RsaPrivateKey:Dh,RsaPublicKey:Mh,converters:Vh,idBrainpoolP160r1:Zh,idBrainpoolP160t1:ef,idBrainpoolP192r1:tf,idBrainpoolP192t1:rf,idBrainpoolP224r1:sf,idBrainpoolP224t1:nf,idBrainpoolP256r1:af,idBrainpoolP256t1:of,idBrainpoolP320r1:cf,idBrainpoolP320t1:lf,idBrainpoolP384r1:df,idBrainpoolP384t1:uf,idBrainpoolP512r1:hf,idBrainpoolP512t1:ff,idEd25519:"1.3.101.112",idEd448:"1.3.101.113",idEllipticCurve:zh,idSecp256k1:Yh,idSecp256r1:qh,idSecp384r1:Wh,idSecp521r1:Jh,idVersionOne:Xh,idX25519:"1.3.101.110",idX448:"1.3.101.111"});class pf{constructor(){}static register(e){const t=new _h;t.value=e.id;const r=Du.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}}pf.items=[],pf.names=[],pf.register({name:"P-256",id:qh,size:256}),pf.register({name:"P-384",id:Wh,size:384}),pf.register({name:"P-521",id:Jh,size:521}),pf.register({name:"K-256",id:Yh,size:256}),pf.register({name:"brainpoolP160r1",id:Zh,size:160}),pf.register({name:"brainpoolP160t1",id:ef,size:160}),pf.register({name:"brainpoolP192r1",id:tf,size:192}),pf.register({name:"brainpoolP192t1",id:rf,size:192}),pf.register({name:"brainpoolP224r1",id:sf,size:224}),pf.register({name:"brainpoolP224t1",id:nf,size:224}),pf.register({name:"brainpoolP256r1",id:af,size:256}),pf.register({name:"brainpoolP256t1",id:of,size:256}),pf.register({name:"brainpoolP320r1",id:cf,size:320}),pf.register({name:"brainpoolP320t1",id:lf,size:320}),pf.register({name:"brainpoolP384r1",id:df,size:384}),pf.register({name:"brainpoolP384t1",id:uf,size:384}),pf.register({name:"brainpoolP512r1",id:hf,size:512}),pf.register({name:"brainpoolP512t1",id:ff,size:512});class bf extends lh{constructor(){super(...arguments),this.name="X25519",this.usages={privateKey:["deriveKey","deriveBits"],publicKey:[]}}checkAlgorithmParams(e){this.checkRequiredProperty(e,"public")}}class mf extends lh{constructor(){super(...arguments),this.name="Ed25519",this.usages={privateKey:["sign"],publicKey:["verify"]}}}class yf extends lh{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 Af extends lh{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 If extends lh{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"),!bc.isBufferSource(e.salt))throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");if(this.checkRequiredProperty(e,"info"),!bc.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 vf extends lh{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 wf extends vf{constructor(){super(...arguments),this.name="shake128",this.defaultLength=16}}class Sf extends vf{constructor(){super(...arguments),this.name="shake256",this.defaultLength=32}}class Ef{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=Sc.ToHex(e).toLowerCase();return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}}class Cf{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 kf={jwk:["private","public","secret"],pkcs8:["private"],spki:["public"],raw:["secret","public"]},xf=["pkcs8","spki","raw"];class Bf{constructor(){this.providers=new Cf}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=bc.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=bc.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=bc.toArrayBuffer(i),c=bc.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=bc.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=bc.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),!kf[t])throw new TypeError("Invalid keyFormat argument");if(!kf[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(!xf.includes(t))throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView or JsonWebKey)'");if(!bc.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=Sc.FromUtf8String(e)}const a=this.prepareAlgorithm(s),o=bc.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=bc.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(Sc.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(Bf.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 ih("Unrecognized name");return t}checkCryptoKey(e){if(!(e instanceof Ch))throw new TypeError("Key is not of type 'CryptoKey'")}}const _f=t(import.meta.url)("buffer"),Rf=t(import.meta.url)("crypto");var Of=a.n(Rf);const Uf=t(import.meta.url)("process"),Tf={fromJSON:e=>_f.Buffer.from(Sc.FromBase64Url(e)),toJSON:e=>Sc.ToBase64Url(e)};class Nf extends Ch{constructor(){super(...arguments),this.data=_f.Buffer.alloc(0),this.algorithm={name:""},this.extractable=!1,this.type="secret",this.usages=[],this.kty="oct",this.alg=""}}Mu([rh({name:"ext",type:$u.Boolean,optional:!0})],Nf.prototype,"extractable",void 0),Mu([rh({name:"key_ops",type:$u.String,repeated:!0,optional:!0})],Nf.prototype,"usages",void 0),Mu([rh({type:$u.String})],Nf.prototype,"kty",void 0),Mu([rh({type:$u.String,optional:!0})],Nf.prototype,"alg",void 0);class Df extends Nf{constructor(){super(...arguments),this.kty="oct",this.type="secret"}}class Mf extends Nf{}class Pf extends Df{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 ih("Unsupported algorithm name")}}set alg(e){}}Mu([rh({name:"k",converter:Tf})],Pf.prototype,"data",void 0);class Lf{static async generateKey(e,t,r){const s=new Pf;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=Of().randomBytes(e.length>>3),s}static async exportKey(e,t){if(!(t instanceof Pf))throw new Error("key: Is not AesCryptoKey");switch(e.toLowerCase()){case"jwk":return eh.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new ah("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=th.fromJSON(t,{targetSchema:Pf});break;case"raw":n=new Pf,n.data=_f.Buffer.from(t);break;default:throw new ah("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 ah("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,_f.Buffer.from(r));case"AES-CTR":return this.encryptAesCTR(e,t,_f.Buffer.from(r));case"AES-GCM":return this.encryptAesGCM(e,t,_f.Buffer.from(r));case"AES-KW":return this.encryptAesKW(e,t,_f.Buffer.from(r));case"AES-ECB":return this.encryptAesECB(e,t,_f.Buffer.from(r));default:throw new ah("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof Pf))throw new Error("key: Is not AesCryptoKey");switch(e.name.toUpperCase()){case"AES-CBC":return this.decryptAesCBC(e,t,_f.Buffer.from(r));case"AES-CTR":return this.decryptAesCTR(e,t,_f.Buffer.from(r));case"AES-GCM":return this.decryptAesGCM(e,t,_f.Buffer.from(r));case"AES-KW":return this.decryptAesKW(e,t,_f.Buffer.from(r));case"AES-ECB":return this.decryptAesECB(e,t,_f.Buffer.from(r));default:throw new ah("algorithm: Is not recognized")}}static async encryptAesCBC(e,t,r){const s=Of().createCipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=_f.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCBC(e,t,r){const s=Of().createDecipheriv(`aes-${t.algorithm.length}-cbc`,t.data,new Uint8Array(e.iv));let i=s.update(r);return i=_f.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesCTR(e,t,r){const s=Of().createCipheriv(`aes-${t.algorithm.length}-ctr`,t.data,_f.Buffer.from(e.counter));let i=s.update(r);return i=_f.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesCTR(e,t,r){const s=Of().createDecipheriv(`aes-${t.algorithm.length}-ctr`,t.data,new Uint8Array(e.counter));let i=s.update(r);return i=_f.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesGCM(e,t,r){const s=Of().createCipheriv(`aes-${t.algorithm.length}-gcm`,t.data,_f.Buffer.from(e.iv),{authTagLength:(e.tagLength||128)>>3});e.additionalData&&s.setAAD(_f.Buffer.from(e.additionalData));let i=s.update(r);return i=_f.Buffer.concat([i,s.final(),s.getAuthTag()]),new Uint8Array(i).buffer}static async decryptAesGCM(e,t,r){const s=(e.tagLength||128)>>3,i=Of().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(_f.Buffer.from(e.additionalData)),i.setAuthTag(a);let o=i.update(n);return o=_f.Buffer.concat([o,i.final()]),new Uint8Array(o).buffer}static async encryptAesKW(e,t,r){const s=Of().createCipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=_f.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesKW(e,t,r){const s=Of().createDecipheriv(`id-aes${t.algorithm.length}-wrap`,t.data,this.AES_KW_IV);let i=s.update(r);return i=_f.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptAesECB(e,t,r){const s=Of().createCipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=_f.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptAesECB(e,t,r){const s=Of().createDecipheriv(`aes-${t.algorithm.length}-ecb`,t.data,new Uint8Array(0));let i=s.update(r);return i=_f.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}Lf.AES_KW_IV=_f.Buffer.from("A6A6A6A6A6A6A6A6","hex");const Hf=new WeakMap;function Vf(e){const t=Hf.get(e);if(!t)throw new ah("Cannot get CryptoKey from secure storage");return t}function Kf(e){const t=Ch.create(e.algorithm,e.type,e.extractable,e.usages);return Object.freeze(t),Hf.set(t,e),t}class Qf extends uh{async onGenerateKey(e,t,r){return Kf(await Lf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Lf.encrypt(e,Vf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Lf.decrypt(e,Vf(t),new Uint8Array(r))}async onExportKey(e,t){return Lf.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await Lf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Vf(e)instanceof Pf))throw new TypeError("key: Is not a AesCryptoKey")}}const $f=_f.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Ff=_f.Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,135]),Gf=16;function jf(e){const t=_f.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 qf(e,t){const r=Math.min(e.length,t.length),s=_f.Buffer.alloc(r);for(let i=0;i<r;i++)s[i]=e[i]^t[i];return s}function zf(e,t){const r=Of().createCipheriv("aes"+(e.length<<3),e,$f),s=r.update(t);return r.final(),s}function Wf(e,t){const r=_f.Buffer.alloc(Gf),s=t*Gf,i=s+Gf;return e.copy(r,0,s,i),r}class Jf extends hh{async onGenerateKey(e,t,r){return Kf(await Lf.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=zf(e,$f);let r=jf(t);128&t[0]&&(r=qf(r,Ff));let s=jf(r);return 128&r[0]&&(s=qf(s,Ff)),{subkey1:r,subkey2:s}}(e);let s,i,n=Math.ceil(t.length/Gf);0===n?(n=1,s=!1):s=t.length%Gf===0;const a=n-1;i=s?qf(Wf(t,a),r.subkey1):qf(function(e,t){const r=_f.Buffer.alloc(Gf),s=t*Gf,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=$f;for(let r=0;r<a;r++)o=qf(c,Wf(t,r)),c=zf(e,o);return o=qf(i,c),zf(e,o)}(Vf(t).data,_f.Buffer.from(r));return new Uint8Array(s).buffer}async onVerify(e,t,r,s){const i=await this.sign(e,t,s);return 0===_f.Buffer.from(r).compare(_f.Buffer.from(i))}async onExportKey(e,t){return Lf.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await Lf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Vf(e)instanceof Pf))throw new TypeError("key: Is not a AesCryptoKey")}}class Yf extends fh{async onGenerateKey(e,t,r){return Kf(await Lf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Lf.encrypt(e,Vf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Lf.decrypt(e,Vf(t),new Uint8Array(r))}async onExportKey(e,t){return Lf.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await Lf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Vf(e)instanceof Pf))throw new TypeError("key: Is not a AesCryptoKey")}}class Xf extends ph{async onGenerateKey(e,t,r){return Kf(await Lf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Lf.encrypt(e,Vf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Lf.decrypt(e,Vf(t),new Uint8Array(r))}async onExportKey(e,t){return Lf.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await Lf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Vf(e)instanceof Pf))throw new TypeError("key: Is not a AesCryptoKey")}}class Zf extends bh{async onGenerateKey(e,t,r){return Kf(await Lf.generateKey({name:this.name,length:e.length},t,r))}async onExportKey(e,t){return Lf.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await Lf.importKey(e,t,{name:r.name},s,i))}async onEncrypt(e,t,r){return Lf.encrypt(e,Vf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Lf.decrypt(e,Vf(t),new Uint8Array(r))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Vf(e)instanceof Pf))throw new TypeError("key: Is not a AesCryptoKey")}}class eg extends gh{async onGenerateKey(e,t,r){return Kf(await Lf.generateKey({name:this.name,length:e.length},t,r))}async onEncrypt(e,t,r){return Lf.encrypt(e,Vf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return Lf.decrypt(e,Vf(t),new Uint8Array(r))}async onExportKey(e,t){return Lf.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await Lf.importKey(e,t,{name:r.name},s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Vf(e)instanceof Pf))throw new TypeError("key: Is not a AesCryptoKey")}}class tg extends Df{get alg(){switch(this.algorithm.name.toUpperCase()){case"DES-CBC":return"DES-CBC";case"DES-EDE3-CBC":return"3DES-CBC";default:throw new ih("Unsupported algorithm name")}}set alg(e){}}Mu([rh({name:"k",converter:Tf})],tg.prototype,"data",void 0);class rg{static async generateKey(e,t,r){const s=new tg;return s.algorithm=e,s.extractable=t,s.usages=r,s.data=Of().randomBytes(e.length>>3),s}static async exportKey(e,t){switch(e.toLowerCase()){case"jwk":return eh.toJSON(t);case"raw":return new Uint8Array(t.data).buffer;default:throw new ah("format: Must be 'jwk' or 'raw'")}}static async importKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=th.fromJSON(t,{targetSchema:tg});break;case"raw":n=new tg,n.data=_f.Buffer.from(t);break;default:throw new ah("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,_f.Buffer.from(r));case"DES-EDE3-CBC":return this.encryptDesEDE3CBC(e,t,_f.Buffer.from(r));default:throw new ah("algorithm: Is not recognized")}}static async decrypt(e,t,r){if(!(t instanceof tg))throw new Error("key: Is not DesCryptoKey");switch(e.name.toUpperCase()){case"DES-CBC":return this.decryptDesCBC(e,t,_f.Buffer.from(r));case"DES-EDE3-CBC":return this.decryptDesEDE3CBC(e,t,_f.Buffer.from(r));default:throw new ah("algorithm: Is not recognized")}}static async encryptDesCBC(e,t,r){const s=Of().createCipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=_f.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesCBC(e,t,r){const s=Of().createDecipheriv("des-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=_f.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async encryptDesEDE3CBC(e,t,r){const s=Of().createCipheriv("des-ede3-cbc",t.data,_f.Buffer.from(e.iv));let i=s.update(r);return i=_f.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}static async decryptDesEDE3CBC(e,t,r){const s=Of().createDecipheriv("des-ede3-cbc",t.data,new Uint8Array(e.iv));let i=s.update(r);return i=_f.Buffer.concat([i,s.final()]),new Uint8Array(i).buffer}}class sg extends mh{constructor(){super(...arguments),this.keySizeBits=64,this.ivSize=8,this.name="DES-CBC"}async onGenerateKey(e,t,r){return Kf(await rg.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return rg.encrypt(e,Vf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return rg.decrypt(e,Vf(t),new Uint8Array(r))}async onExportKey(e,t){return rg.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){const n=await rg.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new ah("keyData: Wrong key size");return Kf(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Vf(e)instanceof tg))throw new TypeError("key: Is not a DesCryptoKey")}}class ig extends mh{constructor(){super(...arguments),this.keySizeBits=192,this.ivSize=8,this.name="DES-EDE3-CBC"}async onGenerateKey(e,t,r){return Kf(await rg.generateKey({name:this.name,length:this.keySizeBits},t,r))}async onEncrypt(e,t,r){return rg.encrypt(e,Vf(t),new Uint8Array(r))}async onDecrypt(e,t,r){return rg.decrypt(e,Vf(t),new Uint8Array(r))}async onExportKey(e,t){return rg.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){const n=await rg.importKey(e,t,{name:this.name,length:this.keySizeBits},s,i);if(n.data.length!==this.keySizeBits>>3)throw new ah("keyData: Wrong key size");return Kf(n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Vf(e)instanceof tg))throw new TypeError("key: Is not a DesCryptoKey")}}function ng(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 ah("algorithm: Is not recognized")}}class ag extends Mf{constructor(){super(...arguments),this.type="private"}getKey(){const e=Uu.parse(this.data,gf.PrivateKeyInfo);return Uu.parse(e.privateKey,gf.RsaPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:ng(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,eh.toJSON(e))}fromJSON(e){const t=th.fromJSON(e,{targetSchema:gf.RsaPrivateKey}),r=new gf.PrivateKeyInfo;r.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.privateKeyAlgorithm.parameters=null,r.privateKey=Tu.serialize(t),this.data=_f.Buffer.from(Tu.serialize(r))}}class og extends Mf{constructor(){super(...arguments),this.type="public"}getKey(){const e=Uu.parse(this.data,gf.PublicKeyInfo);return Uu.parse(e.publicKey,gf.RsaPublicKey)}toJSON(){const e=this.getKey(),t={kty:"RSA",alg:ng(this.algorithm),key_ops:this.usages,ext:this.extractable};return Object.assign(t,eh.toJSON(e))}fromJSON(e){const t=th.fromJSON(e,{targetSchema:gf.RsaPublicKey}),r=new gf.PublicKeyInfo;r.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",r.publicKeyAlgorithm.parameters=null,r.publicKey=Tu.serialize(t),this.data=_f.Buffer.from(Tu.serialize(r))}}class cg{static async generateKey(e,t,r){const s=new ag;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new og;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=_f.Buffer.concat([_f.Buffer.alloc(4-e.publicExponent.byteLength,0),_f.Buffer.from(e.publicExponent)]).readInt32BE(0),a=Of().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 eh.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;default:throw new ah("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=th.fromJSON(t,{targetSchema:gf.RsaPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=th.fromJSON(t,{targetSchema:gf.RsaPublicKey});return this.importPublicKey(e,r,s,i)}case"spki":{const e=Uu.parse(new Uint8Array(t),gf.PublicKeyInfo),n=Uu.parse(e.publicKey,gf.RsaPublicKey);return this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=Uu.parse(new Uint8Array(t),gf.PrivateKeyInfo),n=Uu.parse(e.privateKey,gf.RsaPrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new ah("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 ah("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 ah("algorithm: Is not recognized")}}static async encrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.encryptOAEP(e,t,r);throw new ah("algorithm: Is not recognized")}static async decrypt(e,t,r){if("RSA-OAEP"===e.name.toUpperCase())return this.decryptOAEP(e,t,r);throw new ah("algorithm: Is not recognized")}static importPrivateKey(e,t,r,s){const i=new gf.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.privateKeyAlgorithm.parameters=null,i.privateKey=Tu.serialize(e);const n=new ag;return n.data=_f.Buffer.from(Tu.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 gf.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.113549.1.1.1",i.publicKeyAlgorithm.parameters=null,i.publicKey=Tu.serialize(e);const n=new og;return n.data=_f.Buffer.from(Tu.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 ah("algorithm.hash: Is not recognized")}}static signRsa(e,t,r){const s=this.getCryptoAlgorithm(t.algorithm),i=Of().createSign(s);i.update(_f.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=Of().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=Of().createVerify(i);n.update(_f.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=Of().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:Of().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(Of().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:Of().constants.RSA_PKCS1_OAEP_PADDING};return e.label,new Uint8Array(Of().privateDecrypt(s,r)).buffer}}cg.publicKeyUsages=["verify","encrypt","wrapKey"],cg.privateKeyUsages=["sign","decrypt","unwrapKey"];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 cg.generateKey({...e,name:this.name},t,r);return{privateKey:Kf(s.privateKey),publicKey:Kf(s.publicKey)}}async onSign(e,t,r){return cg.sign(e,Vf(t),new Uint8Array(r))}async onVerify(e,t,r,s){return cg.verify(e,Vf(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return cg.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await cg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Vf(e);if(!(r instanceof ag||r instanceof og))throw new TypeError("key: Is not RSA CryptoKey")}}class dg extends Ih{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 cg.generateKey({...e,name:this.name},t,r);return{privateKey:Kf(s.privateKey),publicKey:Kf(s.publicKey)}}async onSign(e,t,r){return cg.sign(e,Vf(t),new Uint8Array(r))}async onVerify(e,t,r,s){return cg.verify(e,Vf(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return cg.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await cg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Vf(e);if(!(r instanceof ag||r instanceof og))throw new TypeError("key: Is not RSA CryptoKey")}}class ug{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=Of().createHash(r).update(_f.Buffer.from(t)).digest();return new Uint8Array(s).buffer}}class hg extends vh{async onGenerateKey(e,t,r){const s=await cg.generateKey({...e,name:this.name},t,r);return{privateKey:Kf(s.privateKey),publicKey:Kf(s.publicKey)}}async onEncrypt(e,t,r){const s=Vf(t),i=new Uint8Array(r),n=Math.ceil(s.algorithm.modulusLength>>3),a=ug.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=Of().createHash(s.algorithm.hash.name.replace("-","")).update(bc.toUint8Array(e.label||new Uint8Array(0))).digest();u.set(h,0),u[a+c]=1,Of().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=Of().publicEncrypt({key:s.pem,padding:Of().constants.RSA_NO_PADDING},_f.Buffer.from(l));return new Uint8Array(p).buffer}async onDecrypt(e,t,r){const s=Vf(t),i=Math.ceil(s.algorithm.modulusLength>>3),n=ug.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=Of().privateDecrypt({key:s.pem,padding:Of().constants.RSA_NO_PADDING},_f.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=Of().createHash(s.algorithm.hash.name.replace("-","")).update(bc.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 cg.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await cg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Vf(e);if(!(r instanceof ag||r instanceof og))throw new TypeError("key: Is not RSA CryptoKey")}mgf1(e,t,r=0){const s=ug.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=Of().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 fg extends lh{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 cg.generateKey({...e,name:this.name},t,r);return{privateKey:Kf(s.privateKey),publicKey:Kf(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=Sc.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=Of().publicEncrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onDecrypt(e,t,r){const s=this.toCryptoOptions(t),i=Of().privateDecrypt(s,new Uint8Array(r));return new Uint8Array(i).buffer}async onExportKey(e,t){return cg.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await cg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Vf(e);if(!(r instanceof ag||r instanceof og))throw new TypeError("key: Is not RSA CryptoKey")}toCryptoOptions(e){const t=e.type.toUpperCase();return{key:`-----BEGIN ${t} KEY-----\n${Vf(e).data.toString("base64")}\n-----END ${t} KEY-----`,padding:Of().constants.RSA_PKCS1_PADDING}}}const gg={"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 pg(e){const t=gg[e];if(!t)throw new ah(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class bg extends Mf{constructor(){super(...arguments),this.type="private"}getKey(){const e=Uu.parse(this.data,gf.PrivateKeyInfo);return Uu.parse(e.privateKey,gf.EcPrivateKey)}toJSON(){const e=this.getKey(),t={kty:"EC",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,eh.toJSON(e))}fromJSON(e){if(!e.crv)throw new ah("Cannot get named curve from JWK. Property 'crv' is required");const t=new gf.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",t.privateKeyAlgorithm.parameters=Tu.serialize(new gf.ObjectIdentifier(pg(e.crv)));const r=th.fromJSON(e,{targetSchema:gf.EcPrivateKey});return t.privateKey=Tu.serialize(r),this.data=_f.Buffer.from(Tu.serialize(t)),this}}class mg extends Mf{constructor(){super(...arguments),this.type="public"}getKey(){const e=Uu.parse(this.data,gf.PublicKeyInfo);return new gf.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,eh.toJSON(e))}fromJSON(e){if(!e.crv)throw new ah("Cannot get named curve from JWK. Property 'crv' is required");const t=th.fromJSON(e,{targetSchema:gf.EcPublicKey}),r=new gf.PublicKeyInfo;return r.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1",r.publicKeyAlgorithm.parameters=Tu.serialize(new gf.ObjectIdentifier(pg(e.crv))),r.publicKey=Tu.toASN(t).valueHex,this.data=_f.Buffer.from(Tu.serialize(r)),this}}class yg extends lh{constructor(){super(...arguments),this.name="SHA-1",this.usages=[]}async onDigest(e,t){return ug.digest(e,t)}}class Ag extends lh{constructor(){super(...arguments),this.name="SHA-256",this.usages=[]}async onDigest(e,t){return ug.digest(e,t)}}class Ig extends lh{constructor(){super(...arguments),this.name="SHA-384",this.usages=[]}async onDigest(e,t){return ug.digest(e,t)}}class vg extends lh{constructor(){super(...arguments),this.name="SHA-512",this.usages=[]}async onDigest(e,t){return ug.digest(e,t)}}class wg extends lh{constructor(){super(...arguments),this.name="SHA3-256",this.usages=[]}async onDigest(e,t){return ug.digest(e,t)}}class Sg extends lh{constructor(){super(...arguments),this.name="SHA3-384",this.usages=[]}async onDigest(e,t){return ug.digest(e,t)}}class Eg extends lh{constructor(){super(...arguments),this.name="SHA3-512",this.usages=[]}async onDigest(e,t){return ug.digest(e,t)}}class Cg{static async generateKey(e,t,r){const s=new bg;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new mg;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=Of().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=ug.getAlgorithmName(e.hash),i=Of().createSign(s);i.update(_f.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=Uu.parse(a,gf.EcDsaSignature);return Kh.encodeSignature(o,pf.get(t.algorithm.namedCurve).size).buffer}static async verify(e,t,r,s){const i=ug.getAlgorithmName(e.hash),n=Of().createVerify(i);n.update(_f.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 gf.EcDsaSignature,c=pf.get(t.algorithm.namedCurve),l=Kh.decodeSignature(r,c.size);o.r=bc.toArrayBuffer(l.r),o.s=bc.toArrayBuffer(l.s);const d=_f.Buffer.from(Tu.serialize(o));return n.verify(a,d)}static async deriveBits(e,t,r){const s=this.getOpenSSLNamedCurve(t.algorithm.namedCurve),i=Of().createECDH(s),n=Uu.parse(t.data,gf.PrivateKeyInfo),a=Uu.parse(n.privateKey,gf.EcPrivateKey);i.setPrivateKey(_f.Buffer.from(a.privateKey));const o=Uu.parse(e.public.data,gf.PublicKeyInfo),c=i.computeSecret(_f.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 eh.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return Uu.parse(t.data,gf.PublicKeyInfo).publicKey;default:throw new ah("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=th.fromJSON(t,{targetSchema:gf.EcPrivateKey});return this.importPrivateKey(e,r,s,i)}{const e=th.fromJSON(t,{targetSchema:gf.EcPublicKey});return this.importPublicKey(e,r,s,i)}case"raw":{const e=new gf.EcPublicKey(t);return this.importPublicKey(e,r,s,i)}case"spki":{const e=Uu.parse(new Uint8Array(t),gf.PublicKeyInfo),n=new gf.EcPublicKey(e.publicKey);return this.assertKeyParameters(e.publicKeyAlgorithm.parameters,r.namedCurve),this.importPublicKey(n,r,s,i)}case"pkcs8":{const e=Uu.parse(new Uint8Array(t),gf.PrivateKeyInfo),n=Uu.parse(e.privateKey,gf.EcPrivateKey);return this.assertKeyParameters(e.privateKeyAlgorithm.parameters,r.namedCurve),this.importPrivateKey(n,r,s,i)}default:throw new ah("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static assertKeyParameters(e,t){if(!e)throw new sh("Key info doesn't have required parameters");let r="";try{r=Uu.parse(e,gf.ObjectIdentifier).value}catch(e){throw new sh("Cannot read key info parameters")}if(pg(t)!==r)throw new sh("Key info parameter doesn't match to named curve")}static async importPrivateKey(e,t,r,s){const i=new gf.PrivateKeyInfo;i.privateKeyAlgorithm.algorithm="1.2.840.10045.2.1",i.privateKeyAlgorithm.parameters=Tu.serialize(new gf.ObjectIdentifier(pg(t.namedCurve))),i.privateKey=Tu.serialize(e);const n=new bg;return n.data=_f.Buffer.from(Tu.serialize(i)),n.algorithm=Object.assign({},t),n.extractable=r,n.usages=s,n}static async importPublicKey(e,t,r,s){const i=new gf.PublicKeyInfo;i.publicKeyAlgorithm.algorithm="1.2.840.10045.2.1";const n=pg(t.namedCurve);i.publicKeyAlgorithm.parameters=Tu.serialize(new gf.ObjectIdentifier(n)),i.publicKey=e.value;const a=new mg;return a.data=_f.Buffer.from(Tu.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}}}Cg.publicKeyUsages=["verify"],Cg.privateKeyUsages=["sign","deriveKey","deriveBits"];class kg extends Sh{constructor(){super(...arguments),this.namedCurves=pf.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 Cg.generateKey({...e,name:this.name},t,r);return{privateKey:Kf(s.privateKey),publicKey:Kf(s.publicKey)}}async onSign(e,t,r){return Cg.sign(e,Vf(t),new Uint8Array(r))}async onVerify(e,t,r,s){return Cg.verify(e,Vf(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return Cg.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await Cg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Vf(e);if(!(r instanceof bg||r instanceof mg))throw new TypeError("key: Is not EC CryptoKey")}}class xg extends kh{constructor(){super(...arguments),this.namedCurves=pf.names}async onGenerateKey(e,t,r){const s=await Cg.generateKey({...e,name:this.name},t,r);return{privateKey:Kf(s.privateKey),publicKey:Kf(s.publicKey)}}async onExportKey(e,t){return Cg.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await Cg.importKey(e,t,{...r,name:this.name},s,i))}checkCryptoKey(e,t){super.checkCryptoKey(e,t);const r=Vf(e);if(!(r instanceof bg||r instanceof mg))throw new TypeError("key: Is not EC CryptoKey")}async onDeriveBits(e,t,r){return await Cg.deriveBits({...e,public:Vf(e.public)},Vf(t),r)}}const Bg={[gf.idEd448]:"Ed448",ed448:gf.idEd448,[gf.idX448]:"X448",x448:gf.idX448,[gf.idEd25519]:"Ed25519",ed25519:gf.idEd25519,[gf.idX25519]:"X25519",x25519:gf.idX25519};function _g(e){const t=Bg[e.toLowerCase()];if(!t)throw new ah(`Cannot convert WebCrypto named curve '${e}' to OID`);return t}class Rg extends Mf{constructor(){super(...arguments),this.type="private"}getKey(){const e=Uu.parse(this.data,gf.PrivateKeyInfo);return Uu.parse(e.privateKey,gf.CurvePrivateKey)}toJSON(){const e=this.getKey(),t={kty:"OKP",crv:this.algorithm.namedCurve,key_ops:this.usages,ext:this.extractable};return Object.assign(t,eh.toJSON(e))}fromJSON(e){if(!e.crv)throw new ah("Cannot get named curve from JWK. Property 'crv' is required");const t=new gf.PrivateKeyInfo;t.privateKeyAlgorithm.algorithm=_g(e.crv);const r=th.fromJSON(e,{targetSchema:gf.CurvePrivateKey});return t.privateKey=Tu.serialize(r),this.data=_f.Buffer.from(Tu.serialize(t)),this}}class Og extends Mf{constructor(){super(...arguments),this.type="public"}getKey(){return Uu.parse(this.data,gf.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:Sc.ToBase64Url(e)})}fromJSON(e){if(!e.crv)throw new ah("Cannot get named curve from JWK. Property 'crv' is required");if(!e.x)throw new ah("Cannot get property from JWK. Property 'x' is required");const t=new gf.PublicKeyInfo;return t.publicKeyAlgorithm.algorithm=_g(e.crv),t.publicKey=Sc.FromBase64Url(e.x),this.data=_f.Buffer.from(Tu.serialize(t)),this}}class Ug{static async generateKey(e,t,r){const s=new Rg;s.algorithm=e,s.extractable=t,s.usages=r.filter(e=>-1!==this.privateKeyUsages.indexOf(e));const i=new Og;i.algorithm=e,i.extractable=!0,i.usages=r.filter(e=>-1!==this.publicKeyUsages.indexOf(e));const n=e.namedCurve.toLowerCase(),a=Of().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=Of().sign(null,_f.Buffer.from(r),s);return bc.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 Of().verify(null,_f.Buffer.from(s),i,_f.Buffer.from(r))}static async deriveBits(e,t,r){const s=Of().createPublicKey({key:e.public.data,format:"der",type:"spki"}),i=Of().createPrivateKey({key:t.data,format:"der",type:"pkcs8"}),n=Of().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 eh.toJSON(t);case"pkcs8":case"spki":return new Uint8Array(t.data).buffer;case"raw":return Uu.parse(t.data,gf.PublicKeyInfo).publicKey;default:throw new ah("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=th.fromJSON(t,{targetSchema:gf.CurvePrivateKey});return this.importPrivateKey(e,r,s,i)}if(!e.x)throw new TypeError("keyData: Cannot get required 'x' filed");return this.importPublicKey(Sc.FromBase64Url(e.x),r,s,i)}case"raw":return this.importPublicKey(t,r,s,i);case"spki":{const e=Uu.parse(new Uint8Array(t),gf.PublicKeyInfo);return this.importPublicKey(e.publicKey,r,s,i)}case"pkcs8":{const e=Uu.parse(new Uint8Array(t),gf.PrivateKeyInfo),n=Uu.parse(e.privateKey,gf.CurvePrivateKey);return this.importPrivateKey(n,r,s,i)}default:throw new ah("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'")}}static importPrivateKey(e,t,r,s){const i=new Rg;return i.fromJSON({crv:t.namedCurve,d:Sc.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 Og;return i.fromJSON({crv:t.namedCurve,x:Sc.ToBase64Url(e)}),i.algorithm=Object.assign({},t),i.extractable=r,i.usages=s,i}}Ug.publicKeyUsages=["verify"],Ug.privateKeyUsages=["sign","deriveKey","deriveBits"];class Tg extends Bh{async onGenerateKey(e,t,r){const s=await Ug.generateKey({name:this.name,namedCurve:e.namedCurve.replace(/^ed/i,"Ed")},t,r);return{privateKey:Kf(s.privateKey),publicKey:Kf(s.publicKey)}}async onSign(e,t,r){return Ug.sign(e,Vf(t),new Uint8Array(r))}async onVerify(e,t,r,s){return Ug.verify(e,Vf(t),new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){return Ug.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await Ug.importKey(e,t,{...r,name:this.name},s,i))}}class Ng extends xh{async onGenerateKey(e,t,r){const s=await Ug.generateKey({name:this.name,namedCurve:e.namedCurve.toUpperCase()},t,r);return{privateKey:Kf(s.privateKey),publicKey:Kf(s.publicKey)}}async onDeriveBits(e,t,r){return await Ug.deriveBits({...e,public:Vf(e.public)},Vf(t),r)}async onExportKey(e,t){return Ug.exportKey(e,Vf(t))}async onImportKey(e,t,r,s,i){return Kf(await Ug.importKey(e,t,{...r,name:this.name},s,i))}}class Dg extends Nf{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 Mg extends Dg{constructor(){super(...arguments),this.type="private"}toJWK(){const e=Of().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"}),t=ch.toUint8Array(this.data.toString()),r=Du.parse(t,gf.PrivateKeyInfo),s=Du.parse(r.privateKey,gf.EdPrivateKey).value;return{...super.toJWK(),...e,d:Buffer.from(new Uint8Array(s)).toString("base64url")}}}class Pg extends Dg{constructor(){super(...arguments),this.type="public"}toJWK(){const e=Of().createPublicKey({key:this.data,format:"pem"}).export({format:"jwk"});return{...super.toJWK(),...e}}}class Lg{static async generateKey(e,t,r){const s=e.name.toLowerCase(),i=Of().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 Mg(n,t,a,i.privateKey),publicKey:new Pg(n,!0,o,i.publicKey)}}static async sign(e,t,r){const s=Of().sign(null,Buffer.from(r),t.data);return bc.toArrayBuffer(s)}static async verify(e,t,r,s){return Of().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 ch.toArrayBuffer(t.data.toString());case"raw":{const e=t.toJWK();return Sc.FromBase64Url(e.x)}default:return Promise.reject(new ah("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 gf.EdPrivateKey;t.value=bc.toArrayBuffer(Buffer.from(e.d,"base64url"));const n=new gf.PrivateKeyInfo;n.privateKeyAlgorithm.algorithm="ed25519"===r.name.toLowerCase()?gf.idEd25519:gf.idX25519,n.privateKey=Du.serialize(t);const a=Du.serialize(n),o=ch.fromBufferSource(a,"PRIVATE KEY");return new Mg(r,s,i,o)}if(e.x){const t=Of().createPublicKey({format:"jwk",key:e}).export({format:"pem",type:"spki"});return new Pg(r,s,i,t)}throw new ah("keyData: Cannot import JWK. 'd' or 'x' must be presented")}case"pkcs8":{const e=ch.fromBufferSource(t,"PRIVATE KEY");return new Mg(r,s,i,e)}case"spki":{const e=ch.fromBufferSource(t,"PUBLIC KEY");return new Pg(r,s,i,e)}case"raw":{const e=t,n=Of().createPublicKey({format:"jwk",key:{kty:"OKP",crv:"ed25519"===r.name.toLowerCase()?"Ed25519":"X25519",x:Sc.ToBase64Url(e)}}).export({format:"pem",type:"spki"});return new Pg(r,s,i,n)}default:return Promise.reject(new ah("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"))}}}Lg.privateKeyUsages=["sign","deriveBits","deriveKey"],Lg.publicKeyUsages=["verify"];class Hg extends mf{async onGenerateKey(e,t,r){const s=await Lg.generateKey(e,t,r);return{privateKey:Kf(s.privateKey),publicKey:Kf(s.publicKey)}}async onSign(e,t,r){const s=Vf(t);return Lg.sign(e,s,new Uint8Array(r))}onVerify(e,t,r,s){const i=Vf(t);return Lg.verify(e,i,new Uint8Array(r),new Uint8Array(s))}async onExportKey(e,t){const r=Vf(t);return Lg.exportKey(e,r)}async onImportKey(e,t,r,s,i){return Kf(await Lg.importKey(e,t,r,s,i))}}class Vg extends bf{async onGenerateKey(e,t,r){const s=await Lg.generateKey(e,t,r);return{privateKey:Kf(s.privateKey),publicKey:Kf(s.publicKey)}}async onDeriveBits(e,t,r){const s=Vf(t),i=Vf(e.public),n=Of().createPublicKey({key:i.data.toString(),format:"pem",type:"spki"}),a=Of().createPrivateKey({key:s.data.toString(),format:"pem",type:"pkcs8"}),o=Of().diffieHellman({publicKey:n,privateKey:a});return new Uint8Array(o).buffer.slice(0,r>>3)}async onExportKey(e,t){const r=Vf(t);return Lg.exportKey(e,r)}async onImportKey(e,t,r,s,i){return Kf(await Lg.importKey(e,t,r,s,i))}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Vf(e)instanceof Dg))throw new TypeError("key: Is not a Ed25519CryptoKey")}}class Kg extends Nf{}class Qg extends Af{async onDeriveBits(e,t,r){return new Promise((s,i)=>{const n=bc.toArrayBuffer(e.salt),a=e.hash.name.replace("-","");Of().pbkdf2(Vf(t).data,_f.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 Kg;return e.data=_f.Buffer.from(t),e.algorithm={name:this.name},e.extractable=!1,e.usages=i,Kf(e)}throw new ah("format: Must be 'raw'")}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Vf(e)instanceof Kg))throw new TypeError("key: Is not PBKDF CryptoKey")}}class $g extends Nf{get alg(){return`HS${this.algorithm.hash.name.toUpperCase().replace("SHA-","")}`}set alg(e){}}Mu([rh({name:"k",converter:Tf})],$g.prototype,"data",void 0);class Fg extends yf{async onGenerateKey(e,t,r){const s=(e.length||this.getDefaultLength(e.hash.name))>>3<<3,i=new $g;return i.algorithm={...e,length:s,name:this.name},i.extractable=t,i.usages=r,i.data=Of().randomBytes(s>>3),Kf(i)}async onSign(e,t,r){const s=ug.getAlgorithmName(t.algorithm.hash),i=Of().createHmac(s,Vf(t).data).update(_f.Buffer.from(r)).digest();return new Uint8Array(i).buffer}async onVerify(e,t,r,s){const i=ug.getAlgorithmName(t.algorithm.hash);return 0===Of().createHmac(i,Vf(t).data).update(_f.Buffer.from(s)).digest().compare(_f.Buffer.from(r))}async onImportKey(e,t,r,s,i){let n;switch(e.toLowerCase()){case"jwk":n=th.fromJSON(t,{targetSchema:$g});break;case"raw":n=new $g,n.data=_f.Buffer.from(t);break;default:throw new ah("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,Kf(n)}async onExportKey(e,t){switch(e.toLowerCase()){case"jwk":return eh.toJSON(Vf(t));case"raw":return new Uint8Array(Vf(t).data).buffer;default:throw new ah("format: Must be 'jwk' or 'raw'")}}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Vf(e)instanceof $g))throw new TypeError("key: Is not HMAC CryptoKey")}}class Gg extends Nf{}class jg extends If{async onImportKey(e,t,r,s,i){if("raw"!==e.toLowerCase())throw new ah("Operation not supported");const n=new Gg;return n.data=_f.Buffer.from(t),n.algorithm={name:this.name},n.extractable=s,n.usages=i,Kf(n)}async onDeriveBits(e,t,r){const s=e.hash.name.replace("-",""),i=Of().createHash(s).digest().length,n=r/8,a=bc.toUint8Array(e.info),o=Of().createHmac(s,bc.toUint8Array(e.salt)).update(bc.toUint8Array(Vf(t).data)).digest(),c=[_f.Buffer.alloc(0)],l=Math.ceil(n/i)+1;for(let e=1;e<l;++e)c.push(Of().createHmac(s,o).update(_f.Buffer.concat([c[e-1],a,_f.Buffer.from([e])])).digest());return _f.Buffer.concat(c).slice(0,n)}checkCryptoKey(e,t){if(super.checkCryptoKey(e,t),!(Vf(e)instanceof Gg))throw new TypeError("key: Is not HKDF CryptoKey")}}class qg{static digest(e,t){const r=Of().createHash(e.name.toLowerCase(),{outputLength:e.length}).update(_f.Buffer.from(t)).digest();return new Uint8Array(r).buffer}}class zg extends wf{async onDigest(e,t){return qg.digest(e,t)}}class Wg extends Sf{async onDigest(e,t){return qg.digest(e,t)}}class Jg extends Bf{constructor(){var e;super(),this.providers.set(new Qf),this.providers.set(new Yf),this.providers.set(new Xf),this.providers.set(new Jf),this.providers.set(new Zf),this.providers.set(new eg),Of().getCiphers().includes("des-cbc")&&this.providers.set(new sg),this.providers.set(new ig),this.providers.set(new lg),this.providers.set(new dg),this.providers.set(new hg),this.providers.set(new fg),this.providers.set(new kg),this.providers.set(new xg),this.providers.set(new yg),this.providers.set(new Ag),this.providers.set(new Ig),this.providers.set(new vg),this.providers.set(new Qg),this.providers.set(new Fg),this.providers.set(new jg);const t=null===(e=/^v(\d+)/.exec(Uf.version))||void 0===e?void 0:e[1];t&&parseInt(t,10)>=12&&(this.providers.set(new zg),this.providers.set(new Wg));const r=Of().getHashes();r.includes("sha3-256")&&this.providers.set(new wg),r.includes("sha3-384")&&this.providers.set(new Sg),r.includes("sha3-512")&&this.providers.set(new Eg),t&&parseInt(t,10)>=14&&(this.providers.set(new Tg),this.providers.set(new Ng),this.providers.set(new Hg),this.providers.set(new Vg))}}var Yg,Xg,Zg;a(909);class ep{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(Sc.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 tp=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};Mu([Ru({type:$l.TeletexString})],tp.prototype,"teletexString",void 0),Mu([Ru({type:$l.PrintableString})],tp.prototype,"printableString",void 0),Mu([Ru({type:$l.UniversalString})],tp.prototype,"universalString",void 0),Mu([Ru({type:$l.Utf8String})],tp.prototype,"utf8String",void 0),Mu([Ru({type:$l.BmpString})],tp.prototype,"bmpString",void 0),tp=Mu([_u({type:Ql.Choice})],tp);let rp=class extends tp{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Sc.ToHex(this.anyValue):super.toString())}};Mu([Ru({type:$l.IA5String})],rp.prototype,"ia5String",void 0),Mu([Ru({type:$l.Any})],rp.prototype,"anyValue",void 0),rp=Mu([_u({type:Ql.Choice})],rp);class sp{constructor(e={}){this.type="",this.value=new rp,Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],sp.prototype,"type",void 0),Mu([Ru({type:rp})],sp.prototype,"value",void 0);let ip=Yg=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,Yg.prototype)}};ip=Yg=Mu([_u({type:Ql.Set,itemType:sp})],ip);let np=Xg=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,Xg.prototype)}};np=Xg=Mu([_u({type:Ql.Sequence,itemType:ip})],np);let ap=Zg=class extends np{constructor(e){super(e),Object.setPrototypeOf(this,Zg.prototype)}};ap=Zg=Mu([_u({type:Ql.Sequence})],ap);const op={fromASN:e=>ep.toString(au.fromASN(e)),toASN:e=>au.toASN(ep.fromString(e))};class cp{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],cp.prototype,"typeId",void 0),Mu([Ru({type:$l.Any,context:0})],cp.prototype,"value",void 0);class lp{constructor(e={}){this.partyName=new tp,Object.assign(this,e)}}Mu([Ru({type:tp,optional:!0,context:0,implicit:!0})],lp.prototype,"nameAssigner",void 0),Mu([Ru({type:tp,context:1,implicit:!0})],lp.prototype,"partyName",void 0);let dp=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:cp,context:0,implicit:!0})],dp.prototype,"otherName",void 0),Mu([Ru({type:$l.IA5String,context:1,implicit:!0})],dp.prototype,"rfc822Name",void 0),Mu([Ru({type:$l.IA5String,context:2,implicit:!0})],dp.prototype,"dNSName",void 0),Mu([Ru({type:$l.Any,context:3,implicit:!0})],dp.prototype,"x400Address",void 0),Mu([Ru({type:ap,context:4,implicit:!1})],dp.prototype,"directoryName",void 0),Mu([Ru({type:lp,context:5})],dp.prototype,"ediPartyName",void 0),Mu([Ru({type:$l.IA5String,context:6,implicit:!0})],dp.prototype,"uniformResourceIdentifier",void 0),Mu([Ru({type:$l.OctetString,context:7,implicit:!0,converter:op})],dp.prototype,"iPAddress",void 0),Mu([Ru({type:$l.ObjectIdentifier,context:8,implicit:!0})],dp.prototype,"registeredID",void 0),dp=Mu([_u({type:Ql.Choice})],dp);const up="1.3.6.1.5.5.7",hp=`${up}.3`,fp=`${up}.48`,gp=`${fp}.1`,pp=`${fp}.2`,bp=`${fp}.3`,mp=`${fp}.5`,yp="2.5.29";var Ap;const Ip=`${up}.1.1`;class vp{constructor(e={}){this.accessMethod="",this.accessLocation=new dp,Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],vp.prototype,"accessMethod",void 0),Mu([Ru({type:dp})],vp.prototype,"accessLocation",void 0);let wp=Ap=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,Ap.prototype)}};wp=Ap=Mu([_u({type:Ql.Sequence,itemType:vp})],wp);const Sp=`${yp}.35`;class Ep extends Xd{}class Cp{constructor(e={}){e&&Object.assign(this,e)}}Mu([Ru({type:Ep,context:0,optional:!0,implicit:!0})],Cp.prototype,"keyIdentifier",void 0),Mu([Ru({type:dp,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Cp.prototype,"authorityCertIssuer",void 0),Mu([Ru({type:$l.Integer,context:2,optional:!0,implicit:!0,converter:ru})],Cp.prototype,"authorityCertSerialNumber",void 0);const kp=`${yp}.19`;class xp{constructor(e={}){this.cA=!1,Object.assign(this,e)}}var Bp;Mu([Ru({type:$l.Boolean,defaultValue:!1})],xp.prototype,"cA",void 0),Mu([Ru({type:$l.Integer,optional:!0})],xp.prototype,"pathLenConstraint",void 0);let _p=Bp=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,Bp.prototype)}};var Rp;_p=Bp=Mu([_u({type:Ql.Sequence,itemType:dp})],_p);let Op=Rp=class extends _p{constructor(e){super(e),Object.setPrototypeOf(this,Rp.prototype)}};var Up;Op=Rp=Mu([_u({type:Ql.Sequence})],Op);const Tp=`${yp}.32`;let Np=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};Mu([Ru({type:$l.IA5String})],Np.prototype,"ia5String",void 0),Mu([Ru({type:$l.VisibleString})],Np.prototype,"visibleString",void 0),Mu([Ru({type:$l.BmpString})],Np.prototype,"bmpString",void 0),Mu([Ru({type:$l.Utf8String})],Np.prototype,"utf8String",void 0),Np=Mu([_u({type:Ql.Choice})],Np);class Dp{constructor(e={}){this.organization=new Np,this.noticeNumbers=[],Object.assign(this,e)}}Mu([Ru({type:Np})],Dp.prototype,"organization",void 0),Mu([Ru({type:$l.Integer,repeated:"sequence"})],Dp.prototype,"noticeNumbers",void 0);class Mp{constructor(e={}){Object.assign(this,e)}}Mu([Ru({type:Dp,optional:!0})],Mp.prototype,"noticeRef",void 0),Mu([Ru({type:Np,optional:!0})],Mp.prototype,"explicitText",void 0);let Pp=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:$l.IA5String})],Pp.prototype,"cPSuri",void 0),Mu([Ru({type:Mp})],Pp.prototype,"userNotice",void 0),Pp=Mu([_u({type:Ql.Choice})],Pp);class Lp{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],Lp.prototype,"policyQualifierId",void 0),Mu([Ru({type:$l.Any})],Lp.prototype,"qualifier",void 0);class Hp{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],Hp.prototype,"policyIdentifier",void 0),Mu([Ru({type:Lp,repeated:"sequence",optional:!0})],Hp.prototype,"policyQualifiers",void 0);let Vp=Up=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,Up.prototype)}};Vp=Up=Mu([_u({type:Ql.Sequence,itemType:Hp})],Vp);let Kp=class{constructor(e=0){this.value=e}};Mu([Ru({type:$l.Integer})],Kp.prototype,"value",void 0),Kp=Mu([_u({type:Ql.Choice})],Kp);let Qp=class extends Kp{};var $p;Qp=Mu([_u({type:Ql.Choice})],Qp);const Fp=`${yp}.31`;var Gp;!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"}(Gp||(Gp={}));class jp extends Yd{toJSON(){const e=[],t=this.toNumber();return t&Gp.aACompromise&&e.push("aACompromise"),t&Gp.affiliationChanged&&e.push("affiliationChanged"),t&Gp.cACompromise&&e.push("cACompromise"),t&Gp.certificateHold&&e.push("certificateHold"),t&Gp.cessationOfOperation&&e.push("cessationOfOperation"),t&Gp.keyCompromise&&e.push("keyCompromise"),t&Gp.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&Gp.superseded&&e.push("superseded"),t&Gp.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let qp=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:dp,context:0,repeated:"sequence",implicit:!0})],qp.prototype,"fullName",void 0),Mu([Ru({type:ip,context:1,implicit:!0})],qp.prototype,"nameRelativeToCRLIssuer",void 0),qp=Mu([_u({type:Ql.Choice})],qp);class zp{constructor(e={}){Object.assign(this,e)}}Mu([Ru({type:qp,context:0,optional:!0})],zp.prototype,"distributionPoint",void 0),Mu([Ru({type:jp,context:1,optional:!0,implicit:!0})],zp.prototype,"reasons",void 0),Mu([Ru({type:dp,context:2,optional:!0,repeated:"sequence",implicit:!0})],zp.prototype,"cRLIssuer",void 0);let Wp=$p=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,$p.prototype)}};var Jp;Wp=$p=Mu([_u({type:Ql.Sequence,itemType:zp})],Wp);let Yp=Jp=class extends Wp{constructor(e){super(e),Object.setPrototypeOf(this,Jp.prototype)}};Yp=Jp=Mu([_u({type:Ql.Sequence,itemType:zp})],Yp);class Xp{constructor(e={}){this.onlyContainsUserCerts=Xp.ONLY,this.onlyContainsCACerts=Xp.ONLY,this.indirectCRL=Xp.ONLY,this.onlyContainsAttributeCerts=Xp.ONLY,Object.assign(this,e)}}var Zp;Xp.ONLY=!1,Mu([Ru({type:qp,context:0,optional:!0})],Xp.prototype,"distributionPoint",void 0),Mu([Ru({type:$l.Boolean,context:1,defaultValue:Xp.ONLY,implicit:!0})],Xp.prototype,"onlyContainsUserCerts",void 0),Mu([Ru({type:$l.Boolean,context:2,defaultValue:Xp.ONLY,implicit:!0})],Xp.prototype,"onlyContainsCACerts",void 0),Mu([Ru({type:jp,context:3,optional:!0,implicit:!0})],Xp.prototype,"onlySomeReasons",void 0),Mu([Ru({type:$l.Boolean,context:4,defaultValue:Xp.ONLY,implicit:!0})],Xp.prototype,"indirectCRL",void 0),Mu([Ru({type:$l.Boolean,context:5,defaultValue:Xp.ONLY,implicit:!0})],Xp.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"}(Zp||(Zp={}));let eb=class{constructor(e=Zp.unspecified){this.reason=Zp.unspecified,this.reason=e}toJSON(){return Zp[this.reason]}toString(){return this.toJSON()}};var tb;Mu([Ru({type:$l.Enumerated})],eb.prototype,"reason",void 0),eb=Mu([_u({type:Ql.Choice})],eb);const rb=`${yp}.37`;let sb=tb=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,tb.prototype)}};sb=tb=Mu([_u({type:Ql.Sequence,itemType:$l.ObjectIdentifier})],sb);const ib=`${hp}.1`,nb=`${hp}.2`,ab=`${hp}.3`,ob=`${hp}.4`,cb=`${hp}.8`,lb=`${hp}.9`;let db=class{constructor(e=new ArrayBuffer(0)){this.value=e}};Mu([Ru({type:$l.Integer,converter:ru})],db.prototype,"value",void 0),db=Mu([_u({type:Ql.Choice})],db);let ub=class{constructor(e){this.value=new Date,e&&(this.value=e)}};var hb;Mu([Ru({type:$l.GeneralizedTime})],ub.prototype,"value",void 0),ub=Mu([_u({type:Ql.Choice})],ub);let fb=hb=class extends _p{constructor(e){super(e),Object.setPrototypeOf(this,hb.prototype)}};fb=hb=Mu([_u({type:Ql.Sequence})],fb);const gb=`${yp}.15`;var pb,bb;!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"}(pb||(pb={}));class mb extends Yd{toJSON(){const e=this.toNumber(),t=[];return e&pb.cRLSign&&t.push("crlSign"),e&pb.dataEncipherment&&t.push("dataEncipherment"),e&pb.decipherOnly&&t.push("decipherOnly"),e&pb.digitalSignature&&t.push("digitalSignature"),e&pb.encipherOnly&&t.push("encipherOnly"),e&pb.keyAgreement&&t.push("keyAgreement"),e&pb.keyCertSign&&t.push("keyCertSign"),e&pb.keyEncipherment&&t.push("keyEncipherment"),e&pb.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return`[${this.toJSON().join(", ")}]`}}class yb{constructor(e={}){this.base=new dp,this.minimum=0,Object.assign(this,e)}}Mu([Ru({type:dp})],yb.prototype,"base",void 0),Mu([Ru({type:$l.Integer,context:0,defaultValue:0,implicit:!0})],yb.prototype,"minimum",void 0),Mu([Ru({type:$l.Integer,context:1,optional:!0,implicit:!0})],yb.prototype,"maximum",void 0);let Ab=bb=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,bb.prototype)}};Ab=bb=Mu([_u({type:Ql.Sequence,itemType:yb})],Ab);class Ib{constructor(e={}){Object.assign(this,e)}}Mu([Ru({type:Ab,context:0,optional:!0,implicit:!0})],Ib.prototype,"permittedSubtrees",void 0),Mu([Ru({type:Ab,context:1,optional:!0,implicit:!0})],Ib.prototype,"excludedSubtrees",void 0);class vb{constructor(e={}){Object.assign(this,e)}}var wb;Mu([Ru({type:$l.Integer,context:0,implicit:!0,optional:!0,converter:ru})],vb.prototype,"requireExplicitPolicy",void 0),Mu([Ru({type:$l.Integer,context:1,implicit:!0,optional:!0,converter:ru})],vb.prototype,"inhibitPolicyMapping",void 0);class Sb{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],Sb.prototype,"issuerDomainPolicy",void 0),Mu([Ru({type:$l.ObjectIdentifier})],Sb.prototype,"subjectDomainPolicy",void 0);let Eb=wb=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,wb.prototype)}};var Cb;Eb=wb=Mu([_u({type:Ql.Sequence,itemType:Sb})],Eb);const kb=`${yp}.17`;let xb=Cb=class extends _p{constructor(e){super(e),Object.setPrototypeOf(this,Cb.prototype)}};xb=Cb=Mu([_u({type:Ql.Sequence})],xb);class Bb{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}}var _b;Mu([Ru({type:$l.ObjectIdentifier})],Bb.prototype,"type",void 0),Mu([Ru({type:$l.Any,repeated:"set"})],Bb.prototype,"values",void 0);let Rb=_b=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,_b.prototype)}};Rb=_b=Mu([_u({type:Ql.Sequence,itemType:Bb})],Rb);const Ob=`${yp}.14`;class Ub extends Ep{}class Tb{constructor(e={}){Object.assign(this,e)}}var Nb,Db;Mu([Ru({type:$l.GeneralizedTime,context:0,implicit:!0,optional:!0})],Tb.prototype,"notBefore",void 0),Mu([Ru({type:$l.GeneralizedTime,context:1,implicit:!0,optional:!0})],Tb.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(Nb||(Nb={}));class Mb extends Yd{toJSON(){const e=[],t=this.toNumber();return t&Nb.pKIXCertificate&&e.push("pKIXCertificate"),t&Nb.newExtensions&&e.push("newExtensions"),t&Nb.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class Pb{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new Mb,Object.assign(this,e)}}Mu([Ru({type:$l.GeneralString})],Pb.prototype,"entrustVers",void 0),Mu([Ru({type:Mb})],Pb.prototype,"entrustInfoFlags",void 0);let Lb=Db=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,Db.prototype)}};Lb=Db=Mu([_u({type:Ql.Sequence,itemType:vp})],Lb);class Hb{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof Hb&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Cc(e.parameters,this.parameters)||e.parameters===this.parameters)}}Mu([Ru({type:$l.ObjectIdentifier})],Hb.prototype,"algorithm",void 0),Mu([Ru({type:$l.Any,optional:!0})],Hb.prototype,"parameters",void 0);class Vb{constructor(e={}){this.algorithm=new Hb,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:Hb})],Vb.prototype,"algorithm",void 0),Mu([Ru({type:$l.BitString})],Vb.prototype,"subjectPublicKey",void 0);let Kb=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}};Mu([Ru({type:$l.UTCTime})],Kb.prototype,"utcTime",void 0),Mu([Ru({type:$l.GeneralizedTime})],Kb.prototype,"generalTime",void 0),Kb=Mu([_u({type:Ql.Choice})],Kb);class Qb{constructor(e){this.notBefore=new Kb(new Date),this.notAfter=new Kb(new Date),e&&(this.notBefore=new Kb(e.notBefore),this.notAfter=new Kb(e.notAfter))}}var $b;Mu([Ru({type:Kb})],Qb.prototype,"notBefore",void 0),Mu([Ru({type:Kb})],Qb.prototype,"notAfter",void 0);class Fb{constructor(e={}){this.extnID="",this.critical=Fb.CRITICAL,this.extnValue=new Xd,Object.assign(this,e)}}Fb.CRITICAL=!1,Mu([Ru({type:$l.ObjectIdentifier})],Fb.prototype,"extnID",void 0),Mu([Ru({type:$l.Boolean,defaultValue:Fb.CRITICAL})],Fb.prototype,"critical",void 0),Mu([Ru({type:Xd})],Fb.prototype,"extnValue",void 0);let Gb=$b=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,$b.prototype)}};var jb;Gb=$b=Mu([_u({type:Ql.Sequence,itemType:Fb})],Gb),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(jb||(jb={}));class qb{constructor(e={}){this.version=jb.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new Hb,this.issuer=new ap,this.validity=new Qb,this.subject=new ap,this.subjectPublicKeyInfo=new Vb,Object.assign(this,e)}}Mu([Ru({type:$l.Integer,context:0,defaultValue:jb.v1})],qb.prototype,"version",void 0),Mu([Ru({type:$l.Integer,converter:ru})],qb.prototype,"serialNumber",void 0),Mu([Ru({type:Hb})],qb.prototype,"signature",void 0),Mu([Ru({type:ap})],qb.prototype,"issuer",void 0),Mu([Ru({type:Qb})],qb.prototype,"validity",void 0),Mu([Ru({type:ap})],qb.prototype,"subject",void 0),Mu([Ru({type:Vb})],qb.prototype,"subjectPublicKeyInfo",void 0),Mu([Ru({type:$l.BitString,context:1,implicit:!0,optional:!0})],qb.prototype,"issuerUniqueID",void 0),Mu([Ru({type:$l.BitString,context:2,implicit:!0,optional:!0})],qb.prototype,"subjectUniqueID",void 0),Mu([Ru({type:Gb,context:3,optional:!0})],qb.prototype,"extensions",void 0);class zb{constructor(e={}){this.tbsCertificate=new qb,this.signatureAlgorithm=new Hb,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:qb})],zb.prototype,"tbsCertificate",void 0),Mu([Ru({type:Hb})],zb.prototype,"signatureAlgorithm",void 0),Mu([Ru({type:$l.BitString})],zb.prototype,"signatureValue",void 0);class Wb{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new Kb,Object.assign(this,e)}}Mu([Ru({type:$l.Integer,converter:ru})],Wb.prototype,"userCertificate",void 0),Mu([Ru({type:Kb})],Wb.prototype,"revocationDate",void 0),Mu([Ru({type:Fb,optional:!0,repeated:"sequence"})],Wb.prototype,"crlEntryExtensions",void 0);class Jb{constructor(e={}){this.signature=new Hb,this.issuer=new ap,this.thisUpdate=new Kb,Object.assign(this,e)}}Mu([Ru({type:$l.Integer,optional:!0})],Jb.prototype,"version",void 0),Mu([Ru({type:Hb})],Jb.prototype,"signature",void 0),Mu([Ru({type:ap})],Jb.prototype,"issuer",void 0),Mu([Ru({type:Kb})],Jb.prototype,"thisUpdate",void 0),Mu([Ru({type:Kb,optional:!0})],Jb.prototype,"nextUpdate",void 0),Mu([Ru({type:Wb,repeated:"sequence",optional:!0})],Jb.prototype,"revokedCertificates",void 0),Mu([Ru({type:Fb,optional:!0,context:0,repeated:"sequence"})],Jb.prototype,"crlExtensions",void 0);class Yb{constructor(e={}){this.tbsCertList=new Jb,this.signatureAlgorithm=new Hb,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:Jb})],Yb.prototype,"tbsCertList",void 0),Mu([Ru({type:Hb})],Yb.prototype,"signatureAlgorithm",void 0),Mu([Ru({type:$l.BitString})],Yb.prototype,"signature",void 0);class Xb{constructor(e={}){this.issuer=new ap,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:ap})],Xb.prototype,"issuer",void 0),Mu([Ru({type:$l.Integer,converter:ru})],Xb.prototype,"serialNumber",void 0);let Zb=class{constructor(e={}){Object.assign(this,e)}};var em;Mu([Ru({type:Ub,context:0,implicit:!0})],Zb.prototype,"subjectKeyIdentifier",void 0),Mu([Ru({type:Xb})],Zb.prototype,"issuerAndSerialNumber",void 0),Zb=Mu([_u({type:Ql.Choice})],Zb),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"}(em||(em={}));let tm=class extends Hb{};tm=Mu([_u({type:Ql.Sequence})],tm);let rm=class extends Hb{};rm=Mu([_u({type:Ql.Sequence})],rm);let sm=class extends Hb{};sm=Mu([_u({type:Ql.Sequence})],sm);let im=class extends Hb{};im=Mu([_u({type:Ql.Sequence})],im);let nm=class extends Hb{};nm=Mu([_u({type:Ql.Sequence})],nm);let am=class extends Hb{};am=Mu([_u({type:Ql.Sequence})],am);class om{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}}var cm;Mu([Ru({type:$l.ObjectIdentifier})],om.prototype,"attrType",void 0),Mu([Ru({type:$l.Any,repeated:"set"})],om.prototype,"attrValues",void 0);class lm{constructor(e={}){this.version=em.v0,this.sid=new Zb,this.digestAlgorithm=new tm,this.signatureAlgorithm=new rm,this.signature=new Xd,Object.assign(this,e)}}Mu([Ru({type:$l.Integer})],lm.prototype,"version",void 0),Mu([Ru({type:Zb})],lm.prototype,"sid",void 0),Mu([Ru({type:tm})],lm.prototype,"digestAlgorithm",void 0),Mu([Ru({type:om,repeated:"set",context:0,implicit:!0,optional:!0})],lm.prototype,"signedAttrs",void 0),Mu([Ru({type:rm})],lm.prototype,"signatureAlgorithm",void 0),Mu([Ru({type:Xd})],lm.prototype,"signature",void 0),Mu([Ru({type:om,repeated:"set",context:1,implicit:!0,optional:!0})],lm.prototype,"unsignedAttrs",void 0);let dm=cm=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,cm.prototype)}};dm=cm=Mu([_u({type:Ql.Set,itemType:lm})],dm);let um=class extends Kb{};um=Mu([_u({type:Ql.Choice})],um);let hm=class extends lm{};hm=Mu([_u({type:Ql.Sequence})],hm);class fm{constructor(e={}){this.acIssuer=new dp,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}var gm;Mu([Ru({type:dp})],fm.prototype,"acIssuer",void 0),Mu([Ru({type:$l.Integer})],fm.prototype,"acSerial",void 0),Mu([Ru({type:Bb,repeated:"sequence"})],fm.prototype,"attrs",void 0);let pm=gm=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,gm.prototype)}};pm=gm=Mu([_u({type:Ql.Sequence,itemType:$l.ObjectIdentifier})],pm);class bm{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}}Mu([Ru({type:$l.Integer,optional:!0})],bm.prototype,"pathLenConstraint",void 0),Mu([Ru({type:pm,implicit:!0,context:0,optional:!0})],bm.prototype,"permittedAttrs",void 0),Mu([Ru({type:pm,implicit:!0,context:1,optional:!0})],bm.prototype,"excludedAttrs",void 0),Mu([Ru({type:$l.Boolean,defaultValue:!0})],bm.prototype,"permitUnSpecified",void 0);class mm{constructor(e={}){this.issuer=new _p,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}var ym;Mu([Ru({type:_p})],mm.prototype,"issuer",void 0),Mu([Ru({type:$l.Integer,converter:ru})],mm.prototype,"serial",void 0),Mu([Ru({type:$l.BitString,optional:!0})],mm.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}(ym||(ym={}));class Am{constructor(e={}){this.digestedObjectType=ym.publicKey,this.digestAlgorithm=new Hb,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.Enumerated})],Am.prototype,"digestedObjectType",void 0),Mu([Ru({type:$l.ObjectIdentifier,optional:!0})],Am.prototype,"otherObjectTypeID",void 0),Mu([Ru({type:Hb})],Am.prototype,"digestAlgorithm",void 0),Mu([Ru({type:$l.BitString})],Am.prototype,"objectDigest",void 0);class Im{constructor(e={}){Object.assign(this,e)}}Mu([Ru({type:_p,optional:!0})],Im.prototype,"issuerName",void 0),Mu([Ru({type:mm,context:0,implicit:!0,optional:!0})],Im.prototype,"baseCertificateID",void 0),Mu([Ru({type:Am,context:1,implicit:!0,optional:!0})],Im.prototype,"objectDigestInfo",void 0);let vm=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:dp,repeated:"sequence"})],vm.prototype,"v1Form",void 0),Mu([Ru({type:Im,context:0,implicit:!0})],vm.prototype,"v2Form",void 0),vm=Mu([_u({type:Ql.Choice})],vm);class wm{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}Mu([Ru({type:$l.GeneralizedTime})],wm.prototype,"notBeforeTime",void 0),Mu([Ru({type:$l.GeneralizedTime})],wm.prototype,"notAfterTime",void 0);class Sm{constructor(e={}){Object.assign(this,e)}}var Em,Cm,km;Mu([Ru({type:mm,implicit:!0,context:0,optional:!0})],Sm.prototype,"baseCertificateID",void 0),Mu([Ru({type:_p,implicit:!0,context:1,optional:!0})],Sm.prototype,"entityName",void 0),Mu([Ru({type:Am,implicit:!0,context:2,optional:!0})],Sm.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(Em||(Em={}));class xm{constructor(e={}){this.version=Em.v2,this.holder=new Sm,this.issuer=new vm,this.signature=new Hb,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new wm,this.attributes=[],Object.assign(this,e)}}Mu([Ru({type:$l.Integer})],xm.prototype,"version",void 0),Mu([Ru({type:Sm})],xm.prototype,"holder",void 0),Mu([Ru({type:vm})],xm.prototype,"issuer",void 0),Mu([Ru({type:Hb})],xm.prototype,"signature",void 0),Mu([Ru({type:$l.Integer,converter:ru})],xm.prototype,"serialNumber",void 0),Mu([Ru({type:wm})],xm.prototype,"attrCertValidityPeriod",void 0),Mu([Ru({type:Bb,repeated:"sequence"})],xm.prototype,"attributes",void 0),Mu([Ru({type:$l.BitString,optional:!0})],xm.prototype,"issuerUniqueID",void 0),Mu([Ru({type:Gb,optional:!0})],xm.prototype,"extensions",void 0);class Bm{constructor(e={}){this.acinfo=new xm,this.signatureAlgorithm=new Hb,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:xm})],Bm.prototype,"acinfo",void 0),Mu([Ru({type:Hb})],Bm.prototype,"signatureAlgorithm",void 0),Mu([Ru({type:$l.BitString})],Bm.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"}(Cm||(Cm={}));class _m extends Yd{}class Rm{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier,implicit:!0,context:0})],Rm.prototype,"type",void 0),Mu([Ru({type:$l.Any,implicit:!0,context:1})],Rm.prototype,"value",void 0);class Om{constructor(e={}){this.policyId="",this.classList=new _m(Cm.unclassified),Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],Om.prototype,"policyId",void 0),Mu([Ru({type:_m,defaultValue:new _m(Cm.unclassified)})],Om.prototype,"classList",void 0),Mu([Ru({type:Rm,repeated:"set"})],Om.prototype,"securityCategories",void 0);class Um{constructor(e={}){Object.assign(this,e)}}Mu([Ru({type:Xd})],Um.prototype,"cotets",void 0),Mu([Ru({type:$l.ObjectIdentifier})],Um.prototype,"oid",void 0),Mu([Ru({type:$l.Utf8String})],Um.prototype,"string",void 0);class Tm{constructor(e={}){this.values=[],Object.assign(this,e)}}Mu([Ru({type:_p,implicit:!0,context:0,optional:!0})],Tm.prototype,"policyAuthority",void 0),Mu([Ru({type:Um,repeated:"sequence"})],Tm.prototype,"values",void 0);class Nm{constructor(e={}){this.targetCertificate=new mm,Object.assign(this,e)}}Mu([Ru({type:mm})],Nm.prototype,"targetCertificate",void 0),Mu([Ru({type:dp,optional:!0})],Nm.prototype,"targetName",void 0),Mu([Ru({type:Am,optional:!0})],Nm.prototype,"certDigestInfo",void 0);let Dm=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:dp,context:0,implicit:!0})],Dm.prototype,"targetName",void 0),Mu([Ru({type:dp,context:1,implicit:!0})],Dm.prototype,"targetGroup",void 0),Mu([Ru({type:Nm,context:2,implicit:!0})],Dm.prototype,"targetCert",void 0),Dm=Mu([_u({type:Ql.Choice})],Dm);let Mm=km=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,km.prototype)}};var Pm;Mm=km=Mu([_u({type:Ql.Sequence,itemType:Dm})],Mm);let Lm=Pm=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,Pm.prototype)}};Lm=Pm=Mu([_u({type:Ql.Sequence,itemType:Mm})],Lm);class Hm{constructor(e={}){Object.assign(this,e)}}Mu([Ru({type:_p,implicit:!0,context:0,optional:!0})],Hm.prototype,"roleAuthority",void 0),Mu([Ru({type:dp,implicit:!0,context:1})],Hm.prototype,"roleName",void 0);class Vm{constructor(e={}){this.service=new dp,this.ident=new dp,Object.assign(this,e)}}var Km;Mu([Ru({type:dp})],Vm.prototype,"service",void 0),Mu([Ru({type:dp})],Vm.prototype,"ident",void 0),Mu([Ru({type:Xd,optional:!0})],Vm.prototype,"authInfo",void 0);class Qm{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],Qm.prototype,"otherCertFormat",void 0),Mu([Ru({type:$l.Any})],Qm.prototype,"otherCert",void 0);let $m=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:zb})],$m.prototype,"certificate",void 0),Mu([Ru({type:Bm,context:2,implicit:!0})],$m.prototype,"v2AttrCert",void 0),Mu([Ru({type:Qm,context:3,implicit:!0})],$m.prototype,"other",void 0),$m=Mu([_u({type:Ql.Choice})],$m);let Fm=Km=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,Km.prototype)}};Fm=Km=Mu([_u({type:Ql.Set,itemType:$m})],Fm);class Gm{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],Gm.prototype,"contentType",void 0),Mu([Ru({type:$l.Any,context:0})],Gm.prototype,"content",void 0);let jm=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:Xd})],jm.prototype,"single",void 0),Mu([Ru({type:$l.Any})],jm.prototype,"any",void 0),jm=Mu([_u({type:Ql.Choice})],jm);class qm{constructor(e={}){this.eContentType="",Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],qm.prototype,"eContentType",void 0),Mu([Ru({type:jm,context:0,optional:!0})],qm.prototype,"eContent",void 0);let zm=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:Xd,context:0,implicit:!0,optional:!0})],zm.prototype,"value",void 0),Mu([Ru({type:Xd,converter:ou,context:0,implicit:!0,optional:!0,repeated:"sequence"})],zm.prototype,"constructedValue",void 0),zm=Mu([_u({type:Ql.Choice})],zm);class Wm{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new im,Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],Wm.prototype,"contentType",void 0),Mu([Ru({type:im})],Wm.prototype,"contentEncryptionAlgorithm",void 0),Mu([Ru({type:zm,optional:!0})],Wm.prototype,"encryptedContent",void 0);class Jm{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}}var Ym;Mu([Ru({type:$l.ObjectIdentifier})],Jm.prototype,"keyAttrId",void 0),Mu([Ru({type:$l.Any,optional:!0})],Jm.prototype,"keyAttr",void 0);class Xm{constructor(e={}){this.subjectKeyIdentifier=new Ub,Object.assign(this,e)}}Mu([Ru({type:Ub})],Xm.prototype,"subjectKeyIdentifier",void 0),Mu([Ru({type:$l.GeneralizedTime,optional:!0})],Xm.prototype,"date",void 0),Mu([Ru({type:Jm,optional:!0})],Xm.prototype,"other",void 0);let Zm=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:Xm,context:0,implicit:!0,optional:!0})],Zm.prototype,"rKeyId",void 0),Mu([Ru({type:Xb,optional:!0})],Zm.prototype,"issuerAndSerialNumber",void 0),Zm=Mu([_u({type:Ql.Choice})],Zm);class ey{constructor(e={}){this.rid=new Zm,this.encryptedKey=new Xd,Object.assign(this,e)}}Mu([Ru({type:Zm})],ey.prototype,"rid",void 0),Mu([Ru({type:Xd})],ey.prototype,"encryptedKey",void 0);let ty=Ym=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,Ym.prototype)}};ty=Ym=Mu([_u({type:Ql.Sequence,itemType:ey})],ty);class ry{constructor(e={}){this.algorithm=new Hb,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:Hb})],ry.prototype,"algorithm",void 0),Mu([Ru({type:$l.BitString})],ry.prototype,"publicKey",void 0);let sy=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:Ub,context:0,implicit:!0,optional:!0})],sy.prototype,"subjectKeyIdentifier",void 0),Mu([Ru({type:ry,context:1,implicit:!0,optional:!0})],sy.prototype,"originatorKey",void 0),Mu([Ru({type:Xb,optional:!0})],sy.prototype,"issuerAndSerialNumber",void 0),sy=Mu([_u({type:Ql.Choice})],sy);class iy{constructor(e={}){this.version=em.v3,this.originator=new sy,this.keyEncryptionAlgorithm=new sm,this.recipientEncryptedKeys=new ty,Object.assign(this,e)}}Mu([Ru({type:$l.Integer})],iy.prototype,"version",void 0),Mu([Ru({type:sy,context:0})],iy.prototype,"originator",void 0),Mu([Ru({type:Xd,context:1,optional:!0})],iy.prototype,"ukm",void 0),Mu([Ru({type:sm})],iy.prototype,"keyEncryptionAlgorithm",void 0),Mu([Ru({type:ty})],iy.prototype,"recipientEncryptedKeys",void 0);let ny=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:Ub,context:0,implicit:!0})],ny.prototype,"subjectKeyIdentifier",void 0),Mu([Ru({type:Xb})],ny.prototype,"issuerAndSerialNumber",void 0),ny=Mu([_u({type:Ql.Choice})],ny);class ay{constructor(e={}){this.version=em.v0,this.rid=new ny,this.keyEncryptionAlgorithm=new sm,this.encryptedKey=new Xd,Object.assign(this,e)}}Mu([Ru({type:$l.Integer})],ay.prototype,"version",void 0),Mu([Ru({type:ny})],ay.prototype,"rid",void 0),Mu([Ru({type:sm})],ay.prototype,"keyEncryptionAlgorithm",void 0),Mu([Ru({type:Xd})],ay.prototype,"encryptedKey",void 0);class oy{constructor(e={}){this.keyIdentifier=new Xd,Object.assign(this,e)}}Mu([Ru({type:Xd})],oy.prototype,"keyIdentifier",void 0),Mu([Ru({type:$l.GeneralizedTime,optional:!0})],oy.prototype,"date",void 0),Mu([Ru({type:Jm,optional:!0})],oy.prototype,"other",void 0);class cy{constructor(e={}){this.version=em.v4,this.kekid=new oy,this.keyEncryptionAlgorithm=new sm,this.encryptedKey=new Xd,Object.assign(this,e)}}Mu([Ru({type:$l.Integer})],cy.prototype,"version",void 0),Mu([Ru({type:oy})],cy.prototype,"kekid",void 0),Mu([Ru({type:sm})],cy.prototype,"keyEncryptionAlgorithm",void 0),Mu([Ru({type:Xd})],cy.prototype,"encryptedKey",void 0);class ly{constructor(e={}){this.version=em.v0,this.keyEncryptionAlgorithm=new sm,this.encryptedKey=new Xd,Object.assign(this,e)}}Mu([Ru({type:$l.Integer})],ly.prototype,"version",void 0),Mu([Ru({type:am,context:0,optional:!0})],ly.prototype,"keyDerivationAlgorithm",void 0),Mu([Ru({type:sm})],ly.prototype,"keyEncryptionAlgorithm",void 0),Mu([Ru({type:Xd})],ly.prototype,"encryptedKey",void 0);class dy{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],dy.prototype,"oriType",void 0),Mu([Ru({type:$l.Any})],dy.prototype,"oriValue",void 0);let uy=class{constructor(e={}){Object.assign(this,e)}};var hy;Mu([Ru({type:ay,optional:!0})],uy.prototype,"ktri",void 0),Mu([Ru({type:iy,context:1,implicit:!0,optional:!0})],uy.prototype,"kari",void 0),Mu([Ru({type:cy,context:2,implicit:!0,optional:!0})],uy.prototype,"kekri",void 0),Mu([Ru({type:ly,context:3,implicit:!0,optional:!0})],uy.prototype,"pwri",void 0),Mu([Ru({type:dy,context:4,implicit:!0,optional:!0})],uy.prototype,"ori",void 0),uy=Mu([_u({type:Ql.Choice})],uy);let fy=hy=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,hy.prototype)}};var gy;fy=hy=Mu([_u({type:Ql.Set,itemType:uy})],fy);class py{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],py.prototype,"otherRevInfoFormat",void 0),Mu([Ru({type:$l.Any})],py.prototype,"otherRevInfo",void 0);let by=class{constructor(e={}){this.other=new py,Object.assign(this,e)}};Mu([Ru({type:py,context:1,implicit:!0})],by.prototype,"other",void 0),by=Mu([_u({type:Ql.Choice})],by);let my=gy=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,gy.prototype)}};my=gy=Mu([_u({type:Ql.Set,itemType:by})],my);class yy{constructor(e={}){Object.assign(this,e)}}var Ay;Mu([Ru({type:Fm,context:0,implicit:!0,optional:!0})],yy.prototype,"certs",void 0),Mu([Ru({type:my,context:1,implicit:!0,optional:!0})],yy.prototype,"crls",void 0);let Iy=Ay=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,Ay.prototype)}};Iy=Ay=Mu([_u({type:Ql.Set,itemType:om})],Iy);class vy{constructor(e={}){this.version=em.v0,this.recipientInfos=new fy,this.encryptedContentInfo=new Wm,Object.assign(this,e)}}Mu([Ru({type:$l.Integer})],vy.prototype,"version",void 0),Mu([Ru({type:yy,context:0,implicit:!0,optional:!0})],vy.prototype,"originatorInfo",void 0),Mu([Ru({type:fy})],vy.prototype,"recipientInfos",void 0),Mu([Ru({type:Wm})],vy.prototype,"encryptedContentInfo",void 0),Mu([Ru({type:Iy,context:1,implicit:!0,optional:!0})],vy.prototype,"unprotectedAttrs",void 0);const wy="1.2.840.113549.1.7.2";var Sy;let Ey=Sy=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,Sy.prototype)}};Ey=Sy=Mu([_u({type:Ql.Set,itemType:tm})],Ey);class Cy{constructor(e={}){this.version=em.v0,this.digestAlgorithms=new Ey,this.encapContentInfo=new qm,this.signerInfos=new dm,Object.assign(this,e)}}Mu([Ru({type:$l.Integer})],Cy.prototype,"version",void 0),Mu([Ru({type:Ey})],Cy.prototype,"digestAlgorithms",void 0),Mu([Ru({type:qm})],Cy.prototype,"encapContentInfo",void 0),Mu([Ru({type:Fm,context:0,implicit:!0,optional:!0})],Cy.prototype,"certificates",void 0),Mu([Ru({type:my,context:1,implicit:!0,optional:!0})],Cy.prototype,"crls",void 0),Mu([Ru({type:dm})],Cy.prototype,"signerInfos",void 0);const ky="1.2.840.10045.2.1",xy="1.2.840.10045.4.1",By="1.2.840.10045.4.3.1",_y="1.2.840.10045.4.3.2",Ry="1.2.840.10045.4.3.3",Oy="1.2.840.10045.4.3.4",Uy="1.2.840.10045.3.1.7",Ty="1.3.132.0.34",Ny="1.3.132.0.35";function Dy(e){return new Hb({algorithm:e})}const My=Dy(xy),Py=(Dy(By),Dy(_y)),Ly=Dy(Ry),Hy=Dy(Oy);let Vy=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:$l.ObjectIdentifier})],Vy.prototype,"fieldType",void 0),Mu([Ru({type:$l.Any})],Vy.prototype,"parameters",void 0),Vy=Mu([_u({type:Ql.Sequence})],Vy);let Ky=class{constructor(e={}){Object.assign(this,e)}};var Qy;Mu([Ru({type:$l.OctetString})],Ky.prototype,"a",void 0),Mu([Ru({type:$l.OctetString})],Ky.prototype,"b",void 0),Mu([Ru({type:$l.BitString,optional:!0})],Ky.prototype,"seed",void 0),Ky=Mu([_u({type:Ql.Sequence})],Ky),function(e){e[e.ecpVer1=1]="ecpVer1"}(Qy||(Qy={}));let $y=class{constructor(e={}){this.version=Qy.ecpVer1,Object.assign(this,e)}};Mu([Ru({type:$l.Integer})],$y.prototype,"version",void 0),Mu([Ru({type:Vy})],$y.prototype,"fieldID",void 0),Mu([Ru({type:Ky})],$y.prototype,"curve",void 0),Mu([Ru({type:class extends Xd{}})],$y.prototype,"base",void 0),Mu([Ru({type:$l.Integer,converter:ru})],$y.prototype,"order",void 0),Mu([Ru({type:$l.Integer,optional:!0})],$y.prototype,"cofactor",void 0),$y=Mu([_u({type:Ql.Sequence})],$y);let Fy=class{constructor(e={}){Object.assign(this,e)}};Mu([Ru({type:$l.ObjectIdentifier})],Fy.prototype,"namedCurve",void 0),Mu([Ru({type:$l.Null})],Fy.prototype,"implicitCurve",void 0),Mu([Ru({type:$y})],Fy.prototype,"specifiedCurve",void 0),Fy=Mu([_u({type:Ql.Choice})],Fy);class Gy{constructor(e={}){this.version=1,this.privateKey=new Xd,Object.assign(this,e)}}Mu([Ru({type:$l.Integer})],Gy.prototype,"version",void 0),Mu([Ru({type:Xd})],Gy.prototype,"privateKey",void 0),Mu([Ru({type:Fy,context:0,optional:!0})],Gy.prototype,"parameters",void 0),Mu([Ru({type:$l.BitString,context:1,optional:!0})],Gy.prototype,"publicKey",void 0);class jy{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.Integer,converter:ru})],jy.prototype,"r",void 0),Mu([Ru({type:$l.Integer,converter:ru})],jy.prototype,"s",void 0);const qy="1.2.840.113549.1.1",zy=`${qy}.1`,Wy=`${qy}.7`,Jy=`${qy}.9`,Yy=`${qy}.10`,Xy=`${qy}.2`,Zy=`${qy}.4`,eA=`${qy}.5`,tA=`${qy}.14`,rA=`${qy}.11`,sA=`${qy}.12`,iA=`${qy}.13`,nA=`${qy}.15`,aA=`${qy}.16`,oA="1.3.14.3.2.26",cA="2.16.840.1.101.3.4.2.4",lA="2.16.840.1.101.3.4.2.1",dA="2.16.840.1.101.3.4.2.2",uA="2.16.840.1.101.3.4.2.3",hA=`${qy}.8`;function fA(e){return new Hb({algorithm:e,parameters:null})}fA("1.2.840.113549.2.2"),fA("1.2.840.113549.2.5");const gA=fA(oA),pA=(fA(cA),fA(lA),fA(dA),fA(uA),fA("2.16.840.1.101.3.4.2.5"),fA("2.16.840.1.101.3.4.2.6"),new Hb({algorithm:hA,parameters:Du.serialize(gA)})),bA=new Hb({algorithm:Jy,parameters:Du.serialize(au.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});fA(zy),fA(Xy),fA(Zy),fA(eA),fA(nA),fA(aA),fA(sA),fA(iA),fA(nA),fA(aA);class mA{constructor(e={}){this.hashAlgorithm=new Hb(gA),this.maskGenAlgorithm=new Hb({algorithm:hA,parameters:Du.serialize(gA)}),this.pSourceAlgorithm=new Hb(bA),Object.assign(this,e)}}Mu([Ru({type:Hb,context:0,defaultValue:gA})],mA.prototype,"hashAlgorithm",void 0),Mu([Ru({type:Hb,context:1,defaultValue:pA})],mA.prototype,"maskGenAlgorithm",void 0),Mu([Ru({type:Hb,context:2,defaultValue:bA})],mA.prototype,"pSourceAlgorithm",void 0),new Hb({algorithm:Wy,parameters:Du.serialize(new mA)});class yA{constructor(e={}){this.hashAlgorithm=new Hb(gA),this.maskGenAlgorithm=new Hb({algorithm:hA,parameters:Du.serialize(gA)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}Mu([Ru({type:Hb,context:0,defaultValue:gA})],yA.prototype,"hashAlgorithm",void 0),Mu([Ru({type:Hb,context:1,defaultValue:pA})],yA.prototype,"maskGenAlgorithm",void 0),Mu([Ru({type:$l.Integer,context:2,defaultValue:20})],yA.prototype,"saltLength",void 0),Mu([Ru({type:$l.Integer,context:3,defaultValue:1})],yA.prototype,"trailerField",void 0),new Hb({algorithm:Yy,parameters:Du.serialize(new yA)});class AA{constructor(e={}){this.digestAlgorithm=new Hb,this.digest=new Xd,Object.assign(this,e)}}var IA;Mu([Ru({type:Hb})],AA.prototype,"digestAlgorithm",void 0),Mu([Ru({type:Xd})],AA.prototype,"digest",void 0);class vA{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.Integer,converter:ru})],vA.prototype,"prime",void 0),Mu([Ru({type:$l.Integer,converter:ru})],vA.prototype,"exponent",void 0),Mu([Ru({type:$l.Integer,converter:ru})],vA.prototype,"coefficient",void 0);let wA=IA=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,IA.prototype)}};wA=IA=Mu([_u({type:Ql.Sequence,itemType:vA})],wA);class SA{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)}}Mu([Ru({type:$l.Integer})],SA.prototype,"version",void 0),Mu([Ru({type:$l.Integer,converter:ru})],SA.prototype,"modulus",void 0),Mu([Ru({type:$l.Integer,converter:ru})],SA.prototype,"publicExponent",void 0),Mu([Ru({type:$l.Integer,converter:ru})],SA.prototype,"privateExponent",void 0),Mu([Ru({type:$l.Integer,converter:ru})],SA.prototype,"prime1",void 0),Mu([Ru({type:$l.Integer,converter:ru})],SA.prototype,"prime2",void 0),Mu([Ru({type:$l.Integer,converter:ru})],SA.prototype,"exponent1",void 0),Mu([Ru({type:$l.Integer,converter:ru})],SA.prototype,"exponent2",void 0),Mu([Ru({type:$l.Integer,converter:ru})],SA.prototype,"coefficient",void 0),Mu([Ru({type:wA,optional:!0})],SA.prototype,"otherPrimeInfos",void 0);class EA{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}var CA;Mu([Ru({type:$l.Integer,converter:ru})],EA.prototype,"modulus",void 0),Mu([Ru({type:$l.Integer,converter:ru})],EA.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"}(CA||(CA={}));const kA=CA;var xA=function(e,t){return xA=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])},xA(e,t)};function BA(e,t){function r(){this.constructor=e}xA(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function _A(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 RA(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 OA(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(RA(arguments[t]));return e}function UA(e){return!!e.useClass}function TA(e){return!!e.useFactory}var NA=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,OA(t))}}),t},e}();function DA(e){return"string"==typeof e||"symbol"==typeof e}function MA(e){return"object"==typeof e&&"token"in e&&"transform"in e}function PA(e){return!!e.useToken}function LA(e){return null!=e.useValue}var HA=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 VA=HA,KA=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return BA(t,e),t}(VA),QA=function(){this.scopedResolutions=new Map};var $A=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return BA(t,e),t}(VA),FA=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return BA(t,e),t}(VA);const GA=function(){this.preResolution=new $A,this.postResolution=new FA};var jA=new Map,qA=function(){function e(e){this.parent=e,this._registry=new KA,this.interceptors=new GA,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var s;if(void 0===r&&(r={lifecycle:kA.Transient}),this.ensureNotDisposed(),s=function(e){return UA(e)||LA(e)||PA(e)||TA(e)}(t)?t:{useClass:t},PA(s))for(var i=[e],n=s;null!=n;){var a=n.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+OA(i,[a]).join(" -> "));i.push(a);var o=this._registry.get(a);n=o&&PA(o.provider)?o.provider:null}if((r.lifecycle===kA.Singleton||r.lifecycle==kA.ContainerScoped||r.lifecycle==kA.ResolutionScoped)&&(LA(s)||TA(s)))throw new Error('Cannot use lifecycle "'+kA[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(),DA(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(),DA(e)){if(DA(t))return this.register(e,{useToken:t},{lifecycle:kA.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:kA.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!DA(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:kA.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new QA),void 0===r&&(r=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&DA(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 NA}(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=_A(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=_A(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===kA.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,s=e.options.lifecycle===kA.Singleton,i=e.options.lifecycle===kA.ContainerScoped,n=s||i;return r=LA(e.provider)?e.provider.useValue:PA(e.provider)?n?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):UA(e.provider)?n?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):TA(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===kA.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var s=this;void 0===t&&(t=new QA),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&DA(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=_A(this._registry.entries()),s=r.next();!s.done;s=r.next()){var i=RA(s.value,2),n=i[0],a=i[1];this._registry.setAll(n,a.filter(function(e){return!LA(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=_A(this._registry.entries()),n=i.next();!n.done;n=i.next()){var a=RA(n.value,2),o=a[0],c=a[1];c.some(function(e){return e.options.lifecycle===kA.ContainerScoped})&&s._registry.setAll(o,c.map(function(e){return e.options.lifecycle===kA.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 NA)return e.createProxy(function(e){return r.resolve(e,t)});var s,i=function(){var s=jA.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,OA([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?MA(s)?s.multiple?(n=r.resolve(s.transform)).transform.apply(n,OA([r.resolveAll(s.token,new QA,s.isOptional)],s.transformArgs)):(a=r.resolve(s.transform)).transform.apply(a,OA([r.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?r.resolveAll(s.token,new QA,s.isOptional):r.resolve(s.token,e,s.isOptional):MA(s)?(o=r.resolve(s.transform,e)).transform.apply(o,OA([r.resolve(s.token,e)],s.transformArgs)):r.resolve(s,e)}catch(e){throw new Error(function(e,t,r){var s,i,n=RA(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1];return function(e,t,r){return void 0===r&&(r=" "),OA([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}(),zA=new qA;const WA=function(e){return function(t){jA.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){zA.register(e,t)}):zA.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 JA;class YA{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}}Mu([Ru({type:$l.ObjectIdentifier})],YA.prototype,"attrId",void 0),Mu([Ru({type:$l.Any,repeated:"set"})],YA.prototype,"attrValues",void 0);let XA=JA=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,JA.prototype)}};var ZA;XA=JA=Mu([_u({type:Ql.Sequence,itemType:YA})],XA);let eI=ZA=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,ZA.prototype)}};eI=ZA=Mu([_u({type:Ql.Sequence,itemType:Gm})],eI);class tI{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],tI.prototype,"certId",void 0),Mu([Ru({type:$l.Any,context:0})],tI.prototype,"certValue",void 0);class rI{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],rI.prototype,"crlId",void 0),Mu([Ru({type:$l.Any,context:0})],rI.prototype,"crltValue",void 0);class sI extends Xd{}class iI{constructor(e={}){this.encryptionAlgorithm=new Hb,this.encryptedData=new sI,Object.assign(this,e)}}var nI,aI;Mu([Ru({type:Hb})],iI.prototype,"encryptionAlgorithm",void 0),Mu([Ru({type:sI})],iI.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(aI||(aI={}));class oI extends Xd{}let cI=nI=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,nI.prototype)}};cI=nI=Mu([_u({type:Ql.Sequence,itemType:Bb})],cI);class lI{constructor(e={}){this.version=aI.v1,this.privateKeyAlgorithm=new Hb,this.privateKey=new oI,Object.assign(this,e)}}Mu([Ru({type:$l.Integer})],lI.prototype,"version",void 0),Mu([Ru({type:Hb})],lI.prototype,"privateKeyAlgorithm",void 0),Mu([Ru({type:oI})],lI.prototype,"privateKey",void 0),Mu([Ru({type:cI,implicit:!0,context:0,optional:!0})],lI.prototype,"attributes",void 0);let dI=class extends lI{};dI=Mu([_u({type:Ql.Sequence})],dI);let uI=class extends iI{};uI=Mu([_u({type:Ql.Sequence})],uI);class hI{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],hI.prototype,"secretTypeId",void 0),Mu([Ru({type:$l.Any,context:0})],hI.prototype,"secretValue",void 0);class fI{constructor(e={}){this.mac=new AA,this.macSalt=new Xd,this.iterations=1,Object.assign(this,e)}}Mu([Ru({type:AA})],fI.prototype,"mac",void 0),Mu([Ru({type:Xd})],fI.prototype,"macSalt",void 0),Mu([Ru({type:$l.Integer,defaultValue:1})],fI.prototype,"iterations",void 0);class gI{constructor(e={}){this.version=3,this.authSafe=new Gm,this.macData=new fI,Object.assign(this,e)}}var pI;Mu([Ru({type:$l.Integer})],gI.prototype,"version",void 0),Mu([Ru({type:Gm})],gI.prototype,"authSafe",void 0),Mu([Ru({type:fI,optional:!0})],gI.prototype,"macData",void 0);class bI{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:$l.ObjectIdentifier})],bI.prototype,"bagId",void 0),Mu([Ru({type:$l.Any,context:0})],bI.prototype,"bagValue",void 0),Mu([Ru({type:YA,repeated:"set",optional:!0})],bI.prototype,"bagAttributes",void 0);let mI=pI=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,pI.prototype)}};var yI,AI,II;mI=pI=Mu([_u({type:Ql.Sequence,itemType:bI})],mI);const vI="1.2.840.113549.1.9",wI=`${vI}.7`,SI=`${vI}.14`;let EI=class extends tp{constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};Mu([Ru({type:$l.IA5String})],EI.prototype,"ia5String",void 0),EI=Mu([_u({type:Ql.Choice})],EI);let CI=class extends Gm{};CI=Mu([_u({type:Ql.Sequence})],CI);let kI=class extends gI{};kI=Mu([_u({type:Ql.Sequence})],kI);let xI=class extends iI{};xI=Mu([_u({type:Ql.Sequence})],xI);let BI=class{constructor(e=""){this.value=e}toString(){return this.value}};Mu([Ru({type:$l.IA5String})],BI.prototype,"value",void 0),BI=Mu([_u({type:Ql.Choice})],BI);let _I=class extends EI{};_I=Mu([_u({type:Ql.Choice})],_I);let RI=class extends tp{};RI=Mu([_u({type:Ql.Choice})],RI);let OI=class{constructor(e=new Date){this.value=e}};Mu([Ru({type:$l.GeneralizedTime})],OI.prototype,"value",void 0),OI=Mu([_u({type:Ql.Choice})],OI);let UI=class extends tp{};UI=Mu([_u({type:Ql.Choice})],UI);let TI=class{constructor(e="M"){this.value=e}toString(){return this.value}};Mu([Ru({type:$l.PrintableString})],TI.prototype,"value",void 0),TI=Mu([_u({type:Ql.Choice})],TI);let NI=class{constructor(e=""){this.value=e}toString(){return this.value}};Mu([Ru({type:$l.PrintableString})],NI.prototype,"value",void 0),NI=Mu([_u({type:Ql.Choice})],NI);let DI=class extends NI{};DI=Mu([_u({type:Ql.Choice})],DI);let MI=class extends tp{};MI=Mu([_u({type:Ql.Choice})],MI);let PI=class{constructor(e=""){this.value=e}toString(){return this.value}};Mu([Ru({type:$l.ObjectIdentifier})],PI.prototype,"value",void 0),PI=Mu([_u({type:Ql.Choice})],PI);let LI=class extends Kb{};LI=Mu([_u({type:Ql.Choice})],LI);let HI=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};Mu([Ru({type:$l.Integer})],HI.prototype,"value",void 0),HI=Mu([_u({type:Ql.Choice})],HI);let VI=class extends lm{};VI=Mu([_u({type:Ql.Sequence})],VI);let KI=class extends tp{};KI=Mu([_u({type:Ql.Choice})],KI);let QI=yI=class extends Gb{constructor(e){super(e),Object.setPrototypeOf(this,yI.prototype)}};QI=yI=Mu([_u({type:Ql.Sequence})],QI);let $I=AI=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,AI.prototype)}};$I=AI=Mu([_u({type:Ql.Set,itemType:om})],$I);let FI=class{constructor(e=""){this.value=e}toString(){return this.value}};Mu([Ru({type:$l.BmpString})],FI.prototype,"value",void 0),FI=Mu([_u({type:Ql.Choice})],FI);let GI=class extends Hb{};GI=Mu([_u({type:Ql.Sequence})],GI);let jI=II=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,II.prototype)}};var qI;jI=II=Mu([_u({type:Ql.Sequence,itemType:GI})],jI);let zI=qI=class extends Nu{constructor(e){super(e),Object.setPrototypeOf(this,qI.prototype)}};zI=qI=Mu([_u({type:Ql.Sequence,itemType:Bb})],zI);class WI{constructor(e={}){this.version=0,this.subject=new ap,this.subjectPKInfo=new Vb,this.attributes=new zI,Object.assign(this,e)}}Mu([Ru({type:$l.Integer})],WI.prototype,"version",void 0),Mu([Ru({type:ap})],WI.prototype,"subject",void 0),Mu([Ru({type:Vb})],WI.prototype,"subjectPKInfo",void 0),Mu([Ru({type:zI,implicit:!0,context:0})],WI.prototype,"attributes",void 0);class JI{constructor(e={}){this.certificationRequestInfo=new WI,this.signatureAlgorithm=new Hb,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Mu([Ru({type:WI})],JI.prototype,"certificationRequestInfo",void 0),Mu([Ru({type:Hb})],JI.prototype,"signatureAlgorithm",void 0),Mu([Ru({type:$l.BitString})],JI.prototype,"signature",void 0);const YI="crypto.algorithm",XI="crypto.algorithmProvider";var ZI;zA.registerSingleton(XI,class{getAlgorithms(){return zA.resolveAll(YI)}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 Hb({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 ev="1.3.36.3.3.2.8.1.1",tv=`${ev}.1`,rv=`${ev}.2`,sv=`${ev}.3`,iv=`${ev}.4`,nv=`${ev}.5`,av=`${ev}.6`,ov=`${ev}.7`,cv=`${ev}.8`,lv=`${ev}.9`,dv=`${ev}.10`,uv=`${ev}.11`,hv=`${ev}.12`,fv=`${ev}.13`,gv=`${ev}.14`,pv="brainpoolP160r1",bv="brainpoolP160t1",mv="brainpoolP192r1",yv="brainpoolP192t1",Av="brainpoolP224r1",Iv="brainpoolP224t1",vv="brainpoolP256r1",wv="brainpoolP256t1",Sv="brainpoolP320r1",Ev="brainpoolP320t1",Cv="brainpoolP384r1",kv="brainpoolP384t1",xv="brainpoolP512r1",Bv="brainpoolP512t1",_v="ECDSA";let Rv=ZI=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===_v.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return My;case"sha-256":return Py;case"sha-384":return Ly;case"sha-512":return Hy}else if("namedCurve"in e){let t="";switch(e.namedCurve){case"P-256":t=Uy;break;case"K-256":t=ZI.SECP256K1;break;case"P-384":t=Ty;break;case"P-521":t=Ny;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;break;case Bv:t=gv}if(t)return new Hb({algorithm:ky,parameters:Du.serialize(new Fy({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case xy:return{name:_v,hash:{name:"SHA-1"}};case _y:return{name:_v,hash:{name:"SHA-256"}};case Ry:return{name:_v,hash:{name:"SHA-384"}};case Oy:return{name:_v,hash:{name:"SHA-512"}};case ky:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Du.parse(e.parameters,Fy).namedCurve){case Uy:return{name:_v,namedCurve:"P-256"};case ZI.SECP256K1:return{name:_v,namedCurve:"K-256"};case Ty:return{name:_v,namedCurve:"P-384"};case Ny:return{name:_v,namedCurve:"P-521"};case tv:return{name:_v,namedCurve:pv};case rv:return{name:_v,namedCurve:bv};case sv:return{name:_v,namedCurve:mv};case iv:return{name:_v,namedCurve:yv};case nv:return{name:_v,namedCurve:Av};case av:return{name:_v,namedCurve:Iv};case ov:return{name:_v,namedCurve:vv};case cv:return{name:_v,namedCurve:wv};case lv:return{name:_v,namedCurve:Sv};case dv:return{name:_v,namedCurve:Ev};case uv:return{name:_v,namedCurve:Cv};case hv:return{name:_v,namedCurve:kv};case fv:return{name:_v,namedCurve:xv};case gv:return{name:_v,namedCurve:Bv}}}return null}};Rv.SECP256K1="1.3.132.0.10",Rv=ZI=Mu([WA()],Rv),zA.registerSingleton(YI,Rv);const Ov=Symbol("name"),Uv=Symbol("value");class Tv{constructor(e,t={},r=""){this[Ov]=e,this[Uv]=r;for(const e in t)this[e]=t[e]}}Tv.NAME=Ov,Tv.VALUE=Uv;class Nv{static toString(e){return this.items[e]||e}}Nv.items={[oA]:"sha1",[cA]:"sha224",[lA]:"sha256",[dA]:"sha384",[uA]:"sha512",[zy]:"rsaEncryption",[eA]:"sha1WithRSAEncryption",[tA]:"sha224WithRSAEncryption",[rA]:"sha256WithRSAEncryption",[sA]:"sha384WithRSAEncryption",[iA]:"sha512WithRSAEncryption",[ky]:"ecPublicKey",[xy]:"ecdsaWithSHA1",[By]:"ecdsaWithSHA224",[_y]:"ecdsaWithSHA256",[Ry]:"ecdsaWithSHA384",[Oy]:"ecdsaWithSHA512",[ib]:"TLS WWW server authentication",[nb]:"TLS WWW client authentication",[ab]:"Code Signing",[ob]:"E-mail Protection",[cb]:"Time Stamping",[lb]:"OCSP Signing",[wy]:"Signed Data"};class Dv{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[Tv.VALUE];n&&(i=` ${n}`),r.push(`${s}${e[Tv.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[Tv.NAME]=i,r.push(...this.serializeObj(e,t));else if(n instanceof Tv)n[Tv.NAME]=i,r.push(...this.serializeObj(n,t));else if(bc.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[Tv.NAME]=i,r.push(...this.serializeObj(e,t))}}}return r}static serializeBufferSource(e,t=0){const r=this.pad(t),s=bc.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)}}Dv.oidSerializer=Nv,Dv.algorithmSerializer=class{static toTextObject(e){const t=new Tv("Algorithm Identifier",{},Nv.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case ky:{const r=(new Rv).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}};class Mv{constructor(...e){if(1===e.length){const t=e[0];this.rawData=Du.serialize(t),this.onInit(t)}else{const t=Du.parse(e[0],e[1]);this.rawData=bc.toArrayBuffer(e[0]),this.onInit(t)}}equal(e){return e instanceof Mv&&Cc(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return Du.toString(this.rawData);case"text":return Dv.serialize(this.toTextObject());case"hex":return Sc.ToHex(this.rawData);case"base64":return Sc.ToBase64(this.rawData);case"base64url":return Sc.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 Tv(this.getTextName(),{},e)}}Mv.NAME="ASN";class Pv extends Mv{constructor(...e){let t;t=bc.isBufferSource(e[0])?bc.toArrayBuffer(e[0]):Du.serialize(new Fb({extnID:e[0],critical:e[1],extnValue:new Xd(bc.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[Tv.NAME]===Pv.NAME&&(e[Tv.NAME]=Nv.toString(this.type)),e}}var Lv;class Hv{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[Lv]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(Hv.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(Hv.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=Hv.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(Hv.DEFAULT,e);return this}}Lv=Symbol.toStringTag,Hv.DEFAULT="default";const Vv=new Hv,Kv=/^[0-2](?:\.[1-9][0-9]*)+$/;class Qv{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(Kv).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}const $v=new Qv;function Fv(e,t){return`\\${Sc.ToHex(Sc.FromUtf8String(t)).toUpperCase()}`}$v.register("CN","2.5.4.3"),$v.register("L","2.5.4.7"),$v.register("ST","2.5.4.8"),$v.register("O","2.5.4.10"),$v.register("OU","2.5.4.11"),$v.register("C","2.5.4.6"),$v.register("DC","0.9.2342.19200300.100.1.25"),$v.register("E","1.2.840.113549.1.9.1"),$v.register("G","2.5.4.42"),$v.register("I","2.5.4.43"),$v.register("SN","2.5.4.4"),$v.register("T","2.5.4.12");class Gv{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 Qv,this.asn=new ap;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 ap?this.asn=e:bc.isBufferSource(e)?this.asn=Du.parse(e,ap):this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||$v.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)||$v.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${Sc.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?`#${Sc.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(s)}return t}fromString(e){const t=new ap,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 ip([o])),i=a}return t}fromJSON(e){const t=new ap;for(const r of e){const e=new ip;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 sp({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=Sc.FromHex(t.slice(1));else{const s=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=s:Gv.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 Du.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]||Vv.get()):r=e[0]||Vv.get(),await r.subtle.digest(s,this.toArrayBuffer())}}const jv="Cannot initialize GeneralName from ASN.1 data.",qv=`${jv} Unsupported string format in use.`,zv=`${jv} Value doesn't match to GUID regular expression.`,Wv=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Jv="1.3.6.1.4.1.311.25.1",Yv="1.3.6.1.4.1.311.20.2.3",Xv="dns",Zv="dn",ew="email",tw="ip",rw="url",sw="guid",iw="upn",nw="id";class aw extends Mv{constructor(...e){let t;if(2===e.length)switch(e[0]){case Zv:{const r=new Gv(e[1]).toArrayBuffer(),s=Du.parse(r,ap);t=new dp({directoryName:s});break}case Xv:t=new dp({dNSName:e[1]});break;case ew:t=new dp({rfc822Name:e[1]});break;case sw:{const r=new RegExp(Wv,"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?Sc.ToHex(new Uint8Array(Sc.FromHex(e)).reverse()):e).join("");t=new dp({otherName:new cp({typeId:Jv,value:Du.serialize(new Xd(Sc.FromHex(s)))})});break}case tw:t=new dp({iPAddress:e[1]});break;case nw:t=new dp({registeredID:e[1]});break;case iw:t=new dp({otherName:new cp({typeId:Yv,value:Du.serialize(lu.toASN(e[1]))})});break;case rw:t=new dp({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else t=bc.isBufferSource(e[0])?Du.parse(e[0],dp):e[0];super(t)}onInit(e){if(null!=e.dNSName)this.type=Xv,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=ew,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=tw,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=rw,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=nw,this.value=e.registeredID;else if(null!=e.directoryName)this.type=Zv,this.value=new Gv(e.directoryName).toString();else{if(null==e.otherName)throw new Error(qv);if(e.otherName.typeId===Jv){this.type=sw;const t=Du.parse(e.otherName.value,Xd),r=new RegExp(Wv,"i").exec(Sc.ToHex(t));if(!r)throw new Error(zv);this.value=r.slice(1).map((e,t)=>t<3?Sc.ToHex(new Uint8Array(Sc.FromHex(e)).reverse()):e).join("-")}else{if(e.otherName.typeId!==Yv)throw new Error(qv);this.type=iw,this.value=Du.parse(e.otherName.value,tp).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case Zv:case Xv:case sw:case tw:case nw:case iw:case rw:e=this.type.toUpperCase();break;case ew:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let t=this.value;return this.type===nw&&(t=Nv.toString(t)),new Tv(e,void 0,t)}}class ow extends Mv{constructor(e){let t;if(e instanceof _p)t=e;else if(Array.isArray(e)){const r=[];for(const t of e)if(t instanceof dp)r.push(t);else{const e=Du.parse(new aw(t.type,t.value).rawData,dp);r.push(e)}t=new _p(r)}else{if(!bc.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=Du.parse(e,_p)}super(t)}onInit(e){const t=[];for(const r of e){let e=null;try{e=new aw(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[Tv.NAME]];Array.isArray(s)||(s=[],e[r[Tv.NAME]]=s),s.push(r)}return e}}ow.NAME="GeneralNames";const cw="-{5}",lw="\\n",dw="\\n",uw=`${cw}BEGIN ([^${lw}]+(?=${cw}))${cw}${dw}(?:((?:[^:${lw}]+: (?:[^${lw}]+${dw}(?: +[^${lw}]+${dw})*))+))?${dw}?((?:[a-zA-Z0-9=+/]+${dw})+)${cw}END \\1${cw}`;class hw{static isPem(e){return"string"==typeof e&&new RegExp(uw,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const t=new RegExp(uw,"g"),r=[];let s=null;for(;s=t.exec(e);){const e=s[3].replace(new RegExp(`[${lw}]+`,"g"),""),t={type:s[1],headers:[],rawData:Sc.FromBase64(e)},i=s[2];if(i){const e=i.split(new RegExp(dw,"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(!bc.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:bc.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:bc.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=Sc.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")}}hw.CertificateTag="CERTIFICATE",hw.CrlTag="CRL",hw.CertificateRequestTag="CERTIFICATE REQUEST",hw.PublicKeyTag="PUBLIC KEY",hw.PrivateKeyTag="PRIVATE KEY";class fw extends Mv{static isAsnEncoded(e){return bc.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(hw.isPem(e))return hw.decode(e)[0];if(Sc.isHex(e))return Sc.FromHex(e);if(Sc.isBase64(e))return Sc.FromBase64(e);if(Sc.isBase64Url(e))return Sc.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}{const t=Sc.ToBinary(e);return hw.isPem(t)?hw.decode(t)[0]:Sc.isHex(t)?Sc.FromHex(t):Sc.isBase64(t)?Sc.FromBase64(t):Sc.isBase64Url(t)?Sc.FromBase64Url(t):bc.toArrayBuffer(e)}}constructor(...e){fw.isAsnEncoded(e[0])?super(fw.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return"pem"===e?hw.encode(this.rawData,this.tag):super.toString(e)}}class gw extends fw{static async create(e,t=Vv.get()){if(e instanceof gw)return e;if(Hv.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");const r=await t.subtle.exportKey("spki",e);return new gw(r)}if(e.publicKey)return e.publicKey;if(bc.isBufferSource(e))return new gw(e);throw new TypeError("Unsupported PublicKeyType")}constructor(e){fw.isAsnEncoded(e)?super(e,Vb):super(e),this.tag=hw.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]||Vv.get()):t=e[0]||Vv.get();let i=this.rawData;const n=Du.parse(this.rawData,Vb);return n.algorithm.algorithm===Yy&&(i=function(e){return e.algorithm=new Hb({algorithm:zy,parameters:null}),Du.serialize(e)}(n)),t.subtle.importKey("spki",i,s,!0,r)}onInit(e){const t=zA.resolve(XI),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case zy:{const t=Du.parse(e.subjectPublicKey,EA),s=bc.toUint8Array(t.modulus);r.publicExponent=bc.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]||Vv.get()):r=e[0]||Vv.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=Vv.get()):t=e[0]:2===e.length?(r=e[0],t=e[1]):t=Vv.get();const s=Du.parse(this.rawData,Vb);return await t.subtle.digest(r,s.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),t=Du.parse(this.rawData,Vb);return e.Algorithm=Dv.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===ky?e["EC Point"]=t.subjectPublicKey:e["Raw Data"]=t.subjectPublicKey,e}}class pw extends Pv{static async create(e,t=!1,r=Vv.get()){if("name"in e&&"serialNumber"in e)return new pw(e,t);const s=await gw.create(e,r),i=await s.getKeyIdentifier(r);return new pw(Sc.ToHex(i),t)}constructor(...e){if(bc.isBufferSource(e[0]))super(e[0]);else if("string"==typeof e[0]){const t=new Cp({keyIdentifier:new Ep(Sc.FromHex(e[0]))});super(Sp,e[1],Du.serialize(t))}else{const t=e[0],r=t.name instanceof ow?Du.parse(t.name.rawData,_p):t.name,s=new Cp({authorityCertIssuer:r,authorityCertSerialNumber:Sc.FromHex(t.serialNumber)});super(Sp,e[1],Du.serialize(s))}}onInit(e){super.onInit(e);const t=Du.parse(e.extnValue,Cp);t.keyIdentifier&&(this.keyId=Sc.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Sc.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Du.parse(this.value,Cp);return t.authorityCertIssuer&&(e["Authority Issuer"]=new ow(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}pw.NAME="Authority Key Identifier";class bw extends Pv{constructor(...e){if(bc.isBufferSource(e[0])){super(e[0]);const t=Du.parse(this.value,xp);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{const t=new xp({cA:e[0],pathLenConstraint:e[1]});super(kp,e[2],Du.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 mw,yw;bw.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"}(mw||(mw={}));class Aw extends Pv{constructor(...e){if(bc.isBufferSource(e[0])){super(e[0]);const t=Du.parse(this.value,sb);this.usages=t.map(e=>e)}else{const t=new sb(e[0]);super(rb,e[1],Du.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(e=>Nv.toString(e)).join(", "),e}}Aw.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"}(yw||(yw={}));class Iw extends Pv{constructor(...e){if(bc.isBufferSource(e[0])){super(e[0]);const t=Du.parse(this.value,mb);this.usages=t.toNumber()}else{const t=new mb(e[0]);super(gb,e[1],Du.serialize(t)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Du.parse(this.value,mb);return e[""]=t.toJSON().join(", "),e}}Iw.NAME="Key Usages";class vw extends Pv{static async create(e,t=!1,r=Vv.get()){const s=await gw.create(e,r),i=await s.getKeyIdentifier(r);return new vw(Sc.ToHex(i),t)}constructor(...e){if(bc.isBufferSource(e[0])){super(e[0]);const t=Du.parse(this.value,Ub);this.keyId=Sc.ToHex(t)}else{const t="string"==typeof e[0]?Sc.FromHex(e[0]):e[0],r=new Ub(t);super(Ob,e[1],Du.serialize(r)),this.keyId=Sc.ToHex(t)}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=Du.parse(this.value,Ub);return e[""]=t,e}}vw.NAME="Subject Key Identifier";class ww extends Pv{constructor(...e){bc.isBufferSource(e[0])?super(e[0]):super(kb,e[1],new ow(e[0]||[]).rawData)}onInit(e){super.onInit(e);const t=Du.parse(e.extnValue,xb);this.names=new ow(t)}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(const r in t)e[r]=t[r];return e}}ww.NAME="Subject Alternative Name";class Sw{static register(e,t){this.items.set(e,t)}static create(e){const t=new Pv(e),r=this.items.get(t.type);return r?new r(e):t}}Sw.items=new Map;class Ew extends Pv{constructor(...e){var t;if(bc.isBufferSource(e[0])){super(e[0]);const t=Du.parse(this.value,Vp);this.policies=t.map(e=>e.policyIdentifier)}else{const r=e[0],s=null!==(t=e[1])&&void 0!==t&&t,i=new Vp(r.map(e=>new Hp({policyIdentifier:e})));super(Tp,s,Du.serialize(i)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new Tv("",{},Nv.toString(e))),e}}Ew.NAME="Certificate Policies",Sw.register(Tp,Ew);class Cw extends Pv{constructor(...e){var t;if(bc.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const t=e[0].map(e=>new zp({distributionPoint:new qp({fullName:[new dp({uniformResourceIdentifier:e})]})})),r=new Wp(t);super(Fp,e[1],Du.serialize(r))}else{const t=new Wp(e[0]);super(Fp,e[1],Du.serialize(t))}null!==(t=this.distributionPoints)&&void 0!==t||(this.distributionPoints=[])}onInit(e){super.onInit(e);const t=Du.parse(e.extnValue,Wp);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 aw(e).toString()).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map(e=>e.toString()).join(", ")),r}),e}}Cw.NAME="CRL Distribution Points";class kw extends Pv{constructor(...e){var t,r,s,i;if(bc.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof wp){const t=new wp(e[0]);super(Ip,e[1],Du.serialize(t))}else{const t=e[0],r=new wp;Bw(r,t,gp,"ocsp"),Bw(r,t,pp,"caIssuers"),Bw(r,t,bp,"timeStamping"),Bw(r,t,mp,"caRepository"),super(Ip,e[1],Du.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=[],Du.parse(e.extnValue,wp).forEach(e=>{switch(e.accessMethod){case gp:this.ocsp.push(new aw(e.accessLocation));break;case pp:this.caIssuers.push(new aw(e.accessLocation));break;case bp:this.timeStamping.push(new aw(e.accessLocation));break;case mp:this.caRepository.push(new aw(e.accessLocation))}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&xw(e,"OCSP",this.ocsp),this.caIssuers.length&&xw(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&xw(e,"Time Stamping",this.timeStamping),this.caRepository.length&&xw(e,"CA Repository",this.caRepository),e}}function xw(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{const s=new Tv("");r.forEach((e,t)=>{const r=e.toTextObject(),i=`${r[Tv.NAME]} ${t+1}`;let n=s[i];Array.isArray(n)||(n=[],s[i]=n),n.push(r)}),e[t]=s}}function Bw(e,t,r,s){const i=t[s];i&&(Array.isArray(i)?i:[i]).forEach(t=>{"string"==typeof t&&(t=new aw("url",t)),e.push(new vp({accessMethod:r,accessLocation:Du.parse(t.rawData,dp)}))})}kw.NAME="Authority Info Access";class _w extends Mv{constructor(...e){let t;if(bc.isBufferSource(e[0]))t=bc.toArrayBuffer(e[0]);else{const r=e[0],s=Array.isArray(e[1])?e[1].map(e=>bc.toArrayBuffer(e)):[];t=Du.serialize(new Bb({type:r,values:s}))}super(t,Bb)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new Tv("",{"":e})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[Tv.NAME]===_w.NAME&&(e[Tv.NAME]=Nv.toString(this.type)),e}}_w.NAME="Attribute";class Rw extends _w{constructor(...e){var t;if(bc.isBufferSource(e[0]))super(e[0]);else{const t=new KI({printableString:e[0]});super(wI,[Du.serialize(t)])}null!==(t=this.password)&&void 0!==t||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const e=Du.parse(this.values[0],KI);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[Tv.VALUE]=this.password,e}}Rw.NAME="Challenge Password";class Ow extends _w{constructor(...e){var t;if(bc.isBufferSource(e[0]))super(e[0]);else{const t=e[0],r=new Gb;for(const e of t)r.push(Du.parse(e.rawData,Fb));super(SI,[Du.serialize(r)])}null!==(t=this.items)&&void 0!==t||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const e=Du.parse(this.values[0],Gb);this.items=e.map(e=>Sw.create(Du.serialize(e)))}}toTextObject(){const e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(const r of t)e[r[Tv.NAME]]=r;return e}}Ow.NAME="Extensions";class Uw{static register(e,t){this.items.set(e,t)}static create(e){const t=new _w(e),r=this.items.get(t.type);return r?new r(e):t}}Uw.items=new Map;const Tw="crypto.signatureFormatter";var Nw;let Dw=Nw=class{static createPssParams(e,t){const r=Nw.getHashAlgorithm(e);return r?new yA({hashAlgorithm:r,maskGenAlgorithm:new Hb({algorithm:hA,parameters:Du.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){const t=zA.resolve(XI);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 Hb({algorithm:zy,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 Hb({algorithm:eA,parameters:null});case"sha-256":return new Hb({algorithm:rA,parameters:null});case"sha-384":return new Hb({algorithm:sA,parameters:null});case"sha-512":return new Hb({algorithm:iA,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=Nw.createPssParams(e.hash,e.saltLength);if(!t)throw new Error("Cannot create PSS parameters");return new Hb({algorithm:Yy,parameters:Du.serialize(t)})}return new Hb({algorithm:Yy,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case zy:return{name:"RSASSA-PKCS1-v1_5"};case eA:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case rA:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case sA:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case iA:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case Yy:if(e.parameters){const t=Du.parse(e.parameters,yA);return{name:"RSA-PSS",hash:zA.resolve(XI).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};Dw=Nw=Mu([WA()],Dw),zA.registerSingleton(YI,Dw);let Mw=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new Hb({algorithm:oA});case"sha-256":return new Hb({algorithm:lA});case"sha-384":return new Hb({algorithm:dA});case"sha-512":return new Hb({algorithm:uA})}return null}toWebAlgorithm(e){switch(e.algorithm){case oA:return{name:"SHA-1"};case lA:return{name:"SHA-256"};case dA:return{name:"SHA-384"};case uA:return{name:"SHA-512"}}return null}};Mw=Mu([WA()],Mw),zA.registerSingleton(YI,Mw);class Pw{addPadding(e,t){const r=bc.toUint8Array(t),s=new Uint8Array(e);return s.set(r,e-r.length),s}removePadding(e,t=!1){let r=bc.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=Pw.namedCurveSize.get(r)||Pw.defaultNamedCurveSize,i=new jy,n=bc.toUint8Array(t);return i.r=this.removePadding(n.slice(0,s),!0),i.s=this.removePadding(n.slice(s,s+s),!0),Du.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){const r=Du.parse(t,jy),s=e.namedCurve,i=Pw.namedCurveSize.get(s)||Pw.defaultNamedCurveSize;return Ec(this.addPadding(i,this.removePadding(r.r)),this.addPadding(i,this.removePadding(r.s)))}return null}}Pw.namedCurveSize=new Map,Pw.defaultNamedCurveSize=32;const Lw="1.3.101.110",Hw="1.3.101.111",Vw="1.3.101.112",Kw="1.3.101.113";let Qw=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case"ed25519":t=Vw;break;case"x25519":t=Lw;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=Vw;break;case"ed448":t=Kw}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=Lw;break;case"x448":t=Hw}}return t?new Hb({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case Vw:return{name:"Ed25519"};case Kw:return{name:"EdDSA",namedCurve:"Ed448"};case Lw:return{name:"X25519"};case Hw:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};Qw=Mu([WA()],Qw),zA.registerSingleton(YI,Qw);(class extends fw{constructor(e){fw.isAsnEncoded(e)?super(e,JI):super(e),this.tag=hw.CertificateRequestTag}onInit(e){this.tbs=Du.serialize(e.certificationRequestInfo),this.publicKey=new gw(e.certificationRequestInfo.subjectPKInfo);const t=zA.resolve(XI);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>Uw.create(Du.serialize(e)));const r=this.getAttribute(SI);this.extensions=[],r instanceof Ow&&(this.extensions=r.items),this.subjectName=new Gv(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=Vv.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),s=zA.resolveAll(Tw).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=Du.parse(this.rawData,JI),r=t.certificationRequestInfo,s=new Tv("",{Version:`${jb[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new Tv("");for(const t of this.attributes){const r=t.toTextObject();e[r[Tv.NAME]]=r}s.Attributes=e}return e.Data=s,e.Signature=new Tv("",{Algorithm:Dv.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";class $w extends fw{constructor(e){fw.isAsnEncoded(e)?super(e,zb):super(e),this.tag=hw.CertificateTag}onInit(e){const t=e.tbsCertificate;this.tbs=Du.serialize(t),this.serialNumber=Sc.ToHex(t.serialNumber),this.subjectName=new Gv(t.subject),this.subject=new Gv(t.subject).toString(),this.issuerName=new Gv(t.issuer),this.issuer=this.issuerName.toString();const r=zA.resolve(XI);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=>Sw.create(Du.serialize(e)))),this.publicKey=new gw(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=Vv.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 gw)r={...i.algorithm,...this.signatureAlgorithm},s=await i.export(r,["verify"],t);else if(bc.isBufferSource(i)){const e=new gw(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=zA.resolveAll(Tw).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=Vv.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=Vv.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),t=Du.parse(this.rawData,zb),r=t.tbsCertificate,s=new Tv("",{Version:`${jb[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":Dv.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new Tv("",{"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 Tv("");for(const t of this.extensions){const r=t.toTextObject();e[r[Tv.NAME]]=r}s.Extensions=e}return e.Data=s,e.Signature=new Tv("",{Algorithm:Dv.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}$w.NAME="Certificate";class Fw{static async createSelfSigned(e,t=Vv.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=Vv.get()){var r;let s;s=e.publicKey instanceof gw?e.publicKey.rawData:"publicKey"in e.publicKey?e.publicKey.publicKey.rawData:bc.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey("spki",e.publicKey);const i=e.serialNumber?bc.toUint8Array(Sc.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 zb({tbsCertificate:new qb({version:jb.v3,serialNumber:i,validity:new Qb({notBefore:n,notAfter:a}),extensions:new Gb((null===(r=e.extensions)||void 0===r?void 0:r.map(e=>Du.parse(e.rawData,Fb)))||[]),subjectPublicKeyInfo:Du.parse(s,Vb)})});if(e.subject){const t=e.subject instanceof Gv?e.subject:new Gv(e.subject);o.tbsCertificate.subject=Du.parse(t.toArrayBuffer(),ap)}if(e.issuer){const t=e.issuer instanceof Gv?e.issuer:new Gv(e.issuer);o.tbsCertificate.issuer=Du.parse(t.toArrayBuffer(),ap)}const c={hash:"SHA-256"},l="signingKey"in e?{...c,...e.signingAlgorithm,...e.signingKey.algorithm}:{...c,...e.signingAlgorithm},d=zA.resolve(XI);o.tbsCertificate.signature=o.signatureAlgorithm=d.toAsnAlgorithm(l);const u=Du.serialize(o.tbsCertificate),h="signingKey"in e?await t.subtle.sign(l,e.signingKey,u):e.signature,f=zA.resolveAll(Tw).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 $w(Du.serialize(o))}}var Gw;!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"}(Gw||(Gw={})),Sw.register(kp,bw),Sw.register(rb,Aw),Sw.register(gb,Iw),Sw.register(Ob,vw),Sw.register(Sp,pw),Sw.register(kb,ww),Sw.register(Fp,Cw),Sw.register(Ip,kw),Uw.register(wI,Rw),Uw.register(SI,Ow),zA.registerSingleton(Tw,class{toAsnSignature(e,t){return bc.toArrayBuffer(t)}toWebSignature(e,t){return bc.toArrayBuffer(t)}}),zA.registerSingleton(Tw,Pw),Pw.namedCurveSize.set("P-256",32),Pw.namedCurveSize.set("K-256",32),Pw.namedCurveSize.set("P-384",48),Pw.namedCurveSize.set("P-521",66);const jw=si.new(void 0,"net"),qw=new class extends Ef{constructor(){super(...arguments),this.subtle=new Jg}getRandomValues(e){if(!ArrayBuffer.isView(e))throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'");const t=_f.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return Of().randomFillSync(t),e}};Vv.set(qw);const zw="Ed25519",Ww="OKP";var Jw,Yw,Xw;function Zw(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 eS(e){const t=new Uint8Array(Buffer.from(e.x??"","base64url"));return Zw(P.blobFrom(t))}async function tS(e,t){if(e.kty!==Ww)throw new Error(`Unsupported key type ${e.kty}`);const r={name:"EdDSA",namedCurve:zw};return await qw.subtle.importKey("jwk",e,r,!0,[t===Yw.Public?"verify":"sign"])}function rS(e){return`${e.toString("pem")}\n`}function sS(e){return{key:iS(e._privKey.raw),ops:{async sign(e,t){const r=await vr(L.fromBlob(new Uint8Array(e),yr).asOpaque());return iS((await wr(r,P.blobFrom(new Uint8Array(t)))).raw)},async verify(e,t,r){const s=await vr(L.fromBlob(new Uint8Array(e),yr).asOpaque());return(await Sr([{signature:L.fromBlob(new Uint8Array(r),Ar).asOpaque(),key:s.pubKey,message:P.blobFrom(new Uint8Array(t))}]))[0]}}}}function iS(e){if(e.buffer instanceof ArrayBuffer)return e.buffer;const t=new ArrayBuffer(e.length);return new Uint8Array(t).set(e,0),t}function nS(){const e={info:null,verifyCallback:async(t,r)=>{const s=await async function(e){if(jw.log("Incoming peer. Verifying certificate"),1!==e.length)return jw.log("Rejecting peer with no certificates."),D.error(Jw.NoCertificate);const t=new(pc().X509Certificate)(e[0]);if(t.publicKey.asymmetricKeyType!==zw.toLowerCase())return jw.log(`Rejecting peer using non-ed25519 certificate: ${t.publicKey.asymmetricKeyType}`),D.error(Jw.NotEd25519);const r=t.publicKey.export({format:"jwk"});if(r.kty!==Ww||r.crv!==zw)return jw.log(`Public key type mismatch: ${r.kty}, ${r.crv}`),D.error(Jw.PublicKeyTypeMismatch);const s=eS(r),i=(t.subjectAltName??"").match(/DNS:([^,]+)/);if(null===i||i[1]!==s)return jw.log(`AltName mismatch. Expected: '${s}', got: '${i?.[1]}'`),D.error(Jw.AltNameMismatch);const n=Buffer.from(r.x??"","base64url");if(!t.verify(t.publicKey))return D.error(Jw.IncorrectSignature);const a=L.fromBlob(new Uint8Array(n),yr);return D.ok({id:s,key:a.asOpaque()})}(t);if(s.isError)return function(e){if(void 0===e)return e;switch(e){case Jw.AltNameMismatch:return rc.IllegalParameter;case Jw.NotEd25519:return rc.InsufficientSecurity;case Jw.PublicKeyTypeMismatch:return rc.BadCertificate;case Jw.NoCertificate:return rc.CertificateRequired;case Jw.IncorrectSignature:return rc.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"}(Jw||(Jw={})),function(e){e[e.Public=0]="Public",e[e.Private=1]="Private"}(Yw||(Yw={})),function(e){e[e.LocalClose=0]="LocalClose",e[e.RemoteClose=1]="RemoteClose",e[e.Exception=2]="Exception"}(Xw||(Xw={}));const aS=si.new(void 0,"peers");function oS(e){return`${e.id}@${e.address.host}:${e.address.port}`}class cS{_onPeerConnected=[];_onPeerDisconnected=[];peers=new Map;peerConnected(e){aS.info(`💡 Peer ${oS(e)} connected.`),void 0!==this.peers.get(e.id)&&aS.warn("Replacing older connection."),this.peers.set(e.id,e);for(const t of this._onPeerConnected)t(e)}peerDisconnected(e){aS.info(`⚡︎Peer ${oS(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 lS=si.new(void 0,"net");class dS{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}),lS.info(`🛜 QUIC socket on ${this.socket.host}:${this.socket.port}`),await this.server.start(),lS.log("🛜 QUIC server listening")}async stop(){if(!this.started)throw new Error("Network not started yet!");lS.info("Stopping the networking."),await this.server.stop(),await this.socket.stop(),this.started=!1,lS.info("Networking stopped.")}get peers(){return this._peers}async dial(e,t={}){return this._dial(e,t)}}const uS=si.new(void 0,"net");function hS(e,t,r){e.addEventListener(t.name,async e=>{try{await r(e)}catch(e){uS.error(`Unhandled exception in ${t.name} event handler: ${e}`)}})}class fS{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){hS(this.stream,Oo,t=>{const r=t.detail instanceof Da||t.detail instanceof Ma||t.detail instanceof xa,s=t.detail instanceof _a,i=r?Xw.LocalClose:s?Xw.RemoteClose:Xw.Exception;e(t.detail,i)})}destroy(){return this.stream.destroy()}}const gS=si.new(void 0,"peers");class pS{conn;connectionId;address;id;key;streamEvents=new(Jn());constructor(e,t){this.conn=e,gS.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,hS(e,xo,e=>{const t=e.detail;gS.log(`🚰 [${this.id}] new stream: [${t.streamId}]`),this.streamEvents.emit("stream",new fS(t))}),hS(e,Co,e=>{gS.error(`❌ [${this.id}] connection failed: ${e.detail}`)})}addOnIncomingStream(e){this.streamEvents.on("stream",e)}openStream(){const e=this.conn.newStream("bidi");return gS.log(`🚰 [${this.id}] opening stream: [${e.streamId}]`),new fS(e)}async disconnect(){gS.log(`👋 [${this.id}] disconnecting`),await this.conn.stop({isApp:!0})}}const bS=si.new(void 0,"net");class mS{static async setup({host:e,port:t,protocols:r,key:s}){const i=si.getLevel("net")>zs.TRACE?ii.WARN:ii.DEBUG,n=new wi("quic",i,[new Ei(mi`${di}:${hi}:${gi}`)]),a=function(e){const t={kty:Ww,crv:zw,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 tS(e.privateKey,Yw.Private),r=await qw.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 tS(t.publicKey,Yw.Public),o=await tS(t.privateKey,Yw.Private),c=await tS(r.privateKey,Yw.Private),l=await tS(r.publicKey,Yw.Public),d=new Date(n.getTime()-n.getTime()%1e3),u=new Date(n.getTime()-n.getTime()%1e3+2e3),h=await qw.subtle.digest("SHA-256",await qw.subtle.exportKey("spki",a)),f=await qw.subtle.digest("SHA-256",await qw.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 bw(!0),new Iw(yw.keyCertSign|yw.cRLSign|yw.digitalSignature|yw.nonRepudiation|yw.keyAgreement|yw.keyEncipherment|yw.dataEncipherment),new Aw([]),new ww([{type:"dns",value:eS(t.publicKey)}]),await vw.create(a)]};return m.signingKey=c,await Fw.create(m)}({certId:P.blobFromString("QUIC Networking"),subjectKeyPair:a,issuerKeyPair:a}),l=nS(),d={keepAliveIntervalTime:3e3,maxIdleTimeout:6e3,applicationProtos:r,cert:rS(c),key:o,verifyPeer:!0,verifyCallback:l.verifyCallback};bS.info(`🆔 Peer id: ** ${Zw(s.pubKey)}@${e}:${t} ** (pubkey: ${s.pubKey})`);const u=new Po({logger:n.getChild("socket")}),h=new dc({socket:u,config:d,crypto:sS(s),logger:n.getChild("server")}),f=new cS;function g(e,t){const r=new pS(e,t);return hS(r.conn,ko,()=>f.peerDisconnected(r)),f.peerConnected(r),r}return hS(h,vo,e=>bS.error(`🛜 Server error: ${e}`)),hS(h,wo,e=>bS.error(`🛜 Server stopped: ${e}`)),hS(h,Io,async e=>{const t=e.detail;if(null!==l.info){if(l.info.key.isEqualTo(s.pubKey))return bS.log(`🛜 Rejecting connection from ourself from ${t.remoteHost}:${t.remotePort}`),void await t.stop();if(f.isConnected(l.info.id))return bS.log(`🛜 Rejecting duplicate connection with peer ${l.info.id} from ${t.remoteHost}:${t.remotePort}`),void await t.stop();bS.log(`🛜 Server handshake with ${t.remoteHost}:${t.remotePort}`),g(t,l.info),l.info=null,await t.start()}else await t.stop()}),new dS(u,h,async function(e,t){const r=nS(),s=fc.createQUICClient({socket:u,host:e.host,port:e.port,crypto:{ops:{async randomBytes(e){gc.webcrypto.getRandomValues(new Uint8Array(e))}}},config:{...d,verifyCallback:r.verifyCallback},logger:n.getChild("client")},{signal:t.signal}),i=await s;if(hS(i,yo,()=>{bS.log("⚰️ Client connection closed.")}),hS(i,bo,e=>{bS.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 bS.log(`🤝 Client handshake with: ${e.host}:${e.port}`),g(i.connection,r.info)},f,{host:e,port:t})}}const yS=t(import.meta.url)("node:buffer");function AS(e){return ue(ae(e.length))}function IS(e,t){let r=yS.Buffer.alloc(0),s=-1;return i=>{r=yS.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 vS{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 wS=si.new(void 0,"net:conn");class SS{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 wS.log(`[${e}] max retries reached. Removing peer.`);const s=Math.min(3*t.currentRetry*t.currentRetry,3600);try{await(0,qs.setTimeout)(1e3*s,void 0,{signal:r})}catch{return}if(null!==t.peerRef)return;try{return wS.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;wS.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 ES(e){return re(e)}function CS(e,t){return e().catch(t)}const kS=si.new(void 0,"stream");class xS{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),kS.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=ES(n.raw[0]),o=this.incomingHandlers.get(a);if(void 0===o)throw new Error(`Unsupported stream kind: ${a}`);kS.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,ae(n));var n;const a=(r,s)=>{this.streams.delete(i),this.backgroundTasks.delete(i),s===Xw.Exception&&kS.error(`🚰 --- [${e.id}:${i}] Stream error: ${r}. Disconnecting peer.`),s!==Xw.LocalClose&&(t.onClose(i,!0),e.disconnect())};r.addOnError(a);const o=new BS(i,r,a);this.streams.set(i,{handler:t,streamSender:o,peer:e});const c=CS(()=>async function(e,t,r,s,i){let n=s,a=!1;const o=IS(s=>{const i=P.blobFrom(new Uint8Array(s));kS.trace(`🚰 --\x3e [${e.id}:${r.streamId}] ${i}`),t.onStreamMessage(r,i)},()=>{kS.error(`🚰 --\x3e [${e.id}:${r.streamId}] got too much data. Disconnecting.`),e.disconnect()});for(;;){if(o(n.raw),a)return void kS.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,Xw.Exception));return this.streams.has(i)&&this.backgroundTasks.set(i,c),o}}class BS{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=CS(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;kS.trace(`🚰 <-- [${this.streamId}] write: ${r}`),s&&await e.write(AS(r.raw)),await e.write(r.raw),this.bufferedLength-=r.length}}finally{e.releaseLock(),this.currentWriterPromise=null}},e=>this.onError(e,Xw.Exception))),0))}close(){CS(async()=>{kS.trace(`🚰 <-- [${this.streamId}] closing`),null!==this.currentWriterPromise&&await this.currentWriterPromise,await this.internal.writable.close()},e=>this.onError(e,Xw.Exception))}flush(){return this.currentWriterPromise??Promise.resolve()}}const _S=ES(128);var RS;!function(e){e[e.AscExcl=0]="AscExcl",e[e.DescIncl=1]="DescIncl"}(RS||(RS={}));class OS extends B{headerHash;direction;maxBlocks;static Codec=_e.Class(OS,{headerHash:_e.bytes(Le).asOpaque(),direction:_e.u8.convert(e=>re(e),e=>{switch(e){case RS.AscExcl:return RS.AscExcl;case RS.DescIncl:return RS.DescIncl;default:throw new Error(`Invalid 'Direction' value: ${e}`)}}),maxBlocks:_e.u32});static create({headerHash:e,direction:t,maxBlocks:r}){return new OS(e,t,r)}constructor(e,t,r){super(),this.headerHash=e,this.direction=t,this.maxBlocks=r}}const US=si.new(void 0,"protocol/ce-128");class TS{chainSpec;getBlockSequence;kind=_S;constructor(e,t){this.chainSpec=e,this.getBlockSequence=t}onStreamMessage(e,t){const r=ge.decodeObject(OS.Codec,t);US.log(`[${e.streamId}] Client has requested: ${r}`);const s=this.getBlockSequence(e.streamId,r.headerHash,r.direction,r.maxBlocks);e.bufferAndSend(Ie.encodeObject(_e.sequenceFixLen(ws.Codec.View,s.length),s,this.chainSpec)),e.close()}onClose(){}}class NS{chainSpec;kind=_S;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=ge.decodeSequence(ws.Codec.View,t,this.chainSpec);US.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(Ie.encodeObject(OS.Codec,OS.create({headerHash:t,direction:r,maxBlocks:s}))),e.close()})}}var DS;!function(e){e[e.NoStartBlock=0]="NoStartBlock",e[e.BlockOnFork=1]="BlockOnFork"}(DS||(DS={}));const MS=ES(0);class PS extends B{hash;slot;static Codec=_e.Class(PS,{hash:_e.bytes(Le).asOpaque(),slot:_e.u32.asOpaque()});static create({hash:e,slot:t}){return new PS(e,t)}constructor(e,t){super(),this.hash=e,this.slot=t}}class LS{final;leafs;static Codec=_e.Class(LS,{final:PS.Codec,leafs:_e.sequenceVarLen(PS.Codec)});static create({final:e,leafs:t}){return new LS(e,t)}constructor(e,t){this.final=e,this.leafs=t}}class HS extends B{header;final;static Codec=_e.Class(HS,{header:bs.Codec,final:PS.Codec});static create({header:e,final:t}){return new HS(e,t)}constructor(e,t){super(),this.header=e,this.final=t}}const VS=si.new(void 0,"protocol/up-0");class KS{spec;getHandshake;onAnnouncement;onHandshake;kind=MS;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=ge.decodeObject(LS.Codec,t);return this.handshakes.set(r,s),this.pendingHandshakes.delete(r)||(VS.log(`[${r}] <-- responding with a handshake.`),e.bufferAndSend(Ie.encodeObject(LS.Codec,this.getHandshake()))),void this.onHandshake(r,s)}const s=ge.decodeObject(HS.Codec,t,this.spec);VS.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();VS.trace(`[${t}] <-- sending handshake`),this.pendingHandshakes.set(e.streamId,!0),e.bufferAndSend(Ie.encodeObject(LS.Codec,r))}sendAnnouncement(e,t){const{streamId:r}=e;this.handshakes.has(r)?(VS.trace(`[${r}] <-- sending block announcement: ${t.final}`),e.bufferAndSend(Ie.encodeObject(HS.Codec,t,this.spec))):VS.warn(`[${r}] <-- no handshake yet, skipping announcement.`)}}const QS=31;var $S;!function(e){e[e.Branch=0]="Branch",e[e.Leaf=1]="Leaf",e[e.EmbedLeaf=2]="EmbedLeaf"}($S||($S={}));class FS{raw;constructor(e=new Uint8Array(64)){this.raw=e}getNodeType(){return 128&this.raw[0]?192&~this.raw[0]?$S.EmbedLeaf:$S.Leaf:$S.Branch}asBranchNode(){return w(this.getNodeType()===$S.Branch),new GS(this)}asLeafNode(){return w(this.getNodeType()!==$S.Branch),new jS(this)}toString(){return P.blobFrom(this.raw).toString()}}class GS{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,Le),r.raw[0]&=127,new GS(r)}getLeft(){return L.fromBlob(this.node.raw.subarray(0,Le),Le).asOpaque()}getRight(){return L.fromBlob(this.node.raw.subarray(Le),Le).asOpaque()}}class jS{node;constructor(e){this.node=e}static fromValue(e,t,r){const s=new FS;return t.length<=Le?(s.raw[0]=128|t.length,s.raw.set(e.raw.subarray(0,QS),1),s.raw.set(t.raw,32)):(s.raw[0]=192,s.raw.set(e.raw.subarray(0,QS),1),s.raw.set(r().raw,32)),new jS(s)}getKey(){return L.fromBlob(this.node.raw.subarray(1,32),QS).asOpaque()}hasEmbeddedValue(){return this.node.getNodeType()===$S.EmbedLeaf}getValueLength(){return 63&this.node.raw[0]}getValue(){const e=this.getValueLength();return P.blobFrom(this.node.raw.subarray(Le,Le+e))}getValueHash(){return L.fromBlob(this.node.raw.subarray(Le),Le).asOpaque()}toString(){return`LeafNode {\n key: ${this.getKey()},\n valueHash: ${this.getValueHash()}\n}`}}const qS=ES(129),zS=_e.bytes(64).convert(e=>L.fromBlob(e.raw,64),e=>new FS(e.raw));class WS extends B{key;value;static Codec=_e.Class(WS,{key:_e.bytes(QS),value:_e.blob});static create({key:e,value:t}){return new WS(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}class JS extends B{keyValuePairs;static Codec=_e.Class(JS,{keyValuePairs:_e.sequenceVarLen(WS.Codec)});static create({keyValuePairs:e}){return new JS(e)}constructor(e){super(),this.keyValuePairs=e}}class YS extends B{headerHash;startKey;endKey;maximumSize;static Codec=_e.Class(YS,{headerHash:_e.bytes(Le).asOpaque(),startKey:_e.bytes(QS),endKey:_e.bytes(QS),maximumSize:_e.u32});static create({headerHash:e,startKey:t,endKey:r,maximumSize:s}){return new YS(e,t,r,s)}constructor(e,t,r,s){super(),this.headerHash=e,this.startKey=t,this.endKey=r,this.maximumSize=s}}const XS=si.new(void 0,"protocol/ce-129");class ZS{isServer;getBoundaryNodes;getKeyValuePairs;kind=qS;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(XS.info(`[${e.streamId}][server]: Received request.`),void 0===this.getBoundaryNodes||void 0===this.getKeyValuePairs)return;const r=ge.decodeObject(YS.Codec,t),s=this.getBoundaryNodes(r.headerHash,r.startKey,r.endKey),i=this.getKeyValuePairs(r.headerHash,r.startKey,r.endKey);return XS.info(`[${e.streamId}][server]: <-- responding with boundary nodes and key value pairs.`),e.bufferAndSend(Ie.encodeObject(_e.sequenceVarLen(zS),s)),e.bufferAndSend(Ie.encodeObject(JS.Codec,JS.create({keyValuePairs:i}))),void e.close()}if(!this.boundaryNodes.has(e.streamId))return this.boundaryNodes.set(e.streamId,ge.decodeObject(_e.sequenceVarLen(zS),t)),void XS.info(`[${e.streamId}][client]: Received boundary nodes.`);this.onResponse.get(e.streamId)?.(ge.decodeObject(JS.Codec,t)),XS.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(Ie.encodeObject(YS.Codec,YS.create({headerHash:t,startKey:r,endKey:r,maximumSize:ae(4096)}))),e.close()}}ES(131),ES(132);class eE extends B{epochIndex;ticket;static Codec=_e.Class(eE,{epochIndex:_e.u32.asOpaque(),ticket:Ot.Codec});static create({epochIndex:e,ticket:t}){return new eE(e,t)}constructor(e,t){super(),this.epochIndex=e,this.ticket=t}}si.new(void 0,"protocol/ce-131-ce-132"),ES(133);class tE extends B{coreIndex;workPackage;static Codec=_e.Class(tE,{coreIndex:_e.u16.asOpaque(),workPackage:Yr.Codec});static create({coreIndex:e,workPackage:t}){return new tE(e,t)}constructor(e,t){super(),this.coreIndex=e,this.workPackage=t}}si.new(void 0,"protocol/ce-133"),_e.blob,ES(134);class rE extends B{coreIndex;segmentsRootMappings;static Codec=_e.Class(rE,{coreIndex:_e.u16.asOpaque(),segmentsRootMappings:_e.sequenceVarLen(is.Codec)});static create({coreIndex:e,segmentsRootMappings:t}){return new rE(e,t)}constructor(e,t){super(),this.coreIndex=e,this.segmentsRootMappings=t}}class sE extends B{workReportHash;signature;static Codec=_e.Class(sE,{workReportHash:_e.bytes(Le).asOpaque(),signature:_e.bytes(Ar).asOpaque()});static create({workReportHash:e,signature:t}){return new sE(e,t)}constructor(e,t){super(),this.workReportHash=e,this.signature=t}}si.new(void 0,"protocol/ce-134"),ES(135);class iE extends B{report;slot;signatures;static Codec=_e.Class(iE,{report:ns.Codec,slot:_e.u32.asOpaque(),signatures:xt(e=>Bt(ls.Codec,{minLength:0,maxLength:e.validatorsCount,typicalLength:e.validatorsCount/2}))});static create({report:e,slot:t,signatures:r}){return new iE(e,t,r)}constructor(e,t,r){super(),this.report=e,this.slot=t,this.signatures=r}}si.new(void 0,"protocol/ce-135");const nE={id:Symbol("sync")},aE=si.new(void 0,"net:sync");class oE{spec;streamManager;connections;blocks;onNewBlocks;static start(e,t,r,s,i){const n=new oE(e,t,r,s,i),a=e=>t.getPeer(e),o=new KS(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 TS(e,(e,t,r,s)=>{const i=a(e);return null!==i?n.handleGetBlockSequence(i,t,r,s):[]})),t.registerOutgoingHandlers(o),t.registerOutgoingHandlers(new NS(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=PS.create({hash:n,slot:a.timeSlotIndex.materialize()})}onUp0Handshake(e,t){const{hash:r,slot:s}=t.final;this.connections.withAuxData(e.id,nE,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=Ie.encodeObject(bs.Codec,e,t);return new Ve(ze(r).asOpaque(),e)}(t.header,this.spec);aE.info(`[${e.id}] --\x3e Received new header #${t.header.timeSlotIndex}: ${i.hash}`),this.connections.withAuxData(e.id,nE,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=PS.create({hash:i.hash,slot:i.data.timeSlotIndex}))}getUp0Handshake(){const e=this.blocks.getBestHeaderHash(),t=this.blocks.getHeader(e),r=t?.timeSlotIndex.materialize(),s=PS.create({hash:e,slot:r??Tr(0)});return LS.create({final:s,leafs:[]})}openUp0(e){this.streamManager.withNewStream(e,MS,(e,t)=>(e.sendHandshake(t),O))}broadcastHeader(e){const t=e.data.timeSlotIndex.materialize(),r=HS.create({header:e.data.materialize(),final:PS.create({hash:e.hash,slot:t})}),s=this.connections.getConnectedPeers();for(const i of s)this.streamManager.withStreamOfKind(i.peerId,MS,(s,n)=>(aE.log(`[${i.peerId}] <-- Broadcasting new header #${t}: ${e.hash}`),s.sendAnnouncement(n,r),O))}handleGetBlockSequence(e,t,r,s){const i=ae(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 ge.decodeObject(ws.Codec.View,n,e)},a=n(r);if(null===a)return D.error(DS.NoStartBlock);if(s===RS.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(DS.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===DS.BlockOnFork?(aE.warn(`[${e.id}] <-- Invalid block sequence request: ${t} is on a fork.`),[]):n.error===DS.NoStartBlock?(aE.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:cE.OurBestHeaderMissing};const s=t.timeSlotIndex.materialize(),i=this.othersBest,n=i.slot-s;if(aE.trace(`Our best. ${s}. Best seen: ${i.slot}`),n<1)return this.connections.getPeerCount(),aE.trace(`No new blocks. ${r} peers.`),{kind:cE.NoNewBlocks,ours:s,theirs:i.slot};const a=[];aE.log(`Sync ${n} blocks from ${r} peers.`);for(const e of this.connections.getConnectedPeers()){const t=this.connections.getAuxData(e.peerId,nE);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,_S,(t,n)=>(CS(async()=>{aE.log(`Fetching blocks from ${e.peerId}.`);const a=await t.requestBlockSequence(n,i,RS.DescIncl,ae(r-s));a.reverse(),this.onNewBlocks(a,e.peerId)},t=>{aE.warn(`[${e.peerId}] --\x3e requesting blocks to import: ${t}`)}),O)))}return{kind:cE.BlocksRequested,ours:s,requested:a}}}var cE;!function(e){e[e.OurBestHeaderMissing=1]="OurBestHeaderMissing",e[e.NoNewBlocks=2]="NoNewBlocks",e[e.BlocksRequested=3]="BlocksRequested"}(cE||(cE={}));const lE=si.new(void 0,"jamnps");function dE(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(!ne(n))throw new Error(`Invalid port number: "${i}"`);return new vS(t,s,n)}class uE extends B{bootnodes;id;genesisHeader;genesisState;static fromJson=te.object({bootnodes:te.optional(te.array(te.fromString(dE))),id:"string",genesis_header:Nt.bytesBlobNoPrefix,genesis_state:te.map(Nt.bytesNNoPrefix(31),Nt.bytesBlobNoPrefix)},e=>uE.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 uE({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 hE=t(import.meta.url)("node:fs");var fE=a.n(hE);const gE=t(import.meta.url)("node:os");var pE=a.n(gE);const bE=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"}'),mE=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 yE{omitSealVerification;static fromJson=te.object({omit_seal_verification:"boolean"},yE.new);static new({omit_seal_verification:e}){return new yE(e)}constructor(e){this.omitSealVerification=e}}const AE="dev",IE="default",vE={name:pE().hostname(),config:IE};var wE;!function(e){e.Tiny="tiny",e.Full="full"}(wE||(wE={}));const SE=te.fromString((e,t)=>{switch(e){case wE.Tiny:return wE.Tiny;case wE.Full:return wE.Full;default:throw Error(`unknown network flavor: ${e} at ${t}`)}});class EE{$schema;version;flavor;chainSpec;databaseBasePath;authorship;static fromJson=te.object({$schema:"string",version:"number",flavor:SE,chain_spec:uE.fromJson,database_base_path:"string",authorship:yE.fromJson},EE.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 EE(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 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,Le).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(Le).asOpaque():L.fromBlob(e,Le).asOpaque()}getHeader(e){const t=this.headers.get(e.raw);return void 0===t?null:ge.decodeObject(bs.Codec.View,t,this.chainSpec)}getExtrinsic(e){const t=this.extrinsics.get(e.raw);return void 0===t?null:ge.decodeObject(vs.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})}close(){return this.db.close()}}class OE{serviceId;output;static Codec=_e.Class(OE,{serviceId:_e.u32.asOpaque(),output:_e.bytes(Le)});static create(e){return new OE(e.serviceId,e.output)}constructor(e,t){this.serviceId=e,this.output=t}}const UE=e=>ke.withView(e.name,e.sizeHint,(t,r)=>e.encode(t,r.data),t=>{const r=t.clone(),s=ze(e.skipEncoded(r));return new Ve(s.asOpaque(),e.decode(t))},e.skip,e.View);class TE extends B{workReport;timeout;static Codec=_e.Class(TE,{workReport:UE(ns.Codec),timeout:_e.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=>xt(t=>Bt(e,{fixedLength:t.coresCount})),ME=()=>xe(_e.sequenceVarLen(_e.bytes(Le))).convert(e=>e.array,e=>{const t=e.map(e=>e.asOpaque());return vt.fromSortedArray(HE,t)}),PE=ME();class LE{goodSet;badSet;wonkySet;punishSet;static Codec=_e.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(vt.fromSortedArray(HE,e),vt.fromSortedArray(HE,t),vt.fromSortedArray(HE,r),vt.fromSortedArray(HE,s))}}function HE(e,t){return e.compare(t)}class VE{service;gasLimit;static Codec=_e.Class(VE,{service:_e.u32.asOpaque(),gasLimit:_e.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=_e.Class(KE,{manager:_e.u32.asOpaque(),authManager:v.isGreaterOrEqual(h.V0_6_7)?DE(_e.u32.asOpaque()):xt(e=>_e.u32.asOpaque().convert(e=>e[0],t=>NE(new Array(e.coresCount).fill(t),e))),validatorsManager:_e.u32.asOpaque(),autoAccumulateServices:xe(_e.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 $E{hasher;mountains;static empty(e){return new $E(e)}static fromPeaks(e,t){return new $E(e,t.peaks.reduce((e,t,r)=>(null!==t&&e.push(FE.fromPeak(t,2**r)),e),[]).reverse())}constructor(e,t=[]){this.hasher=e,this.mountains=t}append(e){let t=FE.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(Le).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 FE{peak;size;constructor(e,t){this.peak=e,this.size=t}static fromPeak(e,t){return new FE(e,t)}static fromChildren(e,t){const[r,s]=t,i=e.hashConcat(r.peak,s.peak),n=r.size+s.size;return new FE(i,n)}mergeWith(e,t){return FE.fromChildren(e,[this,t])}toString(){return`${this.size} @ ${this.peak}`}}class GE extends B{headerHash;mmr;postStateRoot;reported;static Codec=_e.Class(GE,{headerHash:_e.bytes(Le).asOpaque(),mmr:_e.object({peaks:xe(_e.sequenceVarLen(_e.optional(_e.bytes(Le))))}),postStateRoot:_e.bytes(Le).asOpaque(),reported:Rt(is.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=_e.Class(jE,{blocks:Bt(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=_e.Class(qE,{headerHash:_e.bytes(Le).asOpaque(),accumulationResult:_e.bytes(Le),postStateRoot:_e.bytes(Le).asOpaque(),reported:Rt(is.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=_e.Class(zE,{blocks:Bt(qE.Codec,{minLength:0,maxLength:8,typicalLength:8}),accumulationLog:_e.object({peaks:xe(_e.sequenceVarLen(_e.optional(_e.bytes(Le))))})});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=ke.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:$E.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=_e.Class(YE,{bandersnatch:_e.bytes(Ne).asOpaque(),ed25519:_e.bytes(yr).asOpaque(),bls:_e.bytes(Pe).asOpaque(),metadata:_e.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=_e.bytes(Ne).asOpaque();class eC extends B{kind;keys;tickets;static Codec=xt(e=>_e.custom({name:"SafroleSealingKeys",sizeHint:{bytes:1+Le*e.epochLength,isExact:!1}},(e,t)=>{e.varU32(ae(t.kind)),t.kind===XE.Keys?e.sequenceFixLen(ZE,t.keys):e.sequenceFixLen(Ut.Codec,t.tickets)},t=>{const r=e.epochLength,s=t.varU32();if(s===XE.Keys){const s=t.sequenceFixLen(ZE,r);return eC.keys(Kr(s,e))}if(s===XE.Tickets){const s=t.sequenceFixLen(Ut.Codec,r);return eC.tickets(Kr(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(Ut.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=_e.Class(tC,{nextValidatorData:Vr(YE.Codec),epochRoot:_e.bytes(Me).asOpaque(),sealingKeySeries:eC.Codec,ticketsAccumulator:xe(_e.sequenceVarLen(Ut.Codec)).convert(R,yt)});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=>ke.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)?_e.Class(iC,{codeHash:_e.bytes(Le).asOpaque(),balance:_e.u64,accumulateMinGas:_e.u64.convert(e=>e,Mr),onTransferMinGas:_e.u64.convert(e=>e,Mr),storageUtilisationBytes:_e.u64,gratisStorage:_e.u64,storageUtilisationCount:_e.u32,created:_e.u32.convert(e=>e,Tr),lastAccumulation:_e.u32.convert(e=>e,Tr),parentService:_e.u32.convert(e=>e,Dr)}):_e.Class(iC,{codeHash:_e.bytes(Le).asOpaque(),balance:_e.u64,accumulateMinGas:_e.u64.convert(e=>e,Mr),onTransferMinGas:_e.u64.convert(e=>e,Mr),storageUtilisationBytes:_e.u64,storageUtilisationCount:_e.u32,gratisStorage:sC(ce(0)),created:sC(Tr(0)),lastAccumulation:sC(Tr(0)),parentService:sC(Dr(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===ce(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 ce(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=_e.Class(nC,{hash:_e.bytes(Le).asOpaque(),blob:_e.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=_e.Class(aC,{key:_e.blob.convert(e=>e,e=>e),value:_e.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 ae(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)?_e.u32.asOpaque():_e.varU32.convert(e=>ae(e),e=>Dr(e));class bC{blocks;tickets;preImages;preImagesSize;guarantees;assurances;static Codec=_e.Class(bC,{blocks:_e.u32,tickets:_e.u32,preImages:_e.u32,preImagesSize:_e.u32,guarantees:_e.u32,assurances:_e.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=ae(0);return new bC(e,e,e,e,e,e)}}const mC=_e.varU32.convert(e=>ae(e),e=>ie(e)),yC=_e.varU64.convert(e=>ce(e),e=>Mr(e));class AC{dataAvailabilityLoad;popularity;imports;exports;extrinsicSize;extrinsicCount;bundleSize;gasUsed;static Codec=_e.Class(AC,{dataAvailabilityLoad:_e.varU32,popularity:mC,imports:mC,exports:mC,extrinsicSize:_e.varU32,extrinsicCount:mC,bundleSize:_e.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=ae(0),t=ie(0),r=Mr(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=_e.Class(IC,{providedCount:mC,providedSize:_e.varU32,refinementCount:_e.varU32,refinementGasUsed:yC,imports:mC,exports:mC,extrinsicSize:_e.varU32,extrinsicCount:mC,accumulateCount:_e.varU32,accumulateGasUsed:yC,onTransfersCount:_e.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=ae(0),t=ie(0),r=Mr(0);return new IC(t,e,e,r,t,t,e,t,e,r,e,r)}}class vC{current;previous;cores;services;static Codec=_e.Class(vC,{current:Vr(bC.Codec),previous:Vr(bC.Codec),cores:DE(AC.Codec),services:_e.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=bt.new(),i=new Map,n=bt.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=ae(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:bt.new(),storage:new Map,lookupHistory:bt.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:Hr(Array.from({length:e.validatorsCount},()=>YE.create({bandersnatch:L.zero(Ne).asOpaque(),bls:L.zero(Pe).asOpaque(),ed25519:L.zero(yr).asOpaque(),metadata:L.zero(JE).asOpaque()})),e),nextValidatorData:Hr(Array.from({length:e.validatorsCount},()=>YE.create({bandersnatch:L.zero(Ne).asOpaque(),bls:L.zero(Pe).asOpaque(),ed25519:L.zero(yr).asOpaque(),metadata:L.zero(JE).asOpaque()})),e),currentValidatorData:Hr(Array.from({length:e.validatorsCount},()=>YE.create({bandersnatch:L.zero(Ne).asOpaque(),bls:L.zero(Pe).asOpaque(),ed25519:L.zero(yr).asOpaque(),metadata:L.zero(JE).asOpaque()})),e),previousValidatorData:Hr(Array.from({length:e.validatorsCount},()=>YE.create({bandersnatch:L.zero(Ne).asOpaque(),bls:L.zero(Pe).asOpaque(),ed25519:L.zero(yr).asOpaque(),metadata:L.zero(JE).asOpaque()})),e),disputesRecords:LE.create({goodSet:vt.fromSortedArray(HE,[]),badSet:vt.fromSortedArray(HE,[]),wonkySet:vt.fromSortedArray(HE,[]),punishSet:vt.fromSortedArray(HE,[])}),timeslot:Tr(0),entropy:At.fill(()=>L.zero(Le).asOpaque(),4),authPools:NE(Array.from({length:e.coresCount},()=>[]),e),authQueues:NE(Array.from({length:e.coresCount},()=>At.fill(()=>L.zero(Le).asOpaque(),80)),e),recentBlocks:WE.empty(),statistics:vC.create({current:Hr(Array.from({length:e.validatorsCount},()=>bC.empty()),e),previous:Hr(Array.from({length:e.validatorsCount},()=>bC.empty()),e),cores:NE(Array.from({length:e.coresCount},()=>AC.empty()),e),services:new Map}),accumulationQueue:Kr(Array.from({length:e.epochLength},()=>[]),e),recentlyAccumulated:Kr(Array.from({length:e.epochLength},()=>mt.new()),e),ticketsAccumulator:[],sealingKeySeries:eC.keys(Kr(Array.from({length:e.epochLength},()=>L.zero(Ne).asOpaque()),e)),epochRoot:L.zero(Me).asOpaque(),privilegedServices:KE.create({manager:Dr(0),authManager:NE(new Array(e.coresCount).fill(Dr(0)),e),validatorsManager:Dr(0),autoAccumulateServices:[]}),accumulationOutputLog:[],services:new Map})}}const kC=_e.object({storageKeys:_e.sequenceVarLen(_e.blob.convert(e=>e,e=>e)),preimages:_e.sequenceVarLen(_e.bytes(Le).asOpaque()),lookupHistory:_e.sequenceVarLen(_e.object({hash:_e.bytes(Le).asOpaque(),length:_e.u32}))});_e.dictionary(_e.u32.asOpaque(),kC,{sortKeys:(e,t)=>e-t});class xC extends B{report;dependencies;static Codec=_e.Class(xC,{report:ns.Codec,dependencies:Bt(_e.bytes(Le).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(Le);let s=0;for(const i of ue(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,Le-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=ze(P.blobFromParts(ue(t),r.raw)).raw.subarray(0,28),i=L.zero(Le);let n=0;for(const t of ue(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(Le);return t.raw[0]=e,t.asOpaque()},e.serviceInfo=function(e){const t=L.zero(Le);t.raw[0]=BC.Delta;let r=1;for(const s of ue(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(Le);return t.raw.set(ue(ae(2**32-1)),0),t.raw.set(r.raw.subarray(0,28),4),OC(e,t)}return t(e,ae(2**32-1),r)},e.servicePreimage=function(e,r){if(v.isLessThan(h.V0_6_7)){const t=L.zero(Le);return t.raw.set(ue(ae(2**32-2)),0),t.raw.set(r.raw.subarray(1,29),4),OC(e,t)}return t(e,ae(2**32-2),r)},e.serviceLookupHistory=function(e,r,s){if(v.isLessThan(h.V0_6_7)){const t=ze(r),i=L.zero(Le);return i.raw.set(ue(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(Bt(_e.bytes(Le).asOpaque(),{minLength:0,maxLength:8,typicalLength:8})),extract:e=>e.authPools},e.authQueues={key:_C.index(BC.Phi),Codec:DE(_t(_e.bytes(Le).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:_t(_e.bytes(Le).asOpaque(),4),extract:e=>e.entropy},e.designatedValidators={key:_C.index(BC.Iota),Codec:Vr(YE.Codec),extract:e=>e.designatedValidatorData},e.currentValidators={key:_C.index(BC.Kappa),Codec:Vr(YE.Codec),extract:e=>e.currentValidatorData},e.previousValidators={key:_C.index(BC.Lambda),Codec:Vr(YE.Codec),extract:e=>e.previousValidatorData},e.availabilityAssignment={key:_C.index(BC.Rho),Codec:DE(_e.optional(TE.Codec)),extract:e=>e.availabilityAssignment},e.timeslot={key:_C.index(BC.Tau),Codec:_e.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:Qr(xe(_e.sequenceVarLen(xC.Codec))),extract:e=>e.accumulationQueue},e.recentlyAccumulated={key:_C.index(BC.Xi),Codec:Qr(_e.sequenceVarLen(_e.bytes(Le).asOpaque()).convert(e=>Array.from(e),e=>mt.from(e))),extract:e=>e.recentlyAccumulated},e.accumulationOutputLog={key:_C.index(BC.Theta),Codec:_e.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:xe(_e.sequenceVarLen(_e.u32))})}(RC||(RC={}));const UC=ke.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(ue(e)),r.set(t.raw,4),P.blobFrom(ze(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 ge.decodeObject(t,s,this.spec)}retrieveOptional({key:e,Codec:t}){const r=this.backend.get(e);if(null!==r)return ge.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(ue(this.serviceId)),r.set(e.raw,t);const s=P.blobFrom(ze(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(Tr))}}class LC{hasher;nodes=bt.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()!==$S.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 jS.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(Le).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 $C;let i=e,n=t.hashNode(e);for(;;){if(i.getNodeType()!==$S.Branch){const e=i.asLeafNode();return s.leafToReplace=[e,n],s}const e=i.asBranchNode(),a=FC(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(Le)))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=FC(i,e.bitIndex);for(;e.bitIndex<248;){d=FC(i,e.bitIndex);const t=FC(o,e.bitIndex);if(d!==t)break;l.push(t),e.bitIndex+=1}const u=L.zero(Le).asOpaque();(()=>{const t=e.branchingHistory.length;return t>0&&!1===e.branchingHistory[t-1][2]})()&&!d&&(a=t.hashNode(n.node));let h=d?GS.fromSubNodes(a,c):GS.fromSubNodes(c,a),f=t.insert(h.node),g=l.pop();for(;void 0!==g;)h=g?GS.fromSubNodes(u,f):GS.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?GS.fromSubNodes(e.getLeft(),o):GS.fromSubNodes(o,e.getRight());o=t.insert(c.node),a=c.node,n=s.branchingHistory.pop()}return a}class $C{branchingHistory=[];bitIndex=0;leafToReplace}function FC(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()===$S.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=[])=>qe([e,...t])},qC=_e.sequenceVarLen(_e.pair(_e.bytes(He),_e.blob));class zC{entries;static Codec=_e.custom({name:"StateEntries",sizeHint:{isExact:!1,bytes:4100}},(e,t)=>qC.encode(e,Array.from(t.entries)),e=>zC.fromEntriesUnsafe(qC.decode(e)),e=>qC.skip(e));static serializeInMemory(e,t){return new zC(function(e,t){const r=wt.fromEntries([]);function s(s){r.set(s.key,Ie.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,Ie.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,Ie.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,Ie.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,Ie.encodeObject(i,s.slots.slice()))}}return r}(e,t))}static fromDictionaryUnsafe(e){return new zC(e)}static fromEntriesUnsafe(e){return new zC(wt.fromEntries(e))}trieCache=null;constructor(e){this.entries=e}[M](){return Object.fromEntries(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 WC=(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}}={})=>ke.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(ae(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)}),JC=_e.object({hash:_e.bytes(Le).asOpaque(),length:_e.u32,slots:xe(_e.sequenceVarLen(_e.u32.asOpaque())).convert(R,oC)},"LookupHistoryItem",({hash:e,length:t,slots:r})=>new cC(e,t,r)),YC=_e.object({key:_e.bytes(Le).asOpaque(),data:_e.sequenceVarLen(JC)}),XC=_e.sequenceVarLen(YC).convert(e=>{const t=[];for(const[r,s]of e)t.push({key:r,data:s});return t},e=>{const t=bt.new();for(const{key:r,data:s}of e){const e=t.get(r)??[];e.push(...s),t.set(r,e)}return t});class ZC extends EC{static Codec=_e.Class(ZC,{serviceId:_e.u32.asOpaque(),data:_e.object({info:iC.Codec,preimages:Rt(nC.Codec,e=>e.hash),lookupHistory:XC,storage:WC(aC.Codec,e=>e.key.toString())})});constructor(e,t){super(e,t)}static create({serviceId:e,data:t}){return new ZC(e,t)}}var ek,tk,rk;_e.Class(CC,{authPools:RC.authPools.Codec,authQueues:RC.authQueues.Codec,recentBlocks:RC.recentBlocks.Codec,nextValidatorData:Vr(YE.Codec),epochRoot:_e.bytes(Me).asOpaque(),sealingKeySeries:eC.Codec,ticketsAccumulator:xe(_e.sequenceVarLen(Ut.Codec)).convert(e=>e,yt),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:_e.dictionary(_e.u32.asOpaque(),ZC.Codec,{sortKeys:(e,t)=>e-t})}),function(e){e[e.Conflict=0]="Conflict",e[e.Commit=1]="Commit"}(ek||(ek={})),function(e){e[e.InvalidLeafData=0]="InvalidLeafData"}(tk||(tk={}));class sk{leaves;db;static fromLeavesBlob(e,t){if(e.length%64!=0)return D.error(tk.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()===$S.Branch)return D.error(tk.InvalidLeafData,`Branch node detected: ${t}`);r.push(e.asLeafNode())}return D.ok(new sk(r,t))}lookup;constructor(e,t){this.leaves=e,this.db=t,this.lookup=wt.fromEntries(e.map(e=>[e.getKey().asOpaque(),e.hasEmbeddedValue()?{kind:rk.EmbeddedValue,value:e.getValue()}:{kind:rk.DbKey,key:e.getValueHash().raw}]))}get(e){const t=this.lookup.get(e);return void 0===t?null:t.kind===rk.EmbeddedValue?t.value:t.kind===rk.DbKey?P.blobFrom(this.db.get(t.key)):void E(t)}getStateRoot(){return KC.computeStateRoot(jC,this.leaves).asOpaque()}intoStateEntries(){const e=[];for(const[t,r]of this.lookup.entries())switch(r.kind){case rk.EmbeddedValue:e.push([t.asOpaque(),r.value]);continue;case rk.DbKey:e.push([t.asOpaque(),P.blobFrom(this.db.get(r.key))]);continue;default:E(r)}return zC.fromEntriesUnsafe(e)}}!function(e){e[e.EmbeddedValue=0]="EmbeddedValue",e[e.DbKey=1]="DbKey"}(rk||(rk={}));const ik=si.new(void 0,"db");class nk{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,vt.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 ik.error(`${e}`),D.error(ek.Commit)}return D.ok(O)}async updateAndSetState(e,t,r){const s=vt.fromSortedArray(VC,t.backend.leaves),i=function*(e,t){yield*function*(e,t){function r(t,r){return[TC.Insert,r.key,Ie.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)=>Ie.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,ae(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=sk.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 ak=si.new(void 0,"jam");function ok(e){if(e===wE.Full)return Ct;if(e===wE.Tiny)return Et;throw new Error(`Unknown chain spec: ${e}. Possible options: ${[wE.Full,wE.Tiny]}`)}const ck={genesisPath:"",timeSlot:Tr(0),validatorIndex:Nr(0)};class lk{isAuthoring;nodeName;node;dev;network;static new({isAuthoring:e,nodeName:t,nodeConfig:r,devConfig:s,seedConfig:i,networkConfig:n}){let a=s??{...ck};return void 0!==i&&(a={...a,...i}),new lk(e??!1,t,r,a,n??null)}constructor(e,t,r,s,i){this.isAuthoring=e,this.nodeName=t,this.node=r,this.dev=s,this.network=i}}const dk=t(import.meta.url)("node:worker_threads"),uk=2**32,hk=si.new(void 0,"state-machine/port");class fk{port;listeners=new Wn.EventEmitter;responseListeners=new Wn.EventEmitter;messageId=0;constructor(e){this.port=e,e.on("message",e=>{try{this.dispatchPortMessage(e)}catch(t){throw hk.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)%uk,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(gk(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,s){w("request"===t.kind),this.postMessage({kind:"response",id:t.id,name:t.name,data:r,localState:e},s)}close(){this.cleanup("closing"),this.listeners.removeAllListeners(),this.port.close()}postMessage(e,t){try{this.port.postMessage(e,t)}catch(t){throw hk.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(gk(e.id))),this.responseListeners.emit(gk(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 gk(e){return`req:${e}`}const pk=si.new(void 0,"state-machine"),bk="channel";class mk{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 pk.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 pk.error(`[${this.constructor.name}] Unable to dispatch request (${e}): ${t}. ${this.stateInfo(r)}`),t}})}sendSignal(e,t,r){this.port.sendSignal(this.currentState().stateName,e,t,r)}async sendRequest(e,t,r){return this.port.sendRequest(this.currentState().stateName,e,t,r)}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()}execute(e){return e(this.currentState(),this)}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);pk.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 pk.trace(`[${this.machine.name}] transitioned to ${this.currentState()}`),this}static async createAndTransferChannel(e,t){const r=new dk.MessageChannel,s=new fk(r.port2),i=e.currentState().stateName,[n,a]=s.prepareRequest(i,bk,r.port1);t.postMessage(n,[r.port1]);try{await a}catch(e){pk.error(JSON.stringify(e))}return new mk(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===bk),w(t.data instanceof dk.MessagePort);const s=new fk(t.data);s.respond(e.currentState().stateName,t,"OK"),r(s)}catch(e){s(e)}})}),s=await r;return new mk(e,s)}}const yk=Symbol(),Ak=Symbol();class Ik{emitter=new Wn.EventEmitter;emit(e){this.emitter.emit(yk,e)}on(e){return this.emitter.on(yk,e),this}off(e){return this.emitter.off(yk,e),this}once(e){return this.emitter.once(yk,e),this}onceDone(e){return this.emitter.once(Ak,e),this}markDone(){this.emitter.emit(Ak),this.emitter.removeAllListeners(yk),this.emitter.removeAllListeners(Ak)}}class vk{name;state;allStates;stateListeners=new Wn.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 wk=si.new(void 0,"state-machine/state");class Sk{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){wk.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 Ek extends B{major;minor;patch;static Codec=_e.Class(Ek,{major:_e.u8,minor:_e.u8,patch:_e.u8});static tryFromString(e){const t=e=>re(Number(e));try{const[r,s,i]=e.trim().split(".").map(t);return Ek.create({major:r,minor:s,patch:i})}catch(t){throw new Error(`Unable to parse ${e} as Version: ${t}`)}}static create({major:e,minor:t,patch:r}){return new Ek(e,t,r)}constructor(e,t,r){super(),this.major=e,this.minor=t,this.patch=r}}class Ck extends B{name;appVersion;jamVersion;static Codec=_e.Class(Ck,{name:_e.string,appVersion:Ek.Codec,jamVersion:Ek.Codec});static create({name:e,appVersion:t,jamVersion:r}){return new Ck(e,t,r)}constructor(e,t,r){super(),this.name=e,this.appVersion=t,this.jamVersion=r}}class kk extends B{key;value;static Codec=_e.Class(kk,{key:_e.bytes(He),value:_e.blob});static create({key:e,value:t}){return new kk(e,t)}constructor(e,t){super(),this.key=e,this.value=t}}const xk=_e.sequenceVarLen(kk.Codec),Bk=ws.Codec;class _k extends B{header;state;static Codec=_e.Class(_k,{header:bs.Codec,state:_e.sequenceVarLen(kk.Codec)});static create({header:e,state:t}){return new _k(e,t)}constructor(e,t){super(),this.header=e,this.state=t}}const Rk=_e.bytes(Le).asOpaque(),Ok=_e.bytes(Le).asOpaque();var Uk;!function(e){e[e.PeerInfo=0]="PeerInfo",e[e.ImportBlock=1]="ImportBlock",e[e.SetState=2]="SetState",e[e.GetState=3]="GetState",e[e.State=4]="State",e[e.StateRoot=5]="StateRoot"}(Uk||(Uk={}));const Tk=_e.custom({name:"Message",sizeHint:{bytes:1,isExact:!1}},(e,t)=>{switch(e.i8(t.type),t.type){case Uk.PeerInfo:Ck.Codec.encode(e,t.value);break;case Uk.ImportBlock:Bk.encode(e,t.value);break;case Uk.SetState:_k.Codec.encode(e,t.value);break;case Uk.GetState:Rk.encode(e,t.value);break;case Uk.State:xk.encode(e,t.value);break;case Uk.StateRoot:Ok.encode(e,t.value);break;default:throw new Error(`Unknown message type: ${t}`)}},e=>{const t=e.u8();switch(t){case Uk.PeerInfo:return{type:Uk.PeerInfo,value:Ck.Codec.decode(e)};case Uk.ImportBlock:return{type:Uk.ImportBlock,value:Bk.decode(e)};case Uk.SetState:return{type:Uk.SetState,value:_k.Codec.decode(e)};case Uk.GetState:return{type:Uk.GetState,value:Rk.decode(e)};case Uk.State:return{type:Uk.State,value:xk.decode(e)};case Uk.StateRoot:return{type:Uk.StateRoot,value:Ok.decode(e)};default:throw new Error(`Unknown message type: ${t}`)}},e=>{const t=e.decoder.u8();switch(t){case Uk.PeerInfo:Ck.Codec.View.skip(e);break;case Uk.ImportBlock:Bk.View.skip(e);break;case Uk.SetState:_k.Codec.View.skip(e);break;case Uk.GetState:Rk.View.skip(e);break;case Uk.State:xk.View.skip(e);break;case Uk.StateRoot:Ok.View.skip(e);break;default:throw new Error(`Unknown message type: ${t}`)}}),Nk=si.new(void 0,"ext-ipc-fuzz");class Dk{msgHandler;sender;spec;constructor(e,t,r){this.msgHandler=e,this.sender=t,this.spec=r}async onSocketMessage(e){const t=ge.decodeObject(Tk,e,this.spec);return Nk.log(`[${t.type}] incoming message`),void await async function(e,t,r,s){let i=null;switch(t.type){case Uk.PeerInfo:{const e=await r.getPeerInfo(t.value);i={type:Uk.PeerInfo,value:e};break}case Uk.ImportBlock:{const e=await r.importBlock(t.value);i={type:Uk.StateRoot,value:e};break}case Uk.SetState:{const e=await r.resetState(t.value);i={type:Uk.StateRoot,value:e};break}case Uk.GetState:{const e=await r.getSerializedState(t.value);i={type:Uk.State,value:e};break}case Uk.State:return Nk.log("--\x3e Received unexpected 'State' message from the fuzzer. Closing."),void s.close();case Uk.StateRoot:return Nk.log("--\x3e Received unexpected 'StateRoot' message from the fuzzer. Closing."),void s.close();default:Nk.log(`--\x3e Received unexpected message type ${JSON.stringify(t)} from the fuzzer. Closing.`),s.close();try{E(t)}catch{return}}if(null!==i){Nk.trace(`<-- responding with: ${i.type}`);const t=Ie.encodeObject(Tk,i,e);s.send(t)}else Nk.warn(`<-- no response generated for: ${t.type}`)}(this.spec,t,this.msgHandler,this.sender).catch(e=>{Nk.error(`Error while processing fuzz message: ${e}`),Nk.error(e),this.sender.close()})}onClose({error:e}){Nk.log(`Closing the handler. Reason: ${void 0!==e?e.message:"close"}.`)}}const Mk=t(import.meta.url)("node:net"),Pk=t(import.meta.url)("node:path");class Lk{socket;constructor(e){this.socket=e}send(e){!function(e,t){e.write(AS(t)),e.write(t)}(this.socket,e.raw)}close(){this.socket.end()}}function Hk(e,t){const r="win32"===gE.platform()?`\\\\.\\pipe\\${e}`:Pk.join(gE.tmpdir(),`${e}.ipc`),s=si.new(void 0,"ext-ipc"),i=(0,Mk.createServer)(e=>{s.log("Client connected");const r=t(new Lk(e));e.on("data",IS(async t=>{try{e.pause(),await r.onSocketMessage(t)}catch(t){s.error(`Received invalid data on socket: ${t}. Closing connection.`),e.end()}finally{e.resume()}},()=>{s.error("Received too much data on socket. Closing connection."),e.end()})),e.on("end",()=>{s.log("Client disconnected"),r.onClose({})}),e.on("error",t=>{s.error(`Socket error: ${t}`),r.onClose({error:t}),e.end()})});try{hE.unlinkSync(r)}catch{}const n=new AbortController;return i.listen({path:r,signal:n.signal},()=>{s.log(`IPC server is listening at ${r}`)}),i.on("error",e=>{throw e}),()=>{s.info("Closing IPC server."),i.close(),n.abort(),i.unref()}}var Vk;!function(e){e[e.Msg=0]="Msg",e[e.Open=1]="Open",e[e.Close=2]="Close"}(Vk||(Vk={}));class Kk{streamId;type;data;static Codec=_e.Class(Kk,{streamId:_e.u32,type:_e.u8.convert(e=>re(e),e=>{switch(e){case Vk.Msg:return Vk.Msg;case Vk.Open:return Vk.Open;case Vk.Close:return Vk.Close;default:throw new Error(`Invalid 'StreamEnvelopeType' value: ${e}`)}}),data:_e.blob});static create({streamId:e,type:t,data:r}){return new Kk(e,t,r)}constructor(e,t,r){this.streamId=e,this.type=t,this.data=r}}class Qk{streamByte;static Codec=_e.Class(Qk,{streamByte:_e.u8});static create({streamByte:e}){return new Qk(e)}constructor(e){this.streamByte=e}}const $k=si.new(void 0,"ext-ipc-jamnp");class Fk{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 Gk(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 Gk(i,this.sender);n.open(Qk.create({streamByte:e})),t(r,n)}async onSocketMessage(e){const t=ge.decodeObject(Kk.Codec,e),r=t.streamId;$k.log(`[${r}] incoming message: ${t.type} ${t.data}`);const s=this.streams.get(r),i=new Gk(r,this.sender);if(void 0===s){if(t.type!==Vk.Open)return void $k.warn(`[${r}] (unknown) got invalid type ${t.type}.`);const e=ge.decodeObject(Qk.Codec,t.data),s=this.streamHandlers.get(e.streamByte);return void 0!==s?($k.log(`[${r}] new stream for ${s.kind}`),this.streams.set(r,s),void i.open(e)):void i.close()}if(t.type===Vk.Close){const e=this.streams.get(r);return e?.onClose(r,!1),void this.streams.delete(r)}t.type===Vk.Msg?s.onStreamMessage(i,t.data):this.pendingStreams.delete(r)||$k.warn(`[${r}] got invalid type ${t.type}.`)}onClose({error:e}){$k.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 $k.log("Waiting for the handler to be closed."),this.onEnd.listen}}class Gk{streamId;sender;constructor(e,t){this.streamId=e,this.sender=t}open(e){const t=Ie.encodeObject(Qk.Codec,e);this.sender.send(Ie.encodeObject(Kk.Codec,Kk.create({streamId:this.streamId,type:Vk.Open,data:t})))}bufferAndSend(e){return this.sender.send(Ie.encodeObject(Kk.Codec,Kk.create({streamId:this.streamId,type:Vk.Msg,data:e}))),!0}close(){this.sender.send(Ie.encodeObject(Kk.Codec,Kk.create({streamId:this.streamId,type:Vk.Close,data:P.blobFromNumbers([])})))}}const jk=si.new(void 0,"ext-ipc");class qk{api;constructor(e){this.api=e}async getSerializedState(e){const t=await this.api.getPostSerializedState(e);return null===t?(jk.warn(`Fuzzer requested non-existing state for: ${e}`),[]):Array.from(t).map(([e,t])=>({key:L.fromBlob(e.raw.subarray(0,He),He),value:t}))}async resetState(e){const t=zC.fromEntriesUnsafe(e.state.map(({key:e,value:t})=>[e.asOpaque(),t]));return this.api.resetState(e.header,t)}async importBlock(e){const t=await this.api.importBlock(e);return t.isError?(jk.warn(`Fuzzer imported incorrect block with error ${t.error}. ${t.details}`),L.zero(Le).asOpaque()):t.ok}async getPeerInfo(e){return jk.info(`Fuzzer ${e} connected.`),Ck.create({name:this.api.nodeName,appVersion:this.api.nodeVersion,jamVersion:this.api.gpVersion})}}class zk extends Sk{constructor(){super({name:"finished"})}close(e){e.close()}async waitForWorkerToFinish(){return this.data}}class Wk extends Sk{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 Jk extends Sk{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 Yk(e,t,r,s){const i=new dk.Worker(e),n=function(e,t,r){const s=new Wk(t),i=new zk;return new vk(e,s,[s,r,i])}(`main->${r}`,r,s),a=await mk.createAndTransferChannel(n,i);return t.trace(`[${n.name}] Worker spawned ${a.currentState()}`),a}const Xk=4294967295,Zk=4294967296,ex=4096,tx=(w(!0,"incorrect minimal allocation shift"),7),rx=ex>>tx,sx=1048575,ix=1048576,nx=e=>S(e,e>=0&&e<=Xk,`Incorrect memory index: ${e}!`),ax=e=>S(e,e>=0&&e<=4294967296,`Incorrect sbrk index: ${e}!`);var ox,cx;(cx=ox||(ox={}))[cx.OK=255]="OK",cx[cx.HALT=0]="HALT",cx[cx.PANIC=1]="PANIC",cx[cx.FAULT=2]="FAULT",cx[cx.HOST=3]="HOST",cx[cx.OOG=4]="OOG";const lx=e=>S(e,e>=0&&e<=13,`Incorrect register index: ${e}!`);class dx{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 dx(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]=ux(t)}setI32(e,t){this.asSigned[e]=ux(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 ux(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 hx=e=>ae(e);var fx,gx;function px(...e){return e.map(lx)}!function(e){e[e.Halt=0]="Halt",e[e.Panic=1]="Panic"}(fx||(fx={}));class bx{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 bx(Y.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"}(gx||(gx={}));class mx{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 yx{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 Ax{nibblesDecoder=new yx;offsetDecoder=new mx;code=new Uint8Array;mask=bx.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 gx.NO_ARGUMENTS:break;case gx.ONE_IMMEDIATE:{const s=Math.min(4,r-1),i=e+1;t.immediateDecoder.setBytes(this.code.subarray(i,i+s));break}case gx.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 gx.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 gx.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 gx.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 gx.TWO_REGISTERS:{const r=this.code[e+1];this.nibblesDecoder.setByte(r),t.firstRegisterIndex=this.nibblesDecoder.getHighNibbleAsRegisterIndex(),t.secondRegisterIndex=this.nibblesDecoder.getLowNibbleAsRegisterIndex();break}case gx.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 gx.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 gx.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 gx.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 gx.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 gx.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 Ix{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 vx=Object.keys(gx).length/2;var wx;!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"}(wx||(wx={}));const Sx=wx.MIN_U,Ex=(()=>{const e=new Array(Sx+1);return e[wx.TRAP]=gx.NO_ARGUMENTS,e[wx.FALLTHROUGH]=gx.NO_ARGUMENTS,e[wx.ECALLI]=gx.ONE_IMMEDIATE,e[wx.LOAD_IMM_64]=gx.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,e[wx.STORE_IMM_U8]=gx.TWO_IMMEDIATES,e[wx.STORE_IMM_U16]=gx.TWO_IMMEDIATES,e[wx.STORE_IMM_U32]=gx.TWO_IMMEDIATES,e[wx.STORE_IMM_U64]=gx.TWO_IMMEDIATES,e[wx.JUMP]=gx.ONE_OFFSET,e[wx.JUMP_IND]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.LOAD_IMM]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.LOAD_U8]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.LOAD_I8]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.LOAD_U16]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.LOAD_I16]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.LOAD_U32]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.LOAD_I32]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.LOAD_U64]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.STORE_U8]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.STORE_U16]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.STORE_U32]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.STORE_U64]=gx.ONE_REGISTER_ONE_IMMEDIATE,e[wx.STORE_IMM_IND_U8]=gx.ONE_REGISTER_TWO_IMMEDIATES,e[wx.STORE_IMM_IND_U16]=gx.ONE_REGISTER_TWO_IMMEDIATES,e[wx.STORE_IMM_IND_U32]=gx.ONE_REGISTER_TWO_IMMEDIATES,e[wx.STORE_IMM_IND_U64]=gx.ONE_REGISTER_TWO_IMMEDIATES,e[wx.LOAD_IMM_JUMP]=gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[wx.BRANCH_EQ_IMM]=gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[wx.BRANCH_NE_IMM]=gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[wx.BRANCH_LT_U_IMM]=gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[wx.BRANCH_LE_U_IMM]=gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[wx.BRANCH_GE_U_IMM]=gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[wx.BRANCH_GT_U_IMM]=gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[wx.BRANCH_LT_S_IMM]=gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[wx.BRANCH_LE_S_IMM]=gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[wx.BRANCH_GE_S_IMM]=gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[wx.BRANCH_GT_S_IMM]=gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,e[wx.MOVE_REG]=gx.TWO_REGISTERS,e[wx.SBRK]=gx.TWO_REGISTERS,e[wx.COUNT_SET_BITS_64]=gx.TWO_REGISTERS,e[wx.COUNT_SET_BITS_32]=gx.TWO_REGISTERS,e[wx.LEADING_ZERO_BITS_64]=gx.TWO_REGISTERS,e[wx.LEADING_ZERO_BITS_32]=gx.TWO_REGISTERS,e[wx.TRAILING_ZERO_BITS_64]=gx.TWO_REGISTERS,e[wx.TRAILING_ZERO_BITS_32]=gx.TWO_REGISTERS,e[wx.SIGN_EXTEND_8]=gx.TWO_REGISTERS,e[wx.SIGN_EXTEND_16]=gx.TWO_REGISTERS,e[wx.ZERO_EXTEND_16]=gx.TWO_REGISTERS,e[wx.REVERSE_BYTES]=gx.TWO_REGISTERS,e[wx.STORE_IND_U8]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.STORE_IND_U16]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.STORE_IND_U32]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.STORE_IND_U64]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.LOAD_IND_U8]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.LOAD_IND_I8]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.LOAD_IND_U16]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.LOAD_IND_I16]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.LOAD_IND_U32]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.LOAD_IND_I32]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.LOAD_IND_U64]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.ADD_IMM_32]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.ADD_IMM_64]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.AND_IMM]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.XOR_IMM]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.OR_IMM]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.MUL_IMM_32]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.MUL_IMM_64]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SET_LT_U_IMM]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SET_LT_S_IMM]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SHLO_L_IMM_32]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SHLO_R_IMM_32]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SHAR_R_IMM_32]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.NEG_ADD_IMM_32]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SHLO_L_IMM_64]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SHLO_R_IMM_64]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SHAR_R_IMM_64]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.NEG_ADD_IMM_64]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SET_GT_U_IMM]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SET_GT_S_IMM]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SHLO_L_IMM_ALT_32]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SHLO_R_IMM_ALT_32]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SHAR_R_IMM_ALT_32]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SHLO_L_IMM_ALT_64]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SHLO_R_IMM_ALT_64]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.SHAR_R_IMM_ALT_64]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.CMOV_IZ_IMM]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.CMOV_NZ_IMM]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.ROT_R_64_IMM]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.ROT_R_64_IMM_ALT]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.ROT_R_32_IMM]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.ROT_R_32_IMM_ALT]=gx.TWO_REGISTERS_ONE_IMMEDIATE,e[wx.BRANCH_EQ]=gx.TWO_REGISTERS_ONE_OFFSET,e[wx.BRANCH_NE]=gx.TWO_REGISTERS_ONE_OFFSET,e[wx.BRANCH_LT_U]=gx.TWO_REGISTERS_ONE_OFFSET,e[wx.BRANCH_LT_S]=gx.TWO_REGISTERS_ONE_OFFSET,e[wx.BRANCH_GE_U]=gx.TWO_REGISTERS_ONE_OFFSET,e[wx.BRANCH_GE_S]=gx.TWO_REGISTERS_ONE_OFFSET,e[wx.LOAD_IMM_JUMP_IND]=gx.TWO_REGISTERS_TWO_IMMEDIATES,e[wx.ADD_32]=gx.THREE_REGISTERS,e[wx.ADD_64]=gx.THREE_REGISTERS,e[wx.SUB_32]=gx.THREE_REGISTERS,e[wx.SUB_64]=gx.THREE_REGISTERS,e[wx.AND]=gx.THREE_REGISTERS,e[wx.XOR]=gx.THREE_REGISTERS,e[wx.OR]=gx.THREE_REGISTERS,e[wx.MUL_32]=gx.THREE_REGISTERS,e[wx.MUL_64]=gx.THREE_REGISTERS,e[wx.MUL_UPPER_S_S]=gx.THREE_REGISTERS,e[wx.MUL_UPPER_U_U]=gx.THREE_REGISTERS,e[wx.MUL_UPPER_S_U]=gx.THREE_REGISTERS,e[wx.DIV_U_32]=gx.THREE_REGISTERS,e[wx.DIV_S_32]=gx.THREE_REGISTERS,e[wx.REM_U_32]=gx.THREE_REGISTERS,e[wx.REM_S_32]=gx.THREE_REGISTERS,e[wx.DIV_U_64]=gx.THREE_REGISTERS,e[wx.DIV_S_64]=gx.THREE_REGISTERS,e[wx.REM_U_64]=gx.THREE_REGISTERS,e[wx.REM_S_64]=gx.THREE_REGISTERS,e[wx.SET_LT_U]=gx.THREE_REGISTERS,e[wx.SET_LT_S]=gx.THREE_REGISTERS,e[wx.SHLO_L_32]=gx.THREE_REGISTERS,e[wx.SHLO_R_32]=gx.THREE_REGISTERS,e[wx.SHAR_R_32]=gx.THREE_REGISTERS,e[wx.SHLO_L_64]=gx.THREE_REGISTERS,e[wx.SHLO_R_64]=gx.THREE_REGISTERS,e[wx.SHAR_R_64]=gx.THREE_REGISTERS,e[wx.CMOV_IZ]=gx.THREE_REGISTERS,e[wx.CMOV_NZ]=gx.THREE_REGISTERS,e[wx.ROT_L_64]=gx.THREE_REGISTERS,e[wx.ROT_L_32]=gx.THREE_REGISTERS,e[wx.ROT_R_64]=gx.THREE_REGISTERS,e[wx.ROT_R_32]=gx.THREE_REGISTERS,e[wx.AND_INV]=gx.THREE_REGISTERS,e[wx.OR_INV]=gx.THREE_REGISTERS,e[wx.XNOR]=gx.THREE_REGISTERS,e[wx.MAX]=gx.THREE_REGISTERS,e[wx.MAX_U]=gx.THREE_REGISTERS,e[wx.MIN]=gx.THREE_REGISTERS,e[wx.MIN_U]=gx.THREE_REGISTERS,e})(),Cx=e=>ae(e),kx=e=>ce(e),xx=e=>"number"==typeof e&&e<2**32?Cx(e):kx(e);function Bx(e){return new _x(ce(e))}class _x{gas;constructor(e){this.gas=e}set(e){this.gas=ce(e)}get(){return xx(this.gas)}sub(e){const t=this.gas-ce(e);return t>=0n?(this.gas=ce(t),!1):(this.gas=ce(0n),!0)}}const Rx=[[wx.TRAP,1],[wx.FALLTHROUGH,1],[wx.ECALLI,v.isSuite(f.JAMDUNA,h.V0_6_5)?0:1],[wx.LOAD_IMM_64,1],[wx.STORE_IMM_U8,1],[wx.STORE_IMM_U16,1],[wx.STORE_IMM_U32,1],[wx.STORE_IMM_U64,1],[wx.JUMP,1],[wx.JUMP_IND,1],[wx.LOAD_IMM,1],[wx.LOAD_U8,1],[wx.LOAD_I8,1],[wx.LOAD_U16,1],[wx.LOAD_I16,1],[wx.LOAD_U32,1],[wx.LOAD_I32,1],[wx.LOAD_U64,1],[wx.STORE_U8,1],[wx.STORE_U16,1],[wx.STORE_U32,1],[wx.STORE_U64,1],[wx.STORE_IMM_IND_U8,1],[wx.STORE_IMM_IND_U16,1],[wx.STORE_IMM_IND_U32,1],[wx.STORE_IMM_IND_U64,1],[wx.LOAD_IMM_JUMP,1],[wx.BRANCH_EQ_IMM,1],[wx.BRANCH_NE_IMM,1],[wx.BRANCH_LT_U_IMM,1],[wx.BRANCH_LE_U_IMM,1],[wx.BRANCH_GE_U_IMM,1],[wx.BRANCH_GT_U_IMM,1],[wx.BRANCH_LT_S_IMM,1],[wx.BRANCH_LE_S_IMM,1],[wx.BRANCH_GE_S_IMM,1],[wx.BRANCH_GT_S_IMM,1],[wx.MOVE_REG,1],[wx.SBRK,1],[wx.COUNT_SET_BITS_64,1],[wx.COUNT_SET_BITS_32,1],[wx.LEADING_ZERO_BITS_64,1],[wx.LEADING_ZERO_BITS_32,1],[wx.TRAILING_ZERO_BITS_64,1],[wx.TRAILING_ZERO_BITS_32,1],[wx.SIGN_EXTEND_8,1],[wx.SIGN_EXTEND_16,1],[wx.ZERO_EXTEND_16,1],[wx.REVERSE_BYTES,1],[wx.STORE_IND_U8,1],[wx.STORE_IND_U16,1],[wx.STORE_IND_U32,1],[wx.STORE_IND_U64,1],[wx.LOAD_IND_U8,1],[wx.LOAD_IND_I8,1],[wx.LOAD_IND_U16,1],[wx.LOAD_IND_I16,1],[wx.LOAD_IND_U32,1],[wx.LOAD_IND_I32,1],[wx.LOAD_IND_U64,1],[wx.ADD_IMM_32,1],[wx.AND_IMM,1],[wx.XOR_IMM,1],[wx.OR_IMM,1],[wx.MUL_IMM_32,1],[wx.SET_LT_U_IMM,1],[wx.SET_LT_S_IMM,1],[wx.SHLO_L_IMM_32,1],[wx.SHLO_R_IMM_32,1],[wx.SHAR_R_IMM_32,1],[wx.NEG_ADD_IMM_32,1],[wx.SET_GT_U_IMM,1],[wx.SET_GT_S_IMM,1],[wx.SHLO_L_IMM_ALT_32,1],[wx.SHLO_R_IMM_ALT_32,1],[wx.SHAR_R_IMM_ALT_32,1],[wx.CMOV_IZ_IMM,1],[wx.CMOV_NZ_IMM,1],[wx.ADD_IMM_64,1],[wx.MUL_IMM_64,1],[wx.SHLO_L_IMM_64,1],[wx.SHLO_R_IMM_64,1],[wx.SHAR_R_IMM_64,1],[wx.NEG_ADD_IMM_64,1],[wx.SHLO_L_IMM_ALT_64,1],[wx.SHLO_R_IMM_ALT_64,1],[wx.SHAR_R_IMM_ALT_64,1],[wx.ROT_R_64_IMM,1],[wx.ROT_R_64_IMM_ALT,1],[wx.ROT_R_32_IMM,1],[wx.ROT_R_32_IMM_ALT,1],[wx.BRANCH_EQ,1],[wx.BRANCH_NE,1],[wx.BRANCH_LT_U,1],[wx.BRANCH_LT_S,1],[wx.BRANCH_GE_U,1],[wx.BRANCH_GE_S,1],[wx.LOAD_IMM_JUMP_IND,1],[wx.ADD_32,1],[wx.SUB_32,1],[wx.MUL_32,1],[wx.DIV_U_32,1],[wx.DIV_S_32,1],[wx.REM_U_32,1],[wx.REM_S_32,1],[wx.SHLO_L_32,1],[wx.SHLO_R_32,1],[wx.SHAR_R_32,1],[wx.ADD_64,1],[wx.SUB_64,1],[wx.MUL_64,1],[wx.DIV_U_64,1],[wx.DIV_S_64,1],[wx.REM_U_64,1],[wx.REM_S_64,1],[wx.SHLO_L_64,1],[wx.SHLO_R_64,1],[wx.SHAR_R_64,1],[wx.AND,1],[wx.XOR,1],[wx.OR,1],[wx.MUL_UPPER_S_S,1],[wx.MUL_UPPER_U_U,1],[wx.MUL_UPPER_S_U,1],[wx.SET_LT_U,1],[wx.SET_LT_S,1],[wx.CMOV_IZ,1],[wx.CMOV_NZ,1],[wx.ROT_L_64,1],[wx.ROT_L_32,1],[wx.ROT_R_64,1],[wx.ROT_R_32,1],[wx.AND_INV,1],[wx.OR_INV,1],[wx.XNOR,1],[wx.MAX,1],[wx.MAX_U,1],[wx.MIN,1],[wx.MIN_U,1]].reduce((e,t)=>{const[r,s]=(([e,t])=>[e,{gas:Cx(t)}])(t);return e[r]=s,e},{}),Ox=(()=>{const e=new Array(Sx+1);return e.fill(!1),e[wx.TRAP]=!0,e[wx.FALLTHROUGH]=!0,e[wx.JUMP]=!0,e[wx.JUMP_IND]=!0,e[wx.LOAD_IMM_JUMP]=!0,e[wx.LOAD_IMM_JUMP_IND]=!0,e[wx.BRANCH_EQ]=!0,e[wx.BRANCH_NE]=!0,e[wx.BRANCH_GE_U]=!0,e[wx.BRANCH_GE_S]=!0,e[wx.BRANCH_LT_U]=!0,e[wx.BRANCH_LT_S]=!0,e[wx.BRANCH_EQ_IMM]=!0,e[wx.BRANCH_NE_IMM]=!0,e[wx.BRANCH_LT_U_IMM]=!0,e[wx.BRANCH_LT_S_IMM]=!0,e[wx.BRANCH_LE_U_IMM]=!0,e[wx.BRANCH_LE_S_IMM]=!0,e[wx.BRANCH_GE_U_IMM]=!0,e[wx.BRANCH_GE_S_IMM]=!0,e[wx.BRANCH_GT_U_IMM]=!0,e[wx.BRANCH_GT_S_IMM]=!0,e})();class Ux{basicBlocks=new Set;reset(e,t){this.basicBlocks.clear(),this.basicBlocks.add(0);const r=e.length,s=r=>t.isInstruction(r)&&Ox[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 Tx=(()=>{const e=new Array(Sx+1);for(let t=0;t<Sx+1;t++){const r=Rx[t]?.gas;e[t]=r}return e})();class Nx{nextPc=0;status=null;exitParam=null;reset(){this.nextPc=0,this.status=null,this.exitParam=null}}const Dx=e=>S(e,e>=0&&e<ex,`Incorect page index: ${e}!`),Mx=e=>S(e,e>=0&&e<=sx,`Incorrect page number: ${e}!`);function Px(e){return Mx(e===sx?0:e+1)}function Lx(e){return ex*Math.ceil(e/ex)}function Hx(e){return Mx(e>>>12)}function Vx(e){return nx(e>>>12<<12)}function Kx(e){return nx(e<<12>>>0)}class Qx{address;isAccessFault;constructor(e,t=!0){this.address=e,this.isAccessFault=t}static fromPageNumber(e,t=!1){const r=Kx(Mx(e));return new Qx(r,t)}static fromMemoryIndex(e,t=!1){const r=Vx(nx(e%Zk));return new Qx(r,t)}}class $x 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 jx extends Error{constructor(){super("You are trying to access reserved memory!")}}class qx extends Error{constructor(){super("You try to fill data on memory page that does not exist!")}}Error;class zx extends Error{constructor(){super("Out of memory")}}class Wx{start;length;end;lastIndex=null;constructor(e,t){this.start=e,this.length=t,this.end=nx((this.start+this.length)%Zk),t>0&&(this.lastIndex=nx((this.end-1+Zk)%Zk))}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>Zk)throw new TypeError(`length must be a non-negative integer and less than 4294967296, got ${t}`);return new Wx(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 Jx=Wx.fromStartAndLength(nx(0),65536);class Yx{start;length;end;constructor(e,t){this.start=e,this.length=t,this.end=Mx((this.start+this.length)%ix)}static fromMemoryRange(e){const t=Hx(e.start);if(e.isEmpty())return new Yx(t,0);const r=Hx(e.lastIndex??e.end),s=Px(r);if((t===s||t===r)&&e.length>ex)return new Yx(t,ix);const i=t<s?s-t:ix-t+s;return Yx.fromStartAndLength(t,i)}static fromStartAndLength(e,t){if(!Number.isInteger(t)||t<0||t>ix)throw new TypeError(`length must be a non-negative integer and less than 1048576, got ${t}`);return new Yx(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=Px(t)}while(t!==e)}}class Xx{start;constructor(e){this.start=Kx(e)}}class Zx extends Xx{data;constructor(e,t){super(e),this.data=t}loadInto(e,t,r){const s=t+r;if(s>ex)return D.error(Qx.fromMemoryIndex(this.start+ex));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(Qx.fromMemoryIndex(this.start,!0))}setData(e,t){this.data.set(t,e)}isWriteable(){return!1}getPageDump(){return this.data}}class eB extends Xx{buffer;view;constructor(e,t){super(e);const r=t?.length??0,s=Math.min(ex,Math.max(r,rx));this.buffer=new ArrayBuffer(s,{maxByteLength:ex}),this.view=new Uint8Array(this.buffer),void 0!==t&&this.view.set(t)}loadInto(e,t,r){const s=t+r;if(s>ex)return D.error(Qx.fromMemoryIndex(this.start+ex));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<ex){const r=Math.min(ex,Math.max(rx,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<ex){const r=Math.min(ex,Math.max(rx,e+t.length));this.buffer.resize(r)}this.view.set(t,e)}isWriteable(){return!0}getPageDump(){return this.view}}var tB;!function(e){e[e.READ=0]="READ",e[e.WRITE=1]="WRITE"}(tB||(tB={}));class rB{sbrkIndex;virtualSbrkIndex;endHeapIndex;memory;static fromInitialMemory(e){return new rB(e?.sbrkIndex,e?.sbrkIndex,e?.endHeapIndex,e?.memory)}constructor(e=ax(Jx.end),t=ax(Jx.end),r=ax(Xk),s=new Map){this.sbrkIndex=e,this.virtualSbrkIndex=t,this.endHeapIndex=r,this.memory=s}reset(){this.sbrkIndex=ax(Jx.end),this.virtualSbrkIndex=ax(Jx.end),this.endHeapIndex=ax(Xk),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,tB.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=Dx(i%ex),a=Math.min(ex-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=Wx.fromStartAndLength(e,t),i=Yx.fromMemoryRange(s),n=[];for(const e of i){if(e<16)return D.error(Qx.fromPageNumber(e,!0));const t=this.memory.get(e);if(void 0===t)return D.error(Qx.fromPageNumber(e));if(r===tB.WRITE&&!t.isWriteable())return D.error(Qx.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,tB.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=Dx(i%ex),a=Math.min(ex-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(Xk<r+e||r+e>this.endHeapIndex)throw new zx;const s=ax(this.virtualSbrkIndex+e);if(s<=t)return this.virtualSbrkIndex=s,r;const i=ax(Lx(s)),n=Hx(t),a=(i-t)/ex,o=Yx.fromStartAndLength(n,a);for(const e of o){const t=new eB(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 sB{initialMemory=new Map;isFinalized=!1;ensureNotFinalized(){if(this.isFinalized)throw new Gx}ensureNoReservedMemoryUsage(e){if(e.overlapsWith(Jx))throw new jx}setReadablePages(e,t,r=new Uint8Array){this.ensureNotFinalized(),w(e<t,"end has to be bigger than start"),w(e%ex===0,"start needs to be a multiple of page size (4096)"),w(t%ex===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=Wx.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(Yx.fromMemoryRange(i)),a=n.length;for(let e=0;e<a;e++){const t=n[e],s=r.subarray(e*ex,(e+1)*ex),i=new Zx(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%ex===0,"start needs to be a multiple of page size (4096)"),w(t%ex===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=Wx.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Array.from(Yx.fromMemoryRange(i)),a=n.length;for(let e=0;e<a;e++){const t=n[e],s=r.subarray(e*ex,(e+1)*ex),i=new eB(t,s);this.initialMemory.set(t,i)}return this}setData(e,t){this.ensureNotFinalized();const r=ex-e%ex;w(t.length<=r,"The data has to fit into a single page.");const s=t.length,i=Wx.fromStartAndLength(e,s);this.ensureNoReservedMemoryUsage(i);const n=Hx(e),a=this.initialMemory.get(n);if(void 0===a)throw new qx;const o=Dx(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=Wx.fromStartAndLength(e,t-e),s=Yx.fromMemoryRange(r);for(const e of s)if(this.initialMemory.has(e))throw new Fx;const i=rB.fromInitialMemory({memory:this.initialMemory,sbrkIndex:ax(e),endHeapIndex:t});return this.isFinalized=!0,i}}class iB{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 wx.ADD_32:this.mathOps.addU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.ADD_64:this.mathOps.addU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.MUL_32:this.mathOps.mulU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.MUL_64:this.mathOps.mulU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.MUL_UPPER_U_U:this.mathOps.mulUpperUU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.MUL_UPPER_S_S:this.mathOps.mulUpperSS(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.MUL_UPPER_S_U:this.mathOps.mulUpperSU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.SUB_32:this.mathOps.subU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.SUB_64:this.mathOps.subU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.DIV_S_32:this.mathOps.divSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.DIV_S_64:this.mathOps.divSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.DIV_U_32:this.mathOps.divUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.DIV_U_64:this.mathOps.divUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.REM_S_32:this.mathOps.remSignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.REM_S_64:this.mathOps.remSignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.REM_U_32:this.mathOps.remUnsignedU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.REM_U_64:this.mathOps.remUnsignedU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.SHLO_L_32:this.shiftOps.shiftLogicalLeftU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.SHLO_L_64:this.shiftOps.shiftLogicalLeftU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.SHLO_R_32:this.shiftOps.shiftLogicalRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.SHLO_R_64:this.shiftOps.shiftLogicalRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.SHAR_R_32:this.shiftOps.shiftArithmeticRightU32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.SHAR_R_64:this.shiftOps.shiftArithmeticRightU64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.OR:this.bitOps.or(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.AND:this.bitOps.and(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.XOR:this.bitOps.xor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.SET_LT_S:this.booleanOps.setLessThanSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.SET_LT_U:this.booleanOps.setLessThanUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.CMOV_IZ:this.moveOps.cmovIfZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.CMOV_NZ:this.moveOps.cmovIfNotZero(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.ROT_L_64:this.bitRotationOps.rotL64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.ROT_L_32:this.bitRotationOps.rotL32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.ROT_R_64:this.bitRotationOps.rotR64(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.ROT_R_32:this.bitRotationOps.rotR32(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.AND_INV:this.bitOps.andInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.OR_INV:this.bitOps.orInv(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.XNOR:this.bitOps.xnor(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.MAX:this.mathOps.max(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.MAX_U:this.mathOps.maxU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.MIN:this.mathOps.min(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex);break;case wx.MIN_U:this.mathOps.minU(t.firstRegisterIndex,t.secondRegisterIndex,t.thirdRegisterIndex)}}}class nB{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 wx.ADD_IMM_32:this.mathOps.addImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.ADD_IMM_64:this.mathOps.addImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.MUL_IMM_32:this.mathOps.mulImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.MUL_IMM_64:this.mathOps.mulImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.NEG_ADD_IMM_32:this.mathOps.negAddImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.NEG_ADD_IMM_64:this.mathOps.negAddImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SHLO_L_IMM_32:this.shiftOps.shiftLogicalLeftImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SHLO_L_IMM_64:this.shiftOps.shiftLogicalLeftImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SHLO_L_IMM_ALT_32:this.shiftOps.shiftLogicalLeftImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SHLO_L_IMM_ALT_64:this.shiftOps.shiftLogicalLeftImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SHLO_R_IMM_32:this.shiftOps.shiftLogicalRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SHLO_R_IMM_64:this.shiftOps.shiftLogicalRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SHLO_R_IMM_ALT_32:this.shiftOps.shiftLogicalRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SHLO_R_IMM_ALT_64:this.shiftOps.shiftLogicalRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SHAR_R_IMM_32:this.shiftOps.shiftArithmeticRightImmediateU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SHAR_R_IMM_64:this.shiftOps.shiftArithmeticRightImmediateU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SHAR_R_IMM_ALT_32:this.shiftOps.shiftArithmeticRightImmediateAlternativeU32(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SHAR_R_IMM_ALT_64:this.shiftOps.shiftArithmeticRightImmediateAlternativeU64(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.OR_IMM:this.bitOps.orImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.AND_IMM:this.bitOps.andImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.XOR_IMM:this.bitOps.xorImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SET_LT_S_IMM:this.booleanOps.setLessThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SET_LT_U_IMM:this.booleanOps.setLessThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SET_GT_S_IMM:this.booleanOps.setGreaterThanSignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.SET_GT_U_IMM:this.booleanOps.setGreaterThanUnsignedImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.CMOV_IZ_IMM:this.moveOps.cmovIfZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.CMOV_NZ_IMM:this.moveOps.cmovIfNotZeroImmediate(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.STORE_IND_U8:this.storeOps.storeIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case wx.STORE_IND_U16:this.storeOps.storeIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case wx.STORE_IND_U32:this.storeOps.storeIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case wx.STORE_IND_U64:this.storeOps.storeIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case wx.LOAD_IND_U8:this.loadOps.loadIndU8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case wx.LOAD_IND_U16:this.loadOps.loadIndU16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case wx.LOAD_IND_U32:this.loadOps.loadIndU32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case wx.LOAD_IND_U64:this.loadOps.loadIndU64(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case wx.LOAD_IND_I8:this.loadOps.loadIndI8(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case wx.LOAD_IND_I16:this.loadOps.loadIndI16(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case wx.LOAD_IND_I32:this.loadOps.loadIndI32(t.firstRegisterIndex,t.secondRegisterIndex,t.immediateDecoder);break;case wx.ROT_R_64_IMM:this.bitRotationOps.rotR64Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.ROT_R_64_IMM_ALT:this.bitRotationOps.rotR64ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.ROT_R_32_IMM:this.bitRotationOps.rotR32Imm(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex);break;case wx.ROT_R_32_IMM_ALT:this.bitRotationOps.rotR32ImmAlt(t.secondRegisterIndex,t.immediateDecoder,t.firstRegisterIndex)}}}class aB{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 wx.MOVE_REG:this.moveOps.moveRegister(t.firstRegisterIndex,t.secondRegisterIndex);break;case wx.SBRK:this.memoryOps.sbrk(t.firstRegisterIndex,t.secondRegisterIndex);break;case wx.COUNT_SET_BITS_64:this.bitOps.countSetBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case wx.COUNT_SET_BITS_32:this.bitOps.countSetBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case wx.LEADING_ZERO_BITS_64:this.bitOps.leadingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case wx.LEADING_ZERO_BITS_32:this.bitOps.leadingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case wx.TRAILING_ZERO_BITS_64:this.bitOps.trailingZeroBits64(t.firstRegisterIndex,t.secondRegisterIndex);break;case wx.TRAILING_ZERO_BITS_32:this.bitOps.trailingZeroBits32(t.firstRegisterIndex,t.secondRegisterIndex);break;case wx.SIGN_EXTEND_8:this.bitOps.signExtend8(t.firstRegisterIndex,t.secondRegisterIndex);break;case wx.SIGN_EXTEND_16:this.bitOps.signExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case wx.ZERO_EXTEND_16:this.bitOps.zeroExtend16(t.firstRegisterIndex,t.secondRegisterIndex);break;case wx.REVERSE_BYTES:this.bitRotationOps.reverseBytes(t.firstRegisterIndex,t.secondRegisterIndex)}}}class oB{branchOps;loadOps;constructor(e,t){this.branchOps=e,this.loadOps=t}dispatch(e,t){switch(e){case wx.LOAD_IMM_JUMP:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder),this.branchOps.jump(t.nextPc);break;case wx.BRANCH_EQ_IMM:this.branchOps.branchEqImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case wx.BRANCH_NE_IMM:this.branchOps.branchNeImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case wx.BRANCH_LT_U_IMM:this.branchOps.branchLtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case wx.BRANCH_LE_U_IMM:this.branchOps.branchLeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case wx.BRANCH_GE_U_IMM:this.branchOps.branchGeUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case wx.BRANCH_GT_U_IMM:this.branchOps.branchGtUnsignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case wx.BRANCH_LT_S_IMM:this.branchOps.branchLtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case wx.BRANCH_LE_S_IMM:this.branchOps.branchLeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case wx.BRANCH_GE_S_IMM:this.branchOps.branchGeSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc);break;case wx.BRANCH_GT_S_IMM:this.branchOps.branchGtSignedImmediate(t.registerIndex,t.immediateDecoder,t.nextPc)}}}class cB{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){switch(e){case wx.BRANCH_EQ:this.branchOps.branchEq(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case wx.BRANCH_NE:this.branchOps.branchNe(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case wx.BRANCH_LT_U:this.branchOps.branchLtUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case wx.BRANCH_LT_S:this.branchOps.branchLtSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case wx.BRANCH_GE_U:this.branchOps.branchGeUnsigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc);break;case wx.BRANCH_GE_S:this.branchOps.branchGeSigned(t.firstRegisterIndex,t.secondRegisterIndex,t.nextPc)}}}class lB{branchOps;constructor(e){this.branchOps=e}dispatch(e,t){e===wx.JUMP&&this.branchOps.jump(t.nextPc)}}class dB{loadOps;storeOps;dynamicJumpOps;constructor(e,t,r){this.loadOps=e,this.storeOps=t,this.dynamicJumpOps=r}dispatch(e,t){switch(e){case wx.LOAD_IMM:this.loadOps.loadImmediate(t.registerIndex,t.immediateDecoder);break;case wx.STORE_U8:this.storeOps.storeU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case wx.STORE_U16:this.storeOps.storeU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case wx.STORE_U32:this.storeOps.storeU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case wx.STORE_U64:this.storeOps.storeU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case wx.LOAD_U8:this.loadOps.loadU8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case wx.LOAD_U16:this.loadOps.loadU16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case wx.LOAD_U32:this.loadOps.loadU32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case wx.LOAD_U64:this.loadOps.loadU64(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case wx.LOAD_I8:this.loadOps.loadI8(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case wx.LOAD_I16:this.loadOps.loadI16(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case wx.LOAD_I32:this.loadOps.loadI32(t.immediateDecoder.getUnsigned(),t.registerIndex);break;case wx.JUMP_IND:{const e=this.dynamicJumpOps.caluclateJumpAddress(t.immediateDecoder,t.registerIndex);this.dynamicJumpOps.jumpInd(e);break}}}}class uB{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case wx.STORE_IMM_IND_U8:this.storeOps.storeImmediateIndU8(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case wx.STORE_IMM_IND_U16:this.storeOps.storeImmediateIndU16(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case wx.STORE_IMM_IND_U32:this.storeOps.storeImmediateIndU32(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder);break;case wx.STORE_IMM_IND_U64:this.storeOps.storeImmediateIndU64(t.registerIndex,t.firstImmediateDecoder,t.secondImmediateDecoder)}}}class hB{storeOps;constructor(e){this.storeOps=e}dispatch(e,t){switch(e){case wx.STORE_IMM_U8:this.storeOps.storeImmediateU8(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case wx.STORE_IMM_U16:this.storeOps.storeImmediateU16(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case wx.STORE_IMM_U32:this.storeOps.storeImmediateU32(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder);break;case wx.STORE_IMM_U64:this.storeOps.storeImmediateU64(t.firstImmediateDecoder.getUnsigned(),t.secondImmediateDecoder)}}}class fB{noArgsOps;constructor(e){this.noArgsOps=e}dispatch(e){switch(e){case wx.TRAP:this.noArgsOps.trap();break;case wx.FALLTHROUGH:this.noArgsOps.fallthrough()}}}class gB{loadOps;dynamicJumpOps;constructor(e,t){this.loadOps=e,this.dynamicJumpOps=t}dispatch(e,t){switch(e){case wx.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 pB{hostCallOps;constructor(e){this.hostCallOps=e}dispatch(e,t){e===wx.ECALLI&&this.hostCallOps.hostCall(t.immediateDecoder)}}class bB{loadOps;constructor(e){this.loadOps=e}dispatch(e,t){e===wx.LOAD_IMM_64&&this.loadOps.loadImmediateU64(t.registerIndex,t.immediateDecoder)}}class mB{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 yB=4294967295,AB=-(2**31),IB=32,vB=64n;function wB(e,t){return e>yB-t?yB-(yB-e+(yB-t))-1:e+t}function SB(e,t){return(e+t)%2n**64n}function EB(e,t){return t>e?yB-t+e+1:e-t}function CB(e,t){return(2n**64n+e-t)%2n**64n}function kB(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 xB(e,t){return e*t%2n**64n}function BB(e){return e>=1n<<63n?e-(1n<<64n):e}function _B(e,t){return(0xffffffffffffffffn&e)*(0xffffffffffffffffn&t)>>64n&0xffffffffffffffffn}function RB(e,t){return BB(0xffffffffffffffffn&e*t>>64n)}function OB(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 UB(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t>e?t:e)}function TB(...e){if(0===e.length)throw new Error("No arguments provided");return e.reduce((e,t)=>t<e?t:e)}class NB{regs;constructor(e){this.regs=e}shiftLogicalLeftU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<this.regs.getLowerU32(t)%IB)}shiftLogicalLeftU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<this.regs.getU64(t)%vB)}shiftLogicalRightU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>this.regs.getLowerU32(t)%IB)}shiftLogicalRightU64(e,t,r){this.regs.setU64(r,OB(this.regs.getU64(e),this.regs.getU64(t)%vB))}shiftArithmeticRightU32(e,t,r){this.regs.setI32(r,this.regs.getLowerI32(e)>>this.regs.getLowerU32(t)%IB)}shiftArithmeticRightU64(e,t,r){this.regs.setI64(r,this.regs.getI64(e)>>this.regs.getU64(t)%vB)}shiftLogicalLeftImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)<<t.getU32()%IB)}shiftLogicalLeftImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getU64(e)<<t.getU64()%vB)}shiftLogicalRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerU32(e)>>>t.getU32()%IB)}shiftLogicalRightImmediateU64(e,t,r){this.regs.setU64(r,OB(this.regs.getU64(e),t.getU64()%vB))}shiftArithmeticRightImmediateU32(e,t,r){this.regs.setU32(r,this.regs.getLowerI32(e)>>t.getU32()%IB)}shiftArithmeticRightImmediateU64(e,t,r){this.regs.setU64(r,this.regs.getI64(e)>>t.getU64()%vB)}shiftLogicalLeftImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()<<this.regs.getLowerU32(e)%IB)}shiftLogicalLeftImmediateAlternativeU64(e,t,r){this.regs.setU64(r,t.getU64()<<this.regs.getU64(e)%vB)}shiftLogicalRightImmediateAlternativeU32(e,t,r){this.regs.setU32(r,t.getU32()>>>this.regs.getLowerU32(e)%IB)}shiftLogicalRightImmediateAlternativeU64(e,t,r){this.regs.setU64(r,OB(t.getU64(),this.regs.getU64(e)%vB))}shiftArithmeticRightImmediateAlternativeU32(e,t,r){this.regs.setI32(r,t.getU32()>>this.regs.getLowerU32(e)%IB)}shiftArithmeticRightImmediateAlternativeU64(e,t,r){this.regs.setI64(r,t.getI64()>>this.regs.getU64(e)%vB)}}class DB{regs;constructor(e){this.regs=e}addU32(e,t,r){this.regs.setU64(r,ux(wB(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}addU64(e,t,r){this.regs.setU64(r,SB(this.regs.getU64(e),this.regs.getU64(t)))}addImmediateU32(e,t,r){this.regs.setU64(r,ux(wB(this.regs.getLowerU32(e),t.getU32())))}addImmediateU64(e,t,r){this.regs.setU64(r,SB(this.regs.getU64(e),t.getU64()))}mulU32(e,t,r){this.regs.setU64(r,ux(kB(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}mulU64(e,t,r){this.regs.setU64(r,xB(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperUU(e,t,r){this.regs.setU64(r,_B(this.regs.getU64(e),this.regs.getU64(t)))}mulUpperSS(e,t,r){this.regs.setI64(r,RB(this.regs.getI64(e),this.regs.getI64(t)))}mulUpperSU(e,t,r){this.regs.setI64(r,BB(0xffffffffffffffffn&this.regs.getI64(e)*(0xffffffffffffffffn&this.regs.getU64(t))>>64n))}mulImmediateU32(e,t,r){this.regs.setU64(r,ux(kB(this.regs.getLowerU32(e),t.getU32())))}mulImmediateU64(e,t,r){this.regs.setU64(r,xB(this.regs.getU64(e),t.getU64()))}mulUpperSSImmediate(e,t,r){this.regs.setI64(r,RB(this.regs.getI64(e),t.getI64()))}mulUpperUUImmediate(e,t,r){this.regs.setU64(r,_B(this.regs.getU64(e),t.getU64()))}subU32(e,t,r){this.regs.setU64(r,ux(EB(this.regs.getLowerU32(e),this.regs.getLowerU32(t))))}subU64(e,t,r){this.regs.setU64(r,CB(this.regs.getU64(e),this.regs.getU64(t)))}negAddImmediateU32(e,t,r){this.regs.setU64(r,ux(EB(t.getU32(),this.regs.getLowerU32(e))))}negAddImmediateU64(e,t,r){this.regs.setU64(r,CB(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)===AB?this.regs.setU64(r,ux(this.regs.getLowerU32(e))):this.regs.setI64(r,ux(~~(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,ux(~~(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)===AB?this.regs.setU64(r,0n):this.regs.setI64(r,ux(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,ux(this.regs.getLowerU32(e))):this.regs.setU64(r,ux(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,UB(this.regs.getI64(e),this.regs.getI64(t)))}maxU(e,t,r){this.regs.setU64(r,UB(this.regs.getU64(e),this.regs.getU64(t)))}min(e,t,r){this.regs.setI64(r,TB(this.regs.getI64(e),this.regs.getI64(t)))}minU(e,t,r){this.regs.setU64(r,TB(this.regs.getU64(e),this.regs.getU64(t)))}}class MB{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 PB{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 LB,HB;(HB=LB||(LB={}))[HB.HALT=0]="HALT",HB[HB.PANIC=1]="PANIC",HB[HB.FAULT_ACCESS=2]="FAULT_ACCESS",HB[HB.FAULT=3]="FAULT",HB[HB.HOST=4]="HOST";class VB{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=LB.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 KB{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),nx(e));i.isError?i.error.isAccessFault?this.instructionResult.status=LB.FAULT_ACCESS:(this.instructionResult.status=LB.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),nx(e));i.isError?i.error.isAccessFault?this.instructionResult.status=LB.FAULT_ACCESS:(this.instructionResult.status=LB.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=wB(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,1)}loadIndU16(e,t,r){const s=wB(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,2)}loadIndU32(e,t,r){const s=wB(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,4)}loadIndU64(e,t,r){const s=wB(this.regs.getLowerU32(t),r.getU32());this.loadNumber(s,e,8)}loadIndI8(e,t,r){const s=wB(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,1)}loadIndI16(e,t,r){const s=wB(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,2)}loadIndI32(e,t,r){const s=wB(this.regs.getLowerU32(t),r.getU32());this.loadSignedNumber(s,e,4)}}class QB{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=wB(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,1))}storeIndU16(e,t,r){const s=wB(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,2))}storeIndU32(e,t,r){const s=wB(this.regs.getLowerU32(t),r.getUnsigned());this.store(s,this.regs.getBytesAsLittleEndian(e,4))}storeIndU64(e,t,r){const s=wB(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=wB(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,1))}storeImmediateIndU16(e,t,r){const s=wB(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,2))}storeImmediateIndU32(e,t,r){const s=wB(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getBytesAsLittleEndian().subarray(0,4))}storeImmediateIndU64(e,t,r){const s=wB(this.regs.getLowerU32(e),t.getUnsigned());this.store(s,r.getExtendedBytesAsLittleEndian())}store(e,t){const r=this.memory.storeFrom(nx(e),t);r.isOk||(r.error.isAccessFault?this.instructionResult.status=LB.FAULT_ACCESS:(this.instructionResult.status=LB.FAULT,this.instructionResult.exitParam=Vx(r.error.address)))}}class $B{instructionResult;constructor(e){this.instructionResult=e}trap(){this.instructionResult.status=LB.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=LB.HALT);if(0===e||e%2!=0)return void(this.instructionResult.status=LB.PANIC);const t=e/2-1;if(!this.jumpTable.hasIndex(t))return void(this.instructionResult.status=LB.PANIC);const r=this.jumpTable.getDestination(t);this.basicBlocks.isBeginningOfBasicBlock(r)?this.instructionResult.nextPc=r:this.instructionResult.status=LB.PANIC}caluclateJumpAddress(e,t){return wB(this.regs.getLowerU32(t),e.getU32())}jumpInd(e){this.djump(e)}}class GB{instructionResult;constructor(e){this.instructionResult=e}hostCall(e){this.instructionResult.status=LB.HOST,this.instructionResult.exitParam=e.getUnsigned()}}class jB{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=LB.FAULT}}}class qB{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|OB(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(OB(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 zB{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 zB(0,new Uint8Array)}copyFrom(e){this.indices=e.indices}}const WB=si.new(void 0,"pvm-interpreter");var JB;!function(e){e[e.InvalidProgramError=0]="InvalidProgramError"}(JB||(JB={}));class YB{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 bx(r),this.jumpTable=new zB(i,s)}decodeProgram(e){const t=ge.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 YB(e))}catch(e){return WB.error(`Invalid program: ${e}`),D.error(JB.InvalidProgramError)}}}class XB{useSbrkGas;ignoreInstructionGas;registers=new dx;code=new Uint8Array;mask=bx.empty();pc=0;gas=Bx(xx(0));initialGas=Bx(xx(0));argsDecoder;threeRegsDispatcher;twoRegsOneImmDispatcher;twoRegsDispatcher;oneRegOneImmOneOffsetDispatcher;twoRegsOneOffsetDispatcher;oneOffsetDispatcher;oneRegOneImmDispatcher;instructionResult=new Nx;memory=new rB;twoImmsDispatcher;oneRegTwoImmsDispatcher;noArgsDispatcher;twoRegsTwoImmsDispatcher;oneImmDispatcher;oneRegOneExtImmDispatcher;status=ox.OK;argsDecodingResults=(()=>{const e=new Array(vx);return e[gx.NO_ARGUMENTS]={type:gx.NO_ARGUMENTS,noOfBytesToSkip:1},e[gx.ONE_IMMEDIATE]={type:gx.ONE_IMMEDIATE,noOfBytesToSkip:1,immediateDecoder:new mx},e[gx.TWO_REGISTERS]={type:gx.TWO_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0},e[gx.THREE_REGISTERS]={type:gx.THREE_REGISTERS,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,thirdRegisterIndex:0},e[gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET]={type:gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new mx,nextPc:0},e[gx.TWO_REGISTERS_ONE_OFFSET]={type:gx.TWO_REGISTERS_ONE_OFFSET,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,nextPc:0},e[gx.TWO_REGISTERS_ONE_IMMEDIATE]={type:gx.TWO_REGISTERS_ONE_IMMEDIATE,noOfBytesToSkip:1,firstRegisterIndex:0,secondRegisterIndex:0,immediateDecoder:new mx},e[gx.ONE_REGISTER_ONE_IMMEDIATE]={type:gx.ONE_REGISTER_ONE_IMMEDIATE,noOfBytesToSkip:1,registerIndex:0,immediateDecoder:new mx},e[gx.ONE_REGISTER_TWO_IMMEDIATES]={type:gx.ONE_REGISTER_TWO_IMMEDIATES,noOfBytesToSkip:1,registerIndex:0,firstImmediateDecoder:new mx,secondImmediateDecoder:new mx},e[gx.ONE_OFFSET]={type:gx.ONE_OFFSET,noOfBytesToSkip:1,nextPc:0},e[gx.TWO_IMMEDIATES]={type:gx.TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new mx,secondImmediateDecoder:new mx},e[gx.TWO_REGISTERS_TWO_IMMEDIATES]={type:gx.TWO_REGISTERS_TWO_IMMEDIATES,noOfBytesToSkip:1,firstImmediateDecoder:new mx,secondImmediateDecoder:new mx,firstRegisterIndex:0,secondRegisterIndex:0},e[gx.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE]={type:gx.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE,noOfBytesToSkip:9,registerIndex:0,immediateDecoder:new Ix},e})();basicBlocks;jumpTable=zB.empty();constructor({useSbrkGas:e=!1,ignoreInstructionGas:t=!1}={}){this.useSbrkGas=e,this.ignoreInstructionGas=t,this.argsDecoder=new Ax,this.basicBlocks=new Ux;const r=new DB(this.registers),s=new NB(this.registers),i=new mB(this.registers),n=new MB(this.registers),a=new PB(this.registers),o=new VB(this.registers,this.instructionResult,this.basicBlocks),c=new KB(this.registers,this.memory,this.instructionResult),l=new QB(this.registers,this.memory,this.instructionResult),d=new $B(this.instructionResult),u=new FB(this.registers,this.jumpTable,this.instructionResult,this.basicBlocks),h=new GB(this.instructionResult),f=new jB(this.registers,this.memory,this.instructionResult),g=new qB(this.registers);this.threeRegsDispatcher=new iB(r,s,i,n,a,g),this.twoRegsOneImmDispatcher=new nB(r,s,i,n,a,l,c,g),this.twoRegsDispatcher=new aB(a,f,i,g),this.oneRegOneImmOneOffsetDispatcher=new oB(o,c),this.twoRegsOneOffsetDispatcher=new cB(o),this.oneOffsetDispatcher=new lB(o),this.oneRegOneImmDispatcher=new dB(c,l,u),this.twoImmsDispatcher=new hB(l),this.oneRegTwoImmsDispatcher=new uB(l),this.noArgsDispatcher=new fB(d),this.twoRegsTwoImmsDispatcher=new gB(c,u),this.oneImmDispatcher=new pB(h),this.oneRegOneExtImmDispatcher=new bB(c)}reset(e,t,r,s,i){const n=new YB(e);this.code=n.getCode(),this.mask=n.getMask(),this.jumpTable.copyFrom(n.getJumpTable()),this.pc=t,this.gas=Bx(r),this.initialGas=Bx(r),this.status=ox.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([wx[t]]):e[e.length-1].push(t),e),[]));var t,r;return console.table(e),e}runProgram(){for(;this.nextStep()===ox.OK;);}nextStep(){this.status===ox.HOST&&(this.status=ox.OK,this.pc=this.instructionResult.nextPc,this.instructionResult.reset());const e=this.code[this.pc]??wx.TRAP,t=void 0!==wx[e],r=Tx[e]??Tx[wx.TRAP];if(!this.ignoreInstructionGas&&this.gas.sub(r))return this.status=ox.OOG,this.status;const s=Ex[e]??gx.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 gx.NO_ARGUMENTS:this.noArgsDispatcher.dispatch(e);break;case gx.ONE_IMMEDIATE:this.oneImmDispatcher.dispatch(e,i);break;case gx.ONE_REGISTER_ONE_IMMEDIATE_ONE_OFFSET:this.oneRegOneImmOneOffsetDispatcher.dispatch(e,i);break;case gx.TWO_REGISTERS:if(this.useSbrkGas&&e===wx.SBRK){const e=e=>Lx(e)/ex*16;if(this.gas.sub(xx(e(this.registers.getLowerU32(i.firstRegisterIndex)))))return this.status=ox.OOG,this.status}this.twoRegsDispatcher.dispatch(e,i);break;case gx.THREE_REGISTERS:this.threeRegsDispatcher.dispatch(e,i);break;case gx.TWO_REGISTERS_ONE_IMMEDIATE:this.twoRegsOneImmDispatcher.dispatch(e,i);break;case gx.TWO_REGISTERS_ONE_OFFSET:this.twoRegsOneOffsetDispatcher.dispatch(e,i);break;case gx.ONE_OFFSET:this.oneOffsetDispatcher.dispatch(e,i);break;case gx.ONE_REGISTER_ONE_IMMEDIATE:this.oneRegOneImmDispatcher.dispatch(e,i);break;case gx.TWO_IMMEDIATES:this.twoImmsDispatcher.dispatch(e,i);break;case gx.ONE_REGISTER_TWO_IMMEDIATES:this.oneRegTwoImmsDispatcher.dispatch(e,i);break;case gx.TWO_REGISTERS_TWO_IMMEDIATES:this.twoRegsTwoImmsDispatcher.dispatch(e,i);break;case gx.ONE_REGISTER_ONE_EXTENDED_WIDTH_IMMEDIATE:this.oneRegOneExtImmDispatcher.dispatch(e,i)}else this.instructionResult.status=LB.PANIC;if(null!==this.instructionResult.status){switch(this.instructionResult.status!==LB.FAULT&&this.instructionResult.status!==LB.FAULT_ACCESS||this.gas.sub(Tx[wx.TRAP]),this.instructionResult.status){case LB.FAULT:this.status=ox.FAULT;break;case LB.HALT:this.status=ox.HALT;break;case LB.PANIC:case LB.FAULT_ACCESS:this.status=ox.PANIC;break;case LB.HOST:this.status=ox.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=kx(this.initialGas.get())-kx(this.gas.get());return e<0?this.initialGas.get():kx(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(Mx(e))}}class ZB{memory;constructor(e){this.memory=e}storeFrom(e,t){return 0===t.length?D.ok(O):e+ce(t.length)>Zk?D.error(new $x):this.memory.storeFrom(nx(Number(e)),t)}loadInto(e,t){return 0===e.length?D.ok(O):t+ce(e.length)>Zk?D.error(new $x):this.memory.loadInto(e,nx(Number(t)))}getMemory(){return this.memory}}class e_{registers;constructor(e){this.registers=e}get(e){return ce(this.registers.getU64(e))}set(e,t){this.registers.setU64(e,t)}}class t_{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 t_(e,t,null)}static fromMemorySlice(e,t){return new t_(e,null,t)}hasMemorySlice(){return this.memorySlice instanceof Uint8Array&&null===this.status}hasStatus(){return!this.hasMemorySlice()}}class r_{pvmInstanceManager;hostCalls;constructor(e,t){this.pvmInstanceManager=e,this.hostCalls=t}getReturnValue(e,t){const r=t.getGasConsumed();if(e===ox.OOG)return t_.fromStatus(r,e);if(e===ox.HALT){const e=t.getMemory(),s=t.getRegisters(),i=s.getLowerU32(7),n=s.getLowerU32(8),a=new Uint8Array(n),o=nx(i);return e.loadInto(a,o).isError?t_.fromMemorySlice(r,new Uint8Array):t_.fromMemorySlice(r,a)}return t_.fromStatus(r,ox.PANIC)}async execute(e){for(e.runProgram();;){let t=e.getStatus();if(t!==ox.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 e_(e.getRegisters()),n=new ZB(e.getMemory()),a=hx(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()),t_.fromStatus(e.getGasConsumed(),ox.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===fx.Halt)return t=ox.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 s_{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 XB({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 i_={NONE:ce(0xffffffffffffffffn),WHAT:ce(0xfffffffffffffffen),OOB:ce(0xfffffffffffffffdn),WHO:ce(0xfffffffffffffffcn),FULL:ce(0xfffffffffffffffbn),CORE:ce(0xfffffffffffffffan),CASH:ce(0xfffffffffffffff9n),LOW:ce(0xfffffffffffffff8n),HUH:ce(0xfffffffffffffff7n),OK:ce(0n)},n_=ae(2**32-1),a_=ce(n_),o_=Dr(2**32-1);function c_(e,t,r){const s=t.get(e);return s===2n**64n-1n?r:l_(s)}function l_(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?Dr(t):null}function d_(e){return e>a_?n_:ae(Number(e))}var u_,h_,f_,g_,p_,b_,m_,y_;function A_(e){if(e.length===u_.Requested)return{status:u_.Requested};if(e.length===u_.Available)return{status:u_.Available,data:[e[0]]};if(e.length===u_.Unavailable)return{status:u_.Unavailable,data:[e[0],e[1]]};if(e.length===u_.Reavailable)return{status:u_.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"}(u_||(u_={})),function(e){e[e.AlreadyRequested=0]="AlreadyRequested",e[e.AlreadyAvailable=1]="AlreadyAvailable",e[e.InsufficientFunds=2]="InsufficientFunds"}(h_||(h_={})),function(e){e[e.NotFound=0]="NotFound",e[e.NotExpired=1]="NotExpired",e[e.StorageUtilisationError=2]="StorageUtilisationError"}(f_||(f_={})),function(e){e[e.DestinationNotFound=0]="DestinationNotFound",e[e.GasTooLow=1]="GasTooLow",e[e.BalanceBelowThreshold=2]="BalanceBelowThreshold"}(g_||(g_={})),function(e){e[e.InvalidService=0]="InvalidService",e[e.InvalidPreimage=1]="InvalidPreimage"}(p_||(p_={})),function(e){e[e.ServiceNotFound=0]="ServiceNotFound",e[e.WasNotRequested=1]="WasNotRequested",e[e.AlreadyProvided=2]="AlreadyProvided"}(b_||(b_={})),function(e){e[e.InsufficientFunds=0]="InsufficientFunds",e[e.UnprivilegedService=1]="UnprivilegedService"}(m_||(m_={})),function(e){e[e.UnprivilegedService=0]="UnprivilegedService",e[e.InvalidServiceId=1]="InvalidServiceId"}(y_||(y_={}));const I_=Symbol("Insufficient privileges.");class v_{source;destination;amount;memo;gas;static Codec=_e.Class(v_,{source:_e.u32.asOpaque(),destination:_e.u32.asOpaque(),amount:_e.u64,memo:_e.bytes(128),gas:_e.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 v_(e,t,r,s,i)}}const w_=e=>ce(e);var S_,E_,C_,k_;!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"}(S_||(S_={})),function(e){e[e.SourcePageFault=0]="SourcePageFault",e[e.DestinationPageFault=1]="DestinationPageFault",e[e.NoMachine=2]="NoMachine"}(E_||(E_={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidPage=1]="InvalidPage"}(C_||(C_={})),function(e){e[e.NoMachine=0]="NoMachine",e[e.InvalidOperation=1]="InvalidOperation",e[e.InvalidPage=2]="InvalidPage"}(k_||(k_={})),Symbol("Machine index not found."),Symbol("Too many segments already exported.");const x_="insufficient funds";class B_{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 B_({servicesUpdates:[],servicesRemoved:[],preimages:[],storage:[]},[])}static new(e){return new B_({...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 B_(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?B_.empty():B_.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:ae(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=!oe(t),n=!le(r);if(i||n)return D.error(x_);const a=iC.calculateThresholdBalance(t,r,s.gratisStorage);return s.balance<a?D.error(x_):(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 R_=si.new(void 0,"pvm");class O_{hostCalls=new Map;missing=new U_;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(", ");R_.trace(`[${n}] ${e} ${o}${a}. Gas: ${i}. Regs: ${c}.`)}}class U_{index=hx(2**32-1);gasCost=Cx(10);currentServiceId=o_;tracedRegisters=px(7);execute(e,t,r){return t.set(7,i_.WHAT),Promise.resolve(void 0)}}const T_=4096,N_=65536,D_=2**24,M_=4278059008,P_=4278124544;function L_(e){return T_*Math.ceil(e/T_)}class H_ extends B{start;end;data;static from({start:e,end:t,data:r}){return new H_(e,t,r)}constructor(e,t,r){super(),this.start=e,this.end=t,this.data=r}}class V_ 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 K_ extends B{code;memory;registers;constructor(e,t,r){super(),this.code=e,this.memory=t,this.registers=r}}function Q_(e,t,r=null){return new H_(e,t,r)}class $_{code;registers;memory;metadata;static fromSpi(e,t,r){const{code:s,metadata:i}=r?F_(e):{code:e},{code:n,memory:a,registers:o}=function(e,t){const r=ge.fromBlob(e),s=r.u24(),i=r.u24(),n=S(t.length,t.length<=D_,"Incorrect arguments length"),a=S(s,s<=D_,"Incorrect readonly segment length"),o=S(i,i<=D_,"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=N_+L_(a),p=131072+(b=a,N_*Math.ceil(b/N_));var b;const m=p+L_(o),y=p+L_(o)+c*T_,A=M_-L_(l),I=M_,v=P_,w=v+L_(n),E=w+L_(n);function C(e){return!1!==e}const k=[a>0&&Q_(65536,g,d),n>0&&Q_(v,w,t),w<E&&Q_(w,E)].filter(C),x=[o>0&&Q_(p,m,u),m<y&&Q_(m,y),A<I&&Q_(A,I)].filter(C);return new K_(f,new V_(k,x,y,A),function(e){const t=new BigUint64Array(13);return t[0]=BigInt(4294901760),t[1]=BigInt(M_),t[7]=BigInt(P_),t[8]=BigInt(e),t}(t.length))}(s,t),c=new dx;c.copyFrom(o);const l=new sB;for(const{start:e,end:t,data:r}of a.readable){const s=nx(e),i=nx(t);l.setReadablePages(s,i,r??new Uint8Array)}for(const{start:e,end:t,data:r}of a.writeable){const s=nx(e),i=nx(t);l.setWriteablePages(s,i,r??new Uint8Array)}const d=nx(a.sbrkIndex),u=ax(a.heapEnd),h=l.finalize(d,u);return new $_(n,c,h,i)}static fromGeneric(e,t){const{code:r,metadata:s}=t?F_(e):{code:e},i=new dx,n=new rB;return new $_(r,i,n,s)}constructor(e,t,r,s=new Uint8Array){this.code=e,this.registers=t,this.memory=r,this.metadata=s}}function F_(e){const t=ge.fromBlob(e);return{metadata:t.bytesBlob().raw,code:t.remainingBytes().raw}}var G_,j_,q_;!function(e){e[e.NoLookup=0]="NoLookup",e[e.NoState=1]="NoState",e[e.NoServiceCode=2]="NoServiceCode",e[e.ServiceCodeMismatch=3]="ServiceCodeMismatch"}(G_||(G_={}));class z_{context;keccakHasher;allocator;constructor(e,t,r){this.context=e,this.keccakHasher=t,this.allocator=r}hashConcat(e,t){return pt(this.keccakHasher,[e,t])}hashConcatPrepend(e,t,r){return pt(this.keccakHasher,[e,t,r])}header(e){return new Ve(ze(e.encoded(),this.allocator).asOpaque(),e)}extrinsic(e){const t=e.guarantees.view().map(e=>e.view()).map(e=>{const t=ze(e.report.encoded(),this.allocator).asOpaque();return P.blobFromParts([t.raw,e.slot.encoded().raw,e.credentials.encoded().raw])}),r=Ie.encodeObject(_e.sequenceVarLen(UC),t,this.context),s=ze(e.tickets.encoded(),this.allocator).asOpaque(),i=ze(e.preimages.encoded(),this.allocator).asOpaque(),n=ze(r,this.allocator).asOpaque(),a=ze(e.assurances.encoded(),this.allocator).asOpaque(),o=ze(e.disputes.encoded(),this.allocator).asOpaque(),c=P.blobFromParts([s.raw,i.raw,n.raw,a.raw,o.raw]);return new Ke(ze(c,this.allocator).asOpaque(),e,c)}workPackage(e){return this.encode(Yr.Codec,e)}encode(e,t){const r=Ie.encodeObject(e,t,this.context);return new Ke(ze(r,this.allocator).asOpaque(),t,r)}}!function(e){e.PreimageUnneeded="preimage_unneeded",e.PreimagesNotSortedUnique="preimages_not_sorted_unique",e.AccountNotFound="account_not_found"}(j_||(j_={}));class W_{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(j_.PreimagesNotSortedUnique)}const{preimages:t,slot:r}=e,s=[];for(const e of t){const{requester:t,blob:i}=e,n=ze(i).asOpaque(),a=this.state.getService(t);if(null===a)return D.error(j_.AccountNotFound);const o=a.hasPreimage(n),c=a.getLookupHistory(n,ae(i.length));if(o||null===c||!cC.isRequested(c))return D.error(j_.PreimageUnneeded);s.push(hC.provide({serviceId:t,preimage:nC.create({hash:n,blob:i}),slot:r}))}return D.ok({preimages:s})}}class J_{spec;importer;toImport=It.fromSortedArray((e,t)=>{const r=e.timeSlot-t.timeSlot;return r<0?g.Greater:r>0?g.Less:g.Equal});queuedBlocks=mt.new();lastEpoch=Lr(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=ze(t).asOpaque();return D.ok(new Ve(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=Lr(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"}(q_||(q_={}));const Y_=L.zero(Le).asOpaque();class X_{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(q_.AlreadyImported,`Block ${r.hash} is already imported.`);const s=t.parentHeaderHash.materialize();if(!s.isEqualTo(Y_)){const e=this.blocks.getHeader(s);if(null===e)return D.error(q_.ParentNotFound,`Parent ${s.toString()} not found`);const r=t.timeSlotIndex.materialize(),i=e.timeSlotIndex.materialize();if(r<=i)return D.error(q_.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(q_.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(q_.StateRootNotFound,`Posterior state root ${s.toString()} not found`):a.isEqualTo(o)?D.ok(r.hash):D.error(q_.InvalidStateRoot,`Invalid prior state root: ${a.toString()}, expected ${o.toString()} (ours)`)}hashHeader(e){return this.hasher.header(e.header.view())}}var Z_;function eR(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"}(Z_||(Z_={}));const tR=P.blobFromString("jam_valid").raw,rR=P.blobFromString("jam_invalid").raw,sR=P.blobFromString("jam_guarantee").raw;function iR({key:e,signature:t,workReportHash:r}){return{key:e,signature:t,message:P.blobFromParts(sR,r.raw)}}function nR({workReportHash:e,wasConsideredValid:t,signature:r,key:s}){const i=t?tR:rR;return{key:s,signature:r,message:P.blobFromParts(i,e.raw)}}function aR(e,t,r){const{isWorkReportValid:s,signature:i}=e,n=s?tR:rR;return{key:r,signature:i,message:P.blobFromParts(n,t.raw)}}class oR{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}verifyCulprits(e,t,r,s){if(!eR(e.culprits,"key"))return D.error(Z_.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(Z_.OffenderAlreadyReported);if(!s.has(i))return D.error(Z_.BadGuarantorKey);if(void 0===t.toAddToBadSet.findExact(a))return D.error(Z_.CulpritsVerdictNotBad);const o=r.culprits[n];if(!o?.isValid)return D.error(Z_.BadSignature)}return D.ok(null)}verifyFaults(e,t,r,s){if(!eR(e.faults,"key"))return D.error(Z_.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(Z_.OffenderAlreadyReported);if(!s.has(i))return D.error(Z_.BadAuditorKey);if(o){const e=t.toAddToGoodSet.findExact(a),r=t.toAddToBadSet.findExact(a);if(void 0!==e||void 0===r)return D.error(Z_.FaultVerdictWrong)}if(!r.faults[n].isValid)return D.error(Z_.BadSignature)}return D.ok(null)}verifyVerdicts(e,t){if(!eR(e.verdicts,"workReportHash"))return D.error(Z_.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(Z_.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(Z_.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(Z_.BadValidatorIndex);if(!t.judgements[s].isValid)return D.error(Z_.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(Z_.AlreadyJudged)}return D.ok(null)}calculateVotesForWorkReports(e){const t=bt.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(Z_.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(Z_.NotEnoughCulprits)}else if(s!==this.chainSpec.thirdOfValidators)return D.error(Z_.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:vt.fromArrayUnique(HE,t),toAddToBadSet:vt.fromArrayUnique(HE,r),toAddToWonkySet:vt.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=mt.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=It.fromArray(HE,Array.from(t));return LE.create({goodSet:vt.fromTwoSortedCollections(this.state.disputesRecords.goodSet,e.toAddToGoodSet),badSet:vt.fromTwoSortedCollections(this.state.disputesRecords.badSet,e.toAddToBadSet),wonkySet:vt.fromTwoSortedCollections(this.state.disputesRecords.wonkySet,e.toAddToWonkySet),punishSet:vt.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(Z_.BadValidatorIndex);const i=s.ed25519;t.judgements.push(aR(r,n,i))}}return t.culprits=e.culprits.map(iR),t.faults=e.faults.map(nR),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 mt.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 Sr(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 cR=P.blobFromString("jam_entropy").raw,lR=P.blobFromString("jam_fallback_seal").raw,dR=P.blobFromString("jam_ticket_seal").raw;var uR;!function(e){e[e.Ok=0]="Ok",e[e.Error=1]="Error"}(uR||(uR={}));const hR=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]===uR.Error?D.error(null):D.ok(L.fromBlob(o.subarray(1),Le).asOpaque())},fR=async function(e,t,r,s){const i=s.length+dR.length+1,n=P.blobFromParts(r.map(e=>P.blobFromParts([e.signature.raw,dR,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]===uR.Ok,entropyHash:L.fromBlob(e.raw.subarray(1,33),Le).asOpaque()}))}catch(e){if("RuntimeError: unreachable"==`${e}`)return Array.from({length:r.length},()=>({isValid:!1,entropyHash:L.zero(Le).asOpaque()}));throw e}},gR=async function(e,t){const r=P.blobFromParts(t.map(e=>e.raw)).raw,s=await e.getRingCommitment(r);return s[0]===uR.Error?D.error(null):D.ok(L.fromBlob(s.subarray(1),Me).asOpaque())};class pR{runInternal;state;static new(e,t){return new pR(e,t)}constructor(e,t){this.runInternal=e,this.state=t}listenToParentPort(){if(null===dk.parentPort)throw new Error("This method is meant to be run inside a worker thread!");dk.parentPort.once("close",()=>{process.exit(0)}),dk.parentPort.once("message",e=>{this.listenTo(e),dk.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 bR{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 mR(e));return new bR(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 mR(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 mR(e){const{port1:t,port2:r}=new MessageChannel,s=new dk.Worker(e,{});return s.postMessage(t,[t]),await new Promise((e,t)=>{s.once("message",e),s.once("error",t)}),s.unref(),new yR(s,r)}class yR{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 AR;!function(e){e[e.RingCommitment=0]="RingCommitment",e[e.BatchVerifyTickets=1]="BatchVerifyTickets",e[e.VerifySeal=2]="VerifySeal"}(AR||(AR={}));class IR{data;constructor(e){this.data=e}getTransferList(){return[]}}class vR{params;constructor(e){this.params=e}getTransferList(){return[]}}const wR=pR.new(e=>{const t=e.params,r=t.method;return r===AR.RingCommitment?Promise.resolve(new IR(Te.ring_commitment(t.keys))):r===AR.BatchVerifyTickets?Promise.resolve(new IR(Te.batch_verify_tickets(t.keys,t.ticketsData,t.contextLength))):r===AR.VerifySeal?Promise.resolve(new IR(Te.verify_seal(t.keys,t.authorIndex,t.signature,t.payload,t.auxData))):void E(r)},null);class SR{executor;constructor(e){this.executor=e}destroy(){return this.executor.destroy()}static async new({synchronous:e}){const t=pE().cpus().length;return new SR(e?wR:await bR.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 vR({method:AR.VerifySeal,keys:e,authorIndex:t,signature:r,payload:s,auxData:i}))).data}async getRingCommitment(e){return(await this.executor.run(new vR({method:AR.RingCommitment,keys:e}))).data}async batchVerifyTicket(e,t,r){return(await this.executor.run(new vR({method:AR.BatchVerifyTickets,keys:e,ticketsData:t,contextLength:r}))).data}}const ER=(e,t)=>J(e.id,t.id);var CR,kR;!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"}(CR||(CR={}));class xR{chainSpec;state;bandersnatch;constructor(e,t,r=SR.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=qe([r.raw,t]).asOpaque();return this.isEpochChanged(e)?At.new([i,r,s[0],s[1]],4):At.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(Ne).asOpaque(),ed25519:L.zero(yr).asOpaque(),bls:L.zero(Pe).asOpaque(),metadata:e.metadata}):e),{nextValidatorData:s,currentValidatorData:i}=this.state,n=await gR(await this.bandersnatch,r.map(e=>e.bandersnatch));return n.isOk?D.ok({nextValidatorData:r,currentValidatorData:s,previousValidatorData:i,epochRoot:n.ok}):D.error(CR.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]),Kr(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=ue(n),a=qe([e.raw,r]).raw,o=ge.fromBlob(a).u32()%i;s.push(t[o].bandersnatch)}return Kr(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 fs.create({entropy:r[0],ticketsEntropy:r[1],validators:t.map(e=>hs.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(CR.DuplicateTicket);if(t.isGreater())return D.error(CR.BadTicketOrder)}return D.ok(null)}async getNewTicketAccumulator(e,t,r,s){const i=0===t.length?[]:await fR(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(CR.BadTicketProof);const a=this.verifyTickets(n);if(a.isError)return D.error(a.error);if(this.isEpochChanged(e))return D.ok(n);const o=vt.fromSortedArray(ER,this.state.ticketsAccumulator),c=vt.fromSortedArray(ER,n),l=vt.fromTwoSortedCollections(o,c);return o.length+c.length!==l.length?D.error(CR.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(CR.BadSlot);if(!this.isExtrinsicLengthValid(e.slot,e.extrinsic))return D.error(CR.UnexpectedTicket);if(!this.areTicketAttemptsValid(e.extrinsic))return D.error(CR.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"}(kR||(kR={}));class BR{bandersnatch;constructor(e=SR.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(cR,r.ok.raw),i=await hR(await this.bandersnatch,t.currentValidatorData.map(e=>e.bandersnatch),e.bandersnatchBlockAuthorIndex.materialize(),e.entropySource.materialize(),s,P.blobFromNumbers([]));return i.isError?D.error(kR.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(kR.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(dR,r.raw,new Uint8Array([c])),d=await hR(await this.bandersnatch,s.map(e=>e.bandersnatch),i,n.seal.materialize(),l,gs(n));return d.isError?D.error(kR.IncorrectSeal):o.isEqualTo(d.ok)?D.ok(d.ok):D.error(kR.InvalidTicket)}async verifySealWithKeys(e,t,r,s,i,n,a){const o=e[r%e.length];if(!o.isEqualTo(t.bandersnatch))return D.error(kR.InvalidValidator,`Expected: ${o}, got: ${t.bandersnatch}`);const c=P.blobFromParts(lR,s.raw),l=await hR(await this.bandersnatch,i.map(e=>e.bandersnatch),n,a.seal.materialize(),c,gs(a));return l.isError?D.error(kR.IncorrectSeal):D.ok(l.ok)}}const _R=ce(81),RR=v.isGreaterOrEqual(h.V0_6_7)?ce(34):ce(32),OR=si.new(void 0,"externalities");class UR{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:A_(s.slots);if(i?.status!==u_.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=Dr((t-256+1+r)%r+256)}}checkPreimageStatus(e,t){const r=this.updatedState.getLookupHistory(this.currentTimeslot,this.currentServiceId,e,t);return null===r?null:A_(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===u_.Requested)return D.error(h_.AlreadyRequested);if(e===u_.Available||e===u_.Reavailable)return D.error(h_.AlreadyAvailable);w(e===u_.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:_R),l=this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,o,c,s);if(l.isError)return D.error(h_.InsufficientFunds,l.details);const d=d_(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(f_.NotFound);const i=A_(s.slots),n=()=>{const e=this.getCurrentServiceInfo(),r=e.storageUtilisationCount-2,s=e.storageUtilisationBytes-t-_R;return this.updatedState.updateServiceStorageUtilisation(this.currentServiceId,r,s,e)};if(i.status===u_.Requested)return n().isError?D.error(f_.StorageUtilisationError):(this.updatedState.updatePreimage(hC.remove({serviceId:r,hash:s.hash,length:s.length})),D.ok(O));const a=this.currentTimeslot;return i.status===u_.Unavailable?i.data[1]<a-this.chainSpec.preimageExpungePeriod?n().isError?D.error(f_.StorageUtilisationError):(this.updatedState.updatePreimage(hC.remove({serviceId:r,hash:s.hash,length:s.length})),D.ok(O)):D.error(f_.NotExpired):i.status===u_.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===u_.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(f_.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(g_.DestinationNotFound);if(r<n.onTransferMinGas)return D.error(g_.GasTooLow);const a=i.balance-t;return a<iC.calculateThresholdBalance(i.storageUtilisationCount,i.storageUtilisationBytes,i.gratisStorage)?D.error(g_.BalanceBelowThreshold):(this.updatedState.stateUpdate.transfers.push(v_.create({source:this.currentServiceId,destination:e,amount:t,memo:s,gas:r})),this.updatedState.updateServiceInfo(this.currentServiceId,iC.create({...i,balance:ce(a)})),D.ok(O))}newService(e,t,r,s,i){const n=this.nextNewServiceId,a=ae(2),o=de(_R,t),c=d_(t);if(i!==ce(0)&&this.currentServiceId!==this.updatedState.getPrivilegedServices().manager)return D.error(m_.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(m_.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:Tr(0),parentService:this.currentServiceId}),lookupHistory:new cC(e.asOpaque(),c,oC([]))})),this.updatedState.updateServiceInfo(this.currentServiceId,iC.create({...d,balance:ce(h)})),this.nextNewServiceId=this.getNextAvailableServiceId(function(e){const t=2**32-512;return Dr(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:Mr(t),onTransferMinGas:Mr(r)}))}updateValidatorsData(e){if(v.isGreaterOrEqual(h.V0_6_7)){const e=this.updatedState.getPrivilegedServices().validatorsManager;if(e!==this.currentServiceId)return OR.trace(`Current service id (${this.currentServiceId}) is not a validators manager. (expected: ${e}) and cannot update validators data. Ignoring`),D.error(I_)}return this.updatedState.stateUpdate.validatorsData=e,D.ok(O)}checkpoint(){this.checkpointedState=B_.copyFrom(this.updatedState.stateUpdate)}updateAuthorizationQueue(e,t,r){const s=this.updatedState.getPrivilegedServices().authManager[e];return s!==this.currentServiceId?(OR.trace(`Current service id (${this.currentServiceId}) is not an auth manager of core ${e} (expected: ${s}) and cannot update authorization queue. Ignoring`),D.error(y_.UnprivilegedService)):null===r&&v.isGreaterOrEqual(h.V0_7_1)?(OR.trace("The new auth manager is not a valid service id. Ignoring"),D.error(y_.InvalidServiceId)):(this.updatedState.stateUpdate.authorizationQueues.set(e,t),D.ok(O))}updatePrivilegedServices(e,t,r,s){return v.isGreaterOrEqual(h.V0_6_7)&&this.updatedState.getPrivilegedServices().manager!==this.currentServiceId?D.error(y_.UnprivilegedService):null===e||null===r?D.error(y_.InvalidServiceId):(this.updatedState.stateUpdate.privilegedServices=KE.create({manager:e,authManager:t,validatorsManager:r,autoAccumulateServices:s.map(([e,t])=>VE.create({service:e,gasLimit:t}))}),D.ok(O))}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(b_.ServiceNotFound);const r=ze(t).asOpaque(),s=this.updatedState.getLookupHistory(this.currentTimeslot,e,r,ce(t.length));return null!==s&&cC.isRequested(s)?this.updatedState.hasPreimage(e,r)?D.error(b_.AlreadyProvided):(this.updatedState.updatePreimage(hC.provide({serviceId:e,preimage:nC.create({hash:r,blob:t}),slot:this.currentTimeslot})),D.ok(O)):D.error(b_.WasNotRequested)}eject(e,t){const r=this.getServiceInfo(e);if(null===r||null===e)return D.error(p_.InvalidService,"Service missing");const s=this.getCurrentServiceInfo(),i=L.zero(Le).asOpaque();if(function(e,t){w(t.length>=4,"Not enough space in the destination."),t.set(ue(e))}(this.currentServiceId,i.raw),!r.codeHash.isEqualTo(i))return D.error(p_.InvalidService,"Invalid code hash");if(2!==r.storageUtilisationCount)return D.error(p_.InvalidPreimage,"Too many storage items");const n=ce(((e,...t)=>t.reduce((e,t)=>t<e?e:t,e))(r.storageUtilisationBytes,_R)-_R),[a,o]=this.isPreviousCodeExpired(e,t,n);if(!a)return D.error(p_.InvalidPreimage,`Previous code available: ${o}`);const c=de(s.balance,r.balance);return c.overflow?D.error(p_.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=ce(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?RR:n?-RR: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 TR extends B{static Codec=_e.Class(TR,v.isSuite(f.JAMDUNA,h.V0_6_5)?{hash:_e.bytes(Le).asOpaque(),exportsRoot:_e.bytes(Le).asOpaque(),authorizerHash:_e.bytes(Le).asOpaque(),authorizationOutput:_e.blob,payloadHash:_e.bytes(Le),gas:_e.varU64.asOpaque(),result:es.Codec}:{hash:_e.bytes(Le).asOpaque(),exportsRoot:_e.bytes(Le).asOpaque(),authorizerHash:_e.bytes(Le).asOpaque(),payloadHash:_e.bytes(Le),gas:_e.varU64.asOpaque(),result:es.Codec,authorizationOutput:_e.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 TR({gas:Mr(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 TR(e)}}class NR{operands;reportsLength;gasCost;constructor(e,t,r){this.operands=e,this.reportsLength=t,this.gasCost=r}static empty(){return new NR([],ae(0),Mr(0n))}}class DR{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)??NR.empty();n.reportsLength=ae(n.reportsLength+1),n.gasCost=Mr(n.gasCost+e.gas),n.operands.push(TR.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=Mr(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??ae(0)}getGasCost(e){return this.reportsDataByServiceId.get(e)?.gasCost??Mr(0n)}getServiceIds(){return this.serviceIds}}function MR(e){const t=e.map(e=>e.workPackageSpec.hash);return mt.from(t)}const PR=_e.object({serviceId:_e.u32.asOpaque(),entropy:_e.bytes(Le).asOpaque(),timeslot:_e.u32.asOpaque()});class LR{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(mt.from(e.context.prerequisites.concat(e.segmentRootLookup.map(e=>e.workPackageHash))))}getWorkReportsToAccumulateLater(e){const t=this.state.recentlyAccumulated.flatMap(e=>Array.from(e));return HR(e.filter(e=>e.context.prerequisites.length>0||e.segmentRootLookup.length>0).map(e=>xC.create({report:e,dependencies:this.getWorkReportDependencies(e)})),mt.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=HR(r,MR(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 HR(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 VR=si.new(void 0,"host-calls"),KR=_e.object({serviceId:_e.u32.convert(e=>e,e=>e),gas:_e.u64.convert(e=>ce(e),e=>Mr(e))});class QR{currentServiceId;index=hx(0);gasCost=Cx(10);tracedRegisters=px(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 VR.trace(`GAS <- ${r}`),t.set(7,ce(r)),Promise.resolve(void 0)}}const $R=me(YE.Codec.sizeHint);class FR{currentServiceId;fetch;index=hx(v.selectIfGreaterOrEqual({fallback:18,versions:{[h.V0_6_7]:1}}));gasCost=Cx(10);tracedRegisters=px(7,8,9,10,11,12);constructor(e,t){this.currentServiceId=e,this.fetch=t}async execute(e,t,r){const s=d_(t.get(10)),i=this.getValue(s,t);VR.trace(`FETCH(${s}) <- ${i?.toStringTruncated()}`);const n=t.get(7),a=ce(i?.length??0),o=fe(t.get(8),a),c=fe(t.get(9),ce(a-o)),l=null===i?new Uint8Array:i.raw.subarray(Number(o),Number(o+c));if(r.storeFrom(n,l).isError)return fx.Panic;t.set(7,null===i?i_.NONE:a)}getValue(e,t){if(e===GR.Constants)return this.fetch.constants();if(e===GR.Entropy)return this.fetch.entropy();if(e===GR.AuthorizerTrace)return this.fetch.authorizerTrace();if(e===GR.OtherWorkItemExtrinsics){const e=t.get(11),r=t.get(12);return this.fetch.workItemExtrinsic(e,r)}if(e===GR.MyExtrinsics){const e=t.get(11);return this.fetch.workItemExtrinsic(null,e)}if(e===GR.OtherWorkItemImports){const e=t.get(11),r=t.get(12);return this.fetch.workItemImport(e,r)}if(e===GR.MyImports){const e=t.get(11);return this.fetch.workItemImport(null,e)}if(e===GR.WorkPackage)return this.fetch.workPackage();if(e===GR.Authorizer)return this.fetch.authorizer();if(e===GR.AuthorizationToken)return this.fetch.authorizationToken();if(e===GR.RefineContext)return this.fetch.refineContext();if(e===GR.AllWorkItems)return this.fetch.allWorkItems();if(e===GR.OneWorkItem){const e=t.get(11);return this.fetch.oneWorkItem(e)}if(e===GR.WorkItemPayload){const e=t.get(11);return this.fetch.workItemPayload(e)}if(e===GR.AllOperands)return this.fetch.allOperands();if(e===GR.OneOperand){const e=t.get(11);return this.fetch.oneOperand(e)}if(e===GR.AllTransfers)return this.fetch.allTransfers();if(e===GR.OneTransfer){const e=t.get(11);return this.fetch.oneTransfer(e)}return null}}var GR;!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"}(GR||(GR={}));class jR{currentServiceId;account;index=hx(v.selectIfGreaterOrEqual({fallback:4,versions:{[h.V0_6_7]:5}}));gasCost=Cx(10);tracedRegisters=px(7,8);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=c_(7,t,this.currentServiceId),i=t.get(8),n=this.account.getServiceInfo(s),a=null===n?P.empty():Ie.encodeObject(qR,{...n,thresholdBalance:iC.calculateThresholdBalance(n.storageUtilisationCount,n.storageUtilisationBytes,n.gratisStorage)});if(VR.trace(`INFO(${s}) <- ${a}`),r.storeFrom(i,a.raw).isError)return fx.Panic;null!==n?t.set(7,i_.OK):t.set(7,i_.NONE)}}const qR=v.isGreaterOrEqual(h.V0_6_7)?_e.object({codeHash:_e.bytes(Le),balance:_e.u64,thresholdBalance:_e.u64,accumulateMinGas:_e.u64.convert(e=>e,Mr),onTransferMinGas:_e.u64.convert(e=>e,Mr),storageUtilisationBytes:_e.u64,storageUtilisationCount:_e.u32,gratisStorage:_e.u64,created:_e.u32.convert(e=>e,Tr),lastAccumulation:_e.u32.convert(e=>e,Tr),parentService:_e.u32.convert(e=>e,Dr)},"ServiceAccountInfoWithThresholdBalance"):_e.object({codeHash:_e.bytes(Le),balance:_e.varU64,thresholdBalance:_e.varU64,accumulateMinGas:_e.varU64.convert(e=>e,Mr),onTransferMinGas:_e.varU64.convert(e=>e,Mr),storageUtilisationBytes:_e.varU64,storageUtilisationCount:_e.varU32,gratisStorage:sC(ce(0)),created:sC(Tr(0)),lastAccumulation:sC(Tr(0)),parentService:sC(Dr(0))},"ServiceAccountInfoWithThresholdBalance"),zR=new TextDecoder("utf8");class WR{currentServiceId;index=hx(100);gasCost=Cx(0);tracedRegisters=px();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(d_(n)),l=new Uint8Array(d_(o));return 0n!==i&&r.loadInto(c,i),r.loadInto(l,a),VR.trace(`SERVICE [${this.currentServiceId}] [${s}] ${zR.decode(c)} ${zR.decode(l)}`),Promise.resolve(void 0)}}class JR{currentServiceId;account;index=hx(v.selectIfGreaterOrEqual({fallback:1,versions:{[h.V0_6_7]:2}}));gasCost=Cx(10);tracedRegisters=px(7,8,9,10,11);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=c_(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),a=L.zero(Le);if(r.loadInto(a.raw,i).isError)return fx.Panic;const o=this.account.lookup(s,a);VR.trace(`LOOKUP(${s}, ${a}) <- ${o?.toStringTruncated()}...`);const c=ce(null===o?0:o.raw.length),l=t.get(10),d=t.get(11),u=fe(l,c),h=fe(d,ce(c-u)),f=null===o?new Uint8Array(0):o.raw.subarray(Number(u),Number(u+h));if(r.storeFrom(n,f).isError)return fx.Panic;null!==o?t.set(7,c):t.set(7,i_.NONE)}}class YR{currentServiceId;account;index=hx(v.selectIfGreaterOrEqual({fallback:2,versions:{[h.V0_6_7]:3}}));gasCost=Cx(10);tracedRegisters=px(7,8,9,10,11,12);constructor(e,t){this.currentServiceId=e,this.account=t}async execute(e,t,r){const s=c_(7,t,this.currentServiceId),i=t.get(8),n=t.get(9),a=t.get(10),o=d_(n),c=P.blobFrom(new Uint8Array(o));if(r.loadInto(c.raw,i).isError)return fx.Panic;const l=this.account.read(s,c);VR.trace(`READ(${s}, ${c}) <- ${l?.toStringTruncated()}`);const d=ce(null===l?0:l.raw.length),u=t.get(11),h=t.get(12),f=fe(u,d),g=fe(h,ce(d-f)),p=null===l?new Uint8Array(0):l.raw.subarray(Number(f),Number(f+g));if(r.storeFrom(a,p).isError)return fx.Panic;null!==l?t.set(7,d):t.set(7,i_.NONE)}}class XR{currentServiceId;account;index=hx(v.selectIfGreaterOrEqual({fallback:3,versions:{[h.V0_6_7]:4}}));gasCost=Cx(10);tracedRegisters=px(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=d_(i),c=new Uint8Array(o);if(r.loadInto(c,s).isError)return fx.Panic;const l=P.blobFrom(c),d=d_(a),u=new Uint8Array(d);if(r.loadInto(u,n).isError)return fx.Panic;const h=0n===a?null:P.blobFrom(u),f=this.account.write(l,h);VR.trace(`WRITE(${l}, ${h?.toStringTruncated()}) <- ${f}`),f.isError?t.set(7,i_.FULL):t.set(7,null===f.ok?i_.NONE:ce(f.ok))}}const ZR=[class{currentServiceId;partialState;chainSpec;index=hx(v.selectIfGreaterOrEqual({fallback:5,versions:{[h.V0_6_7]:14}}));gasCost=Cx(10);tracedRegisters=px(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=l_(t.get(7)),i=t.get(8),n=l_(t.get(9)),a=t.get(10),o=t.get(11),c=new Array,l=new Uint8Array(me(KR.sizeHint)),d=ge.fromBlob(l);let u=a;for(let e=0n;e<o;e+=1n){if(d.resetTo(0),r.loadInto(l,u).isError)return fx.Panic;const{serviceId:e,gas:t}=d.object(KR);c.push([e,t]),u=ce(u+ce(d.bytesRead()))}if(v.isGreaterOrEqual(h.V0_6_7)){const e=new Uint8Array(me(_e.u32.sizeHint)*this.chainSpec.coresCount),a=ge.fromBlob(e);if(r.loadInto(e,i).isError)return fx.Panic;const o=NE(a.sequenceFixLen(_e.u32.asOpaque(),this.chainSpec.coresCount),this.chainSpec),l=this.partialState.updatePrivilegedServices(s,o,n,c);if(VR.trace(`BLESS(${s}, ${o}, ${n}, ${c})`),l.isOk)return VR.trace("BLESS result: OK"),void t.set(7,i_.OK);const d=l.error;if(d===y_.UnprivilegedService)return VR.trace("BLESS result: HUH"),void t.set(7,i_.HUH);if(d===y_.InvalidServiceId)return VR.trace("BLESS result: WHO"),void t.set(7,i_.WHO);E(d)}else{const e=l_(i);if(null===s||null===e||null===n)return void t.set(7,i_.WHO);const r=NE(new Array(this.chainSpec.coresCount).fill(e),this.chainSpec);this.partialState.updatePrivilegedServices(s,r,n,c),VR.trace(`BLESS(${s}, ${r}, ${n}, ${c})`),t.set(7,i_.OK)}}},class{currentServiceId;partialState;chainSpec;index=hx(v.selectIfGreaterOrEqual({fallback:6,versions:{[h.V0_6_7]:15}}));gasCost=Cx(10);tracedRegisters=px(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=l_(t.get(9)),a=new Uint8Array(2560);if(r.loadInto(a,i).isError)return fx.Panic;if(s>=this.chainSpec.coresCount)return void t.set(7,i_.CORE);const o=Pr(Number(s)),c=ge.fromBlob(a).sequenceFixLen(_e.bytes(Le),80),l=At.new(c,80);if(v.isGreaterOrEqual(h.V0_6_7)){VR.trace(`ASSIGN(${o}, ${l})`);const e=this.partialState.updateAuthorizationQueue(o,l,n);if(e.isOk)return t.set(7,i_.OK),void VR.trace("ASSIGN result: OK");const r=e.error;if(r===y_.UnprivilegedService)return t.set(7,i_.HUH),void VR.trace("ASSIGN result: HUH");if(r===y_.InvalidServiceId)return t.set(7,i_.WHO),void VR.trace("ASSIGN result: WHO");E(r)}else t.set(7,i_.OK),this.partialState.updateAuthorizationQueue(o,l,n),VR.trace(`ASSIGN(${o}, ${l})`)}},class{currentServiceId;partialState;chainSpec;index=hx(v.selectIfGreaterOrEqual({fallback:7,versions:{[h.V0_6_7]:16}}));gasCost=Cx(10);tracedRegisters=px(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($R*this.chainSpec.validatorsCount);if(r.loadInto(i,s).isError)return fx.Panic;const n=ge.fromBlob(i).sequenceFixLen(YE.Codec,this.chainSpec.validatorsCount);if(v.isGreaterOrEqual(h.V0_6_7)){const e=this.partialState.updateValidatorsData(Hr(n,this.chainSpec));VR.trace(`DESIGNATE([${n[0]}, ${n[1]}, ...])`),e.isError?(t.set(7,i_.HUH),VR.trace("DESIGNATE result: HUH")):(t.set(7,i_.OK),VR.trace("DESIGNATE result: OK"))}else this.partialState.updateValidatorsData(Hr(n,this.chainSpec)),t.set(7,i_.OK),VR.trace(`DESIGNATE([${n[0]}, ${n[1]}, ...])`)}},class{currentServiceId;partialState;index=hx(v.selectIfGreaterOrEqual({fallback:8,versions:{[h.V0_6_7]:17}}));gasCost=Cx(10);tracedRegisters;gasHostCall;constructor(e,t){this.currentServiceId=e,this.partialState=t,this.gasHostCall=new QR(e),this.tracedRegisters=this.gasHostCall.tracedRegisters}async execute(e,t){await this.gasHostCall.execute(e,t),this.partialState.checkpoint(),VR.trace("CHECKPOINT()")}},class{currentServiceId;partialState;index=hx(v.selectIfGreaterOrEqual({fallback:9,versions:{[h.V0_6_7]:18}}));gasCost=Cx(10);tracedRegisters=px(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=Mr(t.get(9)),a=Mr(t.get(10)),o=v.isGreaterOrEqual(h.V0_6_7)?t.get(11):ce(0),c=L.zero(Le);if(r.loadInto(c.raw,s).isError)return fx.Panic;const l=this.partialState.newService(c.asOpaque(),i,n,a,o);if(VR.trace(`NEW(${c}, ${i}, ${n}, ${a}, ${o}) <- ${N(l)}`),l.isOk)return void t.set(7,ce(l.ok));const d=l.error;d!==m_.InsufficientFunds?d!==m_.UnprivilegedService?E(d):t.set(7,i_.HUH):t.set(7,i_.CASH)}},class{currentServiceId;partialState;index=hx(v.selectIfGreaterOrEqual({fallback:10,versions:{[h.V0_6_7]:19}}));gasCost=Cx(10);tracedRegisters=px(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(Le);if(r.loadInto(a.raw,s).isError)return fx.Panic;this.partialState.upgradeService(a.asOpaque(),i,n),VR.trace(`UPGRADE(${a}, ${i}, ${n})`),t.set(7,i_.OK)}},class{currentServiceId;partialState;index=hx(v.selectIfGreaterOrEqual({fallback:11,versions:{[h.V0_6_7]:20}}));gasCost=e=>{const t=10n+e.get(9);return xx(t)};tracedRegisters=px(7,8,9,10);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=l_(t.get(7)),i=t.get(8),n=Mr(t.get(9)),a=t.get(10),o=L.zero(128);if(r.loadInto(o.raw,a).isError)return fx.Panic;const c=this.partialState.transfer(s,i,n,o);if(VR.trace(`TRANSFER(${s}, ${i}, ${n}, ${o}) <- ${N(c)}`),c.isOk)return void t.set(7,i_.OK);const l=c.error;l!==g_.DestinationNotFound?l!==g_.GasTooLow?l!==g_.BalanceBelowThreshold?E(l):t.set(7,i_.CASH):t.set(7,i_.LOW):t.set(7,i_.WHO)}},class{currentServiceId;partialState;index=hx(v.selectIfGreaterOrEqual({fallback:12,versions:{[h.V0_6_7]:21}}));gasCost=Cx(10);tracedRegisters=px(7,8);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=l_(t.get(7)),i=t.get(8),n=L.zero(Le).asOpaque();if(r.loadInto(n.raw,i).isError)return fx.Panic;if(s===this.currentServiceId)return void t.set(7,i_.WHO);const a=this.partialState.eject(s,n);if(VR.trace(`EJECT(${s}, ${n}) <- ${N(a)}`),a.isOk)return void t.set(7,i_.OK);const o=a.error;o===p_.InvalidService?t.set(7,i_.WHO):o===p_.InvalidPreimage?t.set(7,i_.HUH):E(o)}},class{currentServiceId;partialState;index=hx(v.selectIfGreaterOrEqual({fallback:13,versions:{[h.V0_6_7]:22}}));gasCost=Cx(10);tracedRegisters=px(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(Le);if(r.loadInto(n.raw,s).isError)return fx.Panic;const a=this.partialState.checkPreimageStatus(n.asOpaque(),i);VR.trace(`QUERY(${n}, ${i}) <- ${a}`);const o=ce(0n);if(null===a)return t.set(7,i_.NONE),void t.set(8,o);switch(a.status){case u_.Requested:return t.set(7,o),void t.set(8,o);case u_.Available:return t.set(7,ce(1n+(BigInt(a.data[0])<<32n))),void t.set(8,o);case u_.Unavailable:return t.set(7,ce(2n+(BigInt(a.data[0])<<32n))),void t.set(8,ce(a.data[1]));case u_.Reavailable:return t.set(7,ce(3n+(BigInt(a.data[0])<<32n))),void t.set(8,ce((BigInt(a.data[2])<<32n)+BigInt(a.data[1])))}}},class{currentServiceId;partialState;index=hx(v.selectIfGreaterOrEqual({fallback:14,versions:{[h.V0_6_7]:23}}));gasCost=Cx(10);tracedRegisters=px(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(Le);if(r.loadInto(n.raw,s).isError)return fx.Panic;const a=this.partialState.requestPreimage(n.asOpaque(),i);if(VR.trace(`SOLICIT(${n}, ${i}) <- ${N(a)}`),a.isOk)return void t.set(7,i_.OK);const o=a.error;o!==h_.AlreadyAvailable&&o!==h_.AlreadyRequested?o!==h_.InsufficientFunds?E(o):t.set(7,i_.FULL):t.set(7,i_.HUH)}},class{currentServiceId;partialState;index=hx(v.selectIfGreaterOrEqual({fallback:15,versions:{[h.V0_6_7]:24}}));gasCost=Cx(10);tracedRegisters=px(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(Le);if(r.loadInto(n.raw,s).isError)return fx.Panic;const a=this.partialState.forgetPreimage(n.asOpaque(),i);VR.trace(`FORGET(${n}, ${i}) <- ${N(a)}`),a.isOk?t.set(7,i_.OK):t.set(7,i_.HUH)}},class{currentServiceId;partialState;index=hx(v.selectIfGreaterOrEqual({fallback:16,versions:{[h.V0_6_7]:25}}));gasCost=Cx(10);tracedRegisters=px(7);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=t.get(7),i=L.zero(Le);if(r.loadInto(i.raw,s).isError)return fx.Panic;this.partialState.yield(i),VR.trace(`YIELD(${i})`),t.set(7,i_.OK)}},class{currentServiceId;partialState;index=hx(v.selectIfGreaterOrEqual({fallback:27,versions:{[h.V0_6_7]:26}}));gasCost=Cx(10);tracedRegisters=px(7,8,9);constructor(e,t){this.currentServiceId=e,this.partialState=t}async execute(e,t,r){const s=c_(7,t,this.currentServiceId),i=t.get(8),n=d_(t.get(9)),a=P.blobFrom(new Uint8Array(n));if(r.loadInto(a.raw,i).isError)return fx.Panic;const o=this.partialState.providePreimage(s,a);if(VR.trace(`PROVIDE(${s}, ${a.toStringTruncated()}) <- ${N(o)}`),o.isOk)return void t.set(7,i_.OK);const c=o.error;c!==b_.ServiceNotFound?c!==b_.WasNotRequested&&c!==b_.AlreadyProvided?E(c):t.set(7,i_.HUH):t.set(7,i_.WHO)}}];var eO,tO;!function(e){e.IS_AUTHORIZED=w_(0),e.REFINE=w_(0),e.ACCUMULATE=w_(5),e.ON_TRANSFER=w_(10)}(eO||(eO={}));class rO{serviceCode;entrypoint;pvm;hostCalls;pvmInstanceManager=new s_(4);constructor(e,t,r){this.serviceCode=e,this.entrypoint=r,this.hostCalls=new O_(...t),this.pvm=new r_(this.pvmInstanceManager,this.hostCalls)}static prepareAccumulateHostCalls(e,t,r){const s=ZR.map(s=>new s(e,t.partialState,r)),i=[new WR(e),new QR(e),new YR(e,t.serviceExternalities),new XR(e,t.serviceExternalities),new FR(e,t.fetchExternalities),new JR(e,t.serviceExternalities),new jR(e,t.serviceExternalities)];return s.concat(i)}static prepareOnTransferHostCalls(e,t){return[new WR(e),new QR(e),new FR(e,t.fetchExternalities),new YR(e,t.partialState),new XR(e,t.partialState),new JR(e,t.partialState),new jR(e,t.partialState)]}async run(e,t){const r=$_.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=rO.prepareAccumulateHostCalls(e,r,s);return new rO(t,i,eO.ACCUMULATE)}static createOnTransferExecutor(e,t,r){const s=rO.prepareOnTransferHostCalls(e,r);return new rO(t,s,eO.ON_TRANSFER)}}!function(e){e[e.NoService=0]="NoService",e[e.NoPreimage=1]="NoPreimage"}(tO||(tO={}));const sO=10000000n,iO=si.new(void 0,"accumulate"),nO=_e.object({slot:_e.u32.asOpaque(),serviceId:_e.u32.asOpaque(),operands:_e.sequenceVarLen(TR.Codec)}),aO=_e.object({slot:_e.varU32.asOpaque(),serviceId:_e.varU32.asOpaque(),operands:_e.varU32});class oO{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 iO.log(`Service with id ${t} not found.`),D.error(tO.NoService);const o=a.getInfo().codeHash,c=a.getPreimage(o.asOpaque());if(null===c)return iO.log(`Code with hash ${o} not found for service ${t}.`),D.error(tO.NoPreimage);const l=function({serviceId:e,entropy:t,timeslot:r},s){const i=he(ze(Ie.encodeObject(PR,{serviceId:e,entropy:t,timeslot:r},s)).raw.subarray(0,4))>>>0;return Dr(i%(2**32-512)+256)}({serviceId:t,entropy:i,timeslot:e},this.chainSpec),d=new UR(this.chainSpec,new __(this.state,n),t,l,e),u={partialState:d,serviceExternalities:d,fetchExternalities:bO.createForAccumulate({entropy:i,operands:r},this.chainSpec)},f=rO.createAccumulateExecutor(t,c,u,this.chainSpec);let g=P.empty();g=v.is(h.V0_6_5)?Ie.encodeObject(nO,{slot:e,serviceId:t,operands:r},this.chainSpec):Ie.encodeObject(aO,{slot:e,serviceId:t,operands:ae(r.length)});const p=await f.run(g,xx(s)),[b,m]=d.getStateUpdates();if(p.hasStatus()){const e=p.status;if(e===ox.OOG||e===ox.PANIC)return D.ok({stateUpdate:m,consumedGas:Mr(p.consumedGas)})}if(p.hasMemorySlice()&&p.memorySlice.length===Le){const e=L.fromBlob(p.memorySlice,Le);b.yieldedRoots.set(t,e.asOpaque())}return D.ok({stateUpdate:b,consumedGas:Mr(p.consumedGas)})}async accumulateSingleService(e,t,r,s,i,n){iO.trace(`Accumulating service ${e}, items: ${t.length} at slot: ${s}.`);const a=await this.pvmAccumulateInvocation(s,e,t,r,i,n);return a.isError?(iO.trace(`Accumulation failed for ${e}.`),{stateUpdate:null,consumedGas:r}):(iO.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:ae(0),gasCost:Mr(0),state:n};const o=t.slice(0,a),c=this.state.privilegedServices.autoAccumulateServices,l=new DR(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(Mr(e-u),d,r,s,i,h);return C(m),{accumulatedReports:ae(a+g),gasCost:Mr(u+p),state:b}}async accumulateInParallel(e,t,r,s,i){const n=e.getServiceIds();let a=Mr(0),o=i;for(const i of n){const n=B_.copyFrom(o),{consumedGas:c,stateUpdate:l}=await this.accumulateSingleService(i,e.getOperands(i),e.getGasCost(i),t,r,o);a=Mr(a+c);const d=s.get(i)??{count:ae(0),gasUsed:Mr(0)};d.count=ae(d.count+e.getReportsLength(i)),d.gasUsed=Mr(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=MR(e),c=Array.from(o).sort((e,t)=>HE(e,t).value),l=Kr(this.state.recentlyAccumulated.slice(1).concat(mt.from(c)),this.chainSpec),d=this.state.accumulationQueue.slice();d[a]=HR(t,o);for(let e=1;e<n;e++){const t=(a+n-e)%n;e<r-this.state.timeslot?d[t]=[]:d[t]=HR(d[t],o)}const u=new __(this.state,B_.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:Kr(d,this.chainSpec),timeslot:r,...u.stateUpdate.services}}getGasLimit(){const e=sO*BigInt(this.chainSpec.coresCount)+this.state.privilegedServices.autoAccumulateServices.reduce((e,{gasLimit:t})=>e+t,0n),t=Mr(this.chainSpec.maxBlockGas>e?this.chainSpec.maxBlockGas:e);return Mr(t)}async transition({reports:e,slot:t,entropy:r}){const s=new Map,i=new LR(this.chainSpec,this.state),n=i.getWorkReportsToAccumulateImmediately(e),a=i.getWorkReportsToAccumulateLater(e),o=HR(i.getQueueFromState(t).concat(a),MR(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,B_.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 gt.create(),r=(s=t,{hashConcat:(e,t=[])=>pt(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(Le).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([ue(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 cO;!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"}(cO||(cO={}));class lO{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=At.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(cO.InvalidAnchor,`anchor: expected: ${e.parentHash}, got ${s}`);if(n>=a)return D.error(cO.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(cO.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(cO.InvalidValidatorIndex);r.push({signature:e.signature.materialize(),key:i.ed25519,message:uO(e.anchor.encoded(),e.bitfield.encoded())})}const s=await Sr(r),i=s.every(e=>e);if(!i){const e=s.reduce((e,t,r)=>t?e:e.concat(r),[]);return D.error(cO.InvalidSignature,`invalid signatures at ${e.join(", ")}`)}return D.ok(O)}}const dO=P.blobFromString("jam_available").raw;function uO(e,t){return P.blobFromParts(dO,ze(P.blobFromParts(e.raw,t.raw)).raw)}var hO;!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"}(hO||(hO={}));const fO=_e.object({B_I:_e.u64,B_L:_e.u64,B_S:_e.u64,C:_e.u16,D:_e.u32,E:_e.u32,G_A:_e.u64,G_I:_e.u64,G_R:_e.u64,G_T:_e.u64,H:_e.u16,I:_e.u16,J:_e.u16,K:_e.u16,L:_e.u32,N:_e.u16,O:_e.u16,P:_e.u16,Q:_e.u16,R:_e.u16,T:_e.u16,U:_e.u16,V:_e.u16,W_A:_e.u32,W_B:_e.u32,W_C:_e.u32,W_E:_e.u32,W_M:_e.u32,W_P:_e.u32,W_R:_e.u32,W_T:_e.u32,W_X:_e.u32,Y:_e.u32}),gO=new Map;var pO;!function(e){e[e.Accumulate=0]="Accumulate",e[e.OnTransfer=1]="OnTransfer"}(pO||(pO={}));class bO{fetchData;chainSpec;constructor(e,t){this.fetchData=e,this.chainSpec=t}static createForAccumulate(e,t){return new bO({context:pO.Accumulate,...e},t)}static createForOnTransfer(e,t){return new bO({context:pO.OnTransfer,...e},t)}constants(){return function(e){const t=gO.get(e);if(void 0!==t)return t;const r=Ie.encodeObject(fO,{B_I:ce(10n),B_L:ce(1n),B_S:ce(100n),C:ie(e.coresCount),D:ae(e.preimageExpungePeriod),E:ae(e.epochLength),G_A:ce(sO),G_I:ce(5e7),G_R:ce(e.maxRefineGas),G_T:ce(e.maxBlockGas),H:ie(8),I:ie(Jr),J:ie(8),K:ie(16),L:ae(14400),N:ie(2),O:ie(8),P:ie(e.slotDuration),Q:ie(80),R:ie(e.rotationPeriod),T:ie(128),U:ie(5),V:e.validatorsCount,W_A:ae(64e3),W_B:ae(13794305),W_C:ae(4e6),W_E:ae(e.erasureCodedPieceSize),W_M:ae(3072),W_P:ae(e.numberECPiecesPerSegment),W_R:ae(49152),W_T:ae(128),W_X:ae(3072),Y:ae(e.contestLength)});return gO.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!==pO.Accumulate)return null;const e=this.fetchData.operands;return Ie.encodeObject(_e.sequenceVarLen(TR.Codec),e,this.chainSpec)}oneOperand(e){if(this.fetchData.context!==pO.Accumulate)return null;const{operands:t}=this.fetchData;if(e>=2n**32n)return null;const r=t[Number(e)];return void 0===r?null:Ie.encodeObject(TR.Codec,r,this.chainSpec)}allTransfers(){if(this.fetchData.context!==pO.OnTransfer)return null;const{transfers:e}=this.fetchData;return Ie.encodeObject(_e.sequenceVarLen(v_.Codec),e,this.chainSpec)}oneTransfer(e){if(this.fetchData.context!==pO.OnTransfer)return null;const{transfers:t}=this.fetchData;if(e>=2n**32n)return null;const r=t[Number(e)];return void 0===r?null:Ie.encodeObject(v_.Codec,r,this.chainSpec)}}const mO=_e.object({timeslot:_e.u32.asOpaque(),serviceId:_e.u32.asOpaque(),transfers:_e.sequenceVarLen(v_.Codec)}),yO=_e.object({timeslot:_e.varU32.asOpaque(),serviceId:_e.varU32.asOpaque(),transfersLength:_e.varU32});var AO;!function(e){e[e.ServiceBalanceOverflow=1]="ServiceBalanceOverflow",e[e.ServiceInfoNotExist=2]="ServiceInfoNotExist"}(AO||(AO={}));const IO=si.new(void 0,"deferred-transfers");class vO{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=B_.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(AO.ServiceInfoNotExist);const l=c.codeHash,d=n.getPreimage(r,l.asOpaque()),u=de(c.balance,...o.map(e=>e.amount));if(u.overflow)return D.error(AO.ServiceBalanceOverflow);const f=iC.create({...c,balance:u.value});n.updateServiceInfo(r,f);const g=new UR(this.chainSpec,n,r,r,t),p=bO.createForOnTransfer({entropy:s,transfers:o},this.chainSpec);let b=xx(0);if(null===d||0===o.length)IO.trace(`Skipping ON_TRANSFER execution for service ${r}, code is null or no transfers`);else{const e=()=>v.isGreaterOrEqual(h.V0_6_7)?Ie.encodeObject(yO,{timeslot:t,serviceId:r,transfersLength:ae(o.length)},this.chainSpec):Ie.encodeObject(mO,{timeslot:t,serviceId:r,transfers:o},this.chainSpec),s=rO.createOnTransferExecutor(r,d,{partialState:g,fetchExternalities:p}),i=e(),n=o.reduce((e,t)=>e+t.gas,0n);b=(await s.run(i,xx(n))).consumedGas}i.set(r,{count:ae(o.length),gasUsed:Mr(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 wO{chainSpec;state;constructor(e,t){this.chainSpec=e,this.state=t}transition(e){const t=this.state.authPools.slice();for(let r=Pr(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]=yt(s)}return{authPools:NE(t,this.chainSpec)}}}class SO{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?$E.fromPeaks(this.hasher,this.state.recentBlocks.asCurrent().accumulationLog):$E.empty(this.hasher):null!==r?$E.fromPeaks(this.hasher,r.mmr):$E.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(Le).asOpaque(),reported:e.workPackages})):t.push(GE.create({headerHash:e.headerHash,mmr:i,postStateRoot:L.zero(Le).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 EO(e,t,r){return function(e,t,r){const s=CO(Tr(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(ue(ae(Math.floor(e/8))),32);const t=4*e%32,i=t+4,n=he(ze(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)=>Pr(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 CO(e,t){return Math.floor(e/t)}const kO=P.blobFromString("jam_guarantee").raw;function xO(e){return P.blobFromParts(kO,e.raw)}const BO=1e7;class _O{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(hO.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(hO.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(hO.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(hO.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=Sr(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 Ve(i,r),timeout:e.slot}),l+=1}const u=vt.fromArray(J,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(hO.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(_(ze(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<cs[0]||l.length>cs[1])return D.error(hO.InsufficientGuarantees,`Invalid number of credentials. Expected ${cs}, 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(hO.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(hO.BadValidatorIndex,`Invalid validator index: ${r}`);if(n.core!==o)return D.error(hO.WrongAssignment,`Invalid core assignment for validator ${r}. Expected: ${n.core}, got: ${o}`);i.push({signature:s,key:n.ed25519,message:xO(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(hO.CoreEngaged,`Report pending availability at core: ${n}`);const a=e.authorizerHash;if(void 0===r[n].find(e=>e.isEqualTo(a)))return D.error(hO.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(hO.BadServiceId,`No service with id: ${t.serviceId}`);const r=e.getInfo();if(t.gas<r.accumulateMinGas)return D.error(hO.ServiceItemGasTooLow,`Service (${t.serviceId}) gas is less than minimal. Got: ${t.gas}, expected at least: ${r.accumulateMinGas}`)}const o=de(...e.results.map(e=>e.gas));if(o.overflow||o.value>BO)return D.error(hO.WorkReportGasTooHigh,`Total gas too high. Got: ${o.value} (ovfl: ${o.overflow}), maximal: ${BO}`)}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=bt.new(),a=mt.new(),o=mt.new();for(const r of e.guarantees){const e=r.materialize();i.push(e.report.context);const s=is.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(hO.BadServiceId,`No service with id: ${r.serviceId}`);if(!r.codeHash.isEqualTo(e.getInfo().codeHash))return D.error(hO.BadCodeHash,`Service (${r.serviceId}) code hash mismatch. Got: ${r.codeHash}, expected: ${e.getInfo().codeHash}`)}}if(n.size!==e.guarantees.length)return D.error(hO.DuplicatePackage,"Duplicate work package detected.");const c=function(e,t,r,s,i){const n=bt.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(hO.AnchorNotRecent,`Anchor block ${r.anchor} not found in recent blocks.`);if(!t.postStateRoot.isEqualTo(r.stateRoot))return D.error(hO.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(hO.BadBeefyMmrRoot,`Invalid BEEFY super peak hash. Got: ${r.beefyRoot}, expected: ${a}. Anchor: ${t.headerHash}`);if(r.lookupAnchorSlot<e)return D.error(hO.SegmentRootLookupInvalid,`Lookup anchor slot's too old. Got: ${r.lookupAnchorSlot}, minimal: ${e}`);if(!n.has(r.lookupAnchor)&&!i.isInChain(r.lookupAnchor))return D.error(hO.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=mt.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(hO.DuplicatePackage,`The same work package hash found in the pipeline (workPackageHash: ${e})`);return D.ok(O)}(mt.viewDictionaryKeys(n),t);if(l.isError)return l;const d=bt.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?hO.SegmentRootLookupInvalid:hO.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?is.create({workPackageHash:t.workPackageHash,segmentTreeRoot:r}):void 0}if(void 0===e||!e.segmentTreeRoot.isEqualTo(t.segmentTreeRoot))return D.error(hO.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(hO.BadSignature,`Invalid signatures for validators with keys: ${r.join(", ")}`)}getGuarantorAssignment(e,t,r){const s=this.chainSpec.epochLength,i=this.chainSpec.rotationPeriod,n=CO(e,i),a=CO(t,i),o=Math.max(0,n-1)*i;if(t>e)return D.error(hO.FutureReportSlot,`Report slot is in future. Block ${e}, Report: ${t}`);if(t<o)return D.error(hO.ReportEpochBeforeLast,`Report slot is too old. Block ${e}, Report: ${t}`);let c=r[2],l=this.state.currentValidatorData,d=e;n>a&&(d=Tr(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=EO(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 RO{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=Hr(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 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:Mr(t.gasUsed),exported:ie(t.exported),imported:ie(t.imported),extrinsicCount:ie(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:ie(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,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=ae(d);const u=o[r].tickets+s.tickets.length;o[r].tickets=ae(u);const h=o[r].preImages+s.preimages.length;o[r].preImages=ae(h);const f=s.preimages.reduce((e,t)=>e+t.blob.length,0),g=o[r].preImagesSize+f;o[r].preImagesSize=ae(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=ae(e),p.add(t)}for(const{validatorIndex:e}of s.assurances){const t=o[e].assurances+1;o[e].assurances=ae(t)}for(let e=0;e<this.chainSpec.coresCount;e++){const t=Pr(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:ie(0),extrinsicCount:ie(0),extrinsicSize:ae(0),exported:ie(0),gasUsed:Mr(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=ae(r?.workPackageSpec.length??0),c[t].dataAvailabilityLoad=this.calculateDAScoreCore(h),c[t].popularity=ie(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:ae(0),gasUsed:Mr(0n)},{count:b,gasUsed:m}=e.transferStatistics.get(t)??{count:ae(0),gasUsed:Mr(0n)},y=IC.empty();y.refinementCount=ae(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 OO{blocks;constructor(e){this.blocks=e}isInChain(e){return null!==this.blocks.getHeader(e)}}const UO="offenders not matching header";var TO;!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"}(TO||(TO={}));const NO=(e,t)=>D.taggedError(TO,e,t),DO=si.new(void 0,"stf");class MO{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=SR.new({synchronous:!i});this.statistics=new RO(e,t),this.safrole=new xR(e,t,n),this.safroleSeal=new BR(n),this.recentHistory=new SO(s,t),this.disputes=new oR(e,t),this.reports=new _O(e,t,s,new OO(r)),this.assurances=new lO(e,t),this.accumulate=new oO(e,t),this.deferredTransfers=new vO(e,t),this.preimages=new W_(t),this.authorization=new wO(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=ze(i.seal).asOpaque()),null===a){const t=await this.verifySeal(n,e);if(t.isError)return NO(TO.SafroleSeal,t);a=t.ok}const o=await this.disputes.transition(e.extrinsic.view().disputes.materialize());if(o.isError)return NO(TO.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(UO,`Length mismatch: ${e.size} vs ${t.length}`);for(const r of t)if(!e.has(r))return D.error(UO,`Missing key: ${r}`);return D.ok(O)}(u,e.header.view().offendersMarker.materialize());if(h.isError)return NO(TO.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 NO(TO.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 NO(TO.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 NO(TO.Reports,M);const{reported:P,reporters:L,stateUpdate:H,...V}=M.ok;C(V);const{availabilityAssignment:K,...Q}=H;C(Q);const $=this.preimages.integrate({slot:n,preimages:e.extrinsic.view().preimages.materialize()});if($.isError)return NO(TO.Preimages,$);const{preimages:F,...G}=$.ok;C(G);const j=x("import:accumulate"),q=await this.accumulate.transition({slot:n,reports:_,entropy:y[0]});if(DO.log(j()),q.isError)return NO(TO.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 NO(TO.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:F.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)??mt.new();i.insert(e.authorizerHash.materialize()),t.set(s,i)}return t}}var PO;!function(e){e[e.Verifier=0]="Verifier",e[e.Stf=1]="Stf",e[e.Update=2]="Update"}(PO||(PO={}));const LO=(e,t)=>D.taggedError(PO,e,t);class HO{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 X_(t,s),this.stf=new MO(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 LO(PO.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 LO(PO.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)}`),LO(PO.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 Ve(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 Ve(o,e.header.view()))}getBestStateRootHash(){return this.blocks.getPostStateRoot(this.blocks.getBestHeaderHash())}getBestBlockHash(){return this.blocks.getBestHeaderHash()}getStateEntries(e){const t=this.states.getState(e),r=t?.backend.intoStateEntries();return r??null}}const VO=si.new(void 0,"importer");class KO extends Sk{onBestBlock=new Ik;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=ge.decodeObject(ys,e,t.chainSpec);this.onBestBlock.emit(r)}}sendBlock(e,t){e.sendSignal("block",t,[t.buffer])}async importBlock(e,t){const r=await e.sendRequest("importBlock",t,[t.buffer]);return r instanceof Uint8Array?L.fromBlob(r,Le).asOpaque():null}async getStateEntries(e,t){const r=await e.sendRequest("getStateEntries",t,[t.buffer]);return r instanceof Uint8Array?ge.decodeObject(zC.Codec,r):null}async getBestStateRootHash(e){const t=await e.sendRequest("getBestStateRootHash",void 0);return t instanceof Uint8Array?L.fromBlob(t,Le).asOpaque():(VO.error(`Invalid response for getBestStateRootHash. Expected Uint8Array, got: ${t}`),L.zero(Le).asOpaque())}finish(e){return this.onBestBlock.markDone(),{state:"finished",data:e.sendRequest("finish",null)}}}class QO extends Sk{onBlock=new Ik;importer=null;constructor(){super({name:"ready(importer)",allowedTransitions:["finished"],requestHandlers:{importBlock:async e=>await this.importBlock(e),getStateEntries:async e=>await this.getStateEntries(e),getBestStateRootHash:()=>this.getBestStateRootHash(),finish:async()=>this.endWork()},signalListeners:{block:e=>this.triggerOnBlock(e)}})}setImporter(e){this.importer=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=Ie.encodeObject(ys,t,r.chainSpec).raw;e.sendSignal("bestBlock",s,[s.buffer])}async getStateEntries(e){if(null===this.importer)return VO.error(`${this.constructor.name} importer not initialized yet!`),{response:null};if(e instanceof Uint8Array){const t=L.fromBlob(e,Le).asOpaque(),r=this.importer.getStateEntries(t);return{response:Ie.encodeObject(zC.Codec,r??zC.fromEntriesUnsafe([])).raw}}return VO.error(`${this.constructor.name} got invalid request type: ${JSON.stringify(e)}.`),{response:null}}async getBestStateRootHash(){const e=this.importer?.getBestStateRootHash()??null;return{response:null===e?L.zero(Le).raw:e.raw}}async importBlock(e){if(null===this.importer)return VO.error(`${this.constructor.name} importer not initialized yet!`),{response:null};if(e instanceof Uint8Array){const t=this.getConfig(),r=ge.decodeObject(ws.Codec.View,e,t.chainSpec),s=r.header.view().timeSlotIndex.materialize();try{const e=await this.importer.importBlock(r,null);e.isOk?VO.info(`🧊 Best block: #${s} (${e.ok.hash})`):VO.log(`❌ Rejected block #${s}: ${N(e)}`)}catch(e){VO.error(`Failed to import block: ${e}`),VO.error(`${e instanceof Error?e.stack:""}`)}const i=this.importer.getBestStateRootHash();return{response:null===i?L.zero(Le).raw:i.raw}}return VO.error(`${this.constructor.name} got invalid request type: ${JSON.stringify(e)}.`),{response:null}}triggerOnBlock(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=ge.decodeObject(ws.Codec.View,e,t.chainSpec);this.onBlock.emit(r)}else VO.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 $O=si.new(void 0,"importer");if(!dk.isMainThread){si.configureAll(process.env.JAM_LOG??"",zs.LOG);const e=function(){const e=new Jk("ready(importer)",kt.reInit),t=new QO,r=new zk;return new vk("importer",e,[e,t,r])}();mk.receiveChannel(e,dk.parentPort).then(e=>async function(e){$O.info(`📥 Importer starting ${e.currentState()}`);const t=await e.waitForState("ready(importer)"),r=await t.doUntil("finished",async(e,t)=>{$O.info("📥 Importer waiting for blocks.");const r=e.getConfig(),s=new RE(r.dbPath),i=new kE(r.chainSpec,s),n=new nk(r.chainSpec,s),a=new HO(r.chainSpec,new z_(r.chainSpec,await FO,new Qe),$O,i,n);e.setImporter(a);let o=!1;const c=new J_(r.chainSpec,a);e.onBlock.on(async s=>{const n=J_.getBlockDetails(s);if(n.isError)$O.trace("🧊 Ignoring invalid block.");else if(null===i.getHeader(n.ok.hash)){if(c.push(n.ok).isError)$O.trace(`🧊 Already queued block: #${n.ok.data.timeSlot}.`);else if($O.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),$O.info(`🧊 Best block: #${r.data.timeSlotIndex.materialize()} (${r.hash})`)}else $O.log(`❌ Rejected block #${o}: ${N(d)}`);$O.log(l())}}finally{o=!1}}}else $O.trace(`🧊 Already imported block: #${n.ok.data.timeSlot}.`)})});$O.info("📥 Importer finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>$O.error(e))}const FO=gt.create(),GO=si.new(void 0,"net:worker");class jO{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 jO(kt.reInit(t),L.fromBlob(r.raw,Le).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 jO(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 qO extends Sk{onNewBlocks=new Ik;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{newBlocks:e=>this.triggerNewBlocks(e)}})}triggerNewBlocks(e){if(e instanceof Uint8Array){const t=this.getConfig(),r=ge.decodeObject(_e.sequenceVarLen(ws.Codec.View),e,t.genericConfig.chainSpec);this.onNewBlocks.emit(r)}else GO.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}announceHeader(e,t){const r=Ie.encodeObject(ys,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 zO extends Sk{onNewHeader=new Ik;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=ge.decodeObject(ys,e,t.genericConfig.chainSpec);this.onNewHeader.emit(r)}else GO.error(`${this.constructor.name} got invalid signal type: ${JSON.stringify(e)}.`)}sendBlocks(e,t){const r=this.getConfig(),s=Ie.encodeObject(_e.sequenceVarLen(ws.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 WO{chainSpec;keccakHasher;blocks;states;hashAllocator=new Qe;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}=WO.getLastHeaderAndState(r,s);this.lastHeaderHash=i,this.lastHeader=n,this.lastState=a}refreshLastHeaderAndState(){const{lastHeaderHash:e,lastHeader:t,lastState:r}=WO.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 Ie.encodeObject(ws.Codec,e,this.chainSpec)}async nextBlock(){this.refreshLastHeaderAndState();const e=this.lastHeader.timeSlotIndex+1,t=Nr(e%6),r=new z_(this.chainSpec,this.keccakHasher,this.hashAllocator),s=this.lastHeaderHash,i=this.states.getStateRoot(this.lastState),n=vs.create({tickets:[],preimages:[],guarantees:[],assurances:[],disputes:Ur.create({verdicts:[],culprits:[],faults:[]})}),a=Ie.encodeObject(vs.Codec,n,this.chainSpec),o=ge.decodeObject(vs.Codec.View,a,this.chainSpec),c=r.extrinsic(o).hash,l=L.zero(De),d=Ie.create({destination:l.raw});d.i32(e),d.i16(t);const u=bs.create({parentHeaderHash:s,priorStateRoot:await i,extrinsicHash:c,timeSlotIndex:Tr(e),epochMarker:null,ticketsMarker:null,offendersMarker:[],bandersnatchBlockAuthorIndex:t,entropySource:L.fill(De,42*e%256).asOpaque(),seal:l.asOpaque()}),h=Ie.encodeObject(bs.Codec,u,this.chainSpec),f=ge.decodeObject(bs.Codec.View,h,this.chainSpec);return this.lastHeaderHash=r.header(f).hash,this.lastHeader=u,ws.create({header:u,extrinsic:n})}}const JO=si.new(void 0,"block-generator");class YO extends Sk{onBlock=new Ik;constructor(){super({name:"ready(main)",allowedTransitions:["finished"],signalListeners:{block:e=>this.triggerOnBlock(e)}})}triggerOnBlock(e){e instanceof Uint8Array?this.onBlock.emit(e):JO.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 XO extends Sk{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 ZO=si.new(void 0,"block-generator");if(!dk.isMainThread){si.configureAll(process.env.JAM_LOG??"",zs.LOG);const e=function(){const e=new Jk("ready(generator)",kt.reInit),t=new XO,r=new zk;return new vk("block-generator",e,[e,t,r])}();mk.receiveChannel(e,dk.parentPort).then(e=>async function(e){ZO.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 nk(r.chainSpec,s),a=await t.doUntil("finished",async(e,t,s)=>{let a=0;const o=new WO(r.chainSpec,await gt.create(),i,n);for(;!s();){await(0,qs.setTimeout)(1e3*r.chainSpec.slotDuration),a+=1;const s=await o.nextEncodedBlock();ZO.trace(`Sending block ${a}`),e.sendBlock(t,s)}});ZO.info("Block Generator finished. Closing channel."),a.currentState().close(e)}(e)).catch(e=>{ZO.error(e),void 0!==e.stack&&ZO.error(e.stack),void 0!==e.cause&&ZO.error(e.cause)})}const eU=si.new(void 0,"net");if(!dk.isMainThread){si.configureAll(process.env.JAM_LOG??"",zs.LOG);const e=function(){const e=new Jk("ready(network)",jO.reInit),t=new zO,r=new zk;return new vk("network",e,[e,t,r])}();mk.receiveChannel(e,dk.parentPort).then(e=>async function(e){eU.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 vr(s.key),n=new RE(s.genericConfig.dbPath),a=new kE(s.genericConfig.chainSpec,n);eU.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 mS.setup({host:e.host,port:e.port,key:r,protocols:[`jamnp-s/0/${o}`]}),l=new SS(c);l.addPersistentRetry(s);const d=new xS,u=oE.start(i,d,l,n,a);return setImmediate(async()=>{for(;c.isRunning;)await(0,qs.setTimeout)(3e3),u.maintainSync()}),function(e,t,r){t.peers.onPeerConnected(t=>(t.addOnIncomingStream(e=>(CS(()=>r.onIncomingStream(t,e),r=>{lE.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(dE).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()});eU.info("🛜 Network worker finished. Closing channel."),r.currentState().close(e)}(e)).catch(e=>eU.error(e))}const tU=JSON.parse('{"UU":"@typeberry/node","rE":"0.0.1"}');async function rU(e,t){if(!dk.isMainThread)throw new Error("The main binary cannot be running as a Worker!");ak.info(`🫐 Typeberry ${tU.rE}. GP: ${A} (${I})`),ak.info(`🎸 Starting node: ${e.nodeName}.`);const r=ok(e.node.flavor),{rootDb:s,dbPath:i,genesisHeaderHash:n}=function(e,t,r,{readOnly:s=!1}={}){const i=We(e).toString().substring(2,10),n=ze(t).asOpaque(),a=`${r}/${i}/${n.toString().substring(2,10)}`;ak.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 nk(e,r),a=i.getBestHeaderHash(),o=i.getPostStateRoot(a);if(ak.log(`🛢️ Best header hash: ${a}`),ak.log(`🛢️ Best state root: ${o}`),null!==o&&!o.isEqualTo(L.zero(Le))&&!a.isEqualTo(L.zero(Le)))return void await r.db.close();ak.log("🛢️ Database looks fresh. Initializing.");const c=ge.decodeObject(bs.Codec,s.genesisHeader,e),l=ws.create({header:bs.empty(),extrinsic:vs.create({tickets:[],preimages:[],assurances:[],guarantees:[],disputes:{verdicts:[],culprits:[],faults:[]}})}).extrinsic,d=ws.create({header:c,extrinsic:l}),u=ge.decodeObject(ws.Codec.View,Ie.encodeObject(ws.Codec,d,e),e);ak.log(`🧬 Writing genesis block #${c.timeSlotIndex}: ${t}`);const{genesisStateSerialized:h,genesisStateRootHash:f}=function(e,t){const r=zC.fromEntriesUnsafe(t.entries()),s=MC.fromStateEntries(e,r),i=r.getRootHash();return ak.info(`🧬 Genesis state root: ${i}`),{genesisState:s,genesisStateSerialized:r,genesisStateRootHash:i}}(e,s.genesisState);await i.insertBlock(new Ve(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=$O,t=new KO;return Yk(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){return function(e){const t=new Ik;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}))}),function(e,t,r,s,i){return Hk("typeberry-jamnp",n=>{const a=new Fk(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})}(e.chainSpec,t,()=>{const e=r??c.HashAndSlot.create({hash:L.zero(Le).asOpaque(),slot:Tr(0)});return c.Handshake.create({final:e,leafs:[]})},()=>[],(e,t)=>{let r=P.blobFromNumbers([255,255,0,0]);return L.fromBlob(We("0x83bd3bde264a79a2e67c487696c1d7f0b549da89").raw.subarray(0,He),He).isEqualTo(t)&&(r=P.blobFromNumbers([255,255,255,0])),[new l.KeyValuePair(t,r)]})}(e)}(e);return()=>{t()}}({chainSpec:r,bestHeader:o}),u=new kt(r,i,e.node.authorship.omitSealVerification),h=a.transition((e,t)=>e.sendConfig(t,u)),f=await sU(h,e.isAuthoring,u),g=await iU(h,u,n,e.network,o);return{chainSpec:r,importBlock:async e=>await h.execute(async(t,r)=>t.importBlock(r,e.encoded().raw)),getStateEntries:async e=>await h.execute(async(t,r)=>t.getStateEntries(r,e.raw)),getBestStateRootHash:async()=>await h.execute(async(e,t)=>e.getBestStateRootHash(t)),async close(){h.transition((e,t)=>e.finish(t)),ak.log("[main] ☠️ Closing the extensions"),d(),ak.log("[main] ☠️ Closing the authorship module"),f(),ak.log("[main] ☠️ Closing the networking module"),g(),ak.log("[main] 🛢️ Closing the database"),await s.close(),ak.info("[main] ✅ Done.")}}}const sU=async(e,t,r)=>{if(!t)return ak.log("✍️ Authorship off: disabled"),()=>Promise.resolve();ak.info("✍️ Starting block generator.");const{generator:s,finish:i}=await async function(e){const t=(await async function(){const e=ZO,t=new YO;return Yk(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=>{ak.log(`✍️ Produced block. Size: [${r.length}]`),e.sendBlock(t,r)})}),i},iU=async(e,t,r,s,i)=>{if(null===s)return ak.log("🛜 Networking off: no config"),()=>Promise.resolve();const{key:n,host:o,port:c,bootnodes:l}=s,{network:d,finish:u}=await async function(e){const t=(await async function(){return Yk(new URL(a(493),a.b),eU,"ready(main)",new qO)}()).transition((t,r)=>t.sendConfig(r,e));return{network:t,finish:()=>{t.transition((e,t)=>e.finish(t))}}}(jO.new({genericConfig:t,genesisHeaderHash:r,key:n,host:o,port:c,bootnodes:l.map(e=>e.toString())}));return e.doUntil("finished",async(e,t)=>{d.currentState().onNewBlocks.on(r=>{for(const s of r)e.sendBlock(t,s.encoded().raw)})}),d.doUntil("finished",async(e,t)=>{i.on(r=>{e.announceHeader(t,r)})}),u};var nU;!function(e){e[e.NodeNotRunning=0]="NodeNotRunning",e[e.BlockRejected=1]="BlockRejected"}(nU||(nU={}));const aU=si.new(void 0,"fuzztarget"),oU=BigInt(62208e6);const cU=e=>e.endsWith(".json");function lU(e,t){const r=fE().readFileSync(e),s=P.blobFrom(new Uint8Array(r));return ge.decodeObject(ws.Codec.View,s,t)}function dU(e,t){const r=fE().readFileSync(e,"utf-8"),s=JSON.parse(r),i=Z("block"in s?s.block:s,(n=t,te.object({header:js,extrinsic:(a=n,te.object({tickets:Ks,preimages:Hs,guarantees:Ps,assurances:xr(a),disputes:xs},({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})=>vs.create({tickets:e,preimages:t,guarantees:r,assurances:s,disputes:i})))},({header:e,extrinsic:t})=>ws.create({header:e,extrinsic:t}))));var n,a;const o=Ie.encodeObject(ws.Codec,i,t);return ge.decodeObject(ws.Codec.View,o,t)}const uU=(e=>{var t={};return a.d(t,e),t})({default:()=>s.default}),hU=`\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 jam [options] fuzz-target\n\nOptions:\n --name Override node name. Affects networking key and db location.\n [default: ${vE.name}]\n --config Path to a config file or one of: ['${AE}', '${IE}'].\n [default: ${vE.config}]\n`;var fU;function gU(e,t){const{name:r}=bU(e,"name",e=>e,vE.name),{config:s}=bU(e,"config",e=>e===AE?AE:t(e),vE.config);return{nodeName:r,configPath:s}}function pU(e,t){const r=(0,uU.default)(e),s=r._.shift()??fU.Run;switch(s){case fU.Run:{const e=gU(r,t);return mU(r),{command:fU.Run,args:e}}case fU.Dev:{const e=gU(r,t),s=r._.shift();if(void 0===s)throw new Error("Missing dev-validator index.");const i=Number(s);if(!ne(i))throw new Error(`Invalid dev-validator index: ${i}, need U16`);return mU(r),{command:fU.Dev,args:{...e,index:i}}}case fU.FuzzTarget:{const e=gU(r,t);return mU(r),{command:fU.FuzzTarget,args:e}}case fU.Import:{const e=gU(r,t),s=r._.map(e=>t(e));return r._=[],mU(r),{command:fU.Import,args:{...e,files:s}}}default:r._.unshift(s),mU(r)}throw new Error(`Invalid arguments: ${JSON.stringify(r)}`)}function bU(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 mU(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",e.FuzzTarget="fuzz-target"}(fU||(fU={}));const yU=e=>{const t=function(e){if(e===IE)return Z(bE,EE.fromJson);if(e===AE)return Z(mE,EE.fromJson);try{const t=fE().readFileSync(e,"utf8");return Z(JSON.parse(t),EE.fromJson)}catch(t){throw new Error(`Unable to load config file from ${e}: ${t}`)}}(e.args.configPath),r=e.command===fU.Dev?`${e.args.nodeName}-${e.args.index}`:e.args.nodeName,s=e.command===fU.Dev?e.args.index:0,i=function(e,t=new Qe){return ze(P.blobFromParts([Er.raw,e.raw]),t).asOpaque()}(We(r).asOpaque());return lk.new({isAuthoring:e.command===fU.Dev,nodeName:r,nodeConfig:t,networkConfig:{key:i,host:"127.0.0.1",port:12345+s,bootnodes:t.chainSpec.bootnodes??[]}})};if("file:///home/runner/work/typeberry/typeberry/bin/jam/index.ts"===(0,d.pathToFileURL)(process.argv[1]).href){si.configureAll(process.env.JAM_LOG??"",zs.LOG);const e="undefined/../..",t=t=>t.startsWith("/")?t:`${e}/${t}`;let r;try{r=pU(process.argv.slice(2),t)}catch(e){console.error(`\n${e}\n`),console.info(hU),process.exit(1)}const s=async function(e,t){const r=yU(e);if(e.command===fU.FuzzTarget)return async function(e,t){aU.info("💨 Fuzzer starting up.");const{jamNodeConfig:r}=e;let s=null,i=BigInt(Date.now());const n=ok(r.node.flavor);var a;return a={nodeName:tU.UU,nodeVersion:Ek.tryFromString(tU.rE),gpVersion:Ek.tryFromString(A),chainSpec:n,importBlock:async e=>{if(null===s)return D.error(nU.NodeNotRunning);const t=Ie.encodeObject(ws.Codec,e,n),r=ge.decodeObject(ws.Codec.View,t,n),i=await s.importBlock(r);return null===i?D.error(nU.BlockRejected):D.ok(i)},getPostSerializedState:async e=>null===s?null:s.getStateEntries(e),resetState:async(e,a)=>{if(null!==s){const e=s.close();s=null,await e}i+=oU;const o=await rU({...r,node:{...r.node,databaseBasePath:`${r.node.databaseBasePath}/fuzz/${i}`,chainSpec:{...r.node.chainSpec,genesisHeader:Ie.encodeObject(bs.Codec,e,n),genesisState:new Map(a)}},network:null},t);return s=o,await o.getBestStateRootHash()}},Hk("jam_target.sock",e=>new Dk(new qk(a),e,a.chainSpec))}({jamNodeConfig:r},t);if(e.command===fU.Import){const s=await rU({...r,network:null},t);return await(async(e,t)=>{const r=si.new(void 0,"jam");r.info(`📖 Reading ${t.length} blocks`);const s=function*(e){const{chainSpec:t}=e;for(const r of e.files){const e=cU(r)?dU(r,t):lU(r,t);yield e}}({files:t,chainSpec:e.chainSpec});for(const t of s)r.log(`📖 Importing block: #${t.header.view().timeSlotIndex.materialize()}`),await e.importBlock(t);return r.info("All blocks scheduled to be imported."),await e.close()})(s,e.args.files)}return rU(r,t)}(r,t);s.catch(e=>{console.error(`${e}`),process.exit(-1)})}let AU;si.configureAll(process.env.JAM_LOG??"",zs.LOG);try{AU=pU(process.argv.slice(2),IU)}catch(e){console.error(`\n${e}\n`),console.info(hU),process.exit(1)}function IU(e){return e}rU(yU(AU),IU).catch(e=>{console.error(`${e}`),process.exit(-1)});export{fU as Command,hU as HELP,pU as parseArgs,yU as prepareConfigFile};
|
|
3
3
|
//# sourceMappingURL=typeberry.mjs.map
|