openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
546 lines • 926 kB
JavaScript
import{a as __require,n as __esmMin,o as __toCommonJS,r as __exportAll,s as __toESM,t as __commonJSMin}from"./rolldown-runtime-DIxAIwqz.mjs";import{a as require_build$3,i as require_build$2,n as require_base64,o as init_tslib_es6$1,r as require_bytes,s as tslib_es6_exports$1,t as require_encoding}from"./encoding-CxnPIuT7.mjs";import{n as supports_color_exports,r as require_ms,t as init_supports_color}from"./supports-color-DVEEH1hY.mjs";import*as nc from"node:crypto";import*as os$1 from"node:os";import*as net$1 from"node:net";import{SocketAddress,connect,createServer,isIP,isIPv4,isIPv6}from"node:net";import{EventEmitter}from"node:events";import*as timers from"node:timers/promises";import{promises}from"node:dns";import*as tls$1 from"node:tls";import{isIPv4 as isIPv4$1}from"net";import{createCipheriv as createCipheriv$1,createDecipheriv as createDecipheriv$1,createHash as createHash$1,createHmac as createHmac$1,createSign as createSign$1,randomBytes as randomBytes$1,randomUUID as randomUUID$1,timingSafeEqual as timingSafeEqual$1,webcrypto}from"crypto";import{createSocket}from"dgram";import{setTimeout as setTimeout$2}from"timers/promises";import{performance as performance$1}from"perf_hooks";
//!node_modules/.pnpm/debug@4.4.0_supports-color@10.2.2/node_modules/debug/src/common.js
var require_common$2=/* @__PURE__ */ __commonJSMin(((e,t)=>{function setup(e){createDebug.debug=createDebug;createDebug.default=createDebug;createDebug.coerce=coerce;createDebug.disable=disable;createDebug.enable=enable;createDebug.enabled=enabled;createDebug.humanize=require_ms();createDebug.destroy=destroy;Object.keys(e).forEach(t=>{createDebug[t]=e[t]});createDebug.names=[];createDebug.skips=[];createDebug.formatters={};function selectColor(e){let t=0;for(let n=0;n<e.length;n++){t=(t<<5)-t+e.charCodeAt(n);t|=0}return createDebug.colors[Math.abs(t)%createDebug.colors.length]}createDebug.selectColor=selectColor;function createDebug(e){let t;let n=null;let r;let i;function debug(...e){if(!debug.enabled)return;const n=debug;const r=Number(/* @__PURE__ */ new Date);n.diff=r-(t||r);n.prev=t;n.curr=r;t=r;e[0]=createDebug.coerce(e[0]);if(typeof e[0]!==`string`)e.unshift(`%O`);let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,r)=>{if(t===`%%`)return`%`;i++;const a=createDebug.formatters[r];if(typeof a===`function`){const r=e[i];t=a.call(n,r);e.splice(i,1);i--}return t});createDebug.formatArgs.call(n,e);(n.log||createDebug.log).apply(n,e)}debug.namespace=e;debug.useColors=createDebug.useColors();debug.color=createDebug.selectColor(e);debug.extend=extend;debug.destroy=createDebug.destroy;Object.defineProperty(debug,"enabled",{enumerable:true,configurable:false,get:()=>{if(n!==null)return n;if(r!==createDebug.namespaces){r=createDebug.namespaces;i=createDebug.enabled(e)}return i},set:e=>{n=e}});if(typeof createDebug.init===`function`)createDebug.init(debug);return debug}function extend(e,t){const n=createDebug(this.namespace+(typeof t===`undefined`?`:`:t)+e);n.log=this.log;return n}function enable(e){createDebug.save(e);createDebug.namespaces=e;createDebug.names=[];createDebug.skips=[];const t=(typeof e===`string`?e:``).trim().replace(` `,`,`).split(`,`).filter(Boolean);for(const e of t)if(e[0]===`-`)createDebug.skips.push(e.slice(1));else createDebug.names.push(e)}function matchesTemplate(e,t){let n=0;let r=0;let i=-1;let a=0;while(n<e.length)if(r<t.length&&(t[r]===e[n]||t[r]===`*`)){if(t[r]===`*`){i=r;a=n;r++}else{n++;r++}}else if(i!==-1){r=i+1;a++;n=a}else return false;while(r<t.length&&t[r]===`*`)r++;return r===t.length}function disable(){const e=[...createDebug.names,...createDebug.skips.map(e=>`-`+e)].join(`,`);createDebug.enable(``);return e}function enabled(e){for(const t of createDebug.skips)if(matchesTemplate(e,t))return false;for(const t of createDebug.names)if(matchesTemplate(e,t))return true;return false}function coerce(e){if(e instanceof Error)return e.stack||e.message;return e}function destroy(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}createDebug.enable(createDebug.load());return createDebug}t.exports=setup}));
//!node_modules/.pnpm/debug@4.4.0_supports-color@10.2.2/node_modules/debug/src/browser.js
var require_browser=/* @__PURE__ */ __commonJSMin(((e,t)=>{e.formatArgs=formatArgs;e.save=save;e.load=load;e.useColors=useColors;e.storage=localstorage();e.destroy=(()=>{let e=false;return()=>{if(!e){e=true;console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}}})();e.colors=[`#0000CC`,`#0000FF`,`#0033CC`,`#0033FF`,`#0066CC`,`#0066FF`,`#0099CC`,`#0099FF`,`#00CC00`,`#00CC33`,`#00CC66`,`#00CC99`,`#00CCCC`,`#00CCFF`,`#3300CC`,`#3300FF`,`#3333CC`,`#3333FF`,`#3366CC`,`#3366FF`,`#3399CC`,`#3399FF`,`#33CC00`,`#33CC33`,`#33CC66`,`#33CC99`,`#33CCCC`,`#33CCFF`,`#6600CC`,`#6600FF`,`#6633CC`,`#6633FF`,`#66CC00`,`#66CC33`,`#9900CC`,`#9900FF`,`#9933CC`,`#9933FF`,`#99CC00`,`#99CC33`,`#CC0000`,`#CC0033`,`#CC0066`,`#CC0099`,`#CC00CC`,`#CC00FF`,`#CC3300`,`#CC3333`,`#CC3366`,`#CC3399`,`#CC33CC`,`#CC33FF`,`#CC6600`,`#CC6633`,`#CC9900`,`#CC9933`,`#CCCC00`,`#CCCC33`,`#FF0000`,`#FF0033`,`#FF0066`,`#FF0099`,`#FF00CC`,`#FF00FF`,`#FF3300`,`#FF3333`,`#FF3366`,`#FF3399`,`#FF33CC`,`#FF33FF`,`#FF6600`,`#FF6633`,`#FF9900`,`#FF9933`,`#FFCC00`,`#FFCC33`];function useColors(){if(typeof window!==`undefined`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return true;if(typeof navigator!==`undefined`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return false;let e;return typeof document!==`undefined`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!==`undefined`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!==`undefined`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator!==`undefined`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs(e){e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff);if(!this.useColors)return;const n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0;let i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{if(e===`%%`)return;r++;if(e===`%c`)i=r});e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function save(t){try{if(t)e.storage.setItem(`debug`,t);else e.storage.removeItem(`debug`)}catch(e){}}function load(){let t;try{t=e.storage.getItem(`debug`)}catch(e){}if(!t&&typeof process!==`undefined`&&`env`in process)t=process.env.DEBUG;return t}function localstorage(){try{return localStorage}catch(e){}}t.exports=require_common$2()(e);const{formatters:n}=t.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}}));
//!node_modules/.pnpm/debug@4.4.0_supports-color@10.2.2/node_modules/debug/src/node.js
var require_node=/* @__PURE__ */ __commonJSMin(((e,t)=>{const n=__require(`tty`);const r=__require(`util`);e.init=init;e.log=log;e.formatArgs=formatArgs;e.save=save;e.load=load;e.useColors=useColors;e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");e.colors=[6,2,3,4,5,1];try{const t=(init_supports_color(),__toCommonJS(supports_color_exports));if(t&&(t.stderr||t).level>=2)e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(e){}e.inspectOpts=Object.keys(process.env).filter(e=>{return/^debug_/i.test(e)}).reduce((e,t)=>{const n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>{return t.toUpperCase()});let r=process.env[t];if(/^(yes|on|true|enabled)$/i.test(r))r=true;else if(/^(no|off|false|disabled)$/i.test(r))r=false;else if(r===`null`)r=null;else r=Number(r);e[n]=r;return e},{});function useColors(){return`colors`in e.inspectOpts?Boolean(e.inspectOpts.colors):n.isatty(process.stderr.fd)}function formatArgs(e){const{namespace:n,useColors:r}=this;if(r){const r=this.color;const i=`\x1B[3`+(r<8?r:`8;5;`+r);const a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
`).join(`
`+a);e.push(i+`m+`+t.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=getDate()+n+` `+e[0]}function getDate(){if(e.inspectOpts.hideDate)return``;return(/* @__PURE__ */ new Date()).toISOString()+` `}function log(...t){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...t)+`
`)}function save(e){if(e)process.env.DEBUG=e;else delete process.env.DEBUG}function load(){return process.env.DEBUG}function init(t){t.inspectOpts={};const n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}t.exports=require_common$2()(e);const{formatters:i}=t.exports;i.o=function(e){this.inspectOpts.colors=this.useColors;return r.inspect(e,this.inspectOpts).split(`
`).map(e=>e.trim()).join(` `)};i.O=function(e){this.inspectOpts.colors=this.useColors;return r.inspect(e,this.inspectOpts)}}));
//!node_modules/.pnpm/debug@4.4.0_supports-color@10.2.2/node_modules/debug/src/index.js
var require_src=/* @__PURE__ */ __commonJSMin(((e,t)=>{if(typeof process===`undefined`||process.type===`renderer`||process.browser===true||process.__nwjs)t.exports=require_browser();else t.exports=require_node()}));
//!node_modules/.pnpm/@fidm+x509@1.2.1/node_modules/@fidm/x509/build/common.js
var require_common$1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=__require(`net`);function bytesFromIP(e){switch(t.isIP(e)){case 4:return Buffer.from(e.split(`.`).map(e=>parseInt(e,10)));case 6:const t=e.split(`:`);const n=Buffer.alloc(16);let r=0;if(t[t.length-1]===``)t[t.length-1]=`0`;for(let e=0;e<t.length;e++){if(t[e]===``){if(e+1<t.length&&t[e+1]!==``)r=16-(t.length-e-1)*2;continue}n.writeUInt16BE(parseInt(t[e],16),r);r+=2}return n;default:return null}}e.bytesFromIP=bytesFromIP;function bytesToIP(e){switch(e.length){case 4:return[e[0],e[1],e[2],e[3]].join(`.`);case 16:const t=[];let n=-1;let r=0;let i=-1;let a=0;for(let o=0;o<e.length;o+=2){const s=e[o]<<8|e[o+1];if(s===0){r++;if(n===-1)n=t.length;if(r>a){a=r;i=n}}else{n=-1;r=0}t.push(s.toString(16))}if(a>0){let e=``;const n=t.slice(i+a);t.length=i;if(t.length===0)e+=`:`;if(n.length===0)e+=`:`;t.push(e,...n)}return t.join(`:`);default:return``}}e.bytesToIP=bytesToIP;const n=Object.create(null);const r=/^[0-9.]+$/;function getOID(e){if(r.test(e)&&n[e]!==``)return e;return n[e]==null?``:n[e]}e.getOID=getOID;function getOIDName(e){if(!r.test(e)&&n[e]!==``)return e;return n[e]==null?e:n[e]}e.getOIDName=getOIDName;function initOID(e,t){n[e]=t;n[t]=e}initOID(`1.2.840.113549.1.1.1`,`rsaEncryption`);initOID(`1.2.840.113549.1.1.4`,`md5WithRsaEncryption`);initOID(`1.2.840.113549.1.1.5`,`sha1WithRsaEncryption`);initOID(`1.2.840.113549.1.1.8`,`mgf1`);initOID(`1.2.840.113549.1.1.10`,`RSASSA-PSS`);initOID(`1.2.840.113549.1.1.11`,`sha256WithRsaEncryption`);initOID(`1.2.840.113549.1.1.12`,`sha384WithRsaEncryption`);initOID(`1.2.840.113549.1.1.13`,`sha512WithRsaEncryption`);initOID(`1.2.840.10045.2.1`,`ecEncryption`);initOID(`1.2.840.10045.4.1`,`ecdsaWithSha1`);initOID(`1.2.840.10045.4.3.2`,`ecdsaWithSha256`);initOID(`1.2.840.10045.4.3.3`,`ecdsaWithSha384`);initOID(`1.2.840.10045.4.3.4`,`ecdsaWithSha512`);initOID(`1.2.840.10040.4.3`,`dsaWithSha1`);initOID(`2.16.840.1.101.3.4.3.2`,`dsaWithSha256`);initOID(`1.3.14.3.2.7`,`desCBC`);initOID(`1.3.14.3.2.26`,`sha1`);initOID(`2.16.840.1.101.3.4.2.1`,`sha256`);initOID(`2.16.840.1.101.3.4.2.2`,`sha384`);initOID(`2.16.840.1.101.3.4.2.3`,`sha512`);initOID(`1.2.840.113549.2.5`,`md5`);initOID(`1.3.101.110`,`X25519`);initOID(`1.3.101.111`,`X448`);initOID(`1.3.101.112`,`Ed25519`);initOID(`1.3.101.113`,`Ed448`);initOID(`1.2.840.113549.1.7.1`,`data`);initOID(`1.2.840.113549.1.7.2`,`signedData`);initOID(`1.2.840.113549.1.7.3`,`envelopedData`);initOID(`1.2.840.113549.1.7.4`,`signedAndEnvelopedData`);initOID(`1.2.840.113549.1.7.5`,`digestedData`);initOID(`1.2.840.113549.1.7.6`,`encryptedData`);initOID(`1.2.840.113549.1.9.1`,`emailAddress`);initOID(`1.2.840.113549.1.9.2`,`unstructuredName`);initOID(`1.2.840.113549.1.9.3`,`contentType`);initOID(`1.2.840.113549.1.9.4`,`messageDigest`);initOID(`1.2.840.113549.1.9.5`,`signingTime`);initOID(`1.2.840.113549.1.9.6`,`counterSignature`);initOID(`1.2.840.113549.1.9.7`,`challengePassword`);initOID(`1.2.840.113549.1.9.8`,`unstructuredAddress`);initOID(`1.2.840.113549.1.9.14`,`extensionRequest`);initOID(`1.2.840.113549.1.9.20`,`friendlyName`);initOID(`1.2.840.113549.1.9.21`,`localKeyId`);initOID(`1.2.840.113549.1.9.22.1`,`x509Certificate`);initOID(`1.2.840.113549.1.12.10.1.1`,`keyBag`);initOID(`1.2.840.113549.1.12.10.1.2`,`pkcs8ShroudedKeyBag`);initOID(`1.2.840.113549.1.12.10.1.3`,`certBag`);initOID(`1.2.840.113549.1.12.10.1.4`,`crlBag`);initOID(`1.2.840.113549.1.12.10.1.5`,`secretBag`);initOID(`1.2.840.113549.1.12.10.1.6`,`safeContentsBag`);initOID(`1.2.840.113549.1.5.13`,`pkcs5PBES2`);initOID(`1.2.840.113549.1.5.12`,`pkcs5PBKDF2`);initOID(`1.2.840.113549.2.7`,`hmacWithSha1`);initOID(`1.2.840.113549.2.9`,`hmacWithSha256`);initOID(`1.2.840.113549.2.10`,`hmacWithSha384`);initOID(`1.2.840.113549.2.11`,`hmacWithSha512`);initOID(`1.2.840.113549.3.7`,`3desCBC`);initOID(`2.16.840.1.101.3.4.1.2`,`aesCBC128`);initOID(`2.16.840.1.101.3.4.1.42`,`aesCBC256`);initOID(`2.5.4.3`,`commonName`);initOID(`2.5.4.5`,`serialName`);initOID(`2.5.4.6`,`countryName`);initOID(`2.5.4.7`,`localityName`);initOID(`2.5.4.8`,`stateOrProvinceName`);initOID(`2.5.4.10`,`organizationName`);initOID(`2.5.4.11`,`organizationalUnitName`);initOID(`2.5.4.15`,`businessCategory`);initOID(`2.16.840.1.113730.1.1`,`nsCertType`);initOID(`2.5.29.2`,`keyAttributes`);initOID(`2.5.29.4`,`keyUsageRestriction`);initOID(`2.5.29.6`,`subtreesConstraint`);initOID(`2.5.29.9`,`subjectDirectoryAttributes`);initOID(`2.5.29.14`,`subjectKeyIdentifier`);initOID(`2.5.29.15`,`keyUsage`);initOID(`2.5.29.16`,`privateKeyUsagePeriod`);initOID(`2.5.29.17`,`subjectAltName`);initOID(`2.5.29.18`,`issuerAltName`);initOID(`2.5.29.19`,`basicConstraints`);initOID(`2.5.29.20`,`cRLNumber`);initOID(`2.5.29.21`,`cRLReason`);initOID(`2.5.29.22`,`expirationDate`);initOID(`2.5.29.23`,`instructionCode`);initOID(`2.5.29.24`,`invalidityDate`);initOID(`2.5.29.27`,`deltaCRLIndicator`);initOID(`2.5.29.28`,`issuingDistributionPoint`);initOID(`2.5.29.29`,`certificateIssuer`);initOID(`2.5.29.30`,`nameConstraints`);initOID(`2.5.29.31`,`cRLDistributionPoints`);initOID(`2.5.29.32`,`certificatePolicies`);initOID(`2.5.29.33`,`policyMappings`);initOID(`2.5.29.35`,`authorityKeyIdentifier`);initOID(`2.5.29.36`,`policyConstraints`);initOID(`2.5.29.37`,`extKeyUsage`);initOID(`2.5.29.46`,`freshestCRL`);initOID(`2.5.29.54`,`inhibitAnyPolicy`);initOID(`1.3.6.1.4.1.311.60.2.1.2`,`jurisdictionST`);initOID(`1.3.6.1.4.1.311.60.2.1.3`,`jurisdictionC`);initOID(`1.3.6.1.4.1.11129.2.4.2`,`timestampList`);initOID(`1.3.6.1.5.5.7.1.1`,`authorityInfoAccess`);initOID(`1.3.6.1.5.5.7.3.1`,`serverAuth`);initOID(`1.3.6.1.5.5.7.3.2`,`clientAuth`);initOID(`1.3.6.1.5.5.7.3.3`,`codeSigning`);initOID(`1.3.6.1.5.5.7.3.4`,`emailProtection`);initOID(`1.3.6.1.5.5.7.3.8`,`timeStamping`);initOID(`1.3.6.1.5.5.7.48.1`,`authorityInfoAccessOcsp`);initOID(`1.3.6.1.5.5.7.48.2`,`authorityInfoAccessIssuers`)}));
//!node_modules/.pnpm/tweetnacl@1.0.3/node_modules/tweetnacl/nacl-fast.js
var require_nacl_fast=/* @__PURE__ */ __commonJSMin(((e,t)=>{(function(e){"use strict";var gf=function(e){var t,n=/* @__PURE__ */ new Float64Array(16);if(e)for(t=0;t<e.length;t++)n[t]=e[t];return n};var randombytes=function(){throw new Error(`no PRNG`)};var t=/* @__PURE__ */ new Uint8Array(16);var n=/* @__PURE__ */ new Uint8Array(32);n[0]=9;var r=gf(),i=gf([1]),a=gf([56129,1]),o=gf([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),s=gf([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),c=gf([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),u=gf([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),d=gf([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function ts64(e,t,n,r){e[t]=n>>24&255;e[t+1]=n>>16&255;e[t+2]=n>>8&255;e[t+3]=n&255;e[t+4]=r>>24&255;e[t+5]=r>>16&255;e[t+6]=r>>8&255;e[t+7]=r&255}function vn(e,t,n,r,i){var a,o=0;for(a=0;a<i;a++)o|=e[t+a]^n[r+a];return(1&o-1>>>8)-1}function crypto_verify_16(e,t,n,r){return vn(e,t,n,r,16)}function crypto_verify_32(e,t,n,r){return vn(e,t,n,r,32)}function core_salsa20(e,t,n,r){var i=r[0]&255|(r[1]&255)<<8|(r[2]&255)<<16|(r[3]&255)<<24,a=n[0]&255|(n[1]&255)<<8|(n[2]&255)<<16|(n[3]&255)<<24,o=n[4]&255|(n[5]&255)<<8|(n[6]&255)<<16|(n[7]&255)<<24,s=n[8]&255|(n[9]&255)<<8|(n[10]&255)<<16|(n[11]&255)<<24,c=n[12]&255|(n[13]&255)<<8|(n[14]&255)<<16|(n[15]&255)<<24,u=r[4]&255|(r[5]&255)<<8|(r[6]&255)<<16|(r[7]&255)<<24,d=t[0]&255|(t[1]&255)<<8|(t[2]&255)<<16|(t[3]&255)<<24,f=t[4]&255|(t[5]&255)<<8|(t[6]&255)<<16|(t[7]&255)<<24,p=t[8]&255|(t[9]&255)<<8|(t[10]&255)<<16|(t[11]&255)<<24,m=t[12]&255|(t[13]&255)<<8|(t[14]&255)<<16|(t[15]&255)<<24,g=r[8]&255|(r[9]&255)<<8|(r[10]&255)<<16|(r[11]&255)<<24,_=n[16]&255|(n[17]&255)<<8|(n[18]&255)<<16|(n[19]&255)<<24,v=n[20]&255|(n[21]&255)<<8|(n[22]&255)<<16|(n[23]&255)<<24,y=n[24]&255|(n[25]&255)<<8|(n[26]&255)<<16|(n[27]&255)<<24,b=n[28]&255|(n[29]&255)<<8|(n[30]&255)<<16|(n[31]&255)<<24,x=r[12]&255|(r[13]&255)<<8|(r[14]&255)<<16|(r[15]&255)<<24;var C=i,w=a,T=o,E=s,D=c,O=u,k=d,j=f,N=p,P=m,F=g,I=_,L=v,R=y,z=b,B=x,V;for(var H=0;H<20;H+=2){V=C+L|0;D^=V<<7|V>>>25;V=D+C|0;N^=V<<9|V>>>23;V=N+D|0;L^=V<<13|V>>>19;V=L+N|0;C^=V<<18|V>>>14;V=O+w|0;P^=V<<7|V>>>25;V=P+O|0;R^=V<<9|V>>>23;V=R+P|0;w^=V<<13|V>>>19;V=w+R|0;O^=V<<18|V>>>14;V=F+k|0;z^=V<<7|V>>>25;V=z+F|0;T^=V<<9|V>>>23;V=T+z|0;k^=V<<13|V>>>19;V=k+T|0;F^=V<<18|V>>>14;V=B+I|0;E^=V<<7|V>>>25;V=E+B|0;j^=V<<9|V>>>23;V=j+E|0;I^=V<<13|V>>>19;V=I+j|0;B^=V<<18|V>>>14;V=C+E|0;w^=V<<7|V>>>25;V=w+C|0;T^=V<<9|V>>>23;V=T+w|0;E^=V<<13|V>>>19;V=E+T|0;C^=V<<18|V>>>14;V=O+D|0;k^=V<<7|V>>>25;V=k+O|0;j^=V<<9|V>>>23;V=j+k|0;D^=V<<13|V>>>19;V=D+j|0;O^=V<<18|V>>>14;V=F+P|0;I^=V<<7|V>>>25;V=I+F|0;N^=V<<9|V>>>23;V=N+I|0;P^=V<<13|V>>>19;V=P+N|0;F^=V<<18|V>>>14;V=B+z|0;L^=V<<7|V>>>25;V=L+B|0;R^=V<<9|V>>>23;V=R+L|0;z^=V<<13|V>>>19;V=z+R|0;B^=V<<18|V>>>14}C=C+i|0;w=w+a|0;T=T+o|0;E=E+s|0;D=D+c|0;O=O+u|0;k=k+d|0;j=j+f|0;N=N+p|0;P=P+m|0;F=F+g|0;I=I+_|0;L=L+v|0;R=R+y|0;z=z+b|0;B=B+x|0;e[0]=C>>>0&255;e[1]=C>>>8&255;e[2]=C>>>16&255;e[3]=C>>>24&255;e[4]=w>>>0&255;e[5]=w>>>8&255;e[6]=w>>>16&255;e[7]=w>>>24&255;e[8]=T>>>0&255;e[9]=T>>>8&255;e[10]=T>>>16&255;e[11]=T>>>24&255;e[12]=E>>>0&255;e[13]=E>>>8&255;e[14]=E>>>16&255;e[15]=E>>>24&255;e[16]=D>>>0&255;e[17]=D>>>8&255;e[18]=D>>>16&255;e[19]=D>>>24&255;e[20]=O>>>0&255;e[21]=O>>>8&255;e[22]=O>>>16&255;e[23]=O>>>24&255;e[24]=k>>>0&255;e[25]=k>>>8&255;e[26]=k>>>16&255;e[27]=k>>>24&255;e[28]=j>>>0&255;e[29]=j>>>8&255;e[30]=j>>>16&255;e[31]=j>>>24&255;e[32]=N>>>0&255;e[33]=N>>>8&255;e[34]=N>>>16&255;e[35]=N>>>24&255;e[36]=P>>>0&255;e[37]=P>>>8&255;e[38]=P>>>16&255;e[39]=P>>>24&255;e[40]=F>>>0&255;e[41]=F>>>8&255;e[42]=F>>>16&255;e[43]=F>>>24&255;e[44]=I>>>0&255;e[45]=I>>>8&255;e[46]=I>>>16&255;e[47]=I>>>24&255;e[48]=L>>>0&255;e[49]=L>>>8&255;e[50]=L>>>16&255;e[51]=L>>>24&255;e[52]=R>>>0&255;e[53]=R>>>8&255;e[54]=R>>>16&255;e[55]=R>>>24&255;e[56]=z>>>0&255;e[57]=z>>>8&255;e[58]=z>>>16&255;e[59]=z>>>24&255;e[60]=B>>>0&255;e[61]=B>>>8&255;e[62]=B>>>16&255;e[63]=B>>>24&255}function core_hsalsa20(e,t,n,r){var i=r[0]&255|(r[1]&255)<<8|(r[2]&255)<<16|(r[3]&255)<<24,a=n[0]&255|(n[1]&255)<<8|(n[2]&255)<<16|(n[3]&255)<<24,o=n[4]&255|(n[5]&255)<<8|(n[6]&255)<<16|(n[7]&255)<<24,s=n[8]&255|(n[9]&255)<<8|(n[10]&255)<<16|(n[11]&255)<<24,c=n[12]&255|(n[13]&255)<<8|(n[14]&255)<<16|(n[15]&255)<<24,u=r[4]&255|(r[5]&255)<<8|(r[6]&255)<<16|(r[7]&255)<<24,d=t[0]&255|(t[1]&255)<<8|(t[2]&255)<<16|(t[3]&255)<<24,f=t[4]&255|(t[5]&255)<<8|(t[6]&255)<<16|(t[7]&255)<<24,p=t[8]&255|(t[9]&255)<<8|(t[10]&255)<<16|(t[11]&255)<<24,m=t[12]&255|(t[13]&255)<<8|(t[14]&255)<<16|(t[15]&255)<<24,g=r[8]&255|(r[9]&255)<<8|(r[10]&255)<<16|(r[11]&255)<<24,_=n[16]&255|(n[17]&255)<<8|(n[18]&255)<<16|(n[19]&255)<<24,v=n[20]&255|(n[21]&255)<<8|(n[22]&255)<<16|(n[23]&255)<<24,y=n[24]&255|(n[25]&255)<<8|(n[26]&255)<<16|(n[27]&255)<<24,b=n[28]&255|(n[29]&255)<<8|(n[30]&255)<<16|(n[31]&255)<<24,x=r[12]&255|(r[13]&255)<<8|(r[14]&255)<<16|(r[15]&255)<<24;var C=i,w=a,T=o,E=s,D=c,O=u,k=d,j=f,N=p,P=m,F=g,I=_,L=v,R=y,z=b,B=x,V;for(var H=0;H<20;H+=2){V=C+L|0;D^=V<<7|V>>>25;V=D+C|0;N^=V<<9|V>>>23;V=N+D|0;L^=V<<13|V>>>19;V=L+N|0;C^=V<<18|V>>>14;V=O+w|0;P^=V<<7|V>>>25;V=P+O|0;R^=V<<9|V>>>23;V=R+P|0;w^=V<<13|V>>>19;V=w+R|0;O^=V<<18|V>>>14;V=F+k|0;z^=V<<7|V>>>25;V=z+F|0;T^=V<<9|V>>>23;V=T+z|0;k^=V<<13|V>>>19;V=k+T|0;F^=V<<18|V>>>14;V=B+I|0;E^=V<<7|V>>>25;V=E+B|0;j^=V<<9|V>>>23;V=j+E|0;I^=V<<13|V>>>19;V=I+j|0;B^=V<<18|V>>>14;V=C+E|0;w^=V<<7|V>>>25;V=w+C|0;T^=V<<9|V>>>23;V=T+w|0;E^=V<<13|V>>>19;V=E+T|0;C^=V<<18|V>>>14;V=O+D|0;k^=V<<7|V>>>25;V=k+O|0;j^=V<<9|V>>>23;V=j+k|0;D^=V<<13|V>>>19;V=D+j|0;O^=V<<18|V>>>14;V=F+P|0;I^=V<<7|V>>>25;V=I+F|0;N^=V<<9|V>>>23;V=N+I|0;P^=V<<13|V>>>19;V=P+N|0;F^=V<<18|V>>>14;V=B+z|0;L^=V<<7|V>>>25;V=L+B|0;R^=V<<9|V>>>23;V=R+L|0;z^=V<<13|V>>>19;V=z+R|0;B^=V<<18|V>>>14}e[0]=C>>>0&255;e[1]=C>>>8&255;e[2]=C>>>16&255;e[3]=C>>>24&255;e[4]=O>>>0&255;e[5]=O>>>8&255;e[6]=O>>>16&255;e[7]=O>>>24&255;e[8]=F>>>0&255;e[9]=F>>>8&255;e[10]=F>>>16&255;e[11]=F>>>24&255;e[12]=B>>>0&255;e[13]=B>>>8&255;e[14]=B>>>16&255;e[15]=B>>>24&255;e[16]=k>>>0&255;e[17]=k>>>8&255;e[18]=k>>>16&255;e[19]=k>>>24&255;e[20]=j>>>0&255;e[21]=j>>>8&255;e[22]=j>>>16&255;e[23]=j>>>24&255;e[24]=N>>>0&255;e[25]=N>>>8&255;e[26]=N>>>16&255;e[27]=N>>>24&255;e[28]=P>>>0&255;e[29]=P>>>8&255;e[30]=P>>>16&255;e[31]=P>>>24&255}function crypto_core_salsa20(e,t,n,r){core_salsa20(e,t,n,r)}function crypto_core_hsalsa20(e,t,n,r){core_hsalsa20(e,t,n,r)}var f=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function crypto_stream_salsa20_xor(e,t,n,r,i,a,o){var s=/* @__PURE__ */ new Uint8Array(16),c=/* @__PURE__ */ new Uint8Array(64);var u,d=0;for(;d<16;d++)s[d]=0;for(d=0;d<8;d++)s[d]=a[d];while(i>=64){crypto_core_salsa20(c,s,o,f);for(d=0;d<64;d++)e[t+d]=n[r+d]^c[d];u=1;for(d=8;d<16;d++){u=u+(s[d]&255)|0;s[d]=u&255;u>>>=8}i-=64;t+=64;r+=64}if(i>0){crypto_core_salsa20(c,s,o,f);for(d=0;d<i;d++)e[t+d]=n[r+d]^c[d]}return 0}function crypto_stream_salsa20(e,t,n,r,i){var a=/* @__PURE__ */ new Uint8Array(16),o=/* @__PURE__ */ new Uint8Array(64);var s,c=0;for(;c<16;c++)a[c]=0;for(c=0;c<8;c++)a[c]=r[c];while(n>=64){crypto_core_salsa20(o,a,i,f);for(c=0;c<64;c++)e[t+c]=o[c];s=1;for(c=8;c<16;c++){s=s+(a[c]&255)|0;a[c]=s&255;s>>>=8}n-=64;t+=64}if(n>0){crypto_core_salsa20(o,a,i,f);for(c=0;c<n;c++)e[t+c]=o[c]}return 0}function crypto_stream(e,t,n,r,i){var a=/* @__PURE__ */ new Uint8Array(32);crypto_core_hsalsa20(a,r,i,f);var o=/* @__PURE__ */ new Uint8Array(8);for(var s=0;s<8;s++)o[s]=r[s+16];return crypto_stream_salsa20(e,t,n,o,a)}function crypto_stream_xor(e,t,n,r,i,a,o){var s=/* @__PURE__ */ new Uint8Array(32);crypto_core_hsalsa20(s,a,o,f);var c=/* @__PURE__ */ new Uint8Array(8);for(var u=0;u<8;u++)c[u]=a[u+16];return crypto_stream_salsa20_xor(e,t,n,r,i,c,s)}var poly1305=function(e){this.buffer=/* @__PURE__ */ new Uint8Array(16);this.r=/* @__PURE__ */ new Uint16Array(10);this.h=/* @__PURE__ */ new Uint16Array(10);this.pad=/* @__PURE__ */ new Uint16Array(8);this.leftover=0;this.fin=0;var t=e[0]&255|(e[1]&255)<<8,n,r,i,a,o,s,c;this.r[0]=t&8191;n=e[2]&255|(e[3]&255)<<8;this.r[1]=(t>>>13|n<<3)&8191;r=e[4]&255|(e[5]&255)<<8;this.r[2]=(n>>>10|r<<6)&7939;i=e[6]&255|(e[7]&255)<<8;this.r[3]=(r>>>7|i<<9)&8191;a=e[8]&255|(e[9]&255)<<8;this.r[4]=(i>>>4|a<<12)&255;this.r[5]=a>>>1&8190;o=e[10]&255|(e[11]&255)<<8;this.r[6]=(a>>>14|o<<2)&8191;s=e[12]&255|(e[13]&255)<<8;this.r[7]=(o>>>11|s<<5)&8065;c=e[14]&255|(e[15]&255)<<8;this.r[8]=(s>>>8|c<<8)&8191;this.r[9]=c>>>5&127;this.pad[0]=e[16]&255|(e[17]&255)<<8;this.pad[1]=e[18]&255|(e[19]&255)<<8;this.pad[2]=e[20]&255|(e[21]&255)<<8;this.pad[3]=e[22]&255|(e[23]&255)<<8;this.pad[4]=e[24]&255|(e[25]&255)<<8;this.pad[5]=e[26]&255|(e[27]&255)<<8;this.pad[6]=e[28]&255|(e[29]&255)<<8;this.pad[7]=e[30]&255|(e[31]&255)<<8};poly1305.prototype.blocks=function(e,t,n){var r=this.fin?0:2048;var i,a,o,s,c,u,d,f,p;var m,g,_,v,y,b,x,C,w,T;var E=this.h[0],D=this.h[1],O=this.h[2],k=this.h[3],j=this.h[4],N=this.h[5],P=this.h[6],F=this.h[7],I=this.h[8],L=this.h[9];var R=this.r[0],z=this.r[1],B=this.r[2],V=this.r[3],H=this.r[4],U=this.r[5],W=this.r[6],G=this.r[7],K=this.r[8],q=this.r[9];while(n>=16){i=e[t+0]&255|(e[t+1]&255)<<8;E+=i&8191;a=e[t+2]&255|(e[t+3]&255)<<8;D+=(i>>>13|a<<3)&8191;o=e[t+4]&255|(e[t+5]&255)<<8;O+=(a>>>10|o<<6)&8191;s=e[t+6]&255|(e[t+7]&255)<<8;k+=(o>>>7|s<<9)&8191;c=e[t+8]&255|(e[t+9]&255)<<8;j+=(s>>>4|c<<12)&8191;N+=c>>>1&8191;u=e[t+10]&255|(e[t+11]&255)<<8;P+=(c>>>14|u<<2)&8191;d=e[t+12]&255|(e[t+13]&255)<<8;F+=(u>>>11|d<<5)&8191;f=e[t+14]&255|(e[t+15]&255)<<8;I+=(d>>>8|f<<8)&8191;L+=f>>>5|r;p=0;m=p;m+=E*R;m+=D*(5*q);m+=O*(5*K);m+=k*(5*G);m+=j*(5*W);p=m>>>13;m&=8191;m+=N*(5*U);m+=P*(5*H);m+=F*(5*V);m+=I*(5*B);m+=L*(5*z);p+=m>>>13;m&=8191;g=p;g+=E*z;g+=D*R;g+=O*(5*q);g+=k*(5*K);g+=j*(5*G);p=g>>>13;g&=8191;g+=N*(5*W);g+=P*(5*U);g+=F*(5*H);g+=I*(5*V);g+=L*(5*B);p+=g>>>13;g&=8191;_=p;_+=E*B;_+=D*z;_+=O*R;_+=k*(5*q);_+=j*(5*K);p=_>>>13;_&=8191;_+=N*(5*G);_+=P*(5*W);_+=F*(5*U);_+=I*(5*H);_+=L*(5*V);p+=_>>>13;_&=8191;v=p;v+=E*V;v+=D*B;v+=O*z;v+=k*R;v+=j*(5*q);p=v>>>13;v&=8191;v+=N*(5*K);v+=P*(5*G);v+=F*(5*W);v+=I*(5*U);v+=L*(5*H);p+=v>>>13;v&=8191;y=p;y+=E*H;y+=D*V;y+=O*B;y+=k*z;y+=j*R;p=y>>>13;y&=8191;y+=N*(5*q);y+=P*(5*K);y+=F*(5*G);y+=I*(5*W);y+=L*(5*U);p+=y>>>13;y&=8191;b=p;b+=E*U;b+=D*H;b+=O*V;b+=k*B;b+=j*z;p=b>>>13;b&=8191;b+=N*R;b+=P*(5*q);b+=F*(5*K);b+=I*(5*G);b+=L*(5*W);p+=b>>>13;b&=8191;x=p;x+=E*W;x+=D*U;x+=O*H;x+=k*V;x+=j*B;p=x>>>13;x&=8191;x+=N*z;x+=P*R;x+=F*(5*q);x+=I*(5*K);x+=L*(5*G);p+=x>>>13;x&=8191;C=p;C+=E*G;C+=D*W;C+=O*U;C+=k*H;C+=j*V;p=C>>>13;C&=8191;C+=N*B;C+=P*z;C+=F*R;C+=I*(5*q);C+=L*(5*K);p+=C>>>13;C&=8191;w=p;w+=E*K;w+=D*G;w+=O*W;w+=k*U;w+=j*H;p=w>>>13;w&=8191;w+=N*V;w+=P*B;w+=F*z;w+=I*R;w+=L*(5*q);p+=w>>>13;w&=8191;T=p;T+=E*q;T+=D*K;T+=O*G;T+=k*W;T+=j*U;p=T>>>13;T&=8191;T+=N*H;T+=P*V;T+=F*B;T+=I*z;T+=L*R;p+=T>>>13;T&=8191;p=(p<<2)+p|0;p=p+m|0;m=p&8191;p=p>>>13;g+=p;E=m;D=g;O=_;k=v;j=y;N=b;P=x;F=C;I=w;L=T;t+=16;n-=16}this.h[0]=E;this.h[1]=D;this.h[2]=O;this.h[3]=k;this.h[4]=j;this.h[5]=N;this.h[6]=P;this.h[7]=F;this.h[8]=I;this.h[9]=L};poly1305.prototype.finish=function(e,t){var n=/* @__PURE__ */ new Uint16Array(10);var r,i,a,o;if(this.leftover){o=this.leftover;this.buffer[o++]=1;for(;o<16;o++)this.buffer[o]=0;this.fin=1;this.blocks(this.buffer,0,16)}r=this.h[1]>>>13;this.h[1]&=8191;for(o=2;o<10;o++){this.h[o]+=r;r=this.h[o]>>>13;this.h[o]&=8191}this.h[0]+=r*5;r=this.h[0]>>>13;this.h[0]&=8191;this.h[1]+=r;r=this.h[1]>>>13;this.h[1]&=8191;this.h[2]+=r;n[0]=this.h[0]+5;r=n[0]>>>13;n[0]&=8191;for(o=1;o<10;o++){n[o]=this.h[o]+r;r=n[o]>>>13;n[o]&=8191}n[9]-=8192;i=(r^1)-1;for(o=0;o<10;o++)n[o]&=i;i=~i;for(o=0;o<10;o++)this.h[o]=this.h[o]&i|n[o];this.h[0]=(this.h[0]|this.h[1]<<13)&65535;this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535;this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535;this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535;this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535;this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535;this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535;this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535;a=this.h[0]+this.pad[0];this.h[0]=a&65535;for(o=1;o<8;o++){a=(this.h[o]+this.pad[o]|0)+(a>>>16)|0;this.h[o]=a&65535}e[t+0]=this.h[0]>>>0&255;e[t+1]=this.h[0]>>>8&255;e[t+2]=this.h[1]>>>0&255;e[t+3]=this.h[1]>>>8&255;e[t+4]=this.h[2]>>>0&255;e[t+5]=this.h[2]>>>8&255;e[t+6]=this.h[3]>>>0&255;e[t+7]=this.h[3]>>>8&255;e[t+8]=this.h[4]>>>0&255;e[t+9]=this.h[4]>>>8&255;e[t+10]=this.h[5]>>>0&255;e[t+11]=this.h[5]>>>8&255;e[t+12]=this.h[6]>>>0&255;e[t+13]=this.h[6]>>>8&255;e[t+14]=this.h[7]>>>0&255;e[t+15]=this.h[7]>>>8&255};poly1305.prototype.update=function(e,t,n){var r,i;if(this.leftover){i=16-this.leftover;if(i>n)i=n;for(r=0;r<i;r++)this.buffer[this.leftover+r]=e[t+r];n-=i;t+=i;this.leftover+=i;if(this.leftover<16)return;this.blocks(this.buffer,0,16);this.leftover=0}if(n>=16){i=n-n%16;this.blocks(e,t,i);t+=i;n-=i}if(n){for(r=0;r<n;r++)this.buffer[this.leftover+r]=e[t+r];this.leftover+=n}};function crypto_onetimeauth(e,t,n,r,i,a){var o=new poly1305(a);o.update(n,r,i);o.finish(e,t);return 0}function crypto_onetimeauth_verify(e,t,n,r,i,a){var o=/* @__PURE__ */ new Uint8Array(16);crypto_onetimeauth(o,0,n,r,i,a);return crypto_verify_16(e,t,o,0)}function crypto_secretbox(e,t,n,r,i){var a;if(n<32)return-1;crypto_stream_xor(e,0,t,0,n,r,i);crypto_onetimeauth(e,16,e,32,n-32,e);for(a=0;a<16;a++)e[a]=0;return 0}function crypto_secretbox_open(e,t,n,r,i){var a;var o=/* @__PURE__ */ new Uint8Array(32);if(n<32)return-1;crypto_stream(o,0,32,r,i);if(crypto_onetimeauth_verify(t,16,t,32,n-32,o)!==0)return-1;crypto_stream_xor(e,0,t,0,n,r,i);for(a=0;a<32;a++)e[a]=0;return 0}function set25519(e,t){var n=0;for(;n<16;n++)e[n]=t[n]|0}function car25519(e){var t,n,r=1;for(t=0;t<16;t++){n=e[t]+r+65535;r=Math.floor(n/65536);e[t]=n-r*65536}e[0]+=r-1+37*(r-1)}function sel25519(e,t,n){var r,i=~(n-1);for(var a=0;a<16;a++){r=i&(e[a]^t[a]);e[a]^=r;t[a]^=r}}function pack25519(e,t){var n,r,i;var a=gf(),o=gf();for(n=0;n<16;n++)o[n]=t[n];car25519(o);car25519(o);car25519(o);for(r=0;r<2;r++){a[0]=o[0]-65517;for(n=1;n<15;n++){a[n]=o[n]-65535-(a[n-1]>>16&1);a[n-1]&=65535}a[15]=o[15]-32767-(a[14]>>16&1);i=a[15]>>16&1;a[14]&=65535;sel25519(o,a,1-i)}for(n=0;n<16;n++){e[2*n]=o[n]&255;e[2*n+1]=o[n]>>8}}function neq25519(e,t){var n=/* @__PURE__ */ new Uint8Array(32),r=/* @__PURE__ */ new Uint8Array(32);pack25519(n,e);pack25519(r,t);return crypto_verify_32(n,0,r,0)}function par25519(e){var t=/* @__PURE__ */ new Uint8Array(32);pack25519(t,e);return t[0]&1}function unpack25519(e,t){var n=0;for(;n<16;n++)e[n]=t[2*n]+(t[2*n+1]<<8);e[15]&=32767}function A(e,t,n){for(var r=0;r<16;r++)e[r]=t[r]+n[r]}function Z(e,t,n){for(var r=0;r<16;r++)e[r]=t[r]-n[r]}function M(e,t,n){var r,i,a=0,o=0,s=0,c=0,u=0,d=0,f=0,p=0,m=0,g=0,_=0,v=0,y=0,b=0,x=0,C=0,w=0,T=0,E=0,D=0,O=0,k=0,j=0,N=0,P=0,F=0,I=0,L=0,R=0,z=0,B=0,V=n[0],H=n[1],U=n[2],W=n[3],G=n[4],K=n[5],q=n[6],J=n[7],Y=n[8],X=n[9],ee=n[10],te=n[11],Q=n[12],ne=n[13],re=n[14],ie=n[15];r=t[0];a+=r*V;o+=r*H;s+=r*U;c+=r*W;u+=r*G;d+=r*K;f+=r*q;p+=r*J;m+=r*Y;g+=r*X;_+=r*ee;v+=r*te;y+=r*Q;b+=r*ne;x+=r*re;C+=r*ie;r=t[1];o+=r*V;s+=r*H;c+=r*U;u+=r*W;d+=r*G;f+=r*K;p+=r*q;m+=r*J;g+=r*Y;_+=r*X;v+=r*ee;y+=r*te;b+=r*Q;x+=r*ne;C+=r*re;w+=r*ie;r=t[2];s+=r*V;c+=r*H;u+=r*U;d+=r*W;f+=r*G;p+=r*K;m+=r*q;g+=r*J;_+=r*Y;v+=r*X;y+=r*ee;b+=r*te;x+=r*Q;C+=r*ne;w+=r*re;T+=r*ie;r=t[3];c+=r*V;u+=r*H;d+=r*U;f+=r*W;p+=r*G;m+=r*K;g+=r*q;_+=r*J;v+=r*Y;y+=r*X;b+=r*ee;x+=r*te;C+=r*Q;w+=r*ne;T+=r*re;E+=r*ie;r=t[4];u+=r*V;d+=r*H;f+=r*U;p+=r*W;m+=r*G;g+=r*K;_+=r*q;v+=r*J;y+=r*Y;b+=r*X;x+=r*ee;C+=r*te;w+=r*Q;T+=r*ne;E+=r*re;D+=r*ie;r=t[5];d+=r*V;f+=r*H;p+=r*U;m+=r*W;g+=r*G;_+=r*K;v+=r*q;y+=r*J;b+=r*Y;x+=r*X;C+=r*ee;w+=r*te;T+=r*Q;E+=r*ne;D+=r*re;O+=r*ie;r=t[6];f+=r*V;p+=r*H;m+=r*U;g+=r*W;_+=r*G;v+=r*K;y+=r*q;b+=r*J;x+=r*Y;C+=r*X;w+=r*ee;T+=r*te;E+=r*Q;D+=r*ne;O+=r*re;k+=r*ie;r=t[7];p+=r*V;m+=r*H;g+=r*U;_+=r*W;v+=r*G;y+=r*K;b+=r*q;x+=r*J;C+=r*Y;w+=r*X;T+=r*ee;E+=r*te;D+=r*Q;O+=r*ne;k+=r*re;j+=r*ie;r=t[8];m+=r*V;g+=r*H;_+=r*U;v+=r*W;y+=r*G;b+=r*K;x+=r*q;C+=r*J;w+=r*Y;T+=r*X;E+=r*ee;D+=r*te;O+=r*Q;k+=r*ne;j+=r*re;N+=r*ie;r=t[9];g+=r*V;_+=r*H;v+=r*U;y+=r*W;b+=r*G;x+=r*K;C+=r*q;w+=r*J;T+=r*Y;E+=r*X;D+=r*ee;O+=r*te;k+=r*Q;j+=r*ne;N+=r*re;P+=r*ie;r=t[10];_+=r*V;v+=r*H;y+=r*U;b+=r*W;x+=r*G;C+=r*K;w+=r*q;T+=r*J;E+=r*Y;D+=r*X;O+=r*ee;k+=r*te;j+=r*Q;N+=r*ne;P+=r*re;F+=r*ie;r=t[11];v+=r*V;y+=r*H;b+=r*U;x+=r*W;C+=r*G;w+=r*K;T+=r*q;E+=r*J;D+=r*Y;O+=r*X;k+=r*ee;j+=r*te;N+=r*Q;P+=r*ne;F+=r*re;I+=r*ie;r=t[12];y+=r*V;b+=r*H;x+=r*U;C+=r*W;w+=r*G;T+=r*K;E+=r*q;D+=r*J;O+=r*Y;k+=r*X;j+=r*ee;N+=r*te;P+=r*Q;F+=r*ne;I+=r*re;L+=r*ie;r=t[13];b+=r*V;x+=r*H;C+=r*U;w+=r*W;T+=r*G;E+=r*K;D+=r*q;O+=r*J;k+=r*Y;j+=r*X;N+=r*ee;P+=r*te;F+=r*Q;I+=r*ne;L+=r*re;R+=r*ie;r=t[14];x+=r*V;C+=r*H;w+=r*U;T+=r*W;E+=r*G;D+=r*K;O+=r*q;k+=r*J;j+=r*Y;N+=r*X;P+=r*ee;F+=r*te;I+=r*Q;L+=r*ne;R+=r*re;z+=r*ie;r=t[15];C+=r*V;w+=r*H;T+=r*U;E+=r*W;D+=r*G;O+=r*K;k+=r*q;j+=r*J;N+=r*Y;P+=r*X;F+=r*ee;I+=r*te;L+=r*Q;R+=r*ne;z+=r*re;B+=r*ie;a+=38*w;o+=38*T;s+=38*E;c+=38*D;u+=38*O;d+=38*k;f+=38*j;p+=38*N;m+=38*P;g+=38*F;_+=38*I;v+=38*L;y+=38*R;b+=38*z;x+=38*B;i=1;r=a+i+65535;i=Math.floor(r/65536);a=r-i*65536;r=o+i+65535;i=Math.floor(r/65536);o=r-i*65536;r=s+i+65535;i=Math.floor(r/65536);s=r-i*65536;r=c+i+65535;i=Math.floor(r/65536);c=r-i*65536;r=u+i+65535;i=Math.floor(r/65536);u=r-i*65536;r=d+i+65535;i=Math.floor(r/65536);d=r-i*65536;r=f+i+65535;i=Math.floor(r/65536);f=r-i*65536;r=p+i+65535;i=Math.floor(r/65536);p=r-i*65536;r=m+i+65535;i=Math.floor(r/65536);m=r-i*65536;r=g+i+65535;i=Math.floor(r/65536);g=r-i*65536;r=_+i+65535;i=Math.floor(r/65536);_=r-i*65536;r=v+i+65535;i=Math.floor(r/65536);v=r-i*65536;r=y+i+65535;i=Math.floor(r/65536);y=r-i*65536;r=b+i+65535;i=Math.floor(r/65536);b=r-i*65536;r=x+i+65535;i=Math.floor(r/65536);x=r-i*65536;r=C+i+65535;i=Math.floor(r/65536);C=r-i*65536;a+=i-1+37*(i-1);i=1;r=a+i+65535;i=Math.floor(r/65536);a=r-i*65536;r=o+i+65535;i=Math.floor(r/65536);o=r-i*65536;r=s+i+65535;i=Math.floor(r/65536);s=r-i*65536;r=c+i+65535;i=Math.floor(r/65536);c=r-i*65536;r=u+i+65535;i=Math.floor(r/65536);u=r-i*65536;r=d+i+65535;i=Math.floor(r/65536);d=r-i*65536;r=f+i+65535;i=Math.floor(r/65536);f=r-i*65536;r=p+i+65535;i=Math.floor(r/65536);p=r-i*65536;r=m+i+65535;i=Math.floor(r/65536);m=r-i*65536;r=g+i+65535;i=Math.floor(r/65536);g=r-i*65536;r=_+i+65535;i=Math.floor(r/65536);_=r-i*65536;r=v+i+65535;i=Math.floor(r/65536);v=r-i*65536;r=y+i+65535;i=Math.floor(r/65536);y=r-i*65536;r=b+i+65535;i=Math.floor(r/65536);b=r-i*65536;r=x+i+65535;i=Math.floor(r/65536);x=r-i*65536;r=C+i+65535;i=Math.floor(r/65536);C=r-i*65536;a+=i-1+37*(i-1);e[0]=a;e[1]=o;e[2]=s;e[3]=c;e[4]=u;e[5]=d;e[6]=f;e[7]=p;e[8]=m;e[9]=g;e[10]=_;e[11]=v;e[12]=y;e[13]=b;e[14]=x;e[15]=C}function S(e,t){M(e,t,t)}function inv25519(e,t){var n=gf();var r=0;for(;r<16;r++)n[r]=t[r];for(r=253;r>=0;r--){S(n,n);if(r!==2&&r!==4)M(n,n,t)}for(r=0;r<16;r++)e[r]=n[r]}function pow2523(e,t){var n=gf();var r=0;for(;r<16;r++)n[r]=t[r];for(r=250;r>=0;r--){S(n,n);if(r!==1)M(n,n,t)}for(r=0;r<16;r++)e[r]=n[r]}function crypto_scalarmult(e,t,n){var r=/* @__PURE__ */ new Uint8Array(32);var i=/* @__PURE__ */ new Float64Array(80),o,s;var c=gf(),u=gf(),d=gf(),f=gf(),p=gf(),m=gf();for(s=0;s<31;s++)r[s]=t[s];r[31]=t[31]&127|64;r[0]&=248;unpack25519(i,n);for(s=0;s<16;s++){u[s]=i[s];f[s]=c[s]=d[s]=0}c[0]=f[0]=1;for(s=254;s>=0;--s){o=r[s>>>3]>>>(s&7)&1;sel25519(c,u,o);sel25519(d,f,o);A(p,c,d);Z(c,c,d);A(d,u,f);Z(u,u,f);S(f,p);S(m,c);M(c,d,c);M(d,u,p);A(p,c,d);Z(c,c,d);S(u,c);Z(d,f,m);M(c,d,a);A(c,c,f);M(d,d,c);M(c,f,m);M(f,u,i);S(u,p);sel25519(c,u,o);sel25519(d,f,o)}for(s=0;s<16;s++){i[s+16]=c[s];i[s+32]=d[s];i[s+48]=u[s];i[s+64]=f[s]}var g=i.subarray(32);var _=i.subarray(16);inv25519(g,g);M(_,_,g);pack25519(e,_);return 0}function crypto_scalarmult_base(e,t){return crypto_scalarmult(e,t,n)}function crypto_box_keypair(e,t){randombytes(t,32);return crypto_scalarmult_base(e,t)}function crypto_box_beforenm(e,n,r){var i=/* @__PURE__ */ new Uint8Array(32);crypto_scalarmult(i,r,n);return crypto_core_hsalsa20(e,t,i,f)}var p=crypto_secretbox;var m=crypto_secretbox_open;function crypto_box(e,t,n,r,i,a){var o=/* @__PURE__ */ new Uint8Array(32);crypto_box_beforenm(o,i,a);return p(e,t,n,r,o)}function crypto_box_open(e,t,n,r,i,a){var o=/* @__PURE__ */ new Uint8Array(32);crypto_box_beforenm(o,i,a);return m(e,t,n,r,o)}var g=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function crypto_hashblocks_hl(e,t,n,r){var i=/* @__PURE__ */ new Int32Array(16),a=/* @__PURE__ */ new Int32Array(16),o,s,c,u,d,f,p,m,_,v,y,b,x,C,w,T,E,D,O,k,j,N,P,F,I,L;var R=e[0],z=e[1],B=e[2],V=e[3],H=e[4],U=e[5],W=e[6],G=e[7],K=t[0],q=t[1],J=t[2],Y=t[3],X=t[4],ee=t[5],te=t[6],Q=t[7];var ne=0;while(r>=128){for(O=0;O<16;O++){k=8*O+ne;i[O]=n[k+0]<<24|n[k+1]<<16|n[k+2]<<8|n[k+3];a[O]=n[k+4]<<24|n[k+5]<<16|n[k+6]<<8|n[k+7]}for(O=0;O<80;O++){o=R;s=z;c=B;u=V;d=H;f=U;p=W;m=G;_=K;v=q;y=J;b=Y;x=X;C=ee;w=te;T=Q;j=G;N=Q;P=N&65535;F=N>>>16;I=j&65535;L=j>>>16;j=(H>>>14|X<<18)^(H>>>18|X<<14)^(X>>>9|H<<23);N=(X>>>14|H<<18)^(X>>>18|H<<14)^(H>>>9|X<<23);P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;j=H&U^~H&W;N=X&ee^~X&te;P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;j=g[O*2];N=g[O*2+1];P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;j=i[O%16];N=a[O%16];P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;F+=P>>>16;I+=F>>>16;L+=I>>>16;E=I&65535|L<<16;D=P&65535|F<<16;j=E;N=D;P=N&65535;F=N>>>16;I=j&65535;L=j>>>16;j=(R>>>28|K<<4)^(K>>>2|R<<30)^(K>>>7|R<<25);N=(K>>>28|R<<4)^(R>>>2|K<<30)^(R>>>7|K<<25);P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;j=R&z^R&B^z&B;N=K&q^K&J^q&J;P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;F+=P>>>16;I+=F>>>16;L+=I>>>16;m=I&65535|L<<16;T=P&65535|F<<16;j=u;N=b;P=N&65535;F=N>>>16;I=j&65535;L=j>>>16;j=E;N=D;P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;F+=P>>>16;I+=F>>>16;L+=I>>>16;u=I&65535|L<<16;b=P&65535|F<<16;z=o;B=s;V=c;H=u;U=d;W=f;G=p;R=m;q=_;J=v;Y=y;X=b;ee=x;te=C;Q=w;K=T;if(O%16===15)for(k=0;k<16;k++){j=i[k];N=a[k];P=N&65535;F=N>>>16;I=j&65535;L=j>>>16;j=i[(k+9)%16];N=a[(k+9)%16];P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;E=i[(k+1)%16];D=a[(k+1)%16];j=(E>>>1|D<<31)^(E>>>8|D<<24)^E>>>7;N=(D>>>1|E<<31)^(D>>>8|E<<24)^(D>>>7|E<<25);P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;E=i[(k+14)%16];D=a[(k+14)%16];j=(E>>>19|D<<13)^(D>>>29|E<<3)^E>>>6;N=(D>>>19|E<<13)^(E>>>29|D<<3)^(D>>>6|E<<26);P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;F+=P>>>16;I+=F>>>16;L+=I>>>16;i[k]=I&65535|L<<16;a[k]=P&65535|F<<16}}j=R;N=K;P=N&65535;F=N>>>16;I=j&65535;L=j>>>16;j=e[0];N=t[0];P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;F+=P>>>16;I+=F>>>16;L+=I>>>16;e[0]=R=I&65535|L<<16;t[0]=K=P&65535|F<<16;j=z;N=q;P=N&65535;F=N>>>16;I=j&65535;L=j>>>16;j=e[1];N=t[1];P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;F+=P>>>16;I+=F>>>16;L+=I>>>16;e[1]=z=I&65535|L<<16;t[1]=q=P&65535|F<<16;j=B;N=J;P=N&65535;F=N>>>16;I=j&65535;L=j>>>16;j=e[2];N=t[2];P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;F+=P>>>16;I+=F>>>16;L+=I>>>16;e[2]=B=I&65535|L<<16;t[2]=J=P&65535|F<<16;j=V;N=Y;P=N&65535;F=N>>>16;I=j&65535;L=j>>>16;j=e[3];N=t[3];P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;F+=P>>>16;I+=F>>>16;L+=I>>>16;e[3]=V=I&65535|L<<16;t[3]=Y=P&65535|F<<16;j=H;N=X;P=N&65535;F=N>>>16;I=j&65535;L=j>>>16;j=e[4];N=t[4];P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;F+=P>>>16;I+=F>>>16;L+=I>>>16;e[4]=H=I&65535|L<<16;t[4]=X=P&65535|F<<16;j=U;N=ee;P=N&65535;F=N>>>16;I=j&65535;L=j>>>16;j=e[5];N=t[5];P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;F+=P>>>16;I+=F>>>16;L+=I>>>16;e[5]=U=I&65535|L<<16;t[5]=ee=P&65535|F<<16;j=W;N=te;P=N&65535;F=N>>>16;I=j&65535;L=j>>>16;j=e[6];N=t[6];P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;F+=P>>>16;I+=F>>>16;L+=I>>>16;e[6]=W=I&65535|L<<16;t[6]=te=P&65535|F<<16;j=G;N=Q;P=N&65535;F=N>>>16;I=j&65535;L=j>>>16;j=e[7];N=t[7];P+=N&65535;F+=N>>>16;I+=j&65535;L+=j>>>16;F+=P>>>16;I+=F>>>16;L+=I>>>16;e[7]=G=I&65535|L<<16;t[7]=Q=P&65535|F<<16;ne+=128;r-=128}return r}function crypto_hash(e,t,n){var r=/* @__PURE__ */ new Int32Array(8),i=/* @__PURE__ */ new Int32Array(8),a=/* @__PURE__ */ new Uint8Array(256),o,s=n;r[0]=1779033703;r[1]=3144134277;r[2]=1013904242;r[3]=2773480762;r[4]=1359893119;r[5]=2600822924;r[6]=528734635;r[7]=1541459225;i[0]=4089235720;i[1]=2227873595;i[2]=4271175723;i[3]=1595750129;i[4]=2917565137;i[5]=725511199;i[6]=4215389547;i[7]=327033209;crypto_hashblocks_hl(r,i,t,n);n%=128;for(o=0;o<n;o++)a[o]=t[s-n+o];a[n]=128;n=256-128*(n<112?1:0);a[n-9]=0;ts64(a,n-8,s/536870912|0,s<<3);crypto_hashblocks_hl(r,i,a,n);for(o=0;o<8;o++)ts64(e,8*o,r[o],i[o]);return 0}function add(e,t){var n=gf(),r=gf(),i=gf(),a=gf(),o=gf(),c=gf(),u=gf(),d=gf(),f=gf();Z(n,e[1],e[0]);Z(f,t[1],t[0]);M(n,n,f);A(r,e[0],e[1]);A(f,t[0],t[1]);M(r,r,f);M(i,e[3],t[3]);M(i,i,s);M(a,e[2],t[2]);A(a,a,a);Z(o,r,n);Z(c,a,i);A(u,a,i);A(d,r,n);M(e[0],o,c);M(e[1],d,u);M(e[2],u,c);M(e[3],o,d)}function cswap(e,t,n){var r=0;for(;r<4;r++)sel25519(e[r],t[r],n)}function pack(e,t){var n=gf(),r=gf(),i=gf();inv25519(i,t[2]);M(n,t[0],i);M(r,t[1],i);pack25519(e,r);e[31]^=par25519(n)<<7}function scalarmult(e,t,n){var a,o;set25519(e[0],r);set25519(e[1],i);set25519(e[2],i);set25519(e[3],r);for(o=255;o>=0;--o){a=n[o/8|0]>>(o&7)&1;cswap(e,t,a);add(t,e);add(e,e);cswap(e,t,a)}}function scalarbase(e,t){var n=[gf(),gf(),gf(),gf()];set25519(n[0],c);set25519(n[1],u);set25519(n[2],i);M(n[3],c,u);scalarmult(e,n,t)}function crypto_sign_keypair(e,t,n){var r=/* @__PURE__ */ new Uint8Array(64);var i=[gf(),gf(),gf(),gf()];var a;if(!n)randombytes(t,32);crypto_hash(r,t,32);r[0]&=248;r[31]&=127;r[31]|=64;scalarbase(i,r);pack(e,i);for(a=0;a<32;a++)t[a+32]=e[a];return 0}var _=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function modL(e,t){var n,r=63,i,a;for(;r>=32;--r){n=0;for(i=r-32,a=r-12;i<a;++i){t[i]+=n-16*t[r]*_[i-(r-32)];n=Math.floor((t[i]+128)/256);t[i]-=n*256}t[i]+=n;t[r]=0}n=0;for(i=0;i<32;i++){t[i]+=n-(t[31]>>4)*_[i];n=t[i]>>8;t[i]&=255}for(i=0;i<32;i++)t[i]-=n*_[i];for(r=0;r<32;r++){t[r+1]+=t[r]>>8;e[r]=t[r]&255}}function reduce(e){var t=/* @__PURE__ */ new Float64Array(64),n=0;for(;n<64;n++)t[n]=e[n];for(n=0;n<64;n++)e[n]=0;modL(e,t)}function crypto_sign(e,t,n,r){var i=/* @__PURE__ */ new Uint8Array(64),a=/* @__PURE__ */ new Uint8Array(64),o=/* @__PURE__ */ new Uint8Array(64);var s,c,u=/* @__PURE__ */ new Float64Array(64);var d=[gf(),gf(),gf(),gf()];crypto_hash(i,r,32);i[0]&=248;i[31]&=127;i[31]|=64;var f=n+64;for(s=0;s<n;s++)e[64+s]=t[s];for(s=0;s<32;s++)e[32+s]=i[32+s];crypto_hash(o,e.subarray(32),n+32);reduce(o);scalarbase(d,o);pack(e,d);for(s=32;s<64;s++)e[s]=r[s];crypto_hash(a,e,n+64);reduce(a);for(s=0;s<64;s++)u[s]=0;for(s=0;s<32;s++)u[s]=o[s];for(s=0;s<32;s++)for(c=0;c<32;c++)u[s+c]+=a[s]*i[c];modL(e.subarray(32),u);return f}function unpackneg(e,t){var n=gf(),a=gf(),s=gf(),c=gf(),u=gf(),f=gf(),p=gf();set25519(e[2],i);unpack25519(e[1],t);S(s,e[1]);M(c,s,o);Z(s,s,e[2]);A(c,e[2],c);S(u,c);S(f,u);M(p,f,u);M(n,p,s);M(n,n,c);pow2523(n,n);M(n,n,s);M(n,n,c);M(n,n,c);M(e[0],n,c);S(a,e[0]);M(a,a,c);if(neq25519(a,s))M(e[0],e[0],d);S(a,e[0]);M(a,a,c);if(neq25519(a,s))return-1;if(par25519(e[0])===t[31]>>7)Z(e[0],r,e[0]);M(e[3],e[0],e[1]);return 0}function crypto_sign_open(e,t,n,r){var i;var a=/* @__PURE__ */ new Uint8Array(32),o=/* @__PURE__ */ new Uint8Array(64);var s=[gf(),gf(),gf(),gf()],c=[gf(),gf(),gf(),gf()];if(n<64)return-1;if(unpackneg(c,r))return-1;for(i=0;i<n;i++)e[i]=t[i];for(i=0;i<32;i++)e[i+32]=r[i];crypto_hash(o,e,n);reduce(o);scalarmult(s,c,o);scalarbase(c,t.subarray(32));add(s,c);pack(a,s);n-=64;if(crypto_verify_32(t,0,a,0)){for(i=0;i<n;i++)e[i]=0;return-1}for(i=0;i<n;i++)e[i]=t[i+64];return n}var v=32,y=24,b=32,x=16,C=32,w=32,T=32,E=32,D=32,O=y,k=b,j=x,N=64,P=32,F=64,I=32,L=64;e.lowlevel={crypto_core_hsalsa20,crypto_stream_xor,crypto_stream,crypto_stream_salsa20_xor,crypto_stream_salsa20,crypto_onetimeauth,crypto_onetimeauth_verify,crypto_verify_16,crypto_verify_32,crypto_secretbox,crypto_secretbox_open,crypto_scalarmult,crypto_scalarmult_base,crypto_box_beforenm,crypto_box_afternm:p,crypto_box,crypto_box_open,crypto_box_keypair,crypto_hash,crypto_sign,crypto_sign_keypair,crypto_sign_open,crypto_secretbox_KEYBYTES:v,crypto_secretbox_NONCEBYTES:y,crypto_secretbox_ZEROBYTES:b,crypto_secretbox_BOXZEROBYTES:x,crypto_scalarmult_BYTES:C,crypto_scalarmult_SCALARBYTES:w,crypto_box_PUBLICKEYBYTES:T,crypto_box_SECRETKEYBYTES:E,crypto_box_BEFORENMBYTES:D,crypto_box_NONCEBYTES:O,crypto_box_ZEROBYTES:k,crypto_box_BOXZEROBYTES:j,crypto_sign_BYTES:N,crypto_sign_PUBLICKEYBYTES:P,crypto_sign_SECRETKEYBYTES:F,crypto_sign_SEEDBYTES:I,crypto_hash_BYTES:L,gf,D:o,L:_,pack25519,unpack25519,M,A,S,Z,pow2523,add,set25519,modL,scalarmult,scalarbase};function checkLengths(e,t){if(e.length!==v)throw new Error(`bad key size`);if(t.length!==y)throw new Error(`bad nonce size`)}function checkBoxLengths(e,t){if(e.length!==T)throw new Error(`bad public key size`);if(t.length!==E)throw new Error(`bad secret key size`)}function checkArrayTypes(){for(var e=0;e<arguments.length;e++)if(!(arguments[e]instanceof Uint8Array))throw new TypeError(`unexpected type, use Uint8Array`)}function cleanup(e){for(var t=0;t<e.length;t++)e[t]=0}e.randomBytes=function(e){var t=new Uint8Array(e);randombytes(t,e);return t};e.secretbox=function(e,t,n){checkArrayTypes(e,t,n);checkLengths(n,t);var r=new Uint8Array(b+e.length);var i=new Uint8Array(r.length);for(var a=0;a<e.length;a++)r[a+b]=e[a];crypto_secretbox(i,r,r.length,t,n);return i.subarray(x)};e.secretbox.open=function(e,t,n){checkArrayTypes(e,t,n);checkLengths(n,t);var r=new Uint8Array(x+e.length);var i=new Uint8Array(r.length);for(var a=0;a<e.length;a++)r[a+x]=e[a];if(r.length<32)return null;if(crypto_secretbox_open(i,r,r.length,t,n)!==0)return null;return i.subarray(b)};e.secretbox.keyLength=v;e.secretbox.nonceLength=y;e.secretbox.overheadLength=x;e.scalarMult=function(e,t){checkArrayTypes(e,t);if(e.length!==w)throw new Error(`bad n size`);if(t.length!==C)throw new Error(`bad p size`);var n=new Uint8Array(C);crypto_scalarmult(n,e,t);return n};e.scalarMult.base=function(e){checkArrayTypes(e);if(e.length!==w)throw new Error(`bad n size`);var t=new Uint8Array(C);crypto_scalarmult_base(t,e);return t};e.scalarMult.scalarLength=w;e.scalarMult.groupElementLength=C;e.box=function(t,n,r,i){var a=e.box.before(r,i);return e.secretbox(t,n,a)};e.box.before=function(e,t){checkArrayTypes(e,t);checkBoxLengths(e,t);var n=new Uint8Array(D);crypto_box_beforenm(n,e,t);return n};e.box.after=e.secretbox;e.box.open=function(t,n,r,i){var a=e.box.before(r,i);return e.secretbox.open(t,n,a)};e.box.open.after=e.secretbox.open;e.box.keyPair=function(){var e=new Uint8Array(T);var t=new Uint8Array(E);crypto_box_keypair(e,t);return{publicKey:e,secretKey:t}};e.box.keyPair.fromSecretKey=function(e){checkArrayTypes(e);if(e.length!==E)throw new Error(`bad secret key size`);var t=new Uint8Array(T);crypto_scalarmult_base(t,e);return{publicKey:t,secretKey:new Uint8Array(e)}};e.box.publicKeyLength=T;e.box.secretKeyLength=E;e.box.sharedKeyLength=D;e.box.nonceLength=O;e.box.overheadLength=e.secretbox.overheadLength;e.sign=function(e,t){checkArrayTypes(e,t);if(t.length!==F)throw new Error(`bad secret key size`);var n=new Uint8Array(N+e.length);crypto_sign(n,e,e.length,t);return n};e.sign.open=function(e,t){checkArrayTypes(e,t);if(t.length!==P)throw new Error(`bad public key size`);var n=new Uint8Array(e.length);var r=crypto_sign_open(n,e,e.length,t);if(r<0)return null;var i=new Uint8Array(r);for(var a=0;a<i.length;a++)i[a]=n[a];return i};e.sign.detached=function(t,n){var r=e.sign(t,n);var i=new Uint8Array(N);for(var a=0;a<i.length;a++)i[a]=r[a];return i};e.sign.detached.verify=function(e,t,n){checkArrayTypes(e,t,n);if(t.length!==N)throw new Error(`bad signature size`);if(n.length!==P)throw new Error(`bad public key size`);var r=new Uint8Array(N+e.length);var i=new Uint8Array(N+e.length);var a=0;for(;a<N;a++)r[a]=t[a];for(a=0;a<e.length;a++)r[a+N]=e[a];return crypto_sign_open(i,r,r.length,n)>=0};e.sign.keyPair=function(){var e=new Uint8Array(P);var t=new Uint8Array(F);crypto_sign_keypair(e,t);return{publicKey:e,secretKey:t}};e.sign.keyPair.fromSecretKey=function(e){checkArrayTypes(e);if(e.length!==F)throw new Error(`bad secret key size`);var t=new Uint8Array(P);for(var n=0;n<t.length;n++)t[n]=e[32+n];return{publicKey:t,secretKey:new Uint8Array(e)}};e.sign.keyPair.fromSeed=function(e){checkArrayTypes(e);if(e.length!==I)throw new Error(`bad seed size`);var t=new Uint8Array(P);var n=new Uint8Array(F);for(var r=0;r<32;r++)n[r]=e[r];crypto_sign_keypair(t,n,true);return{publicKey:t,secretKey:n}};e.sign.publicKeyLength=P;e.sign.secretKeyLength=F;e.sign.seedLength=I;e.sign.signatureLength=N;e.hash=function(e){checkArrayTypes(e);var t=new Uint8Array(L);crypto_hash(t,e,e.length);return t};e.hash.hashLength=L;e.verify=function(e,t){checkArrayTypes(e,t);if(e.length===0||t.length===0)return false;if(e.length!==t.length)return false;return vn(e,0,t,0,e.length)===0?true:false};e.setPRNG=function(e){randombytes=e};(function(){var t=typeof self!==`undefined`?self.crypto||self.msCrypto:null;if(t&&t.getRandomValues){var n=65536;e.setPRNG(function(e,r){var i,a=new Uint8Array(r);for(i=0;i<r;i+=n)t.getRandomValues(a.subarray(i,i+Math.min(r-i,n)));for(i=0;i<r;i++)e[i]=a[i];cleanup(a)})}else if(typeof __require!==`undefined`){t=__require(`crypto`);if(t&&t.randomBytes)e.setPRNG(function(e,n){var r,i=t.randomBytes(n);for(r=0;r<n;r++)e[r]=i[r];cleanup(i)})}})()})(typeof t!==`undefined`&&t.exports?t.exports:self.nacl=self.nacl||{})}));
//!node_modules/.pnpm/@fidm+asn1@1.0.4/node_modules/@fidm/asn1/build/common.js
var require_common=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});var BufferVisitor=class{constructor(e,t=0,n=0){this.start=t;this.end=n>t?n:t;this.buf=e}get length(){return this.buf.length}reset(e=0,t=0){this.start=e;if(t>=this.start)this.end=t;else if(this.end<this.start)this.end=this.start;return this}walk(e){this.start=this.end;this.end+=e;return this}mustHas(e,t=`Too few bytes to parse.`){const n=this.end+e;if(n>this.buf.length){const e=new Error(t);e.available=this.buf.length;e.requested=n;throw e}this.walk(0);return this}mustWalk(e,t){this.mustHas(e,t);this.walk(e);return this}};e.BufferVisitor=BufferVisitor}));
//!node_modules/.pnpm/@fidm+asn1@1.0.4/node_modules/@fidm/asn1/build/pem.js
var require_pem$2=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=__require(`util`);const n=64;const r=`-----BEGIN `;const i=`-----END `;const a=`-----`;const o=`Proc-Type`;var PEM=class{static parse(e){const t=[];const n=e.toString(`utf8`).split(`
`).map(e=>e.trim()).filter(e=>e!==``&&!e.startsWith(`#`));while(n.length>0)t.push(parse(n));if(t.length===0)throw new Error(`PEM: no block`);return t}constructor(e,t){this.type=e;this.body=t;this.headers=Object.create(null)}get procType(){return this.getHeader(o)}getHeader(e){const t=this.headers[e];return t==null?``:t}setHeader(e,t){if(e.includes(`:`))throw new Error(`pem: cannot encode a header key that contains a colon`);if(e===``||t===``)throw new Error(`pem: invalid header key or value`);this.headers[e]=t}toString(){let e=r+this.type+`-----
`;const t=Object.keys(this.headers);if(t.length>0){const n=this.procType;if(n!==``)e+=`${o}: ${n}\n`;t.sort();for(const n of t)if(n!==o)e+=`${n}: ${this.headers[n]}\n`;e+=`
`}const a=this.body.toString(`base64`);let s=0;while(s<a.length){e+=a.slice(s,s+n)+`
`;s+=n}e+=i+this.type+`-----
`;return e}toBuffer(){return Buffer.from(this.toString(),`utf8`)}valueOf(){return this.body}toJSON(){return{type:this.type,body:this.body,headers:this.headers}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};e.PEM=PEM;function parse(e){let t=e.shift();if(t==null||!t.startsWith(r)||!t.endsWith(a))throw new Error(`pem: invalid BEGIN line`);const n=t.slice(11,t.length-5);if(n===``)throw new Error(`pem: invalid type`);const o=[];t=e.shift();while(t!=null&&t.includes(`: `)){const n=t.split(`: `);if(n.length!==2||n[0]===``||n[1]===``)throw new Error(`pem: invalid Header line`);o.push(n);t=e.shift()}let s=``;while(t!=null&&!t.startsWith(i)){s+=t;t=e.shift()}if(t==null||t!==`${i}${n}${a}`)throw new Error(`pem: invalid END line`);const c=new PEM(n,Buffer.from(s,`base64`));if(s===``||c.body.toString(`base64`)!==s)throw new Error(`pem: invalid base64 body`);for(const e of o)c.setHeader(e[0],e[1]);return c}}));
//!node_modules/.pnpm/@fidm+asn1@1.0.4/node_modules/@fidm/asn1/build/asn1.js
var require_asn1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=__require(`util`);const n=require_common();var r;(function(e){e[e[`UNIVERSAL`]=0]=`UNIVERSAL`;e[e[`APPLICATION`]=64]=`APPLICATION`;e[e[`CONTEXT_SPECIFIC`]=128]=`CONTEXT_SPECIFIC`;e[e[`PRIVATE`]=192]=`PRIVATE`})(r=e.Class||(e.Class={}));var i;(function(e){e[e[`NONE`]=0]=`NONE`;e[e[`BOOLEAN`]=1]=`BOOLEAN`;e[e[`INTEGER`]=2]=`INTEGER`;e[e[`BITSTRING`]=3]=`BITSTRING`;e[e[`OCTETSTRING`]=4]=`OCTETSTRING`;e[e[`NULL`]=5]=`NULL`;e[e[`OID`]=6]=`OID`;e[e[`ENUMERATED`]=10]=`ENUMERATED`;e[e[`UTF8`]=12]=`UTF8`;e[e[`SEQUENCE`]=16]=`SEQUENCE`;e[e[`SET`]=17]=`SET`;e[e[`NUMERICSTRING`]=18]=`NUMERICSTRING`;e[e[`PRINTABLESTRING`]=19]=`PRINTABLESTRING`;e[e[`T61STRING`]=20]=`T61STRING`;e[e[`IA5STRING`]=22]=`IA5STRING`;e[e[`UTCTIME`]=23]=`UTCTIME`;e[e[`GENERALIZEDTIME`]=24]=`GENERALIZEDTIME`;e[e[`GENERALSTRING`]=27]=`GENERALSTRING`})(i=e.Tag||(e.Tag={}));var BitString=class{constructor(e,t){this.buf=e;this.bitLen=t}at(e){if(e<0||e>=this.bitLen||!Number.isInteger(e))return 0;const t=Math.floor(e/8);const n=7-e%8;return this.buf[t]>>n&1}rightAlign(){const e=8-this.bitLen%8;if(e===8||this.buf.length===0)return this.buf;const t=Buffer.alloc(this.buf.length);t[0]=this.buf[0]>>e;for(let n=1;n<this.buf.length;n++){t[n]=this.buf[n-1]<<8-e;t[n]|=this.buf[n]>>e}return t}};e.BitString=BitString;var a=class ASN1{static Bool(e){const t=new ASN1(r.UNIVERSAL,i.BOOLEAN,Buffer.from([e?255:0]));t._value=e;return t}static parseBool(e){if(!(e instanceof Buffer)||e.length!==1)throw new Error(`ASN1 syntax error: invalid boolean`);switch(e[0]){case 0:return false;case 255:return true;default:throw new Error(`ASN1 syntax error: invalid boolean`)}}static Integer(e){if(e instanceof Buffer){const t=new ASN1(r.UNIVERSAL,i.INTEGER,e);t._value=e.toString(`hex`);return t}if(!Number.isSafeInteger(e))throw new Error(`ASN1 syntax error: invalid integer`);let t;if(e>=-128&&e<128){t=Buffer.alloc(1);t.writeInt8(e,0)}else if(e>=-32768&&e<32768){t=Buffer.alloc(2);t.writeIntBE(e,0,2)}else if(e>=-8388608&&e<8388608){t=Buffer.alloc(3);t.writeIntBE(e,0,3)}else if(e>=-2147483648&&e<2147483648){t=Buffer.alloc(4);t.writeIntBE(e,0,4)}else if(e>=-549755813888&&e<549755813888){t=Buffer.alloc(5);t.writeIntBE(e,0,5)}else if(e>=-0x800000000000&&e<0x800000000000){t=Buffer.alloc(6);t.writeIntBE(e,0,6)}else throw new Error(`ASN1 syntax error: invalid Integer`);const n=new ASN1(r.UNIVERSAL,i.INTEGER,t);n._value=e;return n}static parseInteger(e){if(!(e instanceof Buffer)||e.length===0)throw new Error(`ASN1 syntax error: invalid Integer`);if(e.length>6)return e.toString(`hex`);return e.readIntBE(0,e.length)}static parseIntegerNum(e){const t=ASN1.parseInteger(e);if(typeof t!==`number`)throw new Error(`ASN1 syntax error: invalid Integer number`);return t}static parseIntegerStr(e){const t=ASN1.parseInteger(e);if(typeof t===`number`)return t.toString(16);return t}static BitString(e){if(e instanceof Buffer)e=new BitString(e,e.length*8);const t=e.buf.length*8-e.bitLen;const n=Buffer.alloc(e.buf.length+1);n.writeInt8(t,0);e.buf.copy(n,1);return new ASN1(r.UNIVERSAL,i.BITSTRING,n)}static parseBitString(e){if(!(e instanceof Buffer)||e.length===0)throw new Error(`ASN1 syntax error: invalid BitString`);const t=e[0];if(t>7||e.length===1&&t>0||(e[e.length-1]&(1<<e[0])-1)!==0)throw new Error(`ASN1 syntax error: invalid padding bits in BIT STRING`);return new BitString(e.slice(1),(e.length-1)*8-t)}static Null(){const e=new ASN1(r.UNIVERSAL,i.NULL,Buffer.alloc(0));e._value=null;return e}static parseNull(e){if(!(e instanceof Buffer)||e.length!==0)throw new Error(`ASN1 syntax error: invalid null`);return null}static OID(e){const t=e.split(`.`);if(t.length===0)throw new Error(`ASN1 syntax error: invalid Object Identifier`);const n=[];n.push(40*mustParseInt(t[0])+mustParseInt(t[1]));const a=[];for(let e=2;e<t.length;++e){let r=mustParseInt(t[e]);a.length=0;a.push(r&127);while(r>127){r=r>>>7;a.unshift(r&127|128)}n.push(...a)}const o=new ASN1(r.UNIVERSAL,i.OID,Buffer.from(n));o._value=e;return o}static parseOID(e){if(!(e instanceof Buffer)||e.length===0)throw new Error(`ASN1 syntax error: invalid OID`);let t=Math.floor(e[0]/40)+`.`+e[0]%40;let n=0;for(let r=1;r<e.length;r++)if(e[r]>=128){n+=e[r]&127;n=n<<7}else{t+=`.`+(n+e[r]);n=0}return t}static UTF8(e){const t=new ASN1(r.UNIVERSAL,i.UTF8,Buffer.from(e,`utf8`));t._value=e;return t}static parseUTF8(e){if(!(e instanceof Buffer))throw new Error(`parse ASN1 error: invalid Buffer`);return e.toString(`utf8`)}static NumericString(e){if(!isNumericString(e))throw new Error(`ASN1 syntax error: invalid NumericString`);const t=new ASN1(r.UNIVERSAL,i.NUMERICSTRING,Buffer.from(e,`utf8`));t._value=e;return t}static parseNumericString(e){if(!(e instanceof Buffer))throw new Error(`parse ASN1 error: invalid Buffer`);const t=e.toString(`utf8`);if(!isNumericString(t))throw new Error(`ASN1 syntax error: invalid NumericString`);return t}static PrintableString(e){const t=new ASN1(r.UNIVERSAL,i.PRINTABLESTRING,Buffer.from(e,`utf8`));t._value=e;return t}static parsePrintableString(e){if(!(e instanceof Buffer))throw new Error(`parse ASN1 error: invalid Buffer`);return e.toString(`utf8`)}static IA5String(e){if(!isIA5String(e))throw new Error(`ASN1 syntax error: invalid IA5String`);const t=new ASN1(r.UNIVERSAL,i.IA5STRING,Buffer.from(e,`utf8`));t._value=e;return t}static parseIA5String(e){if(!(e instanceof Buffer))throw new Error(`parse ASN1 error: invalid Buffer`);const t=e.toString(`utf8`);if(!isIA5String(t))throw new Error(`ASN1 syntax error: invalid IA5String`);return t}static T61String(e){const t=new ASN1(r.UNIVERSAL,i.T61STRING,Buffer.from(e,`utf8`));t._value=e;return t}static parseT61String(e){if(!(e instanceof Buffer))throw new Error(`parse ASN1 error: invalid Buffer`);return e.toString(`utf8`)}static GeneralString(e){const t=new ASN1(r.UNIVERSAL,i.GENERALSTRING,Buffer.from(e,`utf8`));t._value=e;return t}static parseGeneralString(e){if(!(e instanceof Buffer))throw new Error(`parse ASN1 error: invalid Buffer`);return e.toString(`utf8`)}static UTCTime(e){let t=``;const n=[];n.push((``+e.getUTCFullYear()).substr(2));n.push(``+(e.getUTCMonth()+1));n.push(``+e.getUTCDate());n.push(``+e.getUTCHours());n.push(``+e.getUTCMinutes());n.push(``+e.getUTCSeconds());for(const e of n){if(e.length<2)t+=`0`;t+=e}t+=`Z`;const a=new ASN1(r.UNIVERSAL,i.UTCTIME,Buffer.from(t,`utf8`));a._value=e;return a}static parseUTCTime(e){if(!(e instanceof Buffer)||e.length===0)throw new Error(`ASN1 syntax error: invalid UTC Time`);const t=e.toString(`utf8`);const n=/* @__PURE__ */ new Date;let r=mustParseInt(t.substr(0,2));r=r>=50?1900+r:2e3+r;const i=mustParseInt(t.substr(2,2))-1;const a=mustParseInt(t.substr(4,2));const o=mustParseInt(t.substr(6,2));const s=mustParseInt(t.substr(8,2));let c=0;let u=0;let d=``;if(t.length>11){u=10;d=t.charAt(u);if(d!==`+`&&d!==`-`){c=mustParseInt(t.substr(10,2));u+=2}}n.setUTCFullYear(r,i,a);n.setUTCHours(o,s,c,0);if(u>0){d=t.charAt(u);if(d===`+`||d===`-`){const e=mustParseInt(t.substr(u+1,2));const r=mustParseInt(t.substr(u+4,2));let i=e*60+r;i*=6e4;if(d===`+`)n.setTime(+n-i);else n.setTime(+n+i)}}return n}static GeneralizedTime(e){let t=``;const n=[];n.push(``+e.getUTCFullYear());n.push(``+(e.getUTCMonth()+1));n.push(``+e.getUTCDate());n.push(``+e.getUTCHours());n.push(``+e.getUTCMinutes());n.push(``+e.getUTCSeconds());for(const e of n){if(e.length<2)t+=`0`;t+=e}t+=`Z`;const a=new ASN1(r.UNIVERSAL,i.GENERALIZEDTIME,Buffer.from(t,`utf8`));a._value=e;return a}static parseGeneralizedTime(e){if(!(e instanceof Buffer)||e.length===0)throw new Error(`ASN1 syntax error: invalid Generalized Time`);const t=e.toString(`utf8`);const n=/* @__PURE__ */ new Date;const r=mustParseInt(t.substr(0,4));const i=mustParseInt(t.substr(4,2))-1;const a=mustParseInt(t.substr(6,2));const o=mustParseInt(t.substr(8,2));const s=mustParseInt(t.substr(10,2));const c=mustParseInt(t.substr(12,2));let u=0;let d=0;let f=false;if(t.charAt(t.length-1)===`Z`)f=true;const p=t.length-5;const m=t.charAt(p);if(m===`+`||m===`-`){const e=mustParseInt(t.substr(p+1,2));const n=mustParseInt(t.substr(p+4,2));d=e*60+n;d*=6e4;if(m===`+`)d*=-1;f=true}if(t.charAt(14)===`.`)u=parseFloat(t.substr(14))*1e3;if(f){n.setUTCFullYear(r,i,a);n.setUTCHours(o,s,c,u);n.setTime(+n+d)}else{n.setFullYear(r,i,a);n.setHours(o,s,c,u)}return n}static parseTime(e,t){switch(e){case i.UTCTIME:return ASN1.parseUTCTime(t);case i.GENERALIZEDTIME:return ASN1.parseGeneralizedTime(t);default:throw new Error(`Invalid ASN1 time tag`)}}static Set(e){const t=new ASN1(r.UNIVERSAL,i.SET,Buffer.concat(e.map(e=>e.toDER())));t._value=e;return t}static Seq(e){const t=new ASN1(r.UNIVERSAL,i.SEQUENCE,Buffer.concat(e.map(e=>e.toDER())));t._value=e;return t}static Spec(e,t,n=true){const i=Array.isArray(t)?Buffer.concat(t.map(e=>e.toDER())):t.toDER();if(Array.isArray(t))n=true;const a=new ASN1(r.CONTEXT_SPECIFIC,e,i,n);a._value=t;return a}static fromDER(e,t=false){return ASN1._fromDER(new n.BufferVisitor(e),t)}static parseDER(e,t,r){const i=ASN1._fromDER(new n.BufferVisitor(e),false);if(i.class!==t&&i.tag!==r)throw new Error(`invalid ASN.1 DER for class ${t} and tag ${r}`);return i}static parseDERWithTemplate(e,t){const r=ASN1._fromDER(new n.BufferVisitor(e),true);const i={};const a=r.validate(t,i);if(a!=null){a.data=r;throw a}return i}static _parseCompound(e,t){const r=[];const i=e.length;const a=new n.BufferVisitor(e);let o=0;while(o<i){const e=a.end;r.push(ASN1._fromDER(a,t));o+=a.end-e}return r}static _fromDER(e,t){if(!(e.buf instanceof Buffer)||e.length===0)throw new Error(`ASN1 syntax error: invalid Generalized Time`);e.mustWalk(1,`Too few bytes to read ASN.1 tag.`);const n=e.start;const r=e.buf[n];const a=r&192;const o=r&31;const s=getValueLength(e);e.mustHas(s);if(s!==0&&o===i.NULL)throw new Error(`invalid value length or NULL tag.`);e.mustWalk(s);const c=(r&32)===32;const u=new ASN1(a,o,e.buf.slice(e.start,e.end),c);if(c&&t)u._value=ASN1._parseCompound(u.bytes,t);u._der=e.buf.slice(n,e.end);return u}constructor(e,t,n,r=false){this.class=e;this.tag=t;this.bytes=n;this.isCompound=r||t===i.SEQUENCE||t===i.SET;this._value=void 0;this._der=null}get value(){if(this._value===void 0)this._value=this.valueOf();return this._value}get DER(){if(this._der==null)this._der=this.toDER();return this._der}mustCompound(e=`asn1 object value is not compound`){if(!this.isCompound||!Array.isArray(this.value)){const t=new Error(e);t.data=this.toJSON();throw t}return this.value}equals(e){if(!(e instanceof ASN1))return false;if(this.class!==e.class||this.tag!==e.tag||this.isCompound!==e.isCompound)return false;if(!this.bytes.equals(e.bytes))return false;return true}toDER(){let e=this.class|this.tag;if(this.isCompound)e|=32;const t=getValueLengthByte(this.bytes.length);const n=Buffer.allocUnsafe(2+t+this.bytes.length);n.writeInt8(e,0);if(t===0){n.writeUInt8(this.bytes.length,1);this.bytes.copy(n,2)}else{n.writeUInt8(t|128,1);n.writeUIntBE(this.bytes.length,2,t);this.bytes.copy(n,2+t)}return n}valueOf(){if(this.isCompound)return ASN1._parseCompound(this.bytes,false);if(this.class!==r.UNIVERSAL)return this.bytes;switch(this.tag){case i.BOOLEAN:return ASN1.parseBool(this.bytes);case i.INTEGER:return ASN1.parseInteger(this.bytes);case i.BITSTRING:return ASN1.parseBitString(this.bytes);case i.NULL:return ASN1.parseNull(this.bytes);case i.OID:return ASN1.parseOID(this.bytes);case i.UTF8:return ASN1.parseUTF8(this.bytes);case i.NUMERICSTRING:return ASN1.parseNumericString(this.bytes);case i.PRINTABLESTRING:return ASN1.parsePrintableString(this.bytes);case i.T61STRING:return ASN1.parseT61String(this.bytes);case i.IA5STRING:return ASN1.parseIA5String(this.bytes);case i.GENERALSTRING:return ASN1.parseGeneralString(this.bytes);case i.UTCTIME:return ASN1.parseUTCTime(this.bytes);case i.GENERALIZEDTIME:return ASN1.parseGeneralizedTime(this.bytes);default:return this.bytes}}validate(e,t={}){if(this.class!==e.class)return/* @__PURE__ */ new Error(`ASN.1 object validate failure for ${e.name} : error class ${r[this.class]}`);if(!(Array.isArray(e.tag)?e.tag:[e.tag]).includes(this.tag))return/* @__PURE__ */ new Error(`ASN.1 object validate failure for ${e.name}: error tag ${i[this.tag]}`);if(e.capture!=null)t[e.capture]=this;if(Array.isArray(e.value)){const n=this.mustCompound(`${e.name} need compound ASN1 value`);for(let r=0,i=0;r<e.value.length;r++)if(n[i]!=null){const a=n[i].validate(e.value[r],t);if(a==null)i++;else if(e.value[r].optional!==true)return a}else if(e.value[r].optional!==true)return/* @__PURE__ */ new Error(`ASN.1 object validate failure for ${e.value[r].name}: not exists`)}else if(e.value!=null){const n=this.tag===i.BITSTRING?this.bytes.slice(1):this.bytes;return ASN1.fromDER(n).validate(e.value,t)}return null}toJSON(){let e=this.value;if(Array.isArray(e))e=e.map(e=>e.toJSON());return{class:r[this.class],tag:this.class===r.UNIVERSAL?i[this.tag]:this.tag,value:e}}[t.inspect.custom](e,n){if(n.depth<=2)n.depth=10;return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};e.ASN1=a;function getValueLength(e){e.mustWalk(1,`Too few bytes to read ASN.1 value length.`);const t=e.buf[e.start];if((t&128)===0)return t;const n=t&127;e.mustWalk(n,`Too few bytes to read ASN.1 value length.`);return e.buf.readUIntBE(e.start,n)}function getValueLengthByte(e){if(e<=127)return 0;else if(e<=255)return 1;else if(e<=65535)return 2;else if(e<=16777215)return 3;else if(e<=4294967295)return 4;else if(e<=0xffffffffff)return 5;else if(e<=0xffffffffffff)return 6;else throw new Error(`invalid value length`)}function isNumericString(e){for(const t of e){const e=t.charCodeAt(0);if(e!==32&&(e<48||e>57))return false}return true}function isIA5String(e){for(const t of e)if(t.charCodeAt(0)>=128)return false;return true}function mustParseInt(e,t=10){const n=parseInt(e,t);if(Number.isNaN(n))throw new Error(`Invalid numeric string "${e}" in radix ${t}.`);return n}}));
//!node_modules/.pnpm/@fidm+asn1@1.0.4/node_modules/@fidm/asn1/build/index.js
var require_build$1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});var t=require_common();e.BufferVisitor=t.BufferVisitor;var n=require_pem$2();e.PEM=n.PEM;var r=require_asn1();e.ASN1=r.ASN1;e.Class=r.Class;e.Tag=r.Tag;e.BitString=r.BitString}));
//!node_modules/.pnpm/@fidm+x509@1.2.1/node_modules/@fidm/x509/build/pki.js
var require_pki=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=__require(`util`);const n=__require(`crypto`);const r=require_nacl_fast();const i=require_build$1();const a=require_common$1();e.publicKeyValidator={name:`PublicKeyInfo`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,capture:`publicKeyInfo`,value:[{name:`PublicKeyInfo.AlgorithmIdentifier`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,value:[{name:`PublicKeyAlgorithmIdentifier.algorithm`,class:i.Class.UNIVERSAL,tag:i.Tag.OID,capture:`publicKeyOID`}]},{name:`PublicKeyInfo.PublicKey`,class:i.Class.UNIVERSAL,tag:i.Tag.BITSTRING,capture:`publicKey`}]};e.privateKeyValidator={name:`PrivateKeyInfo`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,capture:`privateKeyInfo`,value:[{name:`PrivateKeyInfo.Version`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyVersion`},{name:`PrivateKeyInfo.AlgorithmIdentifier`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,value:[{name:`PrivateKeyAlgorithmIdentifier.algorithm`,class:i.Class.UNIVERSAL,tag:i.Tag.OID,capture:`privateKeyOID`}]},{name:`PrivateKeyInfo.PrivateKey`,class:i.Class.UNIVERSAL,tag:i.Tag.OCTETSTRING,capture:`privateKey`}]};const o={name:`RSAPublicKey`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,value:[{name:`RSAPublicKey.modulus`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`publicKeyModulus`},{name:`RSAPublicKey.exponent`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`publicKeyExponent`}]};const s={name:`RSAPrivateKey`,class:i.Class.UNIVERSAL,tag:i.Tag.SEQUENCE,value:[{name:`RSAPrivateKey.version`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyVersion`},{name:`RSAPrivateKey.modulus`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyModulus`},{name:`RSAPrivateKey.publicExponent`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyPublicExponent`},{name:`RSAPrivateKey.privateExponent`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyPrivateExponent`},{name:`RSAPrivateKey.prime1`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyPrime1`},{name:`RSAPrivateKey.prime2`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyPrime2`},{name:`RSAPrivateKey.exponent1`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyExponent1`},{name:`RSAPrivateKey.exponent2`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyExponent2`},{name:`RSAPrivateKey.coefficient`,class:i.Class.UNIVERSAL,tag:i.Tag.INTEGER,capture:`privateKeyCoefficient`}]};const c=[a.getOID(`X25519`),a.getOID(`X448`),a.getOID(`Ed25519`),a.getOID(`Ed448`)];var u=class PublicKey{constructor(t){const n={};const r=t.validate(e.publicKeyValidator,n);if(r!=null)throw new Error(`Cannot read X.509 public key: `+r.message);this.oid=i.ASN1.parseOID(n.publicKeyOID.bytes);this.algo=a.getOIDName(this.oid);this._pkcs8=t;this._keyRaw=i.ASN1.parseBitString(n.publicKey.bytes).buf;this._finalKey=this._keyRaw;this._finalPEM=``}static fromPEM(e){const t=i.PEM.parse(e)[0];if(t.procType.includes(`ENCRYPTED`))throw new Error(`Could not convert public key from PEM, PEM is encrypted.`);const n=i.ASN1.fromDER(t.body,true);switch(t.type){case`PUBLIC KEY`:return new PublicKey(n);case`RSA PUBLIC KEY`:const e=i.ASN1.Seq([i.ASN1.Seq([i.ASN1.OID(a.getOID(`rsaEncryption`)),i.ASN1.Null()]),i.ASN1.BitString(n.DER)]);return new PublicKey(e);default:throw new Error(`Could not convert public key from PEM, recommend PKCS#8 PEM`)}}static addVerifier(e,t){e=a.getOID(e);if(e===``)throw new Error(`Invalid object identifier: ${e}`);if(PublicKey._verifiers[e]!=null)throw new Error(`Verifier ${e} exists`);PublicKey._verifiers[e]=t}get keyRaw(){return this._finalKey}verify(e,t,r){const i=PublicKey._verifiers[this.oid];if(i!=null){const a=n.createHash(r).update(e).digest();return i.call(this,a,t)}const a=n.createVerify(r);a.update(e);return a.verify(this.toPEM(),t)}getFingerprint(e,t=`PublicKey`){let r;switch(t){case`PublicKeyInfo`:r=this._pkcs8.DER;break;case`PublicKey`:r=this._keyRaw;break;default:throw new Error(`Unknown fingerprint type "${t}".`)}const i=n.createHash(e);i.update(r);return i.digest()}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){if(this._finalPEM===``)this._finalPEM=new i.PEM(`PUBLIC KEY`,this._pkcs8.DER).toString();return this._finalPEM}toJSON(){return{oid:this.oid,algo:this.algo,publicKey:this._keyRaw}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};u._verifiers=Object.create(null);e.PublicKey=u;var d=class PrivateKey{constructor(t){const n=Object.create(null);const o=t.validate(e.privateKeyValidator,n);if(o!=null)throw new Error(`Cannot read X.509 private key: `+o.message);this.version=i.ASN1.parseIntegerNum(n.privateKeyVersion.bytes)+1;this.oid=i.ASN1.parseOID(n.privateKeyOID.bytes);this.algo=a.getOIDName(this.oid);this._pkcs8=t;this._keyRaw=n.privateKey.bytes;this._publicKeyRaw=null;this._finalKey=this._keyRaw;this._finalPEM=``;if(c.includes(this.oid)){this._finalKey=this._keyRaw=i.ASN1.parseDER(this._keyRaw,i.Class.UNIVERSAL,i.Tag.OCTETSTRING).bytes;if(this.oid===`1.3.101.112`){const e=r.sign.keyPair.fromSeed(this._keyRaw);this._publicKeyRaw=Buffer.from(e.publicKey);this._finalKey=Buffer.from(e.secretKey)}else if(this.version===2){for(const e of t.mustCompound())if(e.class===i.Class.CONTEXT_SPECIFIC&&e.tag===1){this._publicKeyRaw=i.ASN1.parseBitString(e.bytes).buf;this._finalKey=Buffer.concat([this._keyRaw,this._publicKeyRaw])}}}}static fromPEM(e){const t=i.PEM.parse(e)[0];if(t.procType.includes(`ENCRYPTED`))throw new Error(`Could not convert private key from PEM, PEM is encrypted.`);let n=i.ASN1.fromDER(t.body,true);switch(t.type){case`PRIVATE KEY`:return new PrivateKey(n);case`RSA PRIVATE KEY`:n=i.ASN1.Seq([n.value[0],i.ASN1.Seq([i.ASN1.OID(a.getOID(`rsaEncryption`)),i.ASN1.Null()]),new i.ASN1(i.Class.UNIVERSAL,i.Tag.OCTETSTRING,n.DER)]);return new PrivateKey(n);default:throw new Error(`Could not convert private key from PEM, recommend PKCS#8 PEM`)}}static addSigner(e,t){e=a.getOID(e);if(e===``)throw new Error(`Invalid object identifier: ${e}`);if(PrivateKey._signers[e]!=null)throw new Error(`Signer ${e} exists`);PrivateKey._signers[e]=t}get keyRaw(){return this._finalKey}get publicKeyRaw(){return this._publicKeyRaw}sign(e,t){const r=PrivateKey._signers[this.oid];if(r!=null){const i=n.createHash(t).update(e).digest();return r.call(this,i)}const i=n.createSign(t);i.update(e);return i.sign(this.toPEM())}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){if(this._finalPEM===``)this._finalPEM=new i.PEM(`PRIVATE KEY`,this._pkcs8.DER).toString();return this._finalPEM}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,privateKey:this._keyRaw,publicKey:this._publicKeyRaw}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};d._signers=Object.create(null);e.PrivateKey=d;var f=class RSAPublicKey extends u{static fromPublicKey(e){return new RSAPublicKey(e.toASN1())}constructor(e){super(e);if(a.getOID(this.oid)!==a.getOID(`rsaEncryption`))throw new Error(`Invalid RSA public key, unknown OID: ${this.oid}`);const t=Object.create(null);this._pkcs1=i.ASN1.fromDER(this._keyRaw,true);const n=this._pkcs1.validate(o,t);if(n!=null)throw new Error(`Cannot read RSA public key: `+n.message);this.modulus=i.ASN1.parseIntegerStr(t.publicKeyModulus.bytes);this.exponent=i.ASN1.parseIntegerNum(t.publicKeyExponent.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){if(this._finalPEM===``)this._finalPEM=new i.PEM(`RSA PUBLIC KEY`,this._keyRaw).toString();return this._finalPEM}toPublicKeyPEM(){return new i.PEM(`PUBLIC KEY`,this._pkcs8.DER).toString()}toJSON(){return{oid:this.oid,algo:this.algo,modulus:trimLeadingZeroByte(this.modulus),exponent:this.exponent}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};e.RSAPublicKey=f;var p=class RSAPrivateKey extends d{static fromPrivateKey(e){return new RSAPrivateKey(e.toASN1())}constructor(e){super(e);if(a.getOID(this.oid)!==a.getOID(`rsaEncryption`))throw new Error(`Invalid RSA private key, unknown OID: ${this.oid}`);const t=Object.create(null);this._pkcs1=i.ASN1.fromDER(this._keyRaw,true);const n=this._pkcs1.validate(s,t);if(n!=null)throw new Error(`Cannot read RSA private key: `+n.message);this.publicExponent=i.ASN1.parseIntegerNum(t.privateKeyPublicExponent.bytes);this.privateExponent=i.ASN1.parseIntegerStr(t.privateKeyPrivateExponent.bytes);this.modulus=i.ASN1.parseIntegerStr(t.privateKeyModulus.bytes);this.prime1=i.ASN1.parseIntegerStr(t.privateKeyPrime1.bytes);this.prime2=i.ASN1.parseIntegerStr(t.privateKeyPrime2.bytes);this.exponent1=i.ASN1.parseIntegerStr(t.privateKeyExponent1.bytes);this.exponent2=i.ASN1.parseIntegerStr(t.privateKeyExponent2.bytes);this.coefficient=i.ASN1.parseIntegerStr(t.privateKeyCoefficient.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){if(this._finalPEM===``)this._finalPEM=new i.PEM(`RSA PRIVATE KEY`,this._keyRaw).toString();return this._finalPEM}toPrivateKeyPEM(){return new i.PEM(`PRIVATE KEY`,this._pkcs8.DER).toString()}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,publicExponent:this.publicExponent,privateExponent:trimLeadingZeroByte(this.privateExponent),modulus:trimLeadingZeroByte(this.modulus),prime1:trimLeadingZeroByte(this.prime1),prime2:trimLeadingZeroByte(this.prime2),exponent1:trimLeadingZeroByte(this.exponent1),exponent2:trimLeadingZeroByte(this.exponent2),coefficient:trimLeadingZeroByte(this.coefficient)}}[t.inspect.custom](e,n){return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};e.RSAPrivateKey=p;function trimLeadingZeroByte(e){return e.length%8!==0&&e.startsWith(`00`)?e.slice(2):e}u.addVerifier(a.getOID(`Ed25519`),function(e,t){return r.sign.detached.verify(e,t,this.keyRaw)});d.addSigner(a.getOID(`Ed25519`),function(e){const t=this.keyRaw;if(t.length!==64)throw new Error(`Invalid signing key.`);return Buffer.from(r.sign.detached(e,t))})}));
//!node_modules/.pnpm/@fidm+x509@1.2.1/node_modules/@fidm/x509/build/x509.js
var require_x509=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=__require(`util`);const n=__require(`crypto`);const r=require_build$1();const i=require_common$1();const a=require_pki();const o=Object.create(null);o.CN=i.getOID(`commonName`);o.commonName=`CN`;o.C=i.getOID(`countryName`);o.countryName=`C`;o.L=i.getOID(`localityName`);o.localityName=`L`;o.ST=i.getOID(`stateOrProvinceName`);o.stateOrProvinceName=`ST`;o.O=i.getOID(`organizationName`);o.organizationName=`O`;o.OU=i.getOID(`organizationalUnitName`);o.organizationalUnitName=`OU`;o.E=i.getOID(`emailAddress`);o.emailAddress=`E`;function getShortName(e){return o[e]==null?``:o[e]}const s={name:`Certificate`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`Certificate.TBSCertificate`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,capture:`tbsCertificate`,value:[{name:`Certificate.TBSCertificate.version`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.NONE,optional:true,value:[{name:`Certificate.TBSCertificate.version.integer`,class:r.Class.UNIVERSAL,tag:r.Tag.INTEGER,capture:`certVersion`}]},{name:`Certificate.TBSCertificate.serialNumber`,class:r.Class.UNIVERSAL,tag:r.Tag.INTEGER,capture:`certSerialNumber`},{name:`Certificate.TBSCertificate.signature`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`Certificate.TBSCertificate.signature.algorithm`,class:r.Class.UNIVERSAL,tag:r.Tag.OID,capture:`certinfoSignatureOID`},{name:`Certificate.TBSCertificate.signature.parameters`,class:r.Class.UNIVERSAL,tag:r.Tag.OCTETSTRING,optional:true,capture:`certinfoSignatureParams`}]},{name:`Certificate.TBSCertificate.issuer`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,capture:`certIssuer`},{name:`Certificate.TBSCertificate.validity`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`Certificate.TBSCertificate.validity.notBefore`,class:r.Class.UNIVERSAL,tag:[r.Tag.UTCTIME,r.Tag.GENERALIZEDTIME],capture:`certValidityNotBefore`},{name:`Certificate.TBSCertificate.validity.notAfter`,class:r.Class.UNIVERSAL,tag:[r.Tag.UTCTIME,r.Tag.GENERALIZEDTIME],capture:`certValidityNotAfter`}]},{name:`Certificate.TBSCertificate.subject`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,capture:`certSubject`},a.publicKeyValidator,{name:`Certificate.TBSCertificate.issuerUniqueID`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.BOOLEAN,optional:true,value:[{name:`Certificate.TBSCertificate.issuerUniqueID.id`,class:r.Class.UNIVERSAL,tag:r.Tag.BITSTRING,capture:`certIssuerUniqueId`}]},{name:`Certificate.TBSCertificate.subjectUniqueID`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.INTEGER,optional:true,value:[{name:`Certificate.TBSCertificate.subjectUniqueID.id`,class:r.Class.UNIVERSAL,tag:r.Tag.BITSTRING,capture:`certSubjectUniqueId`}]},{name:`Certificate.TBSCertificate.extensions`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.BITSTRING,capture:`certExtensions`,optional:true}]},{name:`Certificate.signatureAlgorithm`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`Certificate.signatureAlgorithm.algorithm`,class:r.Class.UNIVERSAL,tag:r.Tag.OID,capture:`certSignatureOID`},{name:`Certificate.TBSCertificate.signature.parameters`,class:r.Class.UNIVERSAL,tag:r.Tag.OCTETSTRING,optional:true,capture:`certSignatureParams`}]},{name:`Certificate.signatureValue`,class:r.Class.UNIVERSAL,tag:r.Tag.BITSTRING,capture:`certSignature`}]};var DistinguishedName=class{constructor(){this.attributes=[];this.uniqueId=null}get commonName(){return this.getFieldValue(`commonName`)}get organizationName(){return this.getFieldValue(`organizationName`)}get organizationalUnitName(){return this.getFieldValue(`organizationalUnitName`)}get countryName(){return this.getFieldValue(`countryName`)}get localityName(){return this.getFieldValue(`localityName`)}get serialName(){return this.getFieldValue(`serialName`)}getHash(){const e=n.createHash(`sha1`);for(const t of this.attributes){e.update(t.oid);e.update(t.value)}return e.digest()}getField(e){for(const t of this.attributes)if(e===t.oid||e===t.name||e===t.shortName)return t;return null}addField(e){fillMissingFields([e]);this.attributes.push(e)}setAttrs(e){fillMissingFields(e);this.attributes=e}toJSON(){const e={};for(const t of this.attributes){const n=t.shortName;if(typeof n===`string`&&n!==``)e[n]=t.value}e.uniqueId=this.uniqueId;e.attributes=this.attributes;return e}getFieldValue(e){const t=this.getField(e);if(t!=null)return t.value;return``}};e.DistinguishedName=DistinguishedName;var c=class Certificate{static fromPEMs(e){const t=[];const n=r.PEM.parse(e);for(const e of n){if(e.type!==`CERTIFICATE`&&e.type!==`X509 CERTIFICATE`&&e.type!==`TRUSTED CERTIFICATE`)throw new Error(`Could not convert certificate from PEM: invalid type`);if(e.procType.includes(`ENCRYPTED`))throw new Error(`Could not convert certificate from PEM: PEM is encrypted.`);const n=r.ASN1.fromDER(e.body);t.push(new Certificate(n))}if(t.length===0)throw new Error(`No Certificate`);return t}static fromPEM(e){return Certificate.fromPEMs(e)[0]}constructor(e){const t=Object.create(null);const n=e.validate(s,t);if(n!=null)throw new Error(`Cannot read X.509 certificate: `+n.message);this.raw=e.DER;this.version=t.certVersion==null?0:r.ASN1.parseIntegerNum(t.certVersion.bytes)+1;this.serialNumber=r.ASN1.parseIntegerStr(t.certSerialNumber.bytes);this.signatureOID=r.ASN1.parseOID(t.certSignatureOID.bytes);this.signatureAlgorithm=i.getOIDName(this.signatureOID);this.infoSignatureOID=r.ASN1.parseOID(t.certinfoSignatureOID.bytes);this.signature=r.ASN1.parseBitString(t.certSignature.bytes).buf;this.validFrom=r.ASN1.parseTime(t.certValidityNotBefore.tag,t.certValidityNotBefore.bytes);this.validTo=r.ASN1.parseTime(t.certValidityNotAfter.tag,t.certValidityNotAfter.bytes);this.issuer=new DistinguishedName;this.issuer.setAttrs(RDNAttributesAsArray(t.certIssuer));if(t.certIssuerUniqueId!=null)this.issuer.uniqueId=r.ASN1.parseBitString(t.certIssuerUniqueId.bytes);this.subject=new DistinguishedName;this.subject.setAttrs(RDNAttributesAsArray(t.certSubject));if(t.certSubjectUniqueId!=null)this.subject.uniqueId=r.ASN1.parseBitString(t.certSubjectUniqueId.bytes);this.extensions=[];this.subjectKeyIdentifier=``;this.authorityKeyIdentifier=``;this.ocspServer=``;this.issuingCertificateURL=``;this.isCA=false;this.maxPathLen=-1;this.basicConstraintsValid=false;this.keyUsage=0;this.dnsNames=[];this.emailAddresses=[];this.ipAddresses=[];this.uris=[];if(t.certExtensions!=null){this.extensions=certificateExtensionsFromAsn1(t.certExtensions);for(const e of this.extensions){if(typeof e.subjectKeyIdentifier===`string`)this.subjectKeyIdentifier=e.subjectKeyIdentifier;if(typeof e.authorityKeyIdentifier===`string`)this.authorityKeyIdentifier=e.authorityKeyIdentifier;if(typeof e.authorityInfoAccessOcsp===`string`)this.ocspServer=e.authorityInfoAccessOcsp;if(typeof e.authorityInfoAccessIssuers===`string`)this.issuingCertificateURL=e.authorityInfoAccessIssuers;if(typeof e.basicConstraintsValid===`boolean`){this.isCA=e.isCA;this.maxPathLen=e.maxPathLen;this.basicConstraintsValid=e.basicConstraintsValid}if(typeof e.keyUsage===`number`)this.keyUsage=e.keyUsage;if(Array.isArray(e.altNames))for(const t of e.altNames){if(t.dnsName!=null)this.dnsNames.push(t.dnsName);if(t.email!=null)this.emailAddresses.push(t.email);if(t.ip!=null)this.ipAddresses.push(t.ip);if(t.uri!=null)this.uris.push(t.uri)}}}this.publicKey=new a.PublicKey(t.publicKeyInfo);this.publicKeyRaw=this.publicKey.toDER();this.tbsCertificate=t.tbsCertificate}getExtension(e,t=``){for(const n of this.extensions)if(e===n.oid||e===n.name)return t===``?n:n[t];return null}checkSignature(e){if(this.version===3&&!this.basicConstraintsValid||this.basicConstraintsValid&&!this.isCA)return/* @__PURE__ */ new Error(`The parent constraint violation error`);if(this.getExtension(`keyUsage`,`keyCertSign`)!==true)return/* @__PURE__ */ new Error(`The parent constraint violation error`);if(!e.isIssuer(this))return/* @__PURE__ */ new Error(`The parent certificate did not issue the given child certificate`);const t=getHashAgl(e.signatureOID);if(t===``)return/* @__PURE__ */ new Error(`Unknown child signature OID.`);if(this.publicKey.verify(e.tbsCertificate.DER,e.signature,t)===false)return/* @__PURE__ */ new Error(`Child signature not matched`);return null}isIssuer(e){return this.issuer.getHash().equals(e.subject.getHash())}verifySubjectKeyIdentifier(){return this.publicKey.getFingerprint(`sha1`,`PublicKey`).toString(`hex`)===this.subjectKeyIdentifier}toJSON(){const e={};for(const t of Object.keys(this))e[t]=toJSONify(this[t]);delete e.tbsCertificate;return e}[t.inspect.custom](e,n){if(n.depth<=2)n.depth=10;return`<${this.constructor.name} ${t.inspect(this.toJSON(),n)}>`}};e.Certificate=c;function certificateExtensionsFromAsn1(e){const t=[];for(const n of e.mustCompound())for(const e of n.mustCompound())t.push(certificateExtensionFromAsn1(e));return t}function certificateExtensionFromAsn1(e){const t={};t.oid=r.ASN1.parseOID(e.value[0].bytes);t.critical=false;if(e.value[1].tag===r.Tag.BOOLEAN){t.critical=r.ASN1.parseBool(e.value[1].bytes);t.value=e.value[2].bytes}else t.value=e.value[1].bytes;t.name=i.getOIDName(t.oid);switch(t.name){case`keyUsage`:decodeExtKeyUsage(t);break;case`basicConstraints`:decodeExtBasicConstraints(t);break;case`extKeyUsage`:decodeExtExtKeyUsage(t);break;case`nsCertType`:decodeExtNsCertType(t);break;case`subjectAltName`:decodeExtAltName(t);break;case`issuerAltName`:decodeExtAltName(t);break;case`subjectKeyIdentifier`:decodeExtSubjectKeyIdentifier(t);break;case`authorityKeyIdentifier`:decodeExtAuthorityKeyIdentifier(t);break;case`authorityInfoAccess`:decodeExtAuthorityInfoAccess(t)}return t}function decodeExtKeyUsage(e){const t=r.ASN1.parseBitString(r.ASN1.fromDER(e.value).bytes);let n=0;let i=0;e.keyUsage=0;for(let n=0;n<9;n++)if(t.at(n)!==0)e.keyUsage|=1<<n;if(t.buf.length>0){n=t.buf[0];i=t.buf.length>1?t.buf[1]:0}e.digitalSignature=(n&128)===128;e.nonRepudiation=(n&64)===64;e.keyEncipherment=(n&32)===32;e.dataEncipherment=(n&16)===16;e.keyAgreement=(n&8)===8;e.keyCertSign=(n&4)===4;e.cRLSign=(n&2)===2;e.encipherOnly=(n&1)===1;e.decipherOnly=(i&128)===128}function decodeExtBasicConstraints(e){const t=r.ASN1.fromDER(e.value).mustCompound();if(t.length>0&&t[0].tag===r.Tag.BOOLEAN)e.isCA=r.ASN1.parseBool(t[0].bytes);else e.isCA=false;let n=null;if(t.length>0&&t[0].tag===r.Tag.INTEGER)n=t[0].bytes;else if(t.length>1)n=t[1].bytes;if(n!==null)e.maxPathLen=r.ASN1.parseInteger(n);else e.maxPathLen=-1;e.basicConstraintsValid=true}function decodeExtExtKeyUsage(e){const t=r.ASN1.fromDER(e.value).mustCompound();for(const n of t)e[i.getOIDName(r.ASN1.parseOID(n.bytes))]=true}function decodeExtNsCertType(e){const t=r.ASN1.parseBitString(r.ASN1.fromDER(e.value).bytes);let n=0;if(t.buf.length>0)n=t.buf[0];e.client=(n&128)===128;e.server=(n&64)===64;e.email=(n&32)===32;e.objsign=(n&16)===16;e.reserved=(n&8)===8;e.sslCA=(n&4)===4;e.emailCA=(n&2)===2;e.objCA=(n&1)===1}function decodeExtAltName(e){e.altNames=[];const t=r.ASN1.fromDER(e.value).mustCompound();for(const n of t){const t={tag:n.tag,value:n.bytes};e.altNames.push(t);switch(n.tag){case 1:t.email=n.bytes.toString();break;case 2:t.dnsName=n.bytes.toString();break;case 6:t.uri=n.bytes.toString();break;case 7:t.ip=i.bytesToIP(n.bytes);break;case 8:t.oid=r.ASN1.parseOID(n.bytes)}}}const u={name:`subjectKeyIdentifier`,class:r.Class.UNIVERSAL,tag:r.Tag.OCTETSTRING,capture:`subjectKeyIdentifier`};function decodeExtSubjectKeyIdentifier(e){e.subjectKeyIdentifier=r.ASN1.parseDERWithTemplate(e.value,u).subjectKeyIdentifier.bytes.toString(`hex`)}const d={name:`authorityKeyIdentifier`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`authorityKeyIdentifier.value`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.NONE,capture:`authorityKeyIdentifier`}]};function decodeExtAuthorityKeyIdentifier(e){e.authorityKeyIdentifier=r.ASN1.parseDERWithTemplate(e.value,d).authorityKeyIdentifier.bytes.toString(`hex`)}const f={name:`authorityInfoAccess`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,value:[{name:`authorityInfoAccess.authorityInfoAccessOcsp`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,optional:true,value:[{name:`authorityInfoAccess.authorityInfoAccessOcsp.oid`,class:r.Class.UNIVERSAL,tag:r.Tag.OID},{name:`authorityInfoAccess.authorityInfoAccessOcsp.value`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.OID,capture:`authorityInfoAccessOcsp`}]},{name:`authorityInfoAccess.authorityInfoAccessIssuers`,class:r.Class.UNIVERSAL,tag:r.Tag.SEQUENCE,optional:true,value:[{name:`authorityInfoAccess.authorityInfoAccessIssuers.oid`,class:r.Class.UNIVERSAL,tag:r.Tag.OID},{name:`authorityInfoAccess.authorityInfoAccessIssuers.value`,class:r.Class.CONTEXT_SPECIFIC,tag:r.Tag.OID,capture:`authorityInfoAccessIssuers`}]}]};function decodeExtAuthorityInfoAccess(e){const t=r.ASN1.parseDERWithTemplate(e.value,f);if(t.authorityInfoAccessOcsp!=null)e.authorityInfoAccessOcsp=t.authorityInfoAccessOcsp.bytes.toString();if(t.authorityInfoAccessIssuers!=null)e.authorityInfoAccessIssuers=t.authorityInfoAccessIssuers.bytes.toString()}function fillMissingFields(e){for(const t of e){if(t.name==null||t.name===``){if(t.oid!=null)t.name=i.getOIDName(t.oid);if(t.name===``&&t.shortName!=null)t.name=i.getOIDName(o[t.shortName])}if(t.oid==null||t.oid===``){if(t.name!==``)t.oid=i.getOID(t.name);else throw new Error(`Attribute oid not specified.`)}if(t.shortName==null||t.shortName===``)t.shortName=o[t.name]==null?``:o[t.name];if(t.value==null)throw new Error(`Attribute value not specified.`)}}function getHashAgl(e){switch(i.getOIDName(e)){case`sha1WithRsaEncryption`:return`sha1`;case`md5WithRsaEncryption`:return`md5`;case`sha256WithRsaEncryption`:return`sha256`;case`sha384WithRsaEncryption`:return`sha384`;case`sha512WithRsaEncryption`:return`sha512`;case`RSASSA-PSS`:return`sha256`;case`ecdsaWithSha1`:return`sha1`;case`ecdsaWithSha256`:return`sha256`;case`ecdsaWithSha384`:return`sha384`;case`ecdsaWithSha512`:return`sha512`;case`dsaWithSha1`:return`sha1`;case`dsaWithSha256`:return`sha256`;default:return``}}function RDNAttributesAsArray(e){const t=[];for(const n of e.mustCompound())for(const e of n.mustCompound()){const n=e.mustCompound();const a={};a.oid=r.ASN1.parseOID(n[0].bytes);a.value=n[1].value;a.valueTag=n[1].tag;a.name=i.getOIDName(a.oid);a.shortName=getShortName(a.name);t.push(a)}return t}function toJSONify(e){if(e!=null&&!(e instanceof Buffer)&&typeof e.toJSON===`function`)return e.toJSON();return e}}));
//!node_modules/.pnpm/@fidm+x509@1.2.1/node_modules/@fidm/x509/build/index.js
var require_build=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});var t=require_common$1();e.bytesFromIP=t.bytesFromIP;e.bytesToIP=t.bytesToIP;e.getOID=t.getOID;e.getOIDName=t.getOIDName;var n=require_pki();e.PublicKey=n.PublicKey;e.PrivateKey=n.PrivateKey;e.RSAPublicKey=n.RSAPublicKey;e.RSAPrivateKey=n.RSAPrivateKey;var r=require_x509();e.Certificate=r.Certificate;e.DistinguishedName=r.DistinguishedName}));
//!node_modules/.pnpm/reflect-metadata@0.2.2/node_modules/reflect-metadata/Reflect.js
var require_Reflect=/* @__PURE__ */ __commonJSMin((()=>{
/*! *****************************************************************************
Copyright (C) Microsoft. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
var e;(function(e){(function(t){var n=typeof globalThis===`object`?globalThis:typeof global===`object`?global:typeof self===`object`?self:typeof this===`object`?this:sloppyModeThis();var r=makeExporter(e);if(typeof n.Reflect!==`undefined`)r=makeExporter(n.Reflect,r);t(r,n);if(typeof n.Reflect===`undefined`)n.Reflect=e;function makeExporter(e,t){return function(n,r){Object.defineProperty(e,n,{configurable:true,writable:true,value:r});if(t)t(n,r)}}function functionThis(){try{return Function(`return this;`)()}catch(e){}}function indirectEvalThis(){try{return(0,eval)(`(function() { return this; })()`)}catch(e){}}function sloppyModeThis(){return functionThis()||indirectEvalThis()}})(function(e,t){var n=Object.prototype.hasOwnProperty;var r=typeof Symbol===`function`;var i=r&&typeof Symbol.toPrimitive!==`undefined`?Symbol.toPrimitive:`@@toPrimitive`;var a=r&&typeof Symbol.iterator!==`undefined`?Symbol.iterator:`@@iterator`;var o=typeof Object.create===`function`;var s={__proto__:[]}instanceof Array;var c=!o&&!s;var u={create:o?function(){return MakeDictionary(Object.create(null))}:s?function(){return MakeDictionary({__proto__:null})}:function(){return MakeDictionary({})},has:c?function(e,t){return n.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return n.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}};var d=Object.getPrototypeOf(Function);var f=typeof Map===`function`&&typeof Map.prototype.entries===`function`?Map:CreateMapPolyfill();var p=typeof Set===`function`&&typeof Set.prototype.entries===`function`?Set:CreateSetPolyfill();var m=typeof WeakMap===`function`?WeakMap:CreateWeakMapPolyfill();var g=r?Symbol.for(`@reflect-metadata:registry`):void 0;var _=GetOrCreateMetadataRegistry();var v=CreateMetadataProvider(_);function decorate(e,t,n,r){if(!IsUndefined(n)){if(!IsArray(e))throw new TypeError;if(!IsObject(t))throw new TypeError;if(!IsObject(r)&&!IsUndefined(r)&&!IsNull(r))throw new TypeError;if(IsNull(r))r=void 0;n=ToPropertyKey(n);return DecorateProperty(e,t,n,r)}else{if(!IsArray(e))throw new TypeError;if(!IsConstructor(t))throw new TypeError;return DecorateConstructor(e,t)}}e(`decorate`,decorate);function metadata(e,t){function decorator(n,r){if(!IsObject(n))throw new TypeError;if(!IsUndefined(r)&&!IsPropertyKey(r))throw new TypeError;OrdinaryDefineOwnMetadata(e,t,n,r)}return decorator}e(`metadata`,metadata);function defineMetadata(e,t,n,r){if(!IsObject(n))throw new TypeError;if(!IsUndefined(r))r=ToPropertyKey(r);return OrdinaryDefineOwnMetadata(e,t,n,r)}e(`defineMetadata`,defineMetadata);function hasMetadata(e,t,n){if(!IsObject(t))throw new TypeError;if(!IsUndefined(n))n=ToPropertyKey(n);return OrdinaryHasMetadata(e,t,n)}e(`hasMetadata`,hasMetadata);function hasOwnMetadata(e,t,n){if(!IsObject(t))throw new TypeError;if(!IsUndefined(n))n=ToPropertyKey(n);return OrdinaryHasOwnMetadata(e,t,n)}e(`hasOwnMetadata`,hasOwnMetadata);function getMetadata(e,t,n){if(!IsObject(t))throw new TypeError;if(!IsUndefined(n))n=ToPropertyKey(n);return OrdinaryGetMetadata(e,t,n)}e(`getMetadata`,getMetadata);function getOwnMetadata(e,t,n){if(!IsObject(t))throw new TypeError;if(!IsUndefined(n))n=ToPropertyKey(n);return OrdinaryGetOwnMetadata(e,t,n)}e(`getOwnMetadata`,getOwnMetadata);function getMetadataKeys(e,t){if(!IsObject(e))throw new TypeError;if(!IsUndefined(t))t=ToPropertyKey(t);return OrdinaryMetadataKeys(e,t)}e(`getMetadataKeys`,getMetadataKeys);function getOwnMetadataKeys(e,t){if(!IsObject(e))throw new TypeError;if(!IsUndefined(t))t=ToPropertyKey(t);return OrdinaryOwnMetadataKeys(e,t)}e(`getOwnMetadataKeys`,getOwnMetadataKeys);function deleteMetadata(e,t,n){if(!IsObject(t))throw new TypeError;if(!IsUndefined(n))n=ToPropertyKey(n);if(!IsObject(t))throw new TypeError;if(!IsUndefined(n))n=ToPropertyKey(n);var r=GetMetadataProvider(t,n,false);if(IsUndefined(r))return false;return r.OrdinaryDeleteMetadata(e,t,n)}e(`deleteMetadata`,deleteMetadata);function DecorateConstructor(e,t){for(var n=e.length-1;n>=0;--n){var r=e[n];var i=r(t);if(!IsUndefined(i)&&!IsNull(i)){if(!IsConstructor(i))throw new TypeError;t=i}}return t}function DecorateProperty(e,t,n,r){for(var i=e.length-1;i>=0;--i){var a=e[i];var o=a(t,n,r);if(!IsUndefined(o)&&!IsNull(o)){if(!IsObject(o))throw new TypeError;r=o}}return r}function OrdinaryHasMetadata(e,t,n){if(OrdinaryHasOwnMetadata(e,t,n))return true;var r=OrdinaryGetPrototypeOf(t);if(!IsNull(r))return OrdinaryHasMetadata(e,r,n);return false}function OrdinaryHasOwnMetadata(e,t,n){var r=GetMetadataProvider(t,n,false);if(IsUndefined(r))return false;return ToBoolean(r.OrdinaryHasOwnMetadata(e,t,n))}function OrdinaryGetMetadata(e,t,n){if(OrdinaryHasOwnMetadata(e,t,n))return OrdinaryGetOwnMetadata(e,t,n);var r=OrdinaryGetPrototypeOf(t);if(!IsNull(r))return OrdinaryGetMetadata(e,r,n)}function OrdinaryGetOwnMetadata(e,t,n){var r=GetMetadataProvider(t,n,false);if(IsUndefined(r))return;return r.OrdinaryGetOwnMetadata(e,t,n)}function OrdinaryDefineOwnMetadata(e,t,n,r){GetMetadataProvider(n,r,true).OrdinaryDefineOwnMetadata(e,t,n,r)}function OrdinaryMetadataKeys(e,t){var n=OrdinaryOwnMetadataKeys(e,t);var r=OrdinaryGetPrototypeOf(e);if(r===null)return n;var i=OrdinaryMetadataKeys(r,t);if(i.length<=0)return n;if(n.length<=0)return i;var a=new p;var o=[];for(var s=0,c=n;s<c.length;s++){var u=c[s];var d=a.has(u);if(!d){a.add(u);o.push(u)}}for(var f=0,m=i;f<m.length;f++){var u=m[f];var d=a.has(u);if(!d){a.add(u);o.push(u)}}return o}function OrdinaryOwnMetadataKeys(e,t){var n=GetMetadataProvider(e,t,false);if(!n)return[];return n.OrdinaryOwnMetadataKeys(e,t)}function Type(e){if(e===null)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 e===null?1:6;default:return 6}}function IsUndefined(e){return e===void 0}function IsNull(e){return e===null}function IsSymbol(e){return typeof e===`symbol`}function IsObject(e){return typeof e===`object`?e!==null:typeof e===`function`}function ToPrimitive(e,t){switch(Type(e)){case 0:return e;case 1:return e;case 2:return e;case 3:return e;case 4:return e;case 5:return e}var n=t===3?`string`:t===5?`number`:`default`;var r=GetMethod(e,i);if(r!==void 0){var a=r.call(e,n);if(IsObject(a))throw new TypeError;return a}return OrdinaryToPrimitive(e,n==="default"?`number`:n)}function OrdinaryToPrimitive(e,t){if(t===`string`){var n=e.toString;if(IsCallable(n)){var r=n.call(e);if(!IsObject(r))return r}var i=e.valueOf;if(IsCallable(i)){var r=i.call(e);if(!IsObject(r))return r}}else{var i=e.valueOf;if(IsCallable(i)){var r=i.call(e);if(!IsObject(r))return r}var a=e.toString;if(IsCallable(a)){var r=a.call(e);if(!IsObject(r))return r}}throw new TypeError}function ToBoolean(e){return!!e}function ToString(e){return``+e}function ToPropertyKey(e){var t=ToPrimitive(e,3);if(IsSymbol(t))return t;return ToString(t)}function IsArray(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:Object.prototype.toString.call(e)===`[object Array]`}function IsCallable(e){return typeof e===`function`}function IsConstructor(e){return typeof e===`function`}function IsPropertyKey(e){switch(Type(e)){case 3:return true;case 4:return true;default:return false}}function SameValueZero(e,t){return e===t||e!==e&&t!==t}function GetMethod(e,t){var n=e[t];if(n===void 0||n===null)return void 0;if(!IsCallable(n))throw new TypeError;return n}function GetIterator(e){var t=GetMethod(e,a);if(!IsCallable(t))throw new TypeError;var n=t.call(e);if(!IsObject(n))throw new TypeError;return n}function IteratorValue(e){return e.value}function IteratorStep(e){var t=e.next();return t.done?false:t}function IteratorClose(e){var t=e[`return`];if(t)t.call(e)}function OrdinaryGetPrototypeOf(e){var t=Object.getPrototypeOf(e);if(typeof e!==`function`||e===d)return t;if(t!==d)return t;var n=e.prototype;var r=n&&Object.getPrototypeOf(n);if(r==null||r===Object.prototype)return t;var i=r.constructor;if(typeof i!==`function`)return t;if(i===e)return t;return i}function CreateMetadataRegistry(){var e;if(!IsUndefined(g)&&typeof t.Reflect!==`undefined`&&!(g in t.Reflect)&&typeof t.Reflect.defineMetadata===`function`)e=CreateFallbackProvider(t.Reflect);var n;var r;var i;var a=new m;var o={registerProvider,getProvider,setProvider};return o;function registerProvider(t){if(!Object.isExtensible(o))throw new Error(`Cannot add provider to a frozen registry.`);switch(true){case e===t:break;case IsUndefined(n):n=t;break;case n===t:break;case IsUndefined(r):r=t;break;case r===t:break;default:if(i===void 0)i=new p;i.add(t)}}function getProviderNoCache(t,a){if(!IsUndefined(n)){if(n.isProviderFor(t,a))return n;if(!IsUndefined(r)){if(r.isProviderFor(t,a))return n;if(!IsUndefined(i)){var o=GetIterator(i);while(true){var s=IteratorStep(o);if(!s)return;var c=IteratorValue(s);if(c.isProviderFor(t,a)){IteratorClose(o);return c}}}}}if(!IsUndefined(e)&&e.isProviderFor(t,a))return e}function getProvider(e,t){var n=a.get(e);var r;if(!IsUndefined(n))r=n.get(t);if(!IsUndefined(r))return r;r=getProviderNoCache(e,t);if(!IsUndefined(r)){if(IsUndefined(n)){n=new f;a.set(e,n)}n.set(t,r)}return r}function hasProvider(e){if(IsUndefined(e))throw new TypeError;return n===e||r===e||!IsUndefined(i)&&i.has(e)}function setProvider(e,t,n){if(!hasProvider(n))throw new Error(`Metadata provider not registered.`);var r=getProvider(e,t);if(r!==n){if(!IsUndefined(r))return false;var i=a.get(e);if(IsUndefined(i)){i=new f;a.set(e,i)}i.set(t,n)}return true}}function GetOrCreateMetadataRegistry(){var e;if(!IsUndefined(g)&&IsObject(t.Reflect)&&Object.isExtensible(t.Reflect))e=t.Reflect[g];if(IsUndefined(e))e=CreateMetadataRegistry();if(!IsUndefined(g)&&IsObject(t.Reflect)&&Object.isExtensible(t.Reflect))Object.defineProperty(t.Reflect,g,{enumerable:false,configurable:false,writable:false,value:e});return e}function CreateMetadataProvider(e){var t=new m;var n={isProviderFor:function(e,n){var r=t.get(e);if(IsUndefined(r))return false;return r.has(n)},OrdinaryDefineOwnMetadata,OrdinaryHasOwnMetadata,OrdinaryGetOwnMetadata,OrdinaryOwnMetadataKeys,OrdinaryDeleteMetadata};_.registerProvider(n);return n;function GetOrCreateMetadataMap(r,i,a){var o=t.get(r);var s=false;if(IsUndefined(o)){if(!a)return void 0;o=new f;t.set(r,o);s=true}var c=o.get(i);if(IsUndefined(c)){if(!a)return void 0;c=new f;o.set(i,c);if(!e.setProvider(r,i,n)){o.delete(i);if(s)t.delete(r);throw new Error(`Wrong provider for target.`)}}return c}function OrdinaryHasOwnMetadata(e,t,n){var r=GetOrCreateMetadataMap(t,n,false);if(IsUndefined(r))return false;return ToBoolean(r.has(e))}function OrdinaryGetOwnMetadata(e,t,n){var r=GetOrCreateMetadataMap(t,n,false);if(IsUndefined(r))return void 0;return r.get(e)}function OrdinaryDefineOwnMetadata(e,t,n,r){GetOrCreateMetadataMap(n,r,true).set(e,t)}function OrdinaryOwnMetadataKeys(e,t){var n=[];var r=GetOrCreateMetadataMap(e,t,false);if(IsUndefined(r))return n;var i=GetIterator(r.keys());var a=0;while(true){var o=IteratorStep(i);if(!o){n.length=a;return n}var s=IteratorValue(o);try{n[a]=s}catch(e){try{IteratorClose(i)}finally{throw e}}a++}}function OrdinaryDeleteMetadata(e,n,r){var i=GetOrCreateMetadataMap(n,r,false);if(IsUndefined(i))return false;if(!i.delete(e))return false;if(i.size===0){var a=t.get(n);if(!IsUndefined(a)){a.delete(r);if(a.size===0)t.delete(a)}}return true}}function CreateFallbackProvider(e){var t=e.defineMetadata,n=e.hasOwnMetadata,r=e.getOwnMetadata,i=e.getOwnMetadataKeys,a=e.deleteMetadata;var o=new m;return{isProviderFor:function(e,t){var n=o.get(e);if(!IsUndefined(n)&&n.has(t))return true;if(i(e,t).length){if(IsUndefined(n)){n=new p;o.set(e,n)}n.add(t);return true}return false},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:n,OrdinaryGetOwnMetadata:r,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:a}}function GetMetadataProvider(e,t,n){var r=_.getProvider(e,t);if(!IsUndefined(r))return r;if(n){if(_.setProvider(e,t,v))return v;throw new Error(`Illegal state.`)}}function CreateMapPolyfill(){var e={};var t=[];var n=function(){function MapIterator(e,t,n){this._index=0;this._keys=e;this._values=t;this._selector=n}MapIterator.prototype[`@@iterator`]=function(){return this};MapIterator.prototype[a]=function(){return this};MapIterator.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var n=this._selector(this._keys[e],this._values[e]);if(e+1>=this._keys.length){this._index=-1;this._keys=t;this._values=t}else this._index++;return{value:n,done:false}}return{value:void 0,done:true}};MapIterator.prototype.throw=function(e){if(this._index>=0){this._index=-1;this._keys=t;this._values=t}throw e};MapIterator.prototype.return=function(e){if(this._index>=0){this._index=-1;this._keys=t;this._values=t}return{value:e,done:true}};return MapIterator}();return function(){function Map(){this._keys=[];this._values=[];this._cacheKey=e;this._cacheIndex=-2}Object.defineProperty(Map.prototype,"size",{get:function(){return this._keys.length},enumerable:true,configurable:true});Map.prototype.has=function(e){return this._find(e,false)>=0};Map.prototype.get=function(e){var t=this._find(e,false);return t>=0?this._values[t]:void 0};Map.prototype.set=function(e,t){var n=this._find(e,true);this._values[n]=t;return this};Map.prototype.delete=function(t){var n=this._find(t,false);if(n>=0){var r=this._keys.length;for(var i=n+1;i<r;i++){this._keys[i-1]=this._keys[i];this._values[i-1]=this._values[i]}this._keys.length--;this._values.length--;if(SameValueZero(t,this._cacheKey)){this._cacheKey=e;this._cacheIndex=-2}return true}return false};Map.prototype.clear=function(){this._keys.length=0;this._values.length=0;this._cacheKey=e;this._cacheIndex=-2};Map.prototype.keys=function(){return new n(this._keys,this._values,getKey)};Map.prototype.values=function(){return new n(this._keys,this._values,getValue)};Map.prototype.entries=function(){return new n(this._keys,this._values,getEntry)};Map.prototype[`@@iterator`]=function(){return this.entries()};Map.prototype[a]=function(){return this.entries()};Map.prototype._find=function(e,t){if(!SameValueZero(this._cacheKey,e)){this._cacheIndex=-1;for(var n=0;n<this._keys.length;n++)if(SameValueZero(this._keys[n],e)){this._cacheIndex=n;break}}if(this._cacheIndex<0&&t){this._cacheIndex=this._keys.length;this._keys.push(e);this._values.push(void 0)}return this._cacheIndex};return Map}();function getKey(e,t){return e}function getValue(e,t){return t}function getEntry(e,t){return[e,t]}}function CreateSetPolyfill(){return function(){function Set(){this._map=new f}Object.defineProperty(Set.prototype,"size",{get:function(){return this._map.size},enumerable:true,configurable:true});Set.prototype.has=function(e){return this._map.has(e)};Set.prototype.add=function(e){return this._map.set(e,e),this};Set.prototype.delete=function(e){return this._map.delete(e)};Set.prototype.clear=function(){this._map.clear()};Set.prototype.keys=function(){return this._map.keys()};Set.prototype.values=function(){return this._map.keys()};Set.prototype.entries=function(){return this._map.entries()};Set.prototype[`@@iterator`]=function(){return this.keys()};Set.prototype[a]=function(){return this.keys()};return Set}()}function CreateWeakMapPolyfill(){var e=16;var t=u.create();var r=CreateUniqueKey();return function(){function WeakMap(){this._key=CreateUniqueKey()}WeakMap.prototype.has=function(e){var t=GetOrCreateWeakMapTable(e,false);return t!==void 0?u.has(t,this._key):false};WeakMap.prototype.get=function(e){var t=GetOrCreateWeakMapTable(e,false);return t!==void 0?u.get(t,this._key):void 0};WeakMap.prototype.set=function(e,t){var n=GetOrCreateWeakMapTable(e,true);n[this._key]=t;return this};WeakMap.prototype.delete=function(e){var t=GetOrCreateWeakMapTable(e,false);return t!==void 0?delete t[this._key]:false};WeakMap.prototype.clear=function(){this._key=CreateUniqueKey()};return WeakMap}();function CreateUniqueKey(){var e;do e=`@@WeakMap@@`+CreateUUID();while(u.has(t,e));t[e]=true;return e}function GetOrCreateWeakMapTable(e,t){if(!n.call(e,r)){if(!t)return void 0;Object.defineProperty(e,r,{value:u.create()})}return e[r]}function FillRandomBytes(e,t){for(var n=0;n<t;++n)e[n]=Math.random()*255|0;return e}function GenRandomBytes(e){if(typeof Uint8Array===`function`){var t=new Uint8Array(e);if(typeof crypto!==`undefined`)crypto.getRandomValues(t);else if(typeof msCrypto!==`undefined`)msCrypto.getRandomValues(t);else FillRandomBytes(t,e);return t}return FillRandomBytes(new Array(e),e)}function CreateUUID(){var t=GenRandomBytes(e);t[6]=t[6]&79|64;t[8]=t[8]&191|128;var n=``;for(var r=0;r<e;++r){var i=t[r];if(r===4||r===6||r===8)n+=`-`;if(i<16)n+=`0`;n+=i.toString(16).toLowerCase()}return n}}function MakeDictionary(e){e.__=void 0;delete e.__;return e}})})(e||(e={}))}));
//!node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/pem/pem.js
var require_pem$1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.pemConverter=e.pem=void 0;e.encode=encode;e.encodeMany=encodeMany;e.decode=decode;e.find=find;e.findAll=findAll;e.decodeFirst=decodeFirst;e.parse=parse;e.format=format;const t=require_base64();const n=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i;const r=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function assertLabel(e){if(!n.test(e))throw new TypeError(`Invalid PEM label '${e}'`)}function wrap(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function parseBody(e){const t=e.trim().replace(/\r\n/g,`
`).split(`
`).map(e=>e.trim()).filter(Boolean);const n={};let r=0;for(;r<t.length;r++){const e=t[r];const i=e.indexOf(`:`);if(i<=0)break;n[e.slice(0,i).trim()]=e.slice(i+1).trim()}return{headers:Object.keys(n).length?n:void 0,base64Lines:t.slice(r),base64Text:t.slice(r).join(``)}}function detectNewline(e){return/\r\n/.test(e)?`\r
`:`
`}function collectBlocks(e,n={}){const i=[];const a=n.label;let o;r.lastIndex=0;while(o=r.exec(e)){const e=o[1].trim();if(a&&e!==a)continue;assertLabel(e);const n=parseBody(o[2]);i.push({label:e,data:t.base64.decode(n.base64Text),headers:n.headers,lineLength:n.base64Lines[0]?.length??64,newline:detectNewline(o[0])})}if(n.strict&&i.length===0)throw new TypeError(a?`No PEM block with label '${a}' was found`:`No PEM blocks were found`);return i}function encode(e,n,r={}){assertLabel(e);const i=r.lineLength??64;if(!Number.isInteger(i)||i<1)throw new RangeError(`PEM lineLength must be a positive integer`);const a=r.newline??`
`;const o=[`-----BEGIN ${e}-----`];if(r.headers){for(const[e,t]of Object.entries(r.headers))o.push(`${e}: ${t}`);o.push(``)}o.push(...wrap(t.base64.encode(n),i));o.push(`-----END ${e}-----`);return`${o.join(a)}${a}`}function encodeMany(e,t={}){return e.map(e=>encode(e.label,e.data,{...t,headers:e.headers??t.headers})).join(``)}function decode(e,t={}){return collectBlocks(e,t).map(({lineLength:e,newline:t,...n})=>n)}function find(e,t){return decode(e,{label:t})[0]}function findAll(e,t){return decode(e,{label:t})}function decodeFirst(e,t){const[n]=decode(e,{label:t,strict:true});return n.data}function parse(e,t={}){const[n]=collectBlocks(e,{...t,strict:true});const r={label:n.label,headers:n.headers,lineLength:n.lineLength,newline:n.newline};return{bytes:n.data,format:r,normalized:encode(n.label,n.data,r)}}function format(e,t){return encode(t.label,e,t)}e.pem={decode,decodeFirst,encode,encodeMany,find,findAll,format,parse};e.pemConverter={name:`pem`,encode:(e,t)=>{if(!t?.label)throw new TypeError(`PEM label is required`);return encode(t.label,e,t)},decode:(e,t)=>decodeFirst(e,t?.label),format,is:e=>typeof e===`string`&&/-----BEGIN [^-]+-----/.test(e),parse}}));
//!node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/pem/index.js
var require_pem=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.pemConverter=e.pem=e.parse=e.format=e.findAll=e.find=e.encodeMany=e.encode=e.decodeFirst=e.decode=void 0;var t=require_pem$1();Object.defineProperty(e,"decode",{enumerable:true,get:function(){return t.decode}});Object.defineProperty(e,"decodeFirst",{enumerable:true,get:function(){return t.decodeFirst}});Object.defineProperty(e,"encode",{enumerable:true,get:function(){return t.encode}});Object.defineProperty(e,"encodeMany",{enumerable:true,get:function(){return t.encodeMany}});Object.defineProperty(e,"find",{enumerable:true,get:function(){return t.find}});Object.defineProperty(e,"findAll",{enumerable:true,get:function(){return t.findAll}});Object.defineProperty(e,"format",{enumerable:true,get:function(){return t.format}});Object.defineProperty(e,"parse",{enumerable:true,get:function(){return t.parse}});Object.defineProperty(e,"pem",{enumerable:true,get:function(){return t.pem}});Object.defineProperty(e,"pemConverter",{enumerable:true,get:function(){return t.pemConverter}})}));
//!node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/converters/registry.js
var require_registry$2=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.createConverterRegistry=createConverterRegistry;function keyOf(e){return e.trim().toLowerCase()}function toError(e){return e instanceof Error?e:new Error(String(e))}function removeConverter(e,t,n){for(const t of[n.name,...n.aliases??[]])e.delete(keyOf(t));t.delete(keyOf(n.name))}function requireCapability(e,t,n){const r=e[n];if(typeof r!==`function`)throw new Error(`Converter '${t}' does not support ${n}()`);return r}function detectConfidence(e,t,n){const r=keyOf(n.name||e);const i=t.trim();if(!i)return 0;let a=false;if(n.is)a=n.is(t);let o=false;try{n.decode(t);o=true}catch{o=false}if(!a&&!o)return 0;switch(r){case`pem`:return/-----BEGIN [^-]+-----/.test(t)?1:0;case`hex`:{const e=i.replace(/^0x/i,``).replace(/[\s:.-]/g,``);if(!e||/[^0-9a-f]/i.test(e)||e.length%2!==0)return 0;if(/^0x/i.test(i)||/[:\s.-]/.test(i))return .95;if(/[a-f]/.test(i)||/[A-F]/.test(i))return .8;return .45}case`base64url`:if(/[-_]/.test(i))return .95;if(/=/.test(i))return .1;return .6;case`base64`:if(/[+/=]/.test(i))return .9;return .55;case`binary`:case`utf8`:case`utf16be`:case`utf16le`:return 0;default:return a&&o?.75:.5}}function createConverterRegistry(e=[]){const t=/* @__PURE__ */ new Map;const n=/* @__PURE__ */ new Set;const r={register(e,r={}){if(!e.name||!keyOf(e.name))throw new TypeError(`Converter name is required`);const i=[...new Set([e.name,...e.aliases??[]].map(keyOf))];const a=/* @__PURE__ */ new Set;for(const e of i){const n=t.get(e);if(!n)continue;if(!r.override)throw new Error(`Converter '${e}' is already registered`);a.add(n)}for(const e of a)removeConverter(t,n,e);for(const n of i)t.set(n,e);n.add(keyOf(e.name));return this},unregister(e){const r=t.get(keyOf(e));if(!r)return false;removeConverter(t,n,r);return true},has(e){return t.has(keyOf(e))},get(e){const n=t.get(keyOf(e));if(!n)throw new Error(`Converter '${e}' is not registered`);return n},list(){return[...n].map(e=>this.get(e))},encode(e,t,n){return this.get(e).encode(t,n)},decode(e,t,n){return this.get(e).decode(t,n)},tryDecode(e,t,n){try{return{ok:true,bytes:this.decode(e,t,n)}}catch(e){return{ok:false,error:toError(e)}}},normalize(e,t,n){const r=this.get(e);return requireCapability(r,e,`normalize`).call(r,t,n)},parse(e,t,n){const r=this.get(e);return requireCapability(r,e,`parse`).call(r,t,n)},format(e,t,n){const r=this.get(e);return requireCapability(r,e,`format`).call(r,t,n)},transcode(e,t){const n=this.decode(t.from,e,t.fromOptions);return this.encode(t.to,n,t.toOptions)},detect(e,t={}){const n=t.formats?.length?t.formats.map(e=>String(e)):this.list().map(e=>e.name).filter(e=>![`binary`,`utf8`,`utf16be`,`utf16le`].includes(keyOf(e)));const r=/* @__PURE__ */ new Map;for(const t of n){const n=this.get(t);const i=detectConfidence(t,e,n);if(i<=0)continue;const a=n.name;const o=r.get(a);if(!o||i>o.confidence)r.set(a,{format:a,confidence:i})}return[...r.values()].sort((e,t)=>t.confidence-e.confidence)}};for(const t of e)r.register(t);return r}}));
//!node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/converters/defaults.js
var require_defaults=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.defaultConverterRegistry=e.defaultConverters=e.utf16leConverter=e.utf16beConverter=e.utf8Converter=e.base64urlConverter=e.base64Converter=e.hexConverter=e.binaryConverter=e.pemConverter=void 0;const t=require_encoding();const n=require_pem();var r=require_pem();Object.defineProperty(e,"pemConverter",{enumerable:true,get:function(){return r.pemConverter}});const i=require_registry$2();e.binaryConverter={name:`binary`,aliases:[`latin1`],encode:t.binary.encode,decode:t.binary.decode,is:t.binary.is};e.hexConverter={name:`hex`,encode:t.hex.encode,decode:t.hex.decode,format:t.hex.format,is:t.hex.is,normalize:t.hex.normalize,parse:t.hex.parse};e.base64Converter={name:`base64`,aliases:[`b64`],encode:t.base64.encode,decode:t.base64.decode,is:t.base64.is,normalize:t.base64.normalize};e.base64urlConverter={name:`base64url`,aliases:[`base64-url`,`b64url`],encode:t.base64url.encode,decode:t.base64url.decode,is:t.base64url.is,normalize:t.base64url.normalize};e.utf8Converter={name:`utf8`,aliases:[`utf-8`],encode:e=>t.utf8.decode(e),decode:e=>t.utf8.encode(e),is:e=>typeof e===`string`};e.utf16beConverter={name:`utf16be`,aliases:[`utf16`,`utf-16`,`utf-16be`],encode:e=>t.utf16.decode(e),decode:e=>t.utf16.encode(e),is:e=>typeof e===`string`};e.utf16leConverter={name:`utf16le`,aliases:[`utf-16le`,`ucs2`,`usc2`],encode:e=>t.utf16.decode(e,{littleEndian:true}),decode:e=>t.utf16.encode(e,{littleEndian:true}),is:e=>typeof e===`string`};e.defaultConverters=[e.binaryConverter,e.hexConverter,e.base64Converter,e.base64urlConverter,e.utf8Converter,e.utf16beConverter,e.utf16leConverter,n.pemConverter];e.defaultConverterRegistry=(0,i.createConverterRegistry)(e.defaultConverters)}));
//!node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/converters/convert.js
var require_convert$2=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.convert=void 0;const t=require_bytes();const n=require_encoding();const r=require_defaults();function encode(e,t,...n){return r.defaultConverterRegistry.encode(e,t,...n)}function decode(e,t,...n){return r.defaultConverterRegistry.decode(e,t,...n)}function tryDecode(e,t,...n){return r.defaultConverterRegistry.tryDecode(e,t,...n)}function normalize(e,t,...n){return r.defaultConverterRegistry.normalize(e,t,...n)}function parse(e,t,...n){return r.defaultConverterRegistry.parse(e,t,...n)}function format(e,t,n){return r.defaultConverterRegistry.format(e,t,n)}function transcode(e,t){return r.defaultConverterRegistry.transcode(e,t)}function detect(e,t){return r.defaultConverterRegistry.detect(e,t)}function normalizeEncodingName(e){return e.toLowerCase()}e.convert={encode,decode,tryDecode,normalize,parse,format,transcode,detect,to(e,t,...n){return encode(e,t,...n)},from(e,t,...n){return decode(e,t,...n)},toString(e,t=`utf8`){return encode(t,e)},fromString(e,r=`utf8`){if(normalizeEncodingName(r)===`hex`)return(0,t.toArrayBuffer)(n.hex.decode(e,{allowOddLength:true}));return(0,t.toArrayBuffer)(decode(r,e))},toBase64:n.base64.encode,fromBase64:e=>(0,t.toArrayBuffer)(n.base64.decode(e)),toBase64Url:n.base64url.encode,fromBase64Url:e=>(0,t.toArrayBuffer)(n.base64url.decode(e)),toHex:n.hex.encode,fromHex:e=>(0,t.toArrayBuffer)(n.hex.decode(e,{allowOddLength:true})),toBinary:n.binary.encode,fromBinary:e=>(0,t.toArrayBuffer)(n.binary.decode(e)),toUtf8String:n.utf8.decode,fromUtf8String:e=>(0,t.toArrayBuffer)(n.utf8.encode(e)),toUtf16String:(e,t=false)=>n.utf16.decode(e,{littleEndian:t}),fromUtf16String:(e,r=false)=>(0,t.toArrayBuffer)(n.utf16.encode(e,{littleEndian:r})),isHex:n.hex.is,isBase64:n.base64.is,isBase64Url:n.base64url.is,formatString:n.base64.normalize}}));
//!node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/converters/index.js
var require_converters$1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.convert=e.utf8Converter=e.utf16leConverter=e.utf16beConverter=e.pemConverter=e.hexConverter=e.defaultConverters=e.defaultConverterRegistry=e.binaryConverter=e.base64urlConverter=e.base64Converter=e.createConverterRegistry=void 0;var t=require_registry$2();Object.defineProperty(e,"createConverterRegistry",{enumerable:true,get:function(){return t.createConverterRegistry}});var n=require_defaults();Object.defineProperty(e,"base64Converter",{enumerable:true,get:function(){return n.base64Converter}});Object.defineProperty(e,"base64urlConverter",{enumerable:true,get:function(){return n.base64urlConverter}});Object.defineProperty(e,"binaryConverter",{enumerable:true,get:function(){return n.binaryConverter}});Object.defineProperty(e,"defaultConverterRegistry",{enumerable:true,get:function(){return n.defaultConverterRegistry}});Object.defineProperty(e,"defaultConverters",{enumerable:true,get:function(){return n.defaultConverters}});Object.defineProperty(e,"hexConverter",{enumerable:true,get:function(){return n.hexConverter}});Object.defineProperty(e,"pemConverter",{enumerable:true,get:function(){return n.pemConverter}});Object.defineProperty(e,"utf16beConverter",{enumerable:true,get:function(){return n.utf16beConverter}});Object.defineProperty(e,"utf16leConverter",{enumerable:true,get:function(){return n.utf16leConverter}});Object.defineProperty(e,"utf8Converter",{enumerable:true,get:function(){return n.utf8Converter}});var r=require_convert$2();Object.defineProperty(e,"convert",{enumerable:true,get:function(){return r.convert}})}));
//!node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/legacy/buffer-source-converter.js
var require_buffer_source_converter=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.BufferSourceConverter=void 0;const t=require_bytes();var BufferSourceConverter=class{static isArrayBuffer(e){return(0,t.isArrayBuffer)(e)}static toArrayBuffer(e){return(0,t.toArrayBuffer)(e)}static toUint8Array(e){return(0,t.toUint8Array)(e)}static toView(e,n){return(0,t.toView)(e,n)}static isBufferSource(e){return(0,t.isBufferSource)(e)}static isArrayBufferView(e){return(0,t.isArrayBufferView)(e)}static isEqual(e,n){return(0,t.equal)(e,n)}static concat(e,n,...r){if(Array.isArray(e))return typeof n===`function`?(0,t.concat)(e,n):(0,t.concat)(e);const i=[e,n,...r].filter(Boolean);return(0,t.concat)(i)}};e.BufferSourceConverter=BufferSourceConverter}));
//!node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/legacy/convert.js
var require_convert$1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.Convert=void 0;const t=require_converters$1();function normalizeTextEncoding(e){return e===`ascii`?`binary`:e}var n=class Convert{static DEFAULT_UTF8_ENCODING=`utf8`;static isHex(e){return t.convert.isHex(e)}static isBase64(e){return t.convert.isBase64(e)}static isBase64Url(e){return t.convert.isBase64Url(e)}static ToString(e,n=`utf8`){return t.convert.toString(e,n)}static FromString(e,n=`utf8`){if(!e)return/* @__PURE__ */ new ArrayBuffer(0);return t.convert.fromString(e,n)}static ToBase64(e){return t.convert.toBase64(e)}static FromBase64(e){return t.convert.fromBase64(e)}static FromBase64Url(e){return t.convert.fromBase64Url(e)}static ToBase64Url(e){return t.convert.toBase64Url(e)}static FromUtf8String(e,n=Convert.DEFAULT_UTF8_ENCODING){return t.convert.fromString(e,normalizeTextEncoding(n))}static ToUtf8String(e,n=Convert.DEFAULT_UTF8_ENCODING){return t.convert.toString(e,normalizeTextEncoding(n))}static FromBinary(e){return t.convert.fromBinary(e)}static ToBinary(e){return t.convert.toBinary(e)}static ToHex(e){return t.convert.toHex(e)}static FromHex(e){return t.convert.fromHex(e)}static ToUtf16String(e,n=false){return t.convert.toUtf16String(e,n)}static FromUtf16String(e,n=false){return t.convert.fromUtf16String(e,n)}static Base64Padding(e){const t=4-e.length%4;return t<4?e+`=`.repeat(t):e}static formatString(e){return t.convert.formatString(e)}};e.Convert=n}));
//!node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/legacy/functions.js
var require_functions=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.assign=assign;e.combine=combine;e.isEqual=isEqual;const t=require_bytes();function assign(e,...t){for(const n of t){if(!n)continue;for(const t in n)e[t]=n[t]}return e}function combine(...e){return(0,t.concat)(e)}function isEqual(e,n){return(0,t.equal)(e,n)}}));
//!node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/legacy/index.js
var require_legacy=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.isEqual=e.combine=e.assign=e.Convert=e.BufferSourceConverter=void 0;var t=require_buffer_source_converter();Object.defineProperty(e,"BufferSourceConverter",{enumerable:true,get:function(){return t.BufferSourceConverter}});var n=require_convert$1();Object.defineProperty(e,"Convert",{enumerable:true,get:function(){return n.Convert}});var r=require_functions();Object.defineProperty(e,"assign",{enumerable:true,get:function(){return r.assign}});Object.defineProperty(e,"combine",{enumerable:true,get:function(){return r.combine}});Object.defineProperty(e,"isEqual",{enumerable:true,get:function(){return r.isEqual}})}));
//!node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/index.js
var require_cjs$11=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.bytes=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_bytes(),e);e.bytes=t.__importStar(require_bytes());t.__exportStar(require_encoding(),e);t.__exportStar(require_pem(),e);t.__exportStar(require_converters$1(),e);t.__exportStar(require_legacy(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/enums.js
var require_enums=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AsnPropTypes=e.AsnTypeTypes=void 0;var t;(function(e){e[e[`Sequence`]=0]=`Sequence`;e[e[`Set`]=1]=`Set`;e[e[`Choice`]=2]=`Choice`})(t||(e.AsnTypeTypes=t={}));var n;(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`;e[e[`RelativeObjectIdentifier`]=28]=`RelativeObjectIdentifier`})(n||(e.AsnPropTypes=n={}))}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/types/bit_string.js
var require_bit_string=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.BitString=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1)).__importStar(require_build$2());const n=require_cjs$11();var BitString=class{unusedBits=0;value=/* @__PURE__ */ new ArrayBuffer(0);constructor(e,t=0){if(e){if(typeof e===`number`)this.fromNumber(e);else if((0,n.isBufferSource)(e)){this.unusedBits=t;this.value=(0,n.toArrayBuffer)(e)}else throw TypeError(`Unsupported type of 'params' argument for BitString`)}}fromASN(e){if(!(e instanceof t.BitString))throw new TypeError(`Argument 'asn' is not instance of ASN.1 BitString`);this.unusedBits=e.valueBlock.unusedBits;this.value=(0,n.toArrayBuffer)(e.valueBlock.valueHex);return this}toASN(){return new t.BitString({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new t.BitString({name:e})}toNumber(){let e=``;const t=new Uint8Array(this.value);for(const n of t)e+=n.toString(2).padStart(8,`0`);e=e.split(``).reverse().join(``);if(this.unusedBits)e=e.slice(this.unusedBits).padStart(this.unusedBits,`0`);return parseInt(e,2)}fromNumber(e){let t=e.toString(2);const n=t.length+7>>3;this.unusedBits=(n<<3)-t.length;const r=new Uint8Array(n);t=t.padStart(n<<3,`0`).split(``).reverse().join(``);let i=0;while(i<n){r[i]=parseInt(t.slice(i<<3,(i<<3)+8),2);i++}this.value=r.buffer}};e.BitString=BitString}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/types/octet_string.js
var require_octet_string=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.OctetString=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1)).__importStar(require_build$2());const n=require_cjs$11();var OctetString=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){if(typeof e===`number`)this.buffer=new ArrayBuffer(e);else if((0,n.isBufferSource)(e))this.buffer=(0,n.toArrayBuffer)(e);else if(Array.isArray(e))this.buffer=new Uint8Array(e).buffer;else this.buffer=/* @__PURE__ */ new ArrayBuffer(0)}fromASN(e){if(!(e instanceof t.OctetString))throw new TypeError(`Argument 'asn' is not instance of ASN.1 OctetString`);this.buffer=(0,n.toArrayBuffer)(e.valueBlock.valueHex);return this}toASN(){return new t.OctetString({valueHex:this.buffer})}toSchema(e){return new t.OctetString({name:e})}};e.OctetString=OctetString}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/types/index.js
var require_types$5=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_bit_string(),e);t.__exportStar(require_octet_string(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/converters.js
var require_converters=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AsnNullConverter=e.AsnGeneralizedTimeConverter=e.AsnUTCTimeConverter=e.AsnCharacterStringConverter=e.AsnGeneralStringConverter=e.AsnVisibleStringConverter=e.AsnGraphicStringConverter=e.AsnIA5StringConverter=e.AsnVideotexStringConverter=e.AsnTeletexStringConverter=e.AsnPrintableStringConverter=e.AsnNumericStringConverter=e.AsnUniversalStringConverter=e.AsnBmpStringConverter=e.AsnUtf8StringConverter=e.AsnConstructedOctetStringConverter=e.AsnOctetStringConverter=e.AsnBooleanConverter=e.AsnRelativeObjectIdentifierConverter=e.AsnObjectIdentifierConverter=e.AsnBitStringConverter=e.AsnIntegerBigIntConverter=e.AsnIntegerArrayBufferConverter=e.AsnEnumeratedConverter=e.AsnIntegerConverter=e.AsnAnyConverter=void 0;e.defaultConverter=defaultConverter;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1)).__importStar(require_build$2());const n=require_cjs$11();const r=require_enums();const i=require_types$5();e.AsnAnyConverter={fromASN:e=>e instanceof t.Null?null:(0,n.toArrayBuffer)(e.valueBeforeDecodeView),toASN:e=>{if(e===null)return new t.Null;const n=t.fromBER(e,{maxDepth:Infinity,maxNodes:Infinity,maxContentLength:Infinity});if(n.result.error)throw new Error(n.result.error);return n.result}};e.AsnIntegerConverter={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new t.Integer({value:+e})};e.AsnEnumeratedConverter={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new t.Enumerated({value:e})};e.AsnIntegerArrayBufferConverter={fromASN:e=>(0,n.toArrayBuffer)(e.valueBlock.valueHexView),toASN:e=>new t.Integer({valueHex:e})};e.AsnIntegerBigIntConverter={fromASN:e=>e.toBigInt(),toASN:e=>t.Integer.fromBigInt(e)};e.AsnBitStringConverter={fromASN:e=>(0,n.toArrayBuffer)(e.valueBlock.valueHexView),toASN:e=>new t.BitString({valueHex:e})};e.AsnObjectIdentifierConverter={fromASN:e=>e.valueBlock.toString(),toASN:e=>new t.ObjectIdentifier({value:e})};e.AsnRelativeObjectIdentifierConverter={fromASN:e=>e.valueBlock.toString(),toASN:e=>new t.RelativeObjectIdentifier({value:e})};e.AsnBooleanConverter={fromASN:e=>e.valueBlock.value,toASN:e=>new t.Boolean({value:e})};e.AsnOctetStringConverter={fromASN:e=>(0,n.toArrayBuffer)(e.valueBlock.valueHexView),toASN:e=>new t.OctetString({valueHex:e})};e.AsnConstructedOctetStringConverter={fromASN:e=>new i.OctetString(e.getValue()),toASN:e=>e.toASN()};function createStringConverter(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}e.AsnUtf8StringConverter=createStringConverter(t.Utf8String);e.AsnBmpStringConverter=createStringConverter(t.BmpString);e.AsnUniversalStringConverter=createStringConverter(t.UniversalString);e.AsnNumericStringConverter=createStringConverter(t.NumericString);e.AsnPrintableStringConverter=createStringConverter(t.PrintableString);e.AsnTeletexStringConverter=createStringConverter(t.TeletexString);e.AsnVideotexStringConverter=createStringConverter(t.VideotexString);e.AsnIA5StringConverter=createStringConverter(t.IA5String);e.AsnGraphicStringConverter=createStringConverter(t.GraphicString);e.AsnVisibleStringConverter=createStringConverter(t.VisibleString);e.AsnGeneralStringConverter=createStringConverter(t.GeneralString);e.AsnCharacterStringConverter=createStringConverter(t.CharacterString);e.AsnUTCTimeConverter={fromASN:e=>e.toDate(),toASN:e=>new t.UTCTime({valueDate:e})};e.AsnGeneralizedTimeConverter={fromASN:e=>e.toDate(),toASN:e=>new t.GeneralizedTime({valueDate:e})};e.AsnNullConverter={fromASN:()=>null,toASN:()=>{return new t.Null}};function defaultConverter(t){switch(t){case r.AsnPropTypes.Any:return e.AsnAnyConverter;case r.AsnPropTypes.BitString:return e.AsnBitStringConverter;case r.AsnPropTypes.BmpString:return e.AsnBmpStringConverter;case r.AsnPropTypes.Boolean:return e.AsnBooleanConverter;case r.AsnPropTypes.CharacterString:return e.AsnCharacterStringConverter;case r.AsnPropTypes.Enumerated:return e.AsnEnumeratedConverter;case r.AsnPropTypes.GeneralString:return e.AsnGeneralStringConverter;case r.AsnPropTypes.GeneralizedTime:return e.AsnGeneralizedTimeConverter;case r.AsnPropTypes.GraphicString:return e.AsnGraphicStringConverter;case r.AsnPropTypes.IA5String:return e.AsnIA5StringConverter;case r.AsnPropTypes.Integer:return e.AsnIntegerConverter;case r.AsnPropTypes.Null:return e.AsnNullConverter;case r.AsnPropTypes.NumericString:return e.AsnNumericStringConverter;case r.AsnPropTypes.ObjectIdentifier:return e.AsnObjectIdentifierConverter;case r.AsnPropTypes.RelativeObjectIdentifier:return e.AsnRelativeObjectIdentifierConverter;case r.AsnPropTypes.OctetString:return e.AsnOctetStringConverter;case r.AsnPropTypes.PrintableString:return e.AsnPrintableStringConverter;case r.AsnPropTypes.TeletexString:return e.AsnTeletexStringConverter;case r.AsnPropTypes.UTCTime:return e.AsnUTCTimeConverter;case r.AsnPropTypes.UniversalString:return e.AsnUniversalStringConverter;case r.AsnPropTypes.Utf8String:return e.AsnUtf8StringConverter;case r.AsnPropTypes.VideotexString:return e.AsnVideotexStringConverter;case r.AsnPropTypes.VisibleString:return e.AsnVisibleStringConverter;default:return null}}}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/helper.js
var require_helper=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.isConvertible=isConvertible;e.isTypeOfArray=isTypeOfArray;e.isArrayEqual=isArrayEqual;function isConvertible(e){if(typeof e===`function`&&e.prototype){if(e.prototype.toASN&&e.prototype.fromASN)return true;else return isConvertible(e.prototype)}else return!!(e&&typeof e===`object`&&`toASN`in e&&`fromASN`in e)}function isTypeOfArray(e){if(e){const t=Object.getPrototypeOf(e);if(t?.prototype?.constructor===Array)return true;return isTypeOfArray(t)}return false}function isArrayEqual(e,t){if(!(e&&t))return false;if(e.byteLength!==t.byteLength)return false;const n=new Uint8Array(e);const r=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(n[t]!==r[t])return false;return true}}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/schema.js
var require_schema=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AsnSchemaStorage=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1)).__importStar(require_build$2());const n=require_enums();const r=require_helper();var AsnSchemaStorage=class{items=/* @__PURE__ */ new WeakMap;has(e){return this.items.has(e)}get(e,t=false){const n=this.items.get(e);if(!n)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!n.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return n}cache(e){const t=this.get(e);if(!t.schema)t.schema=this.create(e,true)}createDefault(e){const t={type:n.AsnTypeTypes.Sequence,items:{}};const r=this.findParentSchema(e);if(r){Object.assign(t,r);t.items=Object.assign({},t.items,r.items)}return t}create(e,i){const a=this.items.get(e)||this.createDefault(e);const o=[];for(const e in a.items){const s=a.items[e];const c=i?e:``;let u;if(typeof s.type===`number`){const e=n.AsnPropTypes[s.type];const r=t[e];if(!r)throw new Error(`Cannot get ASN1 class by name '${e}'`);u=new r({name:c})}else if((0,r.isConvertible)(s.type))u=new s.type().toSchema(c);else if(s.optional){if(this.get(s.type).type===n.AsnTypeTypes.Choice)u=new t.Any({name:c});else{u=this.create(s.type,false);u.name=c}}else u=new t.Any({name:c});const d=!!s.optional||s.defaultValue!==void 0;if(s.repeated){u.name=``;u=new(s.repeated===`set`?t.Set:t.Sequence)({name:``,value:[new t.Repeated({name:c,value:u})]})}if(s.context!==null&&s.context!==void 0){if(s.implicit){if(typeof s.type===`number`||(0,r.isConvertible)(s.type)){const e=s.repeated?t.Constructed:t.Primitive;o.push(new e({name:c,optional:d,idBlock:{tagClass:3,tagNumber:s.context}}))}else{this.cache(s.type);const e=!!s.repeated;let n=!e?this.get(s.type,true).schema:u;n=`valueBlock`in n?n.valueBlock.value:n.value;o.push(new t.Constructed({name:!e?c:``,optional:d,idBlock:{tagClass:3,tagNumber:s.context},value:n}))}}else o.push(new t.Constructed({optional:d,idBlock:{tagClass:3,tagNumber:s.context},value:[u]}))}else{u.optional=d;o.push(u)}}switch(a.type){case n.AsnTypeTypes.Sequence:return new t.Sequence({value:o,name:``});case n.AsnTypeTypes.Set:return new t.Set({value:o,name:``});case n.AsnTypeTypes.Choice:return new t.Choice({value:o,name:``});default:throw new Error(`Unsupported ASN1 type in use`)}}set(e,t){this.items.set(e,t);return this}findParentSchema(e){const t=Object.getPrototypeOf(e);if(t)return this.items.get(t)||this.findParentSchema(t);return null}};e.AsnSchemaStorage=AsnSchemaStorage}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/storage.js
var require_storage=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.schemaStorage=void 0;const t=require_schema();e.schemaStorage=new t.AsnSchemaStorage}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/decorators.js
var require_decorators$1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AsnProp=e.AsnSequenceType=e.AsnSetType=e.AsnChoiceType=e.AsnType=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1)).__importStar(require_converters());const n=require_enums();const r=require_storage();const AsnType=e=>t=>{let n;if(!r.schemaStorage.has(t)){n=r.schemaStorage.createDefault(t);r.schemaStorage.set(t,n)}else n=r.schemaStorage.get(t);Object.assign(n,e)};e.AsnType=AsnType;const AsnChoiceType=()=>(0,e.AsnType)({type:n.AsnTypeTypes.Choice});e.AsnChoiceType=AsnChoiceType;const AsnSetType=t=>(0,e.AsnType)({type:n.AsnTypeTypes.Set,...t});e.AsnSetType=AsnSetType;const AsnSequenceType=t=>(0,e.AsnType)({type:n.AsnTypeTypes.Sequence,...t});e.AsnSequenceType=AsnSequenceType;const AsnProp=e=>(n,i)=>{let a;if(!r.schemaStorage.has(n.constructor)){a=r.schemaStorage.createDefault(n.constructor);r.schemaStorage.set(n.constructor,a)}else a=r.schemaStorage.get(n.constructor);const o=Object.assign({},e);if(typeof o.type===`number`&&!o.converter){const r=t.defaultConverter(e.type);if(!r)throw new Error(`Cannot get default converter for property '${i}' of ${n.constructor.name}`);o.converter=r}o.raw=e.raw;a.items[i]=o};e.AsnProp=AsnProp}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/errors/schema_validation.js
var require_schema_validation=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AsnSchemaValidationError=void 0;var AsnSchemaValidationError=class extends Error{schemas=[]};e.AsnSchemaValidationError=AsnSchemaValidationError}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/errors/index.js
var require_errors=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1)).__exportStar(require_schema_validation(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/parser.js
var require_parser=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AsnParser=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=t.__importStar(require_build$2());const r=require_cjs$11();const i=require_enums();const a=t.__importStar(require_converters());const o=require_errors();const s=require_helper();const c=require_storage();var AsnParser=class{static parse(e,t,i){const a=n.fromBER((0,r.toArrayBuffer)(e),i?.berOptions);if(a.result.error)throw new Error(a.result.error);return this.fromASN(a.result,t,i)}static fromASN(e,t,n){try{if((0,s.isConvertible)(t))return new t().fromASN(e);const r=c.schemaStorage.get(t);c.schemaStorage.cache(t);let i=r.schema;const a=this.handleChoiceTypes(e,r,t,i,n);if(a?.result)return a.result;if(a?.targetSchema)i=a.targetSchema;const o=this.handleSequenceTypes(e,r,t,i);const u=new t;if((0,s.isTypeOfArray)(t))return this.handleArrayTypes(e,r,t,n);this.processSchemaItems(r,o,u,n);return u}catch(e){if(e instanceof o.AsnSchemaValidationError)e.schemas.push(t.name);throw e}}static handleChoiceTypes(e,t,r,a,o){if(e.constructor===n.Constructed&&t.type===i.AsnTypeTypes.Choice&&e.idBlock.tagClass===3)for(const a in t.items){const s=t.items[a];if(s.context===e.idBlock.tagNumber&&s.implicit){if(typeof s.type===`function`&&c.schemaStorage.has(s.type)){const t=c.schemaStorage.get(s.type);if(t&&t.type===i.AsnTypeTypes.Sequence){const t=new n.Sequence;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock){t.valueBlock.value=e.valueBlock.value;const n=this.fromASN(t,s.type,o);const i=new r;i[a]=n;return{result:i}}}}}}else if(e.constructor===n.Constructed&&t.type!==i.AsnTypeTypes.Choice){const r=new n.Constructed({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:t.schema.valueBlock.value});for(const n in t.items)delete e[n];return{targetSchema:r}}return null}static handleSequenceTypes(e,t,r,a){if(t.type===i.AsnTypeTypes.Sequence){const t=n.compareSchema({},e,a);if(!t.verified)throw new o.AsnSchemaValidationError(`Data does not match to ${r.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}else{const t=n.compareSchema({},e,a);if(!t.verified)throw new o.AsnSchemaValidationError(`Data does not match to ${r.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}}static processRepeatedField(e,t,n){let r=e.slice(t);if(r.length===1&&r[0].constructor.name===`Sequence`){const e=r[0];if(e.valueBlock&&e.valueBlock.value&&Array.isArray(e.valueBlock.value))r=e.valueBlock.value}if(typeof n.type===`number`){const e=a.defaultConverter(n.type);if(!e)throw new Error(`No converter for ASN.1 type ${n.type}`);return r.filter(e=>e&&e.valueBlock).map(t=>{try{return e.fromASN(t)}catch{return}}).filter(e=>e!==void 0)}else return r.filter(e=>e&&e.valueBlock).map(e=>{try{return this.fromASN(e,n.type)}catch{return}}).filter(e=>e!==void 0)}static processPrimitiveField(e,t){const n=a.defaultConverter(t.type);if(!n)throw new Error(`No converter for ASN.1 type ${t.type}`);return n.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type===`function`&&c.schemaStorage.has(e.type)&&c.schemaStorage.get(e.type).type===i.AsnTypeTypes.Choice}static processOptionalChoiceField(e,t){try{return{processed:true,value:this.fromASN(e,t.type)}}catch(e){if(e instanceof o.AsnSchemaValidationError&&/Wrong values for Choice type/.test(e.message))return{processed:false};throw e}}static handleArrayTypes(e,t,n,r){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 i=t.itemType;if(typeof i===`number`){const t=a.defaultConverter(i);if(!t)throw new Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);return n.from(e.valueBlock.value,e=>t.fromASN(e))}else return n.from(e.valueBlock.value,e=>this.fromASN(e,i,r))}static processSchemaItems(e,t,n,r){for(const i in e.items){const a=t.result[i];if(!a)continue;const o=e.items[i];const c=o.type;let u;if(typeof c===`number`||(0,s.isConvertible)(c))u=this.processPrimitiveSchemaItem(a,o,c,r);else u=this.processComplexSchemaItem(a,o,c,r);if(u&&typeof u===`object`&&`value`in u&&`raw`in u){n[i]=u.value;n[`${i}Raw`]=u.raw}else n[i]=u}}static processPrimitiveSchemaItem(e,t,n,r){const i=t.converter??((0,s.isConvertible)(n)?new n:null);if(!i)throw new Error(`Converter is empty`);if(t.repeated)return this.processRepeatedPrimitiveItem(e,t,i,r);else return this.processSinglePrimitiveItem(e,t,n,i,r)}static processRepeatedPrimitiveItem(e,t,r,i){if(t.implicit){const a=new(t.repeated===`sequence`?n.Sequence:n.Set);a.valueBlock=e.valueBlock;const o=n.fromBER(a.toBER(false),i?.berOptions);if(o.offset===-1)throw new Error(`Cannot parse the child item. ${o.result.error}`);if(!(`value`in o.result.valueBlock&&Array.isArray(o.result.valueBlock.value)))throw new Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);const s=o.result.valueBlock.value;return Array.from(s,e=>r.fromASN(e))}else return Array.from(e,e=>r.fromASN(e))}static processSinglePrimitiveItem(e,t,r,a,o){let c=e;if(t.implicit){let e;if((0,s.isConvertible)(r))e=new r().toSchema(``);else{const t=i.AsnPropTypes[r];const a=n[t];if(!a)throw new Error(`Cannot get '${t}' class from asn1js module`);e=new a}e.valueBlock=c.valueBlock;c=n.fromBER(e.toBER(false),o?.berOptions).result}return a.fromASN(c)}static processComplexSchemaItem(e,t,n,r){if(t.repeated){if(!Array.isArray(e))throw new Error(`Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.`);return Array.from(e,e=>this.fromASN(e,n,r))}else{const i=this.handleImplicitTagging(e,t,n);if(this.isOptionalChoiceField(t))try{return this.fromASN(i,n,r)}catch(e){if(e instanceof o.AsnSchemaValidationError&&/Wrong values for Choice type/.test(e.message))return;throw e}else{const a=this.fromASN(i,n,r);if(t.raw)return{value:a,raw:e.valueBeforeDecodeView};return a}}}static handleImplicitTagging(e,t,r){if(t.implicit&&typeof t.context===`number`){const t=c.schemaStorage.get(r);if(t.type===i.AsnTypeTypes.Sequence){const t=new n.Sequence;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock){t.valueBlock.value=e.valueBlock.value;return t}}else if(t.type===i.AsnTypeTypes.Set){const t=new n.Set;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock){t.valueBlock.value=e.valueBlock.value;return t}}}return e}};e.AsnParser=AsnParser}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/serializer.js
var require_serializer=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AsnSerializer=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=t.__importStar(require_build$2());const r=require_cjs$11();const i=t.__importStar(require_converters());const a=require_enums();const o=require_helper();const s=require_storage();var c=class AsnSerializer{static serialize(e){if(e instanceof n.BaseBlock)return e.toBER(false);return this.toASN(e).toBER(false)}static toASN(e){if(e&&typeof e===`object`&&(0,o.isConvertible)(e))return e.toASN();if(!(e&&typeof e===`object`))throw new TypeError(`Parameter 1 should be type of Object.`);const t=e.constructor;const c=s.schemaStorage.get(t);s.schemaStorage.cache(t);let u=[];if(c.itemType){if(!Array.isArray(e))throw new TypeError(`Parameter 1 should be type of Array.`);if(typeof c.itemType===`number`){const n=i.defaultConverter(c.itemType);if(!n)throw new Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);u=e.map(e=>n.toASN(e))}else u=e.map(e=>this.toAsnItem({type:c.itemType},`[]`,t,e))}else for(const i in c.items){const a=c.items[i];const s=e[i];if(s===void 0||a.defaultValue===s||typeof a.defaultValue===`object`&&typeof s===`object`&&(0,o.isArrayEqual)(this.serialize(a.defaultValue),this.serialize(s)))continue;const d=AsnSerializer.toAsnItem(a,i,t,s);if(typeof a.context===`number`){if(a.implicit){if(!a.repeated&&(typeof a.type===`number`||(0,o.isConvertible)(a.type))){const e={};e.valueHex=d instanceof n.Null?(0,r.toArrayBuffer)(d.valueBeforeDecodeView):d.valueBlock.toBER();u.push(new n.Primitive({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},...e}))}else u.push(new n.Constructed({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:d.valueBlock.value}))}else u.push(new n.Constructed({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:[d]}))}else if(a.repeated)u=u.concat(d);else u.push(d)}let d;switch(c.type){case a.AsnTypeTypes.Sequence:d=new n.Sequence({value:u});break;case a.AsnTypeTypes.Set:d=new n.Set({value:u});break;case a.AsnTypeTypes.Choice:if(!u[0])throw new Error(`Schema '${t.name}' has wrong data. Choice cannot be empty.`);d=u[0]}return d}static toAsnItem(e,t,r,i){let o;if(typeof e.type===`number`){const s=e.converter;if(!s)throw new Error(`Property '${t}' doesn't have converter for type ${a.AsnPropTypes[e.type]} in schema '${r.name}'`);if(e.repeated){if(!Array.isArray(i))throw new TypeError(`Parameter 'objProp' should be type of Array.`);const t=Array.from(i,e=>s.toASN(e));o=new(e.repeated===`sequence`?n.Sequence:n.Set)({value:t})}else o=s.toASN(i)}else if(e.repeated){if(!Array.isArray(i))throw new TypeError(`Parameter 'objProp' should be type of Array.`);const t=Array.from(i,e=>this.toASN(e));o=new(e.repeated===`sequence`?n.Sequence:n.Set)({value:t})}else o=this.toASN(i);return o}};e.AsnSerializer=c}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/objects.js
var require_objects=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AsnArray=void 0;var AsnArray=class extends Array{constructor(e=[]){if(typeof e===`number`)super(e);else{super();for(const t of e)this.push(t)}}};e.AsnArray=AsnArray}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/convert.js
var require_convert=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AsnConvert=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1)).__importStar(require_build$2());const n=require_cjs$11();const r=require_parser();const i=require_serializer();var a=class AsnConvert{static serialize(e){return i.AsnSerializer.serialize(e)}static parse(e,t,n){return r.AsnParser.parse(e,t,n)}static toString(e,r){const i=(0,n.isBufferSource)(e)?(0,n.toArrayBuffer)(e):AsnConvert.serialize(e);const a=t.fromBER(i,r?.berOptions);if(a.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${a.result.error}`);return a.result.toString()}};e.AsnConvert=a}));
//!node_modules/.pnpm/@peculiar+asn1-schema@2.11.0/node_modules/@peculiar/asn1-schema/build/cjs/index.js
var require_cjs$10=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AsnSerializer=e.AsnParser=e.AsnPropTypes=e.AsnTypeTypes=e.AsnSetType=e.AsnSequenceType=e.AsnChoiceType=e.AsnType=e.AsnProp=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_converters(),e);t.__exportStar(require_types$5(),e);var n=require_decorators$1();Object.defineProperty(e,"AsnProp",{enumerable:true,get:function(){return n.AsnProp}});Object.defineProperty(e,"AsnType",{enumerable:true,get:function(){return n.AsnType}});Object.defineProperty(e,"AsnChoiceType",{enumerable:true,get:function(){return n.AsnChoiceType}});Object.defineProperty(e,"AsnSequenceType",{enumerable:true,get:function(){return n.AsnSequenceType}});Object.defineProperty(e,"AsnSetType",{enumerable:true,get:function(){return n.AsnSetType}});var r=require_enums();Object.defineProperty(e,"AsnTypeTypes",{enumerable:true,get:function(){return r.AsnTypeTypes}});Object.defineProperty(e,"AsnPropTypes",{enumerable:true,get:function(){return r.AsnPropTypes}});var i=require_parser();Object.defineProperty(e,"AsnParser",{enumerable:true,get:function(){return i.AsnParser}});var a=require_serializer();Object.defineProperty(e,"AsnSerializer",{enumerable:true,get:function(){return a.AsnSerializer}});t.__exportStar(require_errors(),e);t.__exportStar(require_objects(),e);t.__exportStar(require_convert(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/ip_converter.js
var require_ip_converter=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.IpConverter=void 0;const t=require_encoding();var IpConverter=class{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){const t=e.split(`.`);if(t.length!==4)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(t.length!==8)throw new Error(`Invalid IPv6 address`);return t.reduce((e,t)=>{const n=parseInt(t,16);if(isNaN(n)||n<0||n>65535)throw new Error(`Invalid IPv6 address part`);e.push(n>>8&255);e.push(n&255);return e},[])}static expandIPv6(e){if(!e.includes(`::`))return e;const t=e.split(`::`);if(t.length>2)throw new Error(`Invalid IPv6 address`);const n=t[0]?t[0].split(`:`):[];const r=t[1]?t[1].split(`:`):[];const i=8-(n.length+r.length);if(i<0)throw new Error(`Invalid IPv6 address`);return[...n,...Array(i).fill(`0`),...r].join(`:`)}static formatIPv6(e){const t=[];for(let n=0;n<16;n+=2)t.push((e[n]<<8|e[n+1]).toString(16));return this.compressIPv6(t.join(`:`))}static compressIPv6(e){const t=e.split(`:`);let n=-1;let r=0;let i=-1;let a=0;for(let e=0;e<t.length;e++)if(t[e]===`0`){if(i===-1)i=e;a++}else{if(a>r){n=i;r=a}i=-1;a=0}if(a>r){n=i;r=a}if(r>1)return`${t.slice(0,n).join(`:`)}::${t.slice(n+r).join(`:`)}`;return e}static parseCIDR(e){const[t,n]=e.split(`/`);const r=parseInt(n,10);if(this.isIPv4(t)){if(r<0||r>32)throw new Error(`Invalid IPv4 prefix length`);return[this.parseIPv4(t),r]}else{if(r<0||r>128)throw new Error(`Invalid IPv6 prefix length`);return[this.parseIPv6(t),r]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return`::/0`;if(e.length!==16)return e;const t=parseInt(e.slice(8),16).toString(2).split(``).reduce((e,t)=>e+ +t,0);let n=e.slice(0,8).replace(/(.{2})/g,e=>`${parseInt(e,16)}.`);n=n.slice(0,-1);return`${n}/${t}`}static toString(e){const n=new Uint8Array(e);if(n.length===4)return Array.from(n).join(`.`);if(n.length===16)return this.formatIPv6(n);if(n.length===8||n.length===32){const e=n.length/2;const t=n.slice(0,e);const r=n.slice(e);if(n.every(e=>e===0))return n.length===8?`0.0.0.0/0`:`::/0`;const i=r.reduce((e,t)=>e+(t.toString(2).match(/1/g)||[]).length,0);if(n.length===8)return`${Array.from(t).join(`.`)}/${i}`;else return`${this.formatIPv6(t)}/${i}`}return this.decodeIP(t.hex.encode(e))}static fromString(e){if(e.includes(`/`)){const[t,n]=this.parseCIDR(e);const r=new Uint8Array(t.length);let i=n;for(let e=0;e<r.length;e++)if(i>=8){r[e]=255;i-=8}else if(i>0){r[e]=255<<8-i;i=0}const a=new Uint8Array(t.length*2);a.set(t,0);a.set(r,t.length);return a.buffer}const t=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(t).buffer}};e.IpConverter=IpConverter}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/name.js
var require_name=/* @__PURE__ */ __commonJSMin((e=>{var t;var n;var r;Object.defineProperty(e,"__esModule",{value:true});e.Name=e.RDNSequence=e.RelativeDistinguishedName=e.AttributeTypeAndValue=e.AttributeValue=e.DirectoryString=void 0;const i=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const a=require_cjs$10();const o=require_encoding();let s=class DirectoryString{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||``}};e.DirectoryString=s;i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.TeletexString})],s.prototype,`teletexString`,void 0);i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.PrintableString})],s.prototype,`printableString`,void 0);i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.UniversalString})],s.prototype,`universalString`,void 0);i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.Utf8String})],s.prototype,`utf8String`,void 0);i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.BmpString})],s.prototype,`bmpString`,void 0);e.DirectoryString=s=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],s);let c=class AttributeValue extends s{ia5String;anyValue;constructor(e={}){super(e);Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?o.hex.encode(this.anyValue):super.toString())}};e.AttributeValue=c;i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.IA5String})],c.prototype,`ia5String`,void 0);i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.Any})],c.prototype,`anyValue`,void 0);e.AttributeValue=c=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],c);var AttributeTypeAndValue=class{type=``;value=new c;constructor(e={}){Object.assign(this,e)}};e.AttributeTypeAndValue=AttributeTypeAndValue;i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.ObjectIdentifier})],AttributeTypeAndValue.prototype,`type`,void 0);i.__decorate([(0,a.AsnProp)({type:c})],AttributeTypeAndValue.prototype,`value`,void 0);let u=t=class RelativeDistinguishedName extends a.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.RelativeDistinguishedName=u;e.RelativeDistinguishedName=u=t=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Set,itemType:AttributeTypeAndValue})],u);let d=n=class RDNSequence extends a.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,n.prototype)}};e.RDNSequence=d;e.RDNSequence=d=n=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Sequence,itemType:u})],d);let f=r=class Name extends d{constructor(e){super(e);Object.setPrototypeOf(this,r.prototype)}};e.Name=f;e.Name=f=r=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Sequence})],f)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/general_name.js
var require_general_name=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.GeneralName=e.EDIPartyName=e.OtherName=e.AsnIpConverter=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_ip_converter();const i=require_name();e.AsnIpConverter={fromASN:e=>r.IpConverter.toString(n.AsnOctetStringConverter.fromASN(e)),toASN:e=>n.AsnOctetStringConverter.toASN(r.IpConverter.fromString(e))};var OtherName=class{typeId=``;value=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.OtherName=OtherName;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],OtherName.prototype,`typeId`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any,context:0})],OtherName.prototype,`value`,void 0);var EDIPartyName=class{nameAssigner;partyName=new i.DirectoryString;constructor(e={}){Object.assign(this,e)}};e.EDIPartyName=EDIPartyName;t.__decorate([(0,n.AsnProp)({type:i.DirectoryString,optional:true,context:0,implicit:true})],EDIPartyName.prototype,`nameAssigner`,void 0);t.__decorate([(0,n.AsnProp)({type:i.DirectoryString,context:1,implicit:true})],EDIPartyName.prototype,`partyName`,void 0);let a=class GeneralName{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};e.GeneralName=a;t.__decorate([(0,n.AsnProp)({type:OtherName,context:0,implicit:true})],a.prototype,`otherName`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.IA5String,context:1,implicit:true})],a.prototype,`rfc822Name`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.IA5String,context:2,implicit:true})],a.prototype,`dNSName`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any,context:3,implicit:true})],a.prototype,`x400Address`,void 0);t.__decorate([(0,n.AsnProp)({type:i.Name,context:4,implicit:false})],a.prototype,`directoryName`,void 0);t.__decorate([(0,n.AsnProp)({type:EDIPartyName,context:5})],a.prototype,`ediPartyName`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.IA5String,context:6,implicit:true})],a.prototype,`uniformResourceIdentifier`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.OctetString,context:7,implicit:true,converter:e.AsnIpConverter})],a.prototype,`iPAddress`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier,context:8,implicit:true})],a.prototype,`registeredID`,void 0);e.GeneralName=a=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/object_identifiers.js
var require_object_identifiers$5=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.id_alg_unsigned=e.id_ce=e.id_ad_caRepository=e.id_ad_timeStamping=e.id_ad_caIssuers=e.id_ad_ocsp=e.id_qt_unotice=e.id_qt_csp=e.id_ad=e.id_kp=e.id_qt=e.id_pe=e.id_pkix=void 0;e.id_pkix=`1.3.6.1.5.5.7`;e.id_pe=`${e.id_pkix}.1`;e.id_qt=`${e.id_pkix}.2`;e.id_kp=`${e.id_pkix}.3`;e.id_ad=`${e.id_pkix}.48`;e.id_qt_csp=`${e.id_qt}.1`;e.id_qt_unotice=`${e.id_qt}.2`;e.id_ad_ocsp=`${e.id_ad}.1`;e.id_ad_caIssuers=`${e.id_ad}.2`;e.id_ad_timeStamping=`${e.id_ad}.3`;e.id_ad_caRepository=`${e.id_ad}.5`;e.id_ce=`2.5.29`;e.id_alg_unsigned=`1.3.6.1.5.5.7.6.36`}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/authority_information_access.js
var require_authority_information_access=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.AuthorityInfoAccessSyntax=e.AccessDescription=e.id_pe_authorityInfoAccess=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_general_name();const a=require_object_identifiers$5();e.id_pe_authorityInfoAccess=`${a.id_pe}.1`;var AccessDescription=class{accessMethod=``;accessLocation=new i.GeneralName;constructor(e={}){Object.assign(this,e)}};e.AccessDescription=AccessDescription;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.ObjectIdentifier})],AccessDescription.prototype,`accessMethod`,void 0);n.__decorate([(0,r.AsnProp)({type:i.GeneralName})],AccessDescription.prototype,`accessLocation`,void 0);let o=t=class AuthorityInfoAccessSyntax extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.AuthorityInfoAccessSyntax=o;e.AuthorityInfoAccessSyntax=o=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:AccessDescription})],o)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/authority_key_identifier.js
var require_authority_key_identifier=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AuthorityKeyIdentifier=e.KeyIdentifier=e.id_ce_authorityKeyIdentifier=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_general_name();const i=require_object_identifiers$5();e.id_ce_authorityKeyIdentifier=`${i.id_ce}.35`;var KeyIdentifier=class extends n.OctetString{};e.KeyIdentifier=KeyIdentifier;var AuthorityKeyIdentifier=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){if(e)Object.assign(this,e)}};e.AuthorityKeyIdentifier=AuthorityKeyIdentifier;t.__decorate([(0,n.AsnProp)({type:KeyIdentifier,context:0,optional:true,implicit:true})],AuthorityKeyIdentifier.prototype,`keyIdentifier`,void 0);t.__decorate([(0,n.AsnProp)({type:r.GeneralName,context:1,optional:true,implicit:true,repeated:`sequence`})],AuthorityKeyIdentifier.prototype,`authorityCertIssuer`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,context:2,optional:true,implicit:true,converter:n.AsnIntegerArrayBufferConverter})],AuthorityKeyIdentifier.prototype,`authorityCertSerialNumber`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/basic_constraints.js
var require_basic_constraints=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.BasicConstraints=e.id_ce_basicConstraints=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_object_identifiers$5();e.id_ce_basicConstraints=`${r.id_ce}.19`;var BasicConstraints=class{cA=false;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};e.BasicConstraints=BasicConstraints;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Boolean,defaultValue:false})],BasicConstraints.prototype,`cA`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,optional:true})],BasicConstraints.prototype,`pathLenConstraint`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/general_names.js
var require_general_names=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.GeneralNames=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_general_name();let a=t=class GeneralNames extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.GeneralNames=a;e.GeneralNames=a=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:i.GeneralName})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/certificate_issuer.js
var require_certificate_issuer=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.CertificateIssuer=e.id_ce_certificateIssuer=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_general_names();const a=require_object_identifiers$5();e.id_ce_certificateIssuer=`${a.id_ce}.29`;let o=t=class CertificateIssuer extends i.GeneralNames{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.CertificateIssuer=o;e.CertificateIssuer=o=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence})],o)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/certificate_policies.js
var require_certificate_policies=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.CertificatePolicies=e.PolicyInformation=e.PolicyQualifierInfo=e.Qualifier=e.UserNotice=e.NoticeReference=e.DisplayText=e.id_ce_certificatePolicies_anyPolicy=e.id_ce_certificatePolicies=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_object_identifiers$5();e.id_ce_certificatePolicies=`${i.id_ce}.32`;e.id_ce_certificatePolicies_anyPolicy=`${e.id_ce_certificatePolicies}.0`;let a=class DisplayText{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||``}};e.DisplayText=a;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.IA5String})],a.prototype,`ia5String`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.VisibleString})],a.prototype,`visibleString`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.BmpString})],a.prototype,`bmpString`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Utf8String})],a.prototype,`utf8String`,void 0);e.DisplayText=a=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Choice})],a);var NoticeReference=class{organization=new a;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};e.NoticeReference=NoticeReference;n.__decorate([(0,r.AsnProp)({type:a})],NoticeReference.prototype,`organization`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Integer,repeated:`sequence`})],NoticeReference.prototype,`noticeNumbers`,void 0);var UserNotice=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};e.UserNotice=UserNotice;n.__decorate([(0,r.AsnProp)({type:NoticeReference,optional:true})],UserNotice.prototype,`noticeRef`,void 0);n.__decorate([(0,r.AsnProp)({type:a,optional:true})],UserNotice.prototype,`explicitText`,void 0);let o=class Qualifier{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};e.Qualifier=o;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.IA5String})],o.prototype,`cPSuri`,void 0);n.__decorate([(0,r.AsnProp)({type:UserNotice})],o.prototype,`userNotice`,void 0);e.Qualifier=o=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Choice})],o);var PolicyQualifierInfo=class{policyQualifierId=``;qualifier=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.PolicyQualifierInfo=PolicyQualifierInfo;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.ObjectIdentifier})],PolicyQualifierInfo.prototype,`policyQualifierId`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Any})],PolicyQualifierInfo.prototype,`qualifier`,void 0);var PolicyInformation=class{policyIdentifier=``;policyQualifiers;constructor(e={}){Object.assign(this,e)}};e.PolicyInformation=PolicyInformation;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.ObjectIdentifier})],PolicyInformation.prototype,`policyIdentifier`,void 0);n.__decorate([(0,r.AsnProp)({type:PolicyQualifierInfo,repeated:`sequence`,optional:true})],PolicyInformation.prototype,`policyQualifiers`,void 0);let s=t=class CertificatePolicies extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.CertificatePolicies=s;e.CertificatePolicies=s=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:PolicyInformation})],s)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/crl_number.js
var require_crl_number=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.CRLNumber=e.id_ce_cRLNumber=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_object_identifiers$5();e.id_ce_cRLNumber=`${r.id_ce}.20`;let i=class CRLNumber{value;constructor(e=0){this.value=e}};e.CRLNumber=i;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer})],i.prototype,`value`,void 0);e.CRLNumber=i=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],i)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/crl_delta_indicator.js
var require_crl_delta_indicator=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.BaseCRLNumber=e.id_ce_deltaCRLIndicator=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_object_identifiers$5();const i=require_crl_number();e.id_ce_deltaCRLIndicator=`${r.id_ce}.27`;let a=class BaseCRLNumber extends i.CRLNumber{};e.BaseCRLNumber=a;e.BaseCRLNumber=a=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/crl_distribution_points.js
var require_crl_distribution_points=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.CRLDistributionPoints=e.DistributionPoint=e.DistributionPointName=e.Reason=e.ReasonFlags=e.id_ce_cRLDistributionPoints=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_name();const a=require_general_name();const o=require_object_identifiers$5();e.id_ce_cRLDistributionPoints=`${o.id_ce}.31`;var s;(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`})(s||(e.ReasonFlags=s={}));var Reason=class extends r.BitString{toJSON(){const e=[];const t=this.toNumber();if(t&s.aACompromise)e.push(`aACompromise`);if(t&s.affiliationChanged)e.push(`affiliationChanged`);if(t&s.cACompromise)e.push(`cACompromise`);if(t&s.certificateHold)e.push(`certificateHold`);if(t&s.cessationOfOperation)e.push(`cessationOfOperation`);if(t&s.keyCompromise)e.push(`keyCompromise`);if(t&s.privilegeWithdrawn)e.push(`privilegeWithdrawn`);if(t&s.superseded)e.push(`superseded`);if(t&s.unused)e.push(`unused`);return e}toString(){return`[${this.toJSON().join(`, `)}]`}};e.Reason=Reason;let c=class DistributionPointName{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};e.DistributionPointName=c;n.__decorate([(0,r.AsnProp)({type:a.GeneralName,context:0,repeated:`sequence`,implicit:true})],c.prototype,`fullName`,void 0);n.__decorate([(0,r.AsnProp)({type:i.RelativeDistinguishedName,context:1,implicit:true})],c.prototype,`nameRelativeToCRLIssuer`,void 0);e.DistributionPointName=c=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Choice})],c);var DistributionPoint=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};e.DistributionPoint=DistributionPoint;n.__decorate([(0,r.AsnProp)({type:c,context:0,optional:true})],DistributionPoint.prototype,`distributionPoint`,void 0);n.__decorate([(0,r.AsnProp)({type:Reason,context:1,optional:true,implicit:true})],DistributionPoint.prototype,`reasons`,void 0);n.__decorate([(0,r.AsnProp)({type:a.GeneralName,context:2,optional:true,repeated:`sequence`,implicit:true})],DistributionPoint.prototype,`cRLIssuer`,void 0);let u=t=class CRLDistributionPoints extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.CRLDistributionPoints=u;e.CRLDistributionPoints=u=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:DistributionPoint})],u)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/crl_freshest.js
var require_crl_freshest=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.FreshestCRL=e.id_ce_freshestCRL=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_object_identifiers$5();const a=require_crl_distribution_points();e.id_ce_freshestCRL=`${i.id_ce}.46`;let o=t=class FreshestCRL extends a.CRLDistributionPoints{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.FreshestCRL=o;e.FreshestCRL=o=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:a.DistributionPoint})],o)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/crl_issuing_distribution_point.js
var require_crl_issuing_distribution_point=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.IssuingDistributionPoint=e.id_ce_issuingDistributionPoint=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_object_identifiers$5();const i=require_crl_distribution_points();e.id_ce_issuingDistributionPoint=`${r.id_ce}.28`;var a=class IssuingDistributionPoint{static ONLY=false;distributionPoint;onlyContainsUserCerts=IssuingDistributionPoint.ONLY;onlyContainsCACerts=IssuingDistributionPoint.ONLY;onlySomeReasons;indirectCRL=IssuingDistributionPoint.ONLY;onlyContainsAttributeCerts=IssuingDistributionPoint.ONLY;constructor(e={}){Object.assign(this,e)}};e.IssuingDistributionPoint=a;t.__decorate([(0,n.AsnProp)({type:i.DistributionPointName,context:0,optional:true})],a.prototype,`distributionPoint`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Boolean,context:1,defaultValue:a.ONLY,implicit:true})],a.prototype,`onlyContainsUserCerts`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Boolean,context:2,defaultValue:a.ONLY,implicit:true})],a.prototype,`onlyContainsCACerts`,void 0);t.__decorate([(0,n.AsnProp)({type:i.Reason,context:3,optional:true,implicit:true})],a.prototype,`onlySomeReasons`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Boolean,context:4,defaultValue:a.ONLY,implicit:true})],a.prototype,`indirectCRL`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Boolean,context:5,defaultValue:a.ONLY,implicit:true})],a.prototype,`onlyContainsAttributeCerts`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/crl_reason.js
var require_crl_reason=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.CRLReason=e.CRLReasons=e.id_ce_cRLReasons=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_object_identifiers$5();e.id_ce_cRLReasons=`${r.id_ce}.21`;var i;(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`})(i||(e.CRLReasons=i={}));let a=class CRLReason{reason=i.unspecified;constructor(e=i.unspecified){this.reason=e}toJSON(){return i[this.reason]}toString(){return this.toJSON()}};e.CRLReason=a;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Enumerated})],a.prototype,`reason`,void 0);e.CRLReason=a=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/extended_key_usage.js
var require_extended_key_usage=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.id_kp_OCSPSigning=e.id_kp_timeStamping=e.id_kp_emailProtection=e.id_kp_codeSigning=e.id_kp_clientAuth=e.id_kp_serverAuth=e.anyExtendedKeyUsage=e.ExtendedKeyUsage=e.id_ce_extKeyUsage=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_object_identifiers$5();e.id_ce_extKeyUsage=`${i.id_ce}.37`;let a=t=class ExtendedKeyUsage extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.ExtendedKeyUsage=a;e.ExtendedKeyUsage=a=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:r.AsnPropTypes.ObjectIdentifier})],a);e.anyExtendedKeyUsage=`${e.id_ce_extKeyUsage}.0`;e.id_kp_serverAuth=`${i.id_kp}.1`;e.id_kp_clientAuth=`${i.id_kp}.2`;e.id_kp_codeSigning=`${i.id_kp}.3`;e.id_kp_emailProtection=`${i.id_kp}.4`;e.id_kp_timeStamping=`${i.id_kp}.8`;e.id_kp_OCSPSigning=`${i.id_kp}.9`}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/inhibit_any_policy.js
var require_inhibit_any_policy=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.InhibitAnyPolicy=e.id_ce_inhibitAnyPolicy=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_object_identifiers$5();e.id_ce_inhibitAnyPolicy=`${r.id_ce}.54`;let i=class InhibitAnyPolicy{value;constructor(e=/* @__PURE__ */ new ArrayBuffer(0)){this.value=e}};e.InhibitAnyPolicy=i;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],i.prototype,`value`,void 0);e.InhibitAnyPolicy=i=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],i)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/invalidity_date.js
var require_invalidity_date=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.InvalidityDate=e.id_ce_invalidityDate=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_object_identifiers$5();e.id_ce_invalidityDate=`${r.id_ce}.24`;let i=class InvalidityDate{value=/* @__PURE__ */ new Date;constructor(e){if(e)this.value=e}};e.InvalidityDate=i;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.GeneralizedTime})],i.prototype,`value`,void 0);e.InvalidityDate=i=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],i)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/issuer_alternative_name.js
var require_issuer_alternative_name=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.IssueAlternativeName=e.id_ce_issuerAltName=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_general_names();const a=require_object_identifiers$5();e.id_ce_issuerAltName=`${a.id_ce}.18`;let o=t=class IssueAlternativeName extends i.GeneralNames{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.IssueAlternativeName=o;e.IssueAlternativeName=o=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence})],o)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/key_usage.js
var require_key_usage=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.KeyUsage=e.KeyUsageFlags=e.id_ce_keyUsage=void 0;const t=require_cjs$10();const n=require_object_identifiers$5();e.id_ce_keyUsage=`${n.id_ce}.15`;var r;(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`})(r||(e.KeyUsageFlags=r={}));var KeyUsage=class extends t.BitString{toJSON(){const e=this.toNumber();const t=[];if(e&r.cRLSign)t.push(`crlSign`);if(e&r.dataEncipherment)t.push(`dataEncipherment`);if(e&r.decipherOnly)t.push(`decipherOnly`);if(e&r.digitalSignature)t.push(`digitalSignature`);if(e&r.encipherOnly)t.push(`encipherOnly`);if(e&r.keyAgreement)t.push(`keyAgreement`);if(e&r.keyCertSign)t.push(`keyCertSign`);if(e&r.keyEncipherment)t.push(`keyEncipherment`);if(e&r.nonRepudiation)t.push(`nonRepudiation`);return t}toString(){return`[${this.toJSON().join(`, `)}]`}};e.KeyUsage=KeyUsage}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/name_constraints.js
var require_name_constraints=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.NameConstraints=e.GeneralSubtrees=e.GeneralSubtree=e.id_ce_nameConstraints=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_general_name();const a=require_object_identifiers$5();e.id_ce_nameConstraints=`${a.id_ce}.30`;var GeneralSubtree=class{base=new i.GeneralName;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};e.GeneralSubtree=GeneralSubtree;n.__decorate([(0,r.AsnProp)({type:i.GeneralName})],GeneralSubtree.prototype,`base`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Integer,context:0,defaultValue:0,implicit:true})],GeneralSubtree.prototype,`minimum`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Integer,context:1,optional:true,implicit:true})],GeneralSubtree.prototype,`maximum`,void 0);let o=t=class GeneralSubtrees extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.GeneralSubtrees=o;e.GeneralSubtrees=o=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:GeneralSubtree})],o);var NameConstraints=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};e.NameConstraints=NameConstraints;n.__decorate([(0,r.AsnProp)({type:o,context:0,optional:true,implicit:true})],NameConstraints.prototype,`permittedSubtrees`,void 0);n.__decorate([(0,r.AsnProp)({type:o,context:1,optional:true,implicit:true})],NameConstraints.prototype,`excludedSubtrees`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/policy_constraints.js
var require_policy_constraints=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.PolicyConstraints=e.id_ce_policyConstraints=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_object_identifiers$5();e.id_ce_policyConstraints=`${r.id_ce}.36`;var PolicyConstraints=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};e.PolicyConstraints=PolicyConstraints;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,context:0,implicit:true,optional:true,converter:n.AsnIntegerArrayBufferConverter})],PolicyConstraints.prototype,`requireExplicitPolicy`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,context:1,implicit:true,optional:true,converter:n.AsnIntegerArrayBufferConverter})],PolicyConstraints.prototype,`inhibitPolicyMapping`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/policy_mappings.js
var require_policy_mappings=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.PolicyMappings=e.PolicyMapping=e.id_ce_policyMappings=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_object_identifiers$5();e.id_ce_policyMappings=`${i.id_ce}.33`;var PolicyMapping=class{issuerDomainPolicy=``;subjectDomainPolicy=``;constructor(e={}){Object.assign(this,e)}};e.PolicyMapping=PolicyMapping;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.ObjectIdentifier})],PolicyMapping.prototype,`issuerDomainPolicy`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.ObjectIdentifier})],PolicyMapping.prototype,`subjectDomainPolicy`,void 0);let a=t=class PolicyMappings extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.PolicyMappings=a;e.PolicyMappings=a=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:PolicyMapping})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/subject_alternative_name.js
var require_subject_alternative_name=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.SubjectAlternativeName=e.id_ce_subjectAltName=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_general_names();const a=require_object_identifiers$5();e.id_ce_subjectAltName=`${a.id_ce}.17`;let o=t=class SubjectAlternativeName extends i.GeneralNames{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.SubjectAlternativeName=o;e.SubjectAlternativeName=o=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence})],o)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/attribute.js
var require_attribute$2=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.Attribute=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();var Attribute=class{type=``;values=[];constructor(e={}){Object.assign(this,e)}};e.Attribute=Attribute;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],Attribute.prototype,`type`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any,repeated:`set`})],Attribute.prototype,`values`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/subject_directory_attributes.js
var require_subject_directory_attributes=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.SubjectDirectoryAttributes=e.id_ce_subjectDirectoryAttributes=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_attribute$2();const a=require_object_identifiers$5();e.id_ce_subjectDirectoryAttributes=`${a.id_ce}.9`;let o=t=class SubjectDirectoryAttributes extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.SubjectDirectoryAttributes=o;e.SubjectDirectoryAttributes=o=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:i.Attribute})],o)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/subject_key_identifier.js
var require_subject_key_identifier=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.SubjectKeyIdentifier=e.id_ce_subjectKeyIdentifier=void 0;const t=require_object_identifiers$5();const n=require_authority_key_identifier();e.id_ce_subjectKeyIdentifier=`${t.id_ce}.14`;var SubjectKeyIdentifier=class extends n.KeyIdentifier{};e.SubjectKeyIdentifier=SubjectKeyIdentifier}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/private_key_usage_period.js
var require_private_key_usage_period=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.PrivateKeyUsagePeriod=e.id_ce_privateKeyUsagePeriod=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_object_identifiers$5();e.id_ce_privateKeyUsagePeriod=`${r.id_ce}.16`;var PrivateKeyUsagePeriod=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};e.PrivateKeyUsagePeriod=PrivateKeyUsagePeriod;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.GeneralizedTime,context:0,implicit:true,optional:true})],PrivateKeyUsagePeriod.prototype,`notBefore`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.GeneralizedTime,context:1,implicit:true,optional:true})],PrivateKeyUsagePeriod.prototype,`notAfter`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/entrust_version_info.js
var require_entrust_version_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.EntrustVersionInfo=e.EntrustInfo=e.EntrustInfoFlags=e.id_entrust_entrustVersInfo=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();e.id_entrust_entrustVersInfo=`1.2.840.113533.7.65.0`;var r;(function(e){e[e[`keyUpdateAllowed`]=1]=`keyUpdateAllowed`;e[e[`newExtensions`]=2]=`newExtensions`;e[e[`pKIXCertificate`]=4]=`pKIXCertificate`})(r||(e.EntrustInfoFlags=r={}));var EntrustInfo=class extends n.BitString{toJSON(){const e=[];const t=this.toNumber();if(t&r.pKIXCertificate)e.push(`pKIXCertificate`);if(t&r.newExtensions)e.push(`newExtensions`);if(t&r.keyUpdateAllowed)e.push(`keyUpdateAllowed`);return e}toString(){return`[${this.toJSON().join(`, `)}]`}};e.EntrustInfo=EntrustInfo;var EntrustVersionInfo=class{entrustVers=``;entrustInfoFlags=new EntrustInfo;constructor(e={}){Object.assign(this,e)}};e.EntrustVersionInfo=EntrustVersionInfo;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.GeneralString})],EntrustVersionInfo.prototype,`entrustVers`,void 0);t.__decorate([(0,n.AsnProp)({type:EntrustInfo})],EntrustVersionInfo.prototype,`entrustInfoFlags`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/subject_info_access.js
var require_subject_info_access=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.SubjectInfoAccessSyntax=e.id_pe_subjectInfoAccess=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_object_identifiers$5();const a=require_authority_information_access();e.id_pe_subjectInfoAccess=`${i.id_pe}.11`;let o=t=class SubjectInfoAccessSyntax extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.SubjectInfoAccessSyntax=o;e.SubjectInfoAccessSyntax=o=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:a.AccessDescription})],o)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extensions/index.js
var require_extensions=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_authority_information_access(),e);t.__exportStar(require_authority_key_identifier(),e);t.__exportStar(require_basic_constraints(),e);t.__exportStar(require_certificate_issuer(),e);t.__exportStar(require_certificate_policies(),e);t.__exportStar(require_crl_delta_indicator(),e);t.__exportStar(require_crl_distribution_points(),e);t.__exportStar(require_crl_freshest(),e);t.__exportStar(require_crl_issuing_distribution_point(),e);t.__exportStar(require_crl_number(),e);t.__exportStar(require_crl_reason(),e);t.__exportStar(require_extended_key_usage(),e);t.__exportStar(require_inhibit_any_policy(),e);t.__exportStar(require_invalidity_date(),e);t.__exportStar(require_issuer_alternative_name(),e);t.__exportStar(require_key_usage(),e);t.__exportStar(require_name_constraints(),e);t.__exportStar(require_policy_constraints(),e);t.__exportStar(require_policy_mappings(),e);t.__exportStar(require_subject_alternative_name(),e);t.__exportStar(require_subject_directory_attributes(),e);t.__exportStar(require_subject_key_identifier(),e);t.__exportStar(require_private_key_usage_period(),e);t.__exportStar(require_entrust_version_info(),e);t.__exportStar(require_subject_info_access(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/algorithm_identifier.js
var require_algorithm_identifier=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AlgorithmIdentifier=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_bytes();var i=class AlgorithmIdentifier{algorithm=``;parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof AlgorithmIdentifier&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&(0,r.equal)(e.parameters,this.parameters)||e.parameters===this.parameters)}};e.AlgorithmIdentifier=i;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],i.prototype,`algorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any,optional:true})],i.prototype,`parameters`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/subject_public_key_info.js
var require_subject_public_key_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.SubjectPublicKeyInfo=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_algorithm_identifier();var SubjectPublicKeyInfo=class{algorithm=new r.AlgorithmIdentifier;subjectPublicKey=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.SubjectPublicKeyInfo=SubjectPublicKeyInfo;t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier})],SubjectPublicKeyInfo.prototype,`algorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.BitString})],SubjectPublicKeyInfo.prototype,`subjectPublicKey`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/time.js
var require_time=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.Time=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();let r=class Time{utcTime;generalTime;constructor(e){if(e){if(typeof e===`string`||typeof e===`number`||e instanceof Date){const t=new Date(e);t.setMilliseconds(0);if(t.getUTCFullYear()>2049)this.generalTime=t;else 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}};e.Time=r;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.UTCTime})],r.prototype,`utcTime`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.GeneralizedTime})],r.prototype,`generalTime`,void 0);e.Time=r=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],r)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/validity.js
var require_validity=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.Validity=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_time();var Validity=class{notBefore=new r.Time(/* @__PURE__ */ new Date);notAfter=new r.Time(/* @__PURE__ */ new Date);constructor(e){if(e){this.notBefore=new r.Time(e.notBefore);this.notAfter=new r.Time(e.notAfter)}}};e.Validity=Validity;t.__decorate([(0,n.AsnProp)({type:r.Time})],Validity.prototype,`notBefore`,void 0);t.__decorate([(0,n.AsnProp)({type:r.Time})],Validity.prototype,`notAfter`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/extension.js
var require_extension=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.Extensions=e.Extension=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();var i=class Extension{static CRITICAL=false;extnID=``;critical=Extension.CRITICAL;extnValue=new r.OctetString;constructor(e={}){Object.assign(this,e)}};e.Extension=i;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.ObjectIdentifier})],i.prototype,`extnID`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Boolean,defaultValue:i.CRITICAL})],i.prototype,`critical`,void 0);n.__decorate([(0,r.AsnProp)({type:r.OctetString})],i.prototype,`extnValue`,void 0);let a=t=class Extensions extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.Extensions=a;e.Extensions=a=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:i})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/types.js
var require_types$4=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.Version=void 0;var t;(function(e){e[e[`v1`]=0]=`v1`;e[e[`v2`]=1]=`v2`;e[e[`v3`]=2]=`v3`})(t||(e.Version=t={}))}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/tbs_certificate.js
var require_tbs_certificate=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.TBSCertificate=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_algorithm_identifier();const i=require_name();const a=require_subject_public_key_info();const o=require_validity();const s=require_extension();const c=require_types$4();var TBSCertificate=class{version=c.Version.v1;serialNumber=/* @__PURE__ */ new ArrayBuffer(0);signature=new r.AlgorithmIdentifier;issuer=new i.Name;validity=new o.Validity;subject=new i.Name;subjectPublicKeyInfo=new a.SubjectPublicKeyInfo;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};e.TBSCertificate=TBSCertificate;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,context:0,defaultValue:c.Version.v1})],TBSCertificate.prototype,`version`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],TBSCertificate.prototype,`serialNumber`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier})],TBSCertificate.prototype,`signature`,void 0);t.__decorate([(0,n.AsnProp)({type:i.Name})],TBSCertificate.prototype,`issuer`,void 0);t.__decorate([(0,n.AsnProp)({type:o.Validity})],TBSCertificate.prototype,`validity`,void 0);t.__decorate([(0,n.AsnProp)({type:i.Name})],TBSCertificate.prototype,`subject`,void 0);t.__decorate([(0,n.AsnProp)({type:a.SubjectPublicKeyInfo})],TBSCertificate.prototype,`subjectPublicKeyInfo`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.BitString,context:1,implicit:true,optional:true})],TBSCertificate.prototype,`issuerUniqueID`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.BitString,context:2,implicit:true,optional:true})],TBSCertificate.prototype,`subjectUniqueID`,void 0);t.__decorate([(0,n.AsnProp)({type:s.Extensions,context:3,optional:true})],TBSCertificate.prototype,`extensions`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/certificate.js
var require_certificate=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.Certificate=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_algorithm_identifier();const i=require_tbs_certificate();var Certificate=class{tbsCertificate=new i.TBSCertificate;tbsCertificateRaw;signatureAlgorithm=new r.AlgorithmIdentifier;signatureValue=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.Certificate=Certificate;t.__decorate([(0,n.AsnProp)({type:i.TBSCertificate,raw:true})],Certificate.prototype,`tbsCertificate`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier})],Certificate.prototype,`signatureAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.BitString})],Certificate.prototype,`signatureValue`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/tbs_cert_list.js
var require_tbs_cert_list=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.TBSCertList=e.RevokedCertificate=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_algorithm_identifier();const i=require_name();const a=require_time();const o=require_extension();var RevokedCertificate=class{userCertificate=/* @__PURE__ */ new ArrayBuffer(0);revocationDate=new a.Time;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};e.RevokedCertificate=RevokedCertificate;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],RevokedCertificate.prototype,`userCertificate`,void 0);t.__decorate([(0,n.AsnProp)({type:a.Time})],RevokedCertificate.prototype,`revocationDate`,void 0);t.__decorate([(0,n.AsnProp)({type:o.Extension,optional:true,repeated:`sequence`})],RevokedCertificate.prototype,`crlEntryExtensions`,void 0);var TBSCertList=class{version;signature=new r.AlgorithmIdentifier;issuer=new i.Name;thisUpdate=new a.Time;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};e.TBSCertList=TBSCertList;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,optional:true})],TBSCertList.prototype,`version`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier})],TBSCertList.prototype,`signature`,void 0);t.__decorate([(0,n.AsnProp)({type:i.Name})],TBSCertList.prototype,`issuer`,void 0);t.__decorate([(0,n.AsnProp)({type:a.Time})],TBSCertList.prototype,`thisUpdate`,void 0);t.__decorate([(0,n.AsnProp)({type:a.Time,optional:true})],TBSCertList.prototype,`nextUpdate`,void 0);t.__decorate([(0,n.AsnProp)({type:RevokedCertificate,repeated:`sequence`,optional:true})],TBSCertList.prototype,`revokedCertificates`,void 0);t.__decorate([(0,n.AsnProp)({type:o.Extension,optional:true,context:0,repeated:`sequence`})],TBSCertList.prototype,`crlExtensions`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/certificate_list.js
var require_certificate_list=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.CertificateList=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_algorithm_identifier();const i=require_tbs_cert_list();var CertificateList=class{tbsCertList=new i.TBSCertList;tbsCertListRaw;signatureAlgorithm=new r.AlgorithmIdentifier;signature=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.CertificateList=CertificateList;t.__decorate([(0,n.AsnProp)({type:i.TBSCertList,raw:true})],CertificateList.prototype,`tbsCertList`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier})],CertificateList.prototype,`signatureAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.BitString})],CertificateList.prototype,`signature`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509@2.11.0/node_modules/@peculiar/asn1-x509/build/cjs/index.js
var require_cjs$9=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_extensions(),e);t.__exportStar(require_algorithm_identifier(),e);t.__exportStar(require_attribute$2(),e);t.__exportStar(require_certificate(),e);t.__exportStar(require_certificate_list(),e);t.__exportStar(require_extension(),e);t.__exportStar(require_general_name(),e);t.__exportStar(require_general_names(),e);t.__exportStar(require_name(),e);t.__exportStar(require_object_identifiers$5(),e);t.__exportStar(require_subject_public_key_info(),e);t.__exportStar(require_tbs_cert_list(),e);t.__exportStar(require_tbs_certificate(),e);t.__exportStar(require_time(),e);t.__exportStar(require_types$4(),e);t.__exportStar(require_validity(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/issuer_and_serial_number.js
var require_issuer_and_serial_number=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.IssuerAndSerialNumber=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();var IssuerAndSerialNumber=class{issuer=new r.Name;serialNumber=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.IssuerAndSerialNumber=IssuerAndSerialNumber;t.__decorate([(0,n.AsnProp)({type:r.Name})],IssuerAndSerialNumber.prototype,`issuer`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],IssuerAndSerialNumber.prototype,`serialNumber`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/signer_identifier.js
var require_signer_identifier=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.SignerIdentifier=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();const i=require_issuer_and_serial_number();let a=class SignerIdentifier{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};e.SignerIdentifier=a;t.__decorate([(0,n.AsnProp)({type:r.SubjectKeyIdentifier,context:0,implicit:true})],a.prototype,`subjectKeyIdentifier`,void 0);t.__decorate([(0,n.AsnProp)({type:i.IssuerAndSerialNumber})],a.prototype,`issuerAndSerialNumber`,void 0);e.SignerIdentifier=a=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/types.js
var require_types$3=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.KeyDerivationAlgorithmIdentifier=e.MessageAuthenticationCodeAlgorithm=e.ContentEncryptionAlgorithmIdentifier=e.KeyEncryptionAlgorithmIdentifier=e.SignatureAlgorithmIdentifier=e.DigestAlgorithmIdentifier=e.CMSVersion=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$9();const r=require_cjs$10();var i;(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`})(i||(e.CMSVersion=i={}));let a=class DigestAlgorithmIdentifier extends n.AlgorithmIdentifier{};e.DigestAlgorithmIdentifier=a;e.DigestAlgorithmIdentifier=a=t.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence})],a);let o=class SignatureAlgorithmIdentifier extends n.AlgorithmIdentifier{};e.SignatureAlgorithmIdentifier=o;e.SignatureAlgorithmIdentifier=o=t.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence})],o);let s=class KeyEncryptionAlgorithmIdentifier extends n.AlgorithmIdentifier{};e.KeyEncryptionAlgorithmIdentifier=s;e.KeyEncryptionAlgorithmIdentifier=s=t.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence})],s);let c=class ContentEncryptionAlgorithmIdentifier extends n.AlgorithmIdentifier{};e.ContentEncryptionAlgorithmIdentifier=c;e.ContentEncryptionAlgorithmIdentifier=c=t.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence})],c);let u=class MessageAuthenticationCodeAlgorithm extends n.AlgorithmIdentifier{};e.MessageAuthenticationCodeAlgorithm=u;e.MessageAuthenticationCodeAlgorithm=u=t.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence})],u);let d=class KeyDerivationAlgorithmIdentifier extends n.AlgorithmIdentifier{};e.KeyDerivationAlgorithmIdentifier=d;e.KeyDerivationAlgorithmIdentifier=d=t.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence})],d)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/attribute.js
var require_attribute$1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.Attribute=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();var Attribute=class{attrType=``;attrValues=[];constructor(e={}){Object.assign(this,e)}};e.Attribute=Attribute;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],Attribute.prototype,`attrType`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any,repeated:`set`})],Attribute.prototype,`attrValues`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/signer_info.js
var require_signer_info=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.SignerInfos=e.SignerInfo=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_signer_identifier();const a=require_types$3();const o=require_attribute$1();var SignerInfo=class{version=a.CMSVersion.v0;sid=new i.SignerIdentifier;digestAlgorithm=new a.DigestAlgorithmIdentifier;signedAttrs;signedAttrsRaw;signatureAlgorithm=new a.SignatureAlgorithmIdentifier;signature=new r.OctetString;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};e.SignerInfo=SignerInfo;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Integer})],SignerInfo.prototype,`version`,void 0);n.__decorate([(0,r.AsnProp)({type:i.SignerIdentifier})],SignerInfo.prototype,`sid`,void 0);n.__decorate([(0,r.AsnProp)({type:a.DigestAlgorithmIdentifier})],SignerInfo.prototype,`digestAlgorithm`,void 0);n.__decorate([(0,r.AsnProp)({type:o.Attribute,repeated:`set`,context:0,implicit:true,optional:true,raw:true})],SignerInfo.prototype,`signedAttrs`,void 0);n.__decorate([(0,r.AsnProp)({type:a.SignatureAlgorithmIdentifier})],SignerInfo.prototype,`signatureAlgorithm`,void 0);n.__decorate([(0,r.AsnProp)({type:r.OctetString})],SignerInfo.prototype,`signature`,void 0);n.__decorate([(0,r.AsnProp)({type:o.Attribute,repeated:`set`,context:1,implicit:true,optional:true})],SignerInfo.prototype,`unsignedAttrs`,void 0);let s=t=class SignerInfos extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.SignerInfos=s;e.SignerInfos=s=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Set,itemType:SignerInfo})],s)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/attributes/counter_signature.js
var require_counter_signature=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.CounterSignature=e.id_counterSignature=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_signer_info();e.id_counterSignature=`1.2.840.113549.1.9.6`;let i=class CounterSignature extends r.SignerInfo{};e.CounterSignature=i;e.CounterSignature=i=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Sequence})],i)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/attributes/message_digest.js
var require_message_digest=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.MessageDigest=e.id_messageDigest=void 0;const t=require_cjs$10();e.id_messageDigest=`1.2.840.113549.1.9.4`;var MessageDigest=class extends t.OctetString{};e.MessageDigest=MessageDigest}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/attributes/signing_time.js
var require_signing_time=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.SigningTime=e.id_signingTime=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$9();const r=require_cjs$10();e.id_signingTime=`1.2.840.113549.1.9.5`;let i=class SigningTime extends n.Time{};e.SigningTime=i;e.SigningTime=i=t.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Choice})],i)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/attributes/index.js
var require_attributes$1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.id_contentType=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_counter_signature(),e);t.__exportStar(require_message_digest(),e);t.__exportStar(require_signing_time(),e);e.id_contentType=`1.2.840.113549.1.9.3`}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/aa_clear_attrs.js
var require_aa_clear_attrs=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.ACClearAttrs=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();var ACClearAttrs=class{acIssuer=new r.GeneralName;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};e.ACClearAttrs=ACClearAttrs;t.__decorate([(0,n.AsnProp)({type:r.GeneralName})],ACClearAttrs.prototype,`acIssuer`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer})],ACClearAttrs.prototype,`acSerial`,void 0);t.__decorate([(0,n.AsnProp)({type:r.Attribute,repeated:`sequence`})],ACClearAttrs.prototype,`attrs`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/attr_spec.js
var require_attr_spec=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.AttrSpec=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();let i=t=class AttrSpec extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.AttrSpec=i;e.AttrSpec=i=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:r.AsnPropTypes.ObjectIdentifier})],i)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/aa_controls.js
var require_aa_controls=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AAControls=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_attr_spec();var AAControls=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=true;constructor(e={}){Object.assign(this,e)}};e.AAControls=AAControls;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,optional:true})],AAControls.prototype,`pathLenConstraint`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AttrSpec,implicit:true,context:0,optional:true})],AAControls.prototype,`permittedAttrs`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AttrSpec,implicit:true,context:1,optional:true})],AAControls.prototype,`excludedAttrs`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Boolean,defaultValue:true})],AAControls.prototype,`permitUnSpecified`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/issuer_serial.js
var require_issuer_serial=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.IssuerSerial=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();var IssuerSerial=class{issuer=new r.GeneralNames;serial=/* @__PURE__ */ new ArrayBuffer(0);issuerUID=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.IssuerSerial=IssuerSerial;t.__decorate([(0,n.AsnProp)({type:r.GeneralNames})],IssuerSerial.prototype,`issuer`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],IssuerSerial.prototype,`serial`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.BitString,optional:true})],IssuerSerial.prototype,`issuerUID`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/object_digest_info.js
var require_object_digest_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.ObjectDigestInfo=e.DigestedObjectType=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();var i;(function(e){e[e[`publicKey`]=0]=`publicKey`;e[e[`publicKeyCert`]=1]=`publicKeyCert`;e[e[`otherObjectTypes`]=2]=`otherObjectTypes`})(i||(e.DigestedObjectType=i={}));var ObjectDigestInfo=class{digestedObjectType=i.publicKey;otherObjectTypeID;digestAlgorithm=new r.AlgorithmIdentifier;objectDigest=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.ObjectDigestInfo=ObjectDigestInfo;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Enumerated})],ObjectDigestInfo.prototype,`digestedObjectType`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier,optional:true})],ObjectDigestInfo.prototype,`otherObjectTypeID`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier})],ObjectDigestInfo.prototype,`digestAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.BitString})],ObjectDigestInfo.prototype,`objectDigest`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/v2_form.js
var require_v2_form=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.V2Form=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();const i=require_issuer_serial();const a=require_object_digest_info();var V2Form=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};e.V2Form=V2Form;t.__decorate([(0,n.AsnProp)({type:r.GeneralNames,optional:true})],V2Form.prototype,`issuerName`,void 0);t.__decorate([(0,n.AsnProp)({type:i.IssuerSerial,context:0,implicit:true,optional:true})],V2Form.prototype,`baseCertificateID`,void 0);t.__decorate([(0,n.AsnProp)({type:a.ObjectDigestInfo,context:1,implicit:true,optional:true})],V2Form.prototype,`objectDigestInfo`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/attr_cert_issuer.js
var require_attr_cert_issuer=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AttCertIssuer=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();const i=require_v2_form();let a=class AttCertIssuer{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};e.AttCertIssuer=a;t.__decorate([(0,n.AsnProp)({type:r.GeneralName,repeated:`sequence`})],a.prototype,`v1Form`,void 0);t.__decorate([(0,n.AsnProp)({type:i.V2Form,context:0,implicit:true})],a.prototype,`v2Form`,void 0);e.AttCertIssuer=a=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/attr_cert_validity_period.js
var require_attr_cert_validity_period=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AttCertValidityPeriod=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();var AttCertValidityPeriod=class{notBeforeTime=/* @__PURE__ */ new Date;notAfterTime=/* @__PURE__ */ new Date;constructor(e={}){Object.assign(this,e)}};e.AttCertValidityPeriod=AttCertValidityPeriod;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.GeneralizedTime})],AttCertValidityPeriod.prototype,`notBeforeTime`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.GeneralizedTime})],AttCertValidityPeriod.prototype,`notAfterTime`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/holder.js
var require_holder=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.Holder=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();const i=require_issuer_serial();const a=require_object_digest_info();var Holder=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};e.Holder=Holder;t.__decorate([(0,n.AsnProp)({type:i.IssuerSerial,implicit:true,context:0,optional:true})],Holder.prototype,`baseCertificateID`,void 0);t.__decorate([(0,n.AsnProp)({type:r.GeneralNames,implicit:true,context:1,optional:true})],Holder.prototype,`entityName`,void 0);t.__decorate([(0,n.AsnProp)({type:a.ObjectDigestInfo,implicit:true,context:2,optional:true})],Holder.prototype,`objectDigestInfo`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/attribute_certificate_info.js
var require_attribute_certificate_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AttributeCertificateInfo=e.AttCertVersion=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();const i=require_holder();const a=require_attr_cert_issuer();const o=require_attr_cert_validity_period();var s;(function(e){e[e[`v2`]=1]=`v2`})(s||(e.AttCertVersion=s={}));var AttributeCertificateInfo=class{version=s.v2;holder=new i.Holder;issuer=new a.AttCertIssuer;signature=new r.AlgorithmIdentifier;serialNumber=/* @__PURE__ */ new ArrayBuffer(0);attrCertValidityPeriod=new o.AttCertValidityPeriod;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};e.AttributeCertificateInfo=AttributeCertificateInfo;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer})],AttributeCertificateInfo.prototype,`version`,void 0);t.__decorate([(0,n.AsnProp)({type:i.Holder})],AttributeCertificateInfo.prototype,`holder`,void 0);t.__decorate([(0,n.AsnProp)({type:a.AttCertIssuer})],AttributeCertificateInfo.prototype,`issuer`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier})],AttributeCertificateInfo.prototype,`signature`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],AttributeCertificateInfo.prototype,`serialNumber`,void 0);t.__decorate([(0,n.AsnProp)({type:o.AttCertValidityPeriod})],AttributeCertificateInfo.prototype,`attrCertValidityPeriod`,void 0);t.__decorate([(0,n.AsnProp)({type:r.Attribute,repeated:`sequence`})],AttributeCertificateInfo.prototype,`attributes`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.BitString,optional:true})],AttributeCertificateInfo.prototype,`issuerUniqueID`,void 0);t.__decorate([(0,n.AsnProp)({type:r.Extensions,optional:true})],AttributeCertificateInfo.prototype,`extensions`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/attribute_certificate.js
var require_attribute_certificate=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.AttributeCertificate=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();const i=require_attribute_certificate_info();var AttributeCertificate=class{acinfo=new i.AttributeCertificateInfo;signatureAlgorithm=new r.AlgorithmIdentifier;signatureValue=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.AttributeCertificate=AttributeCertificate;t.__decorate([(0,n.AsnProp)({type:i.AttributeCertificateInfo})],AttributeCertificate.prototype,`acinfo`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier})],AttributeCertificate.prototype,`signatureAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.BitString})],AttributeCertificate.prototype,`signatureValue`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/class_list.js
var require_class_list=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.ClassList=e.ClassListFlags=void 0;const t=require_cjs$10();var n;(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`})(n||(e.ClassListFlags=n={}));var ClassList=class extends t.BitString{};e.ClassList=ClassList}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/security_category.js
var require_security_category=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.SecurityCategory=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();var SecurityCategory=class{type=``;value=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.SecurityCategory=SecurityCategory;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier,implicit:true,context:0})],SecurityCategory.prototype,`type`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any,implicit:true,context:1})],SecurityCategory.prototype,`value`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/clearance.js
var require_clearance=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.Clearance=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_class_list();const i=require_security_category();var Clearance=class{policyId=``;classList=new r.ClassList(r.ClassListFlags.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};e.Clearance=Clearance;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],Clearance.prototype,`policyId`,void 0);t.__decorate([(0,n.AsnProp)({type:r.ClassList,defaultValue:new r.ClassList(r.ClassListFlags.unclassified)})],Clearance.prototype,`classList`,void 0);t.__decorate([(0,n.AsnProp)({type:i.SecurityCategory,repeated:`set`})],Clearance.prototype,`securityCategories`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/ietf_attr_syntax.js
var require_ietf_attr_syntax=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.IetfAttrSyntax=e.IetfAttrSyntaxValueChoices=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();var IetfAttrSyntaxValueChoices=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};e.IetfAttrSyntaxValueChoices=IetfAttrSyntaxValueChoices;t.__decorate([(0,n.AsnProp)({type:n.OctetString})],IetfAttrSyntaxValueChoices.prototype,`cotets`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],IetfAttrSyntaxValueChoices.prototype,`oid`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Utf8String})],IetfAttrSyntaxValueChoices.prototype,`string`,void 0);var IetfAttrSyntax=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};e.IetfAttrSyntax=IetfAttrSyntax;t.__decorate([(0,n.AsnProp)({type:r.GeneralNames,implicit:true,context:0,optional:true})],IetfAttrSyntax.prototype,`policyAuthority`,void 0);t.__decorate([(0,n.AsnProp)({type:IetfAttrSyntaxValueChoices,repeated:`sequence`})],IetfAttrSyntax.prototype,`values`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/object_identifiers.js
var require_object_identifiers$4=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.id_at_clearance=e.id_at_role=e.id_at=e.id_aca_encAttrs=e.id_aca_group=e.id_aca_chargingIdentity=e.id_aca_accessIdentity=e.id_aca_authenticationInfo=e.id_aca=e.id_ce_targetInformation=e.id_pe_ac_proxying=e.id_pe_aaControls=e.id_pe_ac_auditIdentity=void 0;const t=require_cjs$9();e.id_pe_ac_auditIdentity=`${t.id_pe}.4`;e.id_pe_aaControls=`${t.id_pe}.6`;e.id_pe_ac_proxying=`${t.id_pe}.10`;e.id_ce_targetInformation=`${t.id_ce}.55`;e.id_aca=`${t.id_pkix}.10`;e.id_aca_authenticationInfo=`${e.id_aca}.1`;e.id_aca_accessIdentity=`${e.id_aca}.2`;e.id_aca_chargingIdentity=`${e.id_aca}.3`;e.id_aca_group=`${e.id_aca}.4`;e.id_aca_encAttrs=`${e.id_aca}.6`;e.id_at=`2.5.4`;e.id_at_role=`${e.id_at}.72`;e.id_at_clearance=`2.5.1.5.55`}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/target.js
var require_target=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.Targets=e.Target=e.TargetCert=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_cjs$9();const a=require_issuer_serial();const o=require_object_digest_info();var TargetCert=class{targetCertificate=new a.IssuerSerial;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};e.TargetCert=TargetCert;n.__decorate([(0,r.AsnProp)({type:a.IssuerSerial})],TargetCert.prototype,`targetCertificate`,void 0);n.__decorate([(0,r.AsnProp)({type:i.GeneralName,optional:true})],TargetCert.prototype,`targetName`,void 0);n.__decorate([(0,r.AsnProp)({type:o.ObjectDigestInfo,optional:true})],TargetCert.prototype,`certDigestInfo`,void 0);let s=class Target{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};e.Target=s;n.__decorate([(0,r.AsnProp)({type:i.GeneralName,context:0,implicit:true})],s.prototype,`targetName`,void 0);n.__decorate([(0,r.AsnProp)({type:i.GeneralName,context:1,implicit:true})],s.prototype,`targetGroup`,void 0);n.__decorate([(0,r.AsnProp)({type:TargetCert,context:2,implicit:true})],s.prototype,`targetCert`,void 0);e.Target=s=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Choice})],s);let c=t=class Targets extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.Targets=c;e.Targets=c=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:s})],c)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/proxy_info.js
var require_proxy_info=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.ProxyInfo=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_target();let a=t=class ProxyInfo extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.ProxyInfo=a;e.ProxyInfo=a=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:i.Targets})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/role_syntax.js
var require_role_syntax=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.RoleSyntax=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();var RoleSyntax=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};e.RoleSyntax=RoleSyntax;t.__decorate([(0,n.AsnProp)({type:r.GeneralNames,implicit:true,context:0,optional:true})],RoleSyntax.prototype,`roleAuthority`,void 0);t.__decorate([(0,n.AsnProp)({type:r.GeneralName,implicit:true,context:1})],RoleSyntax.prototype,`roleName`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/svce_auth_info.js
var require_svce_auth_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.SvceAuthInfo=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();var SvceAuthInfo=class{service=new r.GeneralName;ident=new r.GeneralName;authInfo;constructor(e={}){Object.assign(this,e)}};e.SvceAuthInfo=SvceAuthInfo;t.__decorate([(0,n.AsnProp)({type:r.GeneralName})],SvceAuthInfo.prototype,`service`,void 0);t.__decorate([(0,n.AsnProp)({type:r.GeneralName})],SvceAuthInfo.prototype,`ident`,void 0);t.__decorate([(0,n.AsnProp)({type:n.OctetString,optional:true})],SvceAuthInfo.prototype,`authInfo`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-x509-attr@2.11.0/node_modules/@peculiar/asn1-x509-attr/build/cjs/index.js
var require_cjs$8=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_aa_clear_attrs(),e);t.__exportStar(require_aa_controls(),e);t.__exportStar(require_attr_cert_issuer(),e);t.__exportStar(require_attr_cert_validity_period(),e);t.__exportStar(require_attr_spec(),e);t.__exportStar(require_attribute_certificate(),e);t.__exportStar(require_attribute_certificate_info(),e);t.__exportStar(require_class_list(),e);t.__exportStar(require_clearance(),e);t.__exportStar(require_holder(),e);t.__exportStar(require_ietf_attr_syntax(),e);t.__exportStar(require_issuer_serial(),e);t.__exportStar(require_object_digest_info(),e);t.__exportStar(require_object_identifiers$4(),e);t.__exportStar(require_proxy_info(),e);t.__exportStar(require_role_syntax(),e);t.__exportStar(require_security_category(),e);t.__exportStar(require_svce_auth_info(),e);t.__exportStar(require_target(),e);t.__exportStar(require_v2_form(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/certificate_choices.js
var require_certificate_choices=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.CertificateSet=e.CertificateChoices=e.OtherCertificateFormat=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_cjs$9();const a=require_cjs$8();var OtherCertificateFormat=class{otherCertFormat=``;otherCert=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.OtherCertificateFormat=OtherCertificateFormat;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.ObjectIdentifier})],OtherCertificateFormat.prototype,`otherCertFormat`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Any})],OtherCertificateFormat.prototype,`otherCert`,void 0);let o=class CertificateChoices{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};e.CertificateChoices=o;n.__decorate([(0,r.AsnProp)({type:i.Certificate})],o.prototype,`certificate`,void 0);n.__decorate([(0,r.AsnProp)({type:a.AttributeCertificate,context:2,implicit:true})],o.prototype,`v2AttrCert`,void 0);n.__decorate([(0,r.AsnProp)({type:OtherCertificateFormat,context:3,implicit:true})],o.prototype,`other`,void 0);e.CertificateChoices=o=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Choice})],o);let s=t=class CertificateSet extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.CertificateSet=s;e.CertificateSet=s=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Set,itemType:o})],s)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/content_info.js
var require_content_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.ContentInfo=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();var ContentInfo=class{contentType=``;content=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.ContentInfo=ContentInfo;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],ContentInfo.prototype,`contentType`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any,context:0})],ContentInfo.prototype,`content`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/encapsulated_content_info.js
var require_encapsulated_content_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.EncapsulatedContentInfo=e.EncapsulatedContent=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();let r=class EncapsulatedContent{single;any;constructor(e={}){Object.assign(this,e)}};e.EncapsulatedContent=r;t.__decorate([(0,n.AsnProp)({type:n.OctetString})],r.prototype,`single`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any})],r.prototype,`any`,void 0);e.EncapsulatedContent=r=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],r);var EncapsulatedContentInfo=class{eContentType=``;eContent;constructor(e={}){Object.assign(this,e)}};e.EncapsulatedContentInfo=EncapsulatedContentInfo;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],EncapsulatedContentInfo.prototype,`eContentType`,void 0);t.__decorate([(0,n.AsnProp)({type:r,context:0,optional:true})],EncapsulatedContentInfo.prototype,`eContent`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/encrypted_content_info.js
var require_encrypted_content_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.EncryptedContentInfo=e.EncryptedContent=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_types$3();let i=class EncryptedContent{value;constructedValue;constructor(e={}){Object.assign(this,e)}};e.EncryptedContent=i;t.__decorate([(0,n.AsnProp)({type:n.OctetString,context:0,implicit:true,optional:true})],i.prototype,`value`,void 0);t.__decorate([(0,n.AsnProp)({type:n.OctetString,converter:n.AsnConstructedOctetStringConverter,context:0,implicit:true,optional:true,repeated:`sequence`})],i.prototype,`constructedValue`,void 0);e.EncryptedContent=i=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],i);var EncryptedContentInfo=class{contentType=``;contentEncryptionAlgorithm=new r.ContentEncryptionAlgorithmIdentifier;encryptedContent;constructor(e={}){Object.assign(this,e)}};e.EncryptedContentInfo=EncryptedContentInfo;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],EncryptedContentInfo.prototype,`contentType`,void 0);t.__decorate([(0,n.AsnProp)({type:r.ContentEncryptionAlgorithmIdentifier})],EncryptedContentInfo.prototype,`contentEncryptionAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:i,optional:true})],EncryptedContentInfo.prototype,`encryptedContent`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/other_key_attribute.js
var require_other_key_attribute=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.OtherKeyAttribute=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();var OtherKeyAttribute=class{keyAttrId=``;keyAttr;constructor(e={}){Object.assign(this,e)}};e.OtherKeyAttribute=OtherKeyAttribute;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],OtherKeyAttribute.prototype,`keyAttrId`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any,optional:true})],OtherKeyAttribute.prototype,`keyAttr`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/key_agree_recipient_info.js
var require_key_agree_recipient_info=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.KeyAgreeRecipientInfo=e.OriginatorIdentifierOrKey=e.OriginatorPublicKey=e.RecipientEncryptedKeys=e.RecipientEncryptedKey=e.KeyAgreeRecipientIdentifier=e.RecipientKeyIdentifier=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_cjs$9();const a=require_types$3();const o=require_issuer_and_serial_number();const s=require_other_key_attribute();var RecipientKeyIdentifier=class{subjectKeyIdentifier=new i.SubjectKeyIdentifier;date;other;constructor(e={}){Object.assign(this,e)}};e.RecipientKeyIdentifier=RecipientKeyIdentifier;n.__decorate([(0,r.AsnProp)({type:i.SubjectKeyIdentifier})],RecipientKeyIdentifier.prototype,`subjectKeyIdentifier`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.GeneralizedTime,optional:true})],RecipientKeyIdentifier.prototype,`date`,void 0);n.__decorate([(0,r.AsnProp)({type:s.OtherKeyAttribute,optional:true})],RecipientKeyIdentifier.prototype,`other`,void 0);let c=class KeyAgreeRecipientIdentifier{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};e.KeyAgreeRecipientIdentifier=c;n.__decorate([(0,r.AsnProp)({type:RecipientKeyIdentifier,context:0,implicit:true,optional:true})],c.prototype,`rKeyId`,void 0);n.__decorate([(0,r.AsnProp)({type:o.IssuerAndSerialNumber,optional:true})],c.prototype,`issuerAndSerialNumber`,void 0);e.KeyAgreeRecipientIdentifier=c=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Choice})],c);var RecipientEncryptedKey=class{rid=new c;encryptedKey=new r.OctetString;constructor(e={}){Object.assign(this,e)}};e.RecipientEncryptedKey=RecipientEncryptedKey;n.__decorate([(0,r.AsnProp)({type:c})],RecipientEncryptedKey.prototype,`rid`,void 0);n.__decorate([(0,r.AsnProp)({type:r.OctetString})],RecipientEncryptedKey.prototype,`encryptedKey`,void 0);let u=t=class RecipientEncryptedKeys extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.RecipientEncryptedKeys=u;e.RecipientEncryptedKeys=u=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:RecipientEncryptedKey})],u);var OriginatorPublicKey=class{algorithm=new i.AlgorithmIdentifier;publicKey=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.OriginatorPublicKey=OriginatorPublicKey;n.__decorate([(0,r.AsnProp)({type:i.AlgorithmIdentifier})],OriginatorPublicKey.prototype,`algorithm`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.BitString})],OriginatorPublicKey.prototype,`publicKey`,void 0);let d=class OriginatorIdentifierOrKey{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};e.OriginatorIdentifierOrKey=d;n.__decorate([(0,r.AsnProp)({type:i.SubjectKeyIdentifier,context:0,implicit:true,optional:true})],d.prototype,`subjectKeyIdentifier`,void 0);n.__decorate([(0,r.AsnProp)({type:OriginatorPublicKey,context:1,implicit:true,optional:true})],d.prototype,`originatorKey`,void 0);n.__decorate([(0,r.AsnProp)({type:o.IssuerAndSerialNumber,optional:true})],d.prototype,`issuerAndSerialNumber`,void 0);e.OriginatorIdentifierOrKey=d=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Choice})],d);var KeyAgreeRecipientInfo=class{version=a.CMSVersion.v3;originator=new d;ukm;keyEncryptionAlgorithm=new a.KeyEncryptionAlgorithmIdentifier;recipientEncryptedKeys=new u;constructor(e={}){Object.assign(this,e)}};e.KeyAgreeRecipientInfo=KeyAgreeRecipientInfo;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Integer})],KeyAgreeRecipientInfo.prototype,`version`,void 0);n.__decorate([(0,r.AsnProp)({type:d,context:0})],KeyAgreeRecipientInfo.prototype,`originator`,void 0);n.__decorate([(0,r.AsnProp)({type:r.OctetString,context:1,optional:true})],KeyAgreeRecipientInfo.prototype,`ukm`,void 0);n.__decorate([(0,r.AsnProp)({type:a.KeyEncryptionAlgorithmIdentifier})],KeyAgreeRecipientInfo.prototype,`keyEncryptionAlgorithm`,void 0);n.__decorate([(0,r.AsnProp)({type:u})],KeyAgreeRecipientInfo.prototype,`recipientEncryptedKeys`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/key_trans_recipient_info.js
var require_key_trans_recipient_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.KeyTransRecipientInfo=e.RecipientIdentifier=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();const i=require_types$3();const a=require_issuer_and_serial_number();let o=class RecipientIdentifier{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};e.RecipientIdentifier=o;t.__decorate([(0,n.AsnProp)({type:r.SubjectKeyIdentifier,context:0,implicit:true})],o.prototype,`subjectKeyIdentifier`,void 0);t.__decorate([(0,n.AsnProp)({type:a.IssuerAndSerialNumber})],o.prototype,`issuerAndSerialNumber`,void 0);e.RecipientIdentifier=o=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],o);var KeyTransRecipientInfo=class{version=i.CMSVersion.v0;rid=new o;keyEncryptionAlgorithm=new i.KeyEncryptionAlgorithmIdentifier;encryptedKey=new n.OctetString;constructor(e={}){Object.assign(this,e)}};e.KeyTransRecipientInfo=KeyTransRecipientInfo;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer})],KeyTransRecipientInfo.prototype,`version`,void 0);t.__decorate([(0,n.AsnProp)({type:o})],KeyTransRecipientInfo.prototype,`rid`,void 0);t.__decorate([(0,n.AsnProp)({type:i.KeyEncryptionAlgorithmIdentifier})],KeyTransRecipientInfo.prototype,`keyEncryptionAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:n.OctetString})],KeyTransRecipientInfo.prototype,`encryptedKey`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/kek_recipient_info.js
var require_kek_recipient_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.KEKRecipientInfo=e.KEKIdentifier=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_other_key_attribute();const i=require_types$3();var KEKIdentifier=class{keyIdentifier=new n.OctetString;date;other;constructor(e={}){Object.assign(this,e)}};e.KEKIdentifier=KEKIdentifier;t.__decorate([(0,n.AsnProp)({type:n.OctetString})],KEKIdentifier.prototype,`keyIdentifier`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.GeneralizedTime,optional:true})],KEKIdentifier.prototype,`date`,void 0);t.__decorate([(0,n.AsnProp)({type:r.OtherKeyAttribute,optional:true})],KEKIdentifier.prototype,`other`,void 0);var KEKRecipientInfo=class{version=i.CMSVersion.v4;kekid=new KEKIdentifier;keyEncryptionAlgorithm=new i.KeyEncryptionAlgorithmIdentifier;encryptedKey=new n.OctetString;constructor(e={}){Object.assign(this,e)}};e.KEKRecipientInfo=KEKRecipientInfo;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer})],KEKRecipientInfo.prototype,`version`,void 0);t.__decorate([(0,n.AsnProp)({type:KEKIdentifier})],KEKRecipientInfo.prototype,`kekid`,void 0);t.__decorate([(0,n.AsnProp)({type:i.KeyEncryptionAlgorithmIdentifier})],KEKRecipientInfo.prototype,`keyEncryptionAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:n.OctetString})],KEKRecipientInfo.prototype,`encryptedKey`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/password_recipient_info.js
var require_password_recipient_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.PasswordRecipientInfo=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_types$3();var PasswordRecipientInfo=class{version=r.CMSVersion.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new r.KeyEncryptionAlgorithmIdentifier;encryptedKey=new n.OctetString;constructor(e={}){Object.assign(this,e)}};e.PasswordRecipientInfo=PasswordRecipientInfo;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer})],PasswordRecipientInfo.prototype,`version`,void 0);t.__decorate([(0,n.AsnProp)({type:r.KeyDerivationAlgorithmIdentifier,context:0,optional:true})],PasswordRecipientInfo.prototype,`keyDerivationAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:r.KeyEncryptionAlgorithmIdentifier})],PasswordRecipientInfo.prototype,`keyEncryptionAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:n.OctetString})],PasswordRecipientInfo.prototype,`encryptedKey`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/recipient_info.js
var require_recipient_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.RecipientInfo=e.OtherRecipientInfo=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_key_agree_recipient_info();const i=require_key_trans_recipient_info();const a=require_kek_recipient_info();const o=require_password_recipient_info();var OtherRecipientInfo=class{oriType=``;oriValue=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.OtherRecipientInfo=OtherRecipientInfo;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],OtherRecipientInfo.prototype,`oriType`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any})],OtherRecipientInfo.prototype,`oriValue`,void 0);let s=class RecipientInfo{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};e.RecipientInfo=s;t.__decorate([(0,n.AsnProp)({type:i.KeyTransRecipientInfo,optional:true})],s.prototype,`ktri`,void 0);t.__decorate([(0,n.AsnProp)({type:r.KeyAgreeRecipientInfo,context:1,implicit:true,optional:true})],s.prototype,`kari`,void 0);t.__decorate([(0,n.AsnProp)({type:a.KEKRecipientInfo,context:2,implicit:true,optional:true})],s.prototype,`kekri`,void 0);t.__decorate([(0,n.AsnProp)({type:o.PasswordRecipientInfo,context:3,implicit:true,optional:true})],s.prototype,`pwri`,void 0);t.__decorate([(0,n.AsnProp)({type:OtherRecipientInfo,context:4,implicit:true,optional:true})],s.prototype,`ori`,void 0);e.RecipientInfo=s=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],s)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/recipient_infos.js
var require_recipient_infos=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.RecipientInfos=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_recipient_info();let a=t=class RecipientInfos extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.RecipientInfos=a;e.RecipientInfos=a=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Set,itemType:i.RecipientInfo})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/revocation_info_choice.js
var require_revocation_info_choice=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.RevocationInfoChoices=e.RevocationInfoChoice=e.OtherRevocationInfoFormat=e.id_ri_scvp=e.id_ri_ocsp_response=e.id_ri=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_cjs$9();e.id_ri=`${i.id_pkix}.16`;e.id_ri_ocsp_response=`${e.id_ri}.2`;e.id_ri_scvp=`${e.id_ri}.4`;var OtherRevocationInfoFormat=class{otherRevInfoFormat=``;otherRevInfo=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.OtherRevocationInfoFormat=OtherRevocationInfoFormat;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.ObjectIdentifier})],OtherRevocationInfoFormat.prototype,`otherRevInfoFormat`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Any})],OtherRevocationInfoFormat.prototype,`otherRevInfo`,void 0);let a=class RevocationInfoChoice{other=new OtherRevocationInfoFormat;constructor(e={}){Object.assign(this,e)}};e.RevocationInfoChoice=a;n.__decorate([(0,r.AsnProp)({type:OtherRevocationInfoFormat,context:1,implicit:true})],a.prototype,`other`,void 0);e.RevocationInfoChoice=a=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Choice})],a);let o=t=class RevocationInfoChoices extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.RevocationInfoChoices=o;e.RevocationInfoChoices=o=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Set,itemType:a})],o)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/originator_info.js
var require_originator_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.OriginatorInfo=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_certificate_choices();const i=require_revocation_info_choice();var OriginatorInfo=class{certs;crls;constructor(e={}){Object.assign(this,e)}};e.OriginatorInfo=OriginatorInfo;t.__decorate([(0,n.AsnProp)({type:r.CertificateSet,context:0,implicit:true,optional:true})],OriginatorInfo.prototype,`certs`,void 0);t.__decorate([(0,n.AsnProp)({type:i.RevocationInfoChoices,context:1,implicit:true,optional:true})],OriginatorInfo.prototype,`crls`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/enveloped_data.js
var require_enveloped_data=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.EnvelopedData=e.UnprotectedAttributes=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_types$3();const a=require_attribute$1();const o=require_recipient_infos();const s=require_originator_info();const c=require_encrypted_content_info();let u=t=class UnprotectedAttributes extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.UnprotectedAttributes=u;e.UnprotectedAttributes=u=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Set,itemType:a.Attribute})],u);var EnvelopedData=class{version=i.CMSVersion.v0;originatorInfo;recipientInfos=new o.RecipientInfos;encryptedContentInfo=new c.EncryptedContentInfo;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};e.EnvelopedData=EnvelopedData;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Integer})],EnvelopedData.prototype,`version`,void 0);n.__decorate([(0,r.AsnProp)({type:s.OriginatorInfo,context:0,implicit:true,optional:true})],EnvelopedData.prototype,`originatorInfo`,void 0);n.__decorate([(0,r.AsnProp)({type:o.RecipientInfos})],EnvelopedData.prototype,`recipientInfos`,void 0);n.__decorate([(0,r.AsnProp)({type:c.EncryptedContentInfo})],EnvelopedData.prototype,`encryptedContentInfo`,void 0);n.__decorate([(0,r.AsnProp)({type:u,context:1,implicit:true,optional:true})],EnvelopedData.prototype,`unprotectedAttrs`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/object_identifiers.js
var require_object_identifiers$3=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.id_authData=e.id_encryptedData=e.id_digestedData=e.id_envelopedData=e.id_signedData=e.id_data=e.id_ct_contentInfo=void 0;e.id_ct_contentInfo=`1.2.840.113549.1.9.16.1.6`;e.id_data=`1.2.840.113549.1.7.1`;e.id_signedData=`1.2.840.113549.1.7.2`;e.id_envelopedData=`1.2.840.113549.1.7.3`;e.id_digestedData=`1.2.840.113549.1.7.5`;e.id_encryptedData=`1.2.840.113549.1.7.6`;e.id_authData=`1.2.840.113549.1.9.16.1.2`}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/signed_data.js
var require_signed_data=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.SignedData=e.DigestAlgorithmIdentifiers=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_certificate_choices();const a=require_types$3();const o=require_encapsulated_content_info();const s=require_revocation_info_choice();const c=require_signer_info();let u=t=class DigestAlgorithmIdentifiers extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.DigestAlgorithmIdentifiers=u;e.DigestAlgorithmIdentifiers=u=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Set,itemType:a.DigestAlgorithmIdentifier})],u);var SignedData=class{version=a.CMSVersion.v0;digestAlgorithms=new u;encapContentInfo=new o.EncapsulatedContentInfo;certificates;crls;signerInfos=new c.SignerInfos;constructor(e={}){Object.assign(this,e)}};e.SignedData=SignedData;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Integer})],SignedData.prototype,`version`,void 0);n.__decorate([(0,r.AsnProp)({type:u})],SignedData.prototype,`digestAlgorithms`,void 0);n.__decorate([(0,r.AsnProp)({type:o.EncapsulatedContentInfo})],SignedData.prototype,`encapContentInfo`,void 0);n.__decorate([(0,r.AsnProp)({type:i.CertificateSet,context:0,implicit:true,optional:true})],SignedData.prototype,`certificates`,void 0);n.__decorate([(0,r.AsnProp)({type:s.RevocationInfoChoices,context:1,implicit:true,optional:true})],SignedData.prototype,`crls`,void 0);n.__decorate([(0,r.AsnProp)({type:c.SignerInfos})],SignedData.prototype,`signerInfos`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-cms@2.11.0/node_modules/@peculiar/asn1-cms/build/cjs/index.js
var require_cjs$7=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_attributes$1(),e);t.__exportStar(require_attribute$1(),e);t.__exportStar(require_certificate_choices(),e);t.__exportStar(require_content_info(),e);t.__exportStar(require_encapsulated_content_info(),e);t.__exportStar(require_encrypted_content_info(),e);t.__exportStar(require_enveloped_data(),e);t.__exportStar(require_issuer_and_serial_number(),e);t.__exportStar(require_kek_recipient_info(),e);t.__exportStar(require_key_agree_recipient_info(),e);t.__exportStar(require_key_trans_recipient_info(),e);t.__exportStar(require_object_identifiers$3(),e);t.__exportStar(require_originator_info(),e);t.__exportStar(require_password_recipient_info(),e);t.__exportStar(require_recipient_info(),e);t.__exportStar(require_recipient_infos(),e);t.__exportStar(require_revocation_info_choice(),e);t.__exportStar(require_signed_data(),e);t.__exportStar(require_signer_identifier(),e);t.__exportStar(require_signer_info(),e);t.__exportStar(require_types$3(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-ecc@2.11.0/node_modules/@peculiar/asn1-ecc/build/cjs/object_identifiers.js
var require_object_identifiers$2=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.id_sect571r1=e.id_sect571k1=e.id_secp521r1=e.id_sect409r1=e.id_sect409k1=e.id_secp384r1=e.id_sect283r1=e.id_sect283k1=e.id_secp256r1=e.id_sect233r1=e.id_sect233k1=e.id_secp224r1=e.id_sect163r2=e.id_sect163k1=e.id_secp192r1=e.id_ecdsaWithSHA512=e.id_ecdsaWithSHA384=e.id_ecdsaWithSHA256=e.id_ecdsaWithSHA224=e.id_ecdsaWithSHA1=e.id_ecMQV=e.id_ecDH=e.id_ecPublicKey=void 0;e.id_ecPublicKey=`1.2.840.10045.2.1`;e.id_ecDH=`1.3.132.1.12`;e.id_ecMQV=`1.3.132.1.13`;e.id_ecdsaWithSHA1=`1.2.840.10045.4.1`;e.id_ecdsaWithSHA224=`1.2.840.10045.4.3.1`;e.id_ecdsaWithSHA256=`1.2.840.10045.4.3.2`;e.id_ecdsaWithSHA384=`1.2.840.10045.4.3.3`;e.id_ecdsaWithSHA512=`1.2.840.10045.4.3.4`;e.id_secp192r1=`1.2.840.10045.3.1.1`;e.id_sect163k1=`1.3.132.0.1`;e.id_sect163r2=`1.3.132.0.15`;e.id_secp224r1=`1.3.132.0.33`;e.id_sect233k1=`1.3.132.0.26`;e.id_sect233r1=`1.3.132.0.27`;e.id_secp256r1=`1.2.840.10045.3.1.7`;e.id_sect283k1=`1.3.132.0.16`;e.id_sect283r1=`1.3.132.0.17`;e.id_secp384r1=`1.3.132.0.34`;e.id_sect409k1=`1.3.132.0.36`;e.id_sect409r1=`1.3.132.0.37`;e.id_secp521r1=`1.3.132.0.35`;e.id_sect571k1=`1.3.132.0.38`;e.id_sect571r1=`1.3.132.0.39`}));
//!node_modules/.pnpm/@peculiar+asn1-ecc@2.11.0/node_modules/@peculiar/asn1-ecc/build/cjs/algorithms.js
var require_algorithms$1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.ecdsaWithSHA512=e.ecdsaWithSHA384=e.ecdsaWithSHA256=e.ecdsaWithSHA224=e.ecdsaWithSHA1=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$9();const r=t.__importStar(require_object_identifiers$2());function create(e){return new n.AlgorithmIdentifier({algorithm:e})}e.ecdsaWithSHA1=create(r.id_ecdsaWithSHA1);e.ecdsaWithSHA224=create(r.id_ecdsaWithSHA224);e.ecdsaWithSHA256=create(r.id_ecdsaWithSHA256);e.ecdsaWithSHA384=create(r.id_ecdsaWithSHA384);e.ecdsaWithSHA512=create(r.id_ecdsaWithSHA512)}));
//!node_modules/.pnpm/@peculiar+asn1-ecc@2.11.0/node_modules/@peculiar/asn1-ecc/build/cjs/rfc3279.js
var require_rfc3279=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.SpecifiedECDomain=e.ECPVer=e.Curve=e.FieldElement=e.ECPoint=e.FieldID=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();let r=class FieldID{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};e.FieldID=r;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],r.prototype,`fieldType`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any})],r.prototype,`parameters`,void 0);e.FieldID=r=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Sequence})],r);var ECPoint=class extends n.OctetString{};e.ECPoint=ECPoint;var FieldElement=class extends n.OctetString{};e.FieldElement=FieldElement;let i=class Curve{a;b;seed;constructor(e={}){Object.assign(this,e)}};e.Curve=i;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.OctetString})],i.prototype,`a`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.OctetString})],i.prototype,`b`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.BitString,optional:true})],i.prototype,`seed`,void 0);e.Curve=i=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Sequence})],i);var a;(function(e){e[e[`ecpVer1`]=1]=`ecpVer1`})(a||(e.ECPVer=a={}));let o=class SpecifiedECDomain{version=a.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};e.SpecifiedECDomain=o;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer})],o.prototype,`version`,void 0);t.__decorate([(0,n.AsnProp)({type:r})],o.prototype,`fieldID`,void 0);t.__decorate([(0,n.AsnProp)({type:i})],o.prototype,`curve`,void 0);t.__decorate([(0,n.AsnProp)({type:ECPoint})],o.prototype,`base`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],o.prototype,`order`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,optional:true})],o.prototype,`cofactor`,void 0);e.SpecifiedECDomain=o=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Sequence})],o)}));
//!node_modules/.pnpm/@peculiar+asn1-ecc@2.11.0/node_modules/@peculiar/asn1-ecc/build/cjs/ec_parameters.js
var require_ec_parameters=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.ECParameters=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_rfc3279();let i=class ECParameters{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};e.ECParameters=i;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],i.prototype,`namedCurve`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Null})],i.prototype,`implicitCurve`,void 0);t.__decorate([(0,n.AsnProp)({type:r.SpecifiedECDomain})],i.prototype,`specifiedCurve`,void 0);e.ECParameters=i=t.__decorate([(0,n.AsnType)({type:n.AsnTypeTypes.Choice})],i)}));
//!node_modules/.pnpm/@peculiar+asn1-ecc@2.11.0/node_modules/@peculiar/asn1-ecc/build/cjs/ec_private_key.js
var require_ec_private_key=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.ECPrivateKey=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_ec_parameters();var ECPrivateKey=class{version=1;privateKey=new n.OctetString;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};e.ECPrivateKey=ECPrivateKey;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer})],ECPrivateKey.prototype,`version`,void 0);t.__decorate([(0,n.AsnProp)({type:n.OctetString})],ECPrivateKey.prototype,`privateKey`,void 0);t.__decorate([(0,n.AsnProp)({type:r.ECParameters,context:0,optional:true})],ECPrivateKey.prototype,`parameters`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.BitString,context:1,optional:true})],ECPrivateKey.prototype,`publicKey`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-ecc@2.11.0/node_modules/@peculiar/asn1-ecc/build/cjs/ec_signature_value.js
var require_ec_signature_value=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.ECDSASigValue=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();var ECDSASigValue=class{r=/* @__PURE__ */ new ArrayBuffer(0);s=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.ECDSASigValue=ECDSASigValue;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],ECDSASigValue.prototype,`r`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],ECDSASigValue.prototype,`s`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-ecc@2.11.0/node_modules/@peculiar/asn1-ecc/build/cjs/index.js
var require_cjs$6=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_algorithms$1(),e);t.__exportStar(require_ec_parameters(),e);t.__exportStar(require_ec_private_key(),e);t.__exportStar(require_ec_signature_value(),e);t.__exportStar(require_object_identifiers$2(),e);t.__exportStar(require_rfc3279(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-rsa@2.11.0/node_modules/@peculiar/asn1-rsa/build/cjs/object_identifiers.js
var require_object_identifiers$1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.id_mgf1=e.id_md5=e.id_md2=e.id_sha512_256=e.id_sha512_224=e.id_sha512=e.id_sha384=e.id_sha256=e.id_sha224=e.id_sha1=e.id_sha512_256WithRSAEncryption=e.id_sha512_224WithRSAEncryption=e.id_sha512WithRSAEncryption=e.id_sha384WithRSAEncryption=e.id_sha256WithRSAEncryption=e.id_ssha224WithRSAEncryption=e.id_sha224WithRSAEncryption=e.id_sha1WithRSAEncryption=e.id_md5WithRSAEncryption=e.id_md2WithRSAEncryption=e.id_RSASSA_PSS=e.id_pSpecified=e.id_RSAES_OAEP=e.id_rsaEncryption=e.id_pkcs_1=void 0;e.id_pkcs_1=`1.2.840.113549.1.1`;e.id_rsaEncryption=`${e.id_pkcs_1}.1`;e.id_RSAES_OAEP=`${e.id_pkcs_1}.7`;e.id_pSpecified=`${e.id_pkcs_1}.9`;e.id_RSASSA_PSS=`${e.id_pkcs_1}.10`;e.id_md2WithRSAEncryption=`${e.id_pkcs_1}.2`;e.id_md5WithRSAEncryption=`${e.id_pkcs_1}.4`;e.id_sha1WithRSAEncryption=`${e.id_pkcs_1}.5`;e.id_sha224WithRSAEncryption=`${e.id_pkcs_1}.14`;e.id_ssha224WithRSAEncryption=e.id_sha224WithRSAEncryption;e.id_sha256WithRSAEncryption=`${e.id_pkcs_1}.11`;e.id_sha384WithRSAEncryption=`${e.id_pkcs_1}.12`;e.id_sha512WithRSAEncryption=`${e.id_pkcs_1}.13`;e.id_sha512_224WithRSAEncryption=`${e.id_pkcs_1}.15`;e.id_sha512_256WithRSAEncryption=`${e.id_pkcs_1}.16`;e.id_sha1=`1.3.14.3.2.26`;e.id_sha224=`2.16.840.1.101.3.4.2.4`;e.id_sha256=`2.16.840.1.101.3.4.2.1`;e.id_sha384=`2.16.840.1.101.3.4.2.2`;e.id_sha512=`2.16.840.1.101.3.4.2.3`;e.id_sha512_224=`2.16.840.1.101.3.4.2.5`;e.id_sha512_256=`2.16.840.1.101.3.4.2.6`;e.id_md2=`1.2.840.113549.2.2`;e.id_md5=`1.2.840.113549.2.5`;e.id_mgf1=`${e.id_pkcs_1}.8`}));
//!node_modules/.pnpm/@peculiar+asn1-rsa@2.11.0/node_modules/@peculiar/asn1-rsa/build/cjs/algorithms.js
var require_algorithms=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.sha512_256WithRSAEncryption=e.sha512_224WithRSAEncryption=e.sha512WithRSAEncryption=e.sha384WithRSAEncryption=e.sha256WithRSAEncryption=e.sha224WithRSAEncryption=e.sha1WithRSAEncryption=e.md5WithRSAEncryption=e.md2WithRSAEncryption=e.rsaEncryption=e.pSpecifiedEmpty=e.mgf1SHA1=e.sha512_256=e.sha512_224=e.sha512=e.sha384=e.sha256=e.sha224=e.sha1=e.md4=e.md2=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();const i=t.__importStar(require_object_identifiers$1());function create(e){return new r.AlgorithmIdentifier({algorithm:e,parameters:null})}e.md2=create(i.id_md2);e.md4=create(i.id_md5);e.sha1=create(i.id_sha1);e.sha224=create(i.id_sha224);e.sha256=create(i.id_sha256);e.sha384=create(i.id_sha384);e.sha512=create(i.id_sha512);e.sha512_224=create(i.id_sha512_224);e.sha512_256=create(i.id_sha512_256);e.mgf1SHA1=new r.AlgorithmIdentifier({algorithm:i.id_mgf1,parameters:n.AsnConvert.serialize(e.sha1)});e.pSpecifiedEmpty=new r.AlgorithmIdentifier({algorithm:i.id_pSpecified,parameters:n.AsnConvert.serialize(n.AsnOctetStringConverter.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});e.rsaEncryption=create(i.id_rsaEncryption);e.md2WithRSAEncryption=create(i.id_md2WithRSAEncryption);e.md5WithRSAEncryption=create(i.id_md5WithRSAEncryption);e.sha1WithRSAEncryption=create(i.id_sha1WithRSAEncryption);e.sha224WithRSAEncryption=create(i.id_sha512_224WithRSAEncryption);e.sha256WithRSAEncryption=create(i.id_sha512_256WithRSAEncryption);e.sha384WithRSAEncryption=create(i.id_sha384WithRSAEncryption);e.sha512WithRSAEncryption=create(i.id_sha512WithRSAEncryption);e.sha512_224WithRSAEncryption=create(i.id_sha512_224WithRSAEncryption);e.sha512_256WithRSAEncryption=create(i.id_sha512_256WithRSAEncryption)}));
//!node_modules/.pnpm/@peculiar+asn1-rsa@2.11.0/node_modules/@peculiar/asn1-rsa/build/cjs/parameters/rsaes_oaep.js
var require_rsaes_oaep=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.RSAES_OAEP=e.RsaEsOaepParams=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();const i=require_object_identifiers$1();const a=require_algorithms();var RsaEsOaepParams=class{hashAlgorithm=new r.AlgorithmIdentifier(a.sha1);maskGenAlgorithm=new r.AlgorithmIdentifier({algorithm:i.id_mgf1,parameters:n.AsnConvert.serialize(a.sha1)});pSourceAlgorithm=new r.AlgorithmIdentifier(a.pSpecifiedEmpty);constructor(e={}){Object.assign(this,e)}};e.RsaEsOaepParams=RsaEsOaepParams;t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier,context:0,defaultValue:a.sha1})],RsaEsOaepParams.prototype,`hashAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier,context:1,defaultValue:a.mgf1SHA1})],RsaEsOaepParams.prototype,`maskGenAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier,context:2,defaultValue:a.pSpecifiedEmpty})],RsaEsOaepParams.prototype,`pSourceAlgorithm`,void 0);e.RSAES_OAEP=new r.AlgorithmIdentifier({algorithm:i.id_RSAES_OAEP,parameters:n.AsnConvert.serialize(new RsaEsOaepParams)})}));
//!node_modules/.pnpm/@peculiar+asn1-rsa@2.11.0/node_modules/@peculiar/asn1-rsa/build/cjs/parameters/rsassa_pss.js
var require_rsassa_pss=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.RSASSA_PSS=e.RsaSaPssParams=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();const i=require_object_identifiers$1();const a=require_algorithms();var RsaSaPssParams=class{hashAlgorithm=new r.AlgorithmIdentifier(a.sha1);maskGenAlgorithm=new r.AlgorithmIdentifier({algorithm:i.id_mgf1,parameters:n.AsnConvert.serialize(a.sha1)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};e.RsaSaPssParams=RsaSaPssParams;t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier,context:0,defaultValue:a.sha1})],RsaSaPssParams.prototype,`hashAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier,context:1,defaultValue:a.mgf1SHA1})],RsaSaPssParams.prototype,`maskGenAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,context:2,defaultValue:20})],RsaSaPssParams.prototype,`saltLength`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,context:3,defaultValue:1})],RsaSaPssParams.prototype,`trailerField`,void 0);e.RSASSA_PSS=new r.AlgorithmIdentifier({algorithm:i.id_RSASSA_PSS,parameters:n.AsnConvert.serialize(new RsaSaPssParams)})}));
//!node_modules/.pnpm/@peculiar+asn1-rsa@2.11.0/node_modules/@peculiar/asn1-rsa/build/cjs/parameters/rsassa_pkcs1_v1_5.js
var require_rsassa_pkcs1_v1_5=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.DigestInfo=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$9();const r=require_cjs$10();var DigestInfo=class{digestAlgorithm=new n.AlgorithmIdentifier;digest=new r.OctetString;constructor(e={}){Object.assign(this,e)}};e.DigestInfo=DigestInfo;t.__decorate([(0,r.AsnProp)({type:n.AlgorithmIdentifier})],DigestInfo.prototype,`digestAlgorithm`,void 0);t.__decorate([(0,r.AsnProp)({type:r.OctetString})],DigestInfo.prototype,`digest`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-rsa@2.11.0/node_modules/@peculiar/asn1-rsa/build/cjs/parameters/index.js
var require_parameters=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_rsaes_oaep(),e);t.__exportStar(require_rsassa_pss(),e);t.__exportStar(require_rsassa_pkcs1_v1_5(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-rsa@2.11.0/node_modules/@peculiar/asn1-rsa/build/cjs/other_prime_info.js
var require_other_prime_info=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.OtherPrimeInfos=e.OtherPrimeInfo=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();var OtherPrimeInfo=class{prime=/* @__PURE__ */ new ArrayBuffer(0);exponent=/* @__PURE__ */ new ArrayBuffer(0);coefficient=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.OtherPrimeInfo=OtherPrimeInfo;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Integer,converter:r.AsnIntegerArrayBufferConverter})],OtherPrimeInfo.prototype,`prime`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Integer,converter:r.AsnIntegerArrayBufferConverter})],OtherPrimeInfo.prototype,`exponent`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Integer,converter:r.AsnIntegerArrayBufferConverter})],OtherPrimeInfo.prototype,`coefficient`,void 0);let i=t=class OtherPrimeInfos extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.OtherPrimeInfos=i;e.OtherPrimeInfos=i=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:OtherPrimeInfo})],i)}));
//!node_modules/.pnpm/@peculiar+asn1-rsa@2.11.0/node_modules/@peculiar/asn1-rsa/build/cjs/rsa_private_key.js
var require_rsa_private_key=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.RSAPrivateKey=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_other_prime_info();var RSAPrivateKey=class{version=0;modulus=/* @__PURE__ */ new ArrayBuffer(0);publicExponent=/* @__PURE__ */ new ArrayBuffer(0);privateExponent=/* @__PURE__ */ new ArrayBuffer(0);prime1=/* @__PURE__ */ new ArrayBuffer(0);prime2=/* @__PURE__ */ new ArrayBuffer(0);exponent1=/* @__PURE__ */ new ArrayBuffer(0);exponent2=/* @__PURE__ */ new ArrayBuffer(0);coefficient=/* @__PURE__ */ new ArrayBuffer(0);otherPrimeInfos;constructor(e={}){Object.assign(this,e)}};e.RSAPrivateKey=RSAPrivateKey;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer})],RSAPrivateKey.prototype,`version`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],RSAPrivateKey.prototype,`modulus`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],RSAPrivateKey.prototype,`publicExponent`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],RSAPrivateKey.prototype,`privateExponent`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],RSAPrivateKey.prototype,`prime1`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],RSAPrivateKey.prototype,`prime2`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],RSAPrivateKey.prototype,`exponent1`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],RSAPrivateKey.prototype,`exponent2`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],RSAPrivateKey.prototype,`coefficient`,void 0);t.__decorate([(0,n.AsnProp)({type:r.OtherPrimeInfos,optional:true})],RSAPrivateKey.prototype,`otherPrimeInfos`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-rsa@2.11.0/node_modules/@peculiar/asn1-rsa/build/cjs/rsa_public_key.js
var require_rsa_public_key=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.RSAPublicKey=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();var RSAPublicKey=class{modulus=/* @__PURE__ */ new ArrayBuffer(0);publicExponent=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.RSAPublicKey=RSAPublicKey;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],RSAPublicKey.prototype,`modulus`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer,converter:n.AsnIntegerArrayBufferConverter})],RSAPublicKey.prototype,`publicExponent`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-rsa@2.11.0/node_modules/@peculiar/asn1-rsa/build/cjs/index.js
var require_cjs$5=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_parameters(),e);t.__exportStar(require_algorithms(),e);t.__exportStar(require_object_identifiers$1(),e);t.__exportStar(require_other_prime_info(),e);t.__exportStar(require_rsa_private_key(),e);t.__exportStar(require_rsa_public_key(),e)}));
//!node_modules/.pnpm/tslib@1.14.1/node_modules/tslib/tslib.es6.js
var tslib_es6_exports=/* @__PURE__ */ __exportAll({__assign:()=>__assign,__asyncDelegator:()=>__asyncDelegator,__asyncGenerator:()=>__asyncGenerator,__asyncValues:()=>__asyncValues,__await:()=>__await,__awaiter:()=>__awaiter,__classPrivateFieldGet:()=>__classPrivateFieldGet,__classPrivateFieldSet:()=>__classPrivateFieldSet,__createBinding:()=>__createBinding,__decorate:()=>__decorate,__exportStar:()=>__exportStar,__extends:()=>__extends,__generator:()=>__generator,__importDefault:()=>__importDefault,__importStar:()=>__importStar,__makeTemplateObject:()=>__makeTemplateObject,__metadata:()=>__metadata,__param:()=>__param,__read:()=>__read,__rest:()=>__rest,__spread:()=>__spread,__spreadArrays:()=>__spreadArrays,__values:()=>__values});
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __extends(e,t){extendStatics(e,t);function __(){this.constructor=e}e.prototype=t===null?Object.create(t):(__.prototype=t.prototype,new __)}function __rest(e,t){var n={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0)n[r]=e[r];if(e!=null&&typeof Object.getOwnPropertySymbols===`function`){for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)if(t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i]))n[r[i]]=e[r[i]]}return n}function __decorate(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect===`object`&&typeof Reflect.decorate===`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)if(o=e[s])a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a;return i>3&&a&&Object.defineProperty(t,n,a),a}function __param(e,t){return function(n,r){t(n,r,e)}}function __metadata(e,t){if(typeof Reflect===`object`&&typeof Reflect.metadata===`function`)return Reflect.metadata(e,t)}function __awaiter(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||(n=Promise))(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r[`throw`](e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})}function __generator(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o={next:verb(0),"throw":verb(1),"return":verb(2)};return typeof Symbol===`function`&&(o[Symbol.iterator]=function(){return this}),o;function verb(e){return function(t){return step([e,t])}}function step(o){if(r)throw new TypeError(`Generator is already executing.`);while(n)try{if(r=1,i&&(a=o[0]&2?i[`return`]:o[0]?i[`throw`]||((a=i[`return`])&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;if(i=0,a)o=[o[0]&2,a.value];switch(o[0]){case 0:case 1:a=o;break;case 4:n.label++;return{value:o[1],done:false};case 5:n.label++;i=o[1];o=[0];continue;case 7:o=n.ops.pop();n.trys.pop();continue;default:if(!(a=n.trys,a=a.length>0&&a[a.length-1])&&(o[0]===6||o[0]===2)){n=0;continue}if(o[0]===3&&(!a||o[1]>a[0]&&o[1]<a[3])){n.label=o[1];break}if(o[0]===6&&n.label<a[1]){n.label=a[1];a=o;break}if(a&&n.label<a[2]){n.label=a[2];n.ops.push(o);break}if(a[2])n.ops.pop();n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e];i=0}finally{r=a=0}if(o[0]&5)throw o[1];return{value:o[0]?o[1]:void 0,done:true}}}function __createBinding(e,t,n,r){if(r===void 0)r=n;e[r]=t[n]}function __exportStar(e,t){for(var n in e)if(n!=="default"&&!t.hasOwnProperty(n))t[n]=e[n]}function __values(e){var t=typeof Symbol===`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length===`number`)return{next:function(){if(e&&r>=e.length)e=void 0;return{value:e&&e[r++],done:!e}}};throw new TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function __read(e,t){var n=typeof Symbol===`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{while((t===void 0||t-->0)&&!(i=r.next()).done)a.push(i.value)}catch(e){o={error:e}}finally{try{if(i&&!i.done&&(n=r[`return`]))n.call(r)}finally{if(o)throw o.error}}return a}function __spread(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(__read(arguments[t]));return e}function __spreadArrays(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var a=arguments[t],o=0,s=a.length;o<s;o++,i++)r[i]=a[o];return r}function __await(e){return this instanceof __await?(this.v=e,this):new __await(e)}function __asyncGenerator(e,t,n){if(!Symbol.asyncIterator)throw new TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i={},verb(`next`),verb(`throw`),verb(`return`),i[Symbol.asyncIterator]=function(){return this},i;function verb(e){if(r[e])i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||resume(e,t)})}}function resume(e,t){try{step(r[e](t))}catch(e){settle(a[0][3],e)}}function step(e){e.value instanceof __await?Promise.resolve(e.value.v).then(fulfill,reject):settle(a[0][2],e)}function fulfill(e){resume(`next`,e)}function reject(e){resume(`throw`,e)}function settle(e,t){if(e(t),a.shift(),a.length)resume(a[0][0],a[0][1])}}function __asyncDelegator(e){var t={},n;return verb(`next`),verb(`throw`,function(e){throw e}),verb(`return`),t[Symbol.iterator]=function(){return this},t;function verb(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:__await(e[r](t)),done:r===`return`}:i?i(t):t}:i}}function __asyncValues(e){if(!Symbol.asyncIterator)throw new TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof __values===`function`?__values(e):e[Symbol.iterator](),n={},verb(`next`),verb(`throw`),verb(`return`),n[Symbol.asyncIterator]=function(){return this},n);function verb(t){n[t]=e[t]&&function(n){return new Promise(function(r,i){n=e[t](n),settle(r,i,n.done,n.value)})}}function settle(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function __makeTemplateObject(e,t){if(Object.defineProperty)Object.defineProperty(e,"raw",{value:t});else e.raw=t;return e}function __importStar(e){if(e&&e.__esModule)return e;var t={};if(e!=null){for(var n in e)if(Object.hasOwnProperty.call(e,n))t[n]=e[n]}t.default=e;return t}function __importDefault(e){return e&&e.__esModule?e:{default:e}}function __classPrivateFieldGet(e,t){if(!t.has(e))throw new TypeError(`attempted to get private field on non-instance`);return t.get(e)}function __classPrivateFieldSet(e,t,n){if(!t.has(e))throw new TypeError(`attempted to set private field on non-instance`);t.set(e,n);return n}var extendStatics,__assign;var init_tslib_es6=__esmMin((()=>{extendStatics=function(e,t){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)if(t.hasOwnProperty(n))e[n]=t[n]};return extendStatics(e,t)};__assign=function(){__assign=Object.assign||function __assign(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i))e[i]=t[i]}return e};return __assign.apply(this,arguments)}}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/types/lifecycle.js
var require_lifecycle=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});var t;(function(e){e[e[`Transient`]=0]=`Transient`;e[e[`Singleton`]=1]=`Singleton`;e[e[`ResolutionScoped`]=2]=`ResolutionScoped`;e[e[`ContainerScoped`]=3]=`ContainerScoped`})(t||(t={}));e.default=t}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/types/index.js
var require_types$2=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});var t=require_lifecycle();Object.defineProperty(e,"Lifecycle",{enumerable:true,get:function(){return t.default}})}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/reflection-helpers.js
var require_reflection_helpers=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.defineInjectionTokenMetadata=e.getParamInfo=e.INJECTION_TOKEN_METADATA_KEY=void 0;e.INJECTION_TOKEN_METADATA_KEY=`injectionTokens`;function getParamInfo(t){const n=Reflect.getMetadata(`design:paramtypes`,t)||[];const r=Reflect.getOwnMetadata(e.INJECTION_TOKEN_METADATA_KEY,t)||{};Object.keys(r).forEach(e=>{n[+e]=r[e]});return n}e.getParamInfo=getParamInfo;function defineInjectionTokenMetadata(t,n){return function(r,i,a){const o=Reflect.getOwnMetadata(e.INJECTION_TOKEN_METADATA_KEY,r)||{};o[a]=n?{token:t,transform:n.transformToken,transformArgs:n.args||[]}:t;Reflect.defineMetadata(e.INJECTION_TOKEN_METADATA_KEY,o,r)}}e.defineInjectionTokenMetadata=defineInjectionTokenMetadata}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/class-provider.js
var require_class_provider=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.isClassProvider=void 0;function isClassProvider(e){return!!e.useClass}e.isClassProvider=isClassProvider}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/factory-provider.js
var require_factory_provider=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.isFactoryProvider=void 0;function isFactoryProvider(e){return!!e.useFactory}e.isFactoryProvider=isFactoryProvider}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/lazy-helpers.js
var require_lazy_helpers=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.delay=e.DelayedConstructor=void 0;var DelayedConstructor=class{constructor(e){this.wrap=e;this.reflectMethods=[`get`,`getPrototypeOf`,`setPrototypeOf`,`getOwnPropertyDescriptor`,`defineProperty`,`has`,`set`,`deleteProperty`,`apply`,`construct`,`ownKeys`]}createProxy(e){const t={};let n=false;let r;const delayedObject=()=>{if(!n){r=e(this.wrap());n=true}return r};return new Proxy(t,this.createHandler(delayedObject))}createHandler(e){const t={};const install=n=>{t[n]=(...t)=>{t[0]=e();const r=Reflect[n];return r(...t)}};this.reflectMethods.forEach(install);return t}};e.DelayedConstructor=DelayedConstructor;function delay(e){if(typeof e===`undefined`)throw new Error("Attempt to `delay` undefined. Constructor must be wrapped in a callback");return new DelayedConstructor(e)}e.delay=delay}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/injection-token.js
var require_injection_token=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.isConstructorToken=e.isTransformDescriptor=e.isTokenDescriptor=e.isNormalToken=void 0;const t=require_lazy_helpers();function isNormalToken(e){return typeof e===`string`||typeof e===`symbol`}e.isNormalToken=isNormalToken;function isTokenDescriptor(e){return typeof e===`object`&&`token`in e&&`multiple`in e}e.isTokenDescriptor=isTokenDescriptor;function isTransformDescriptor(e){return typeof e===`object`&&`token`in e&&`transform`in e}e.isTransformDescriptor=isTransformDescriptor;function isConstructorToken(e){return typeof e===`function`||e instanceof t.DelayedConstructor}e.isConstructorToken=isConstructorToken}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/token-provider.js
var require_token_provider=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.isTokenProvider=void 0;function isTokenProvider(e){return!!e.useToken}e.isTokenProvider=isTokenProvider}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/value-provider.js
var require_value_provider=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.isValueProvider=void 0;function isValueProvider(e){return e.useValue!=void 0}e.isValueProvider=isValueProvider}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/index.js
var require_providers=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});var t=require_class_provider();Object.defineProperty(e,"isClassProvider",{enumerable:true,get:function(){return t.isClassProvider}});var n=require_factory_provider();Object.defineProperty(e,"isFactoryProvider",{enumerable:true,get:function(){return n.isFactoryProvider}});var r=require_injection_token();Object.defineProperty(e,"isNormalToken",{enumerable:true,get:function(){return r.isNormalToken}});var i=require_token_provider();Object.defineProperty(e,"isTokenProvider",{enumerable:true,get:function(){return i.isTokenProvider}});var a=require_value_provider();Object.defineProperty(e,"isValueProvider",{enumerable:true,get:function(){return a.isValueProvider}})}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/provider.js
var require_provider=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.isProvider=void 0;const t=require_class_provider();const n=require_value_provider();const r=require_token_provider();const i=require_factory_provider();function isProvider(e){return t.isClassProvider(e)||n.isValueProvider(e)||r.isTokenProvider(e)||i.isFactoryProvider(e)}e.isProvider=isProvider}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/registry-base.js
var require_registry_base=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});var RegistryBase=class{constructor(){this._registryMap=/* @__PURE__ */ new Map}entries(){return this._registryMap.entries()}getAll(e){this.ensure(e);return this._registryMap.get(e)}get(e){this.ensure(e);const t=this._registryMap.get(e);return t[t.length-1]||null}set(e,t){this.ensure(e);this._registryMap.get(e).push(t)}setAll(e,t){this._registryMap.set(e,t)}has(e){this.ensure(e);return this._registryMap.get(e).length>0}clear(){this._registryMap.clear()}ensure(e){if(!this._registryMap.has(e))this._registryMap.set(e,[])}};e.default=RegistryBase}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/registry.js
var require_registry$1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=require_registry_base();var Registry=class extends t.default{};e.default=Registry}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/resolution-context.js
var require_resolution_context=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});var ResolutionContext=class{constructor(){this.scopedResolutions=/* @__PURE__ */ new Map}};e.default=ResolutionContext}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/error-helpers.js
var require_error_helpers=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.formatErrorCtor=void 0;function formatDependency(e,t){if(e===null)return`at position #${t}`;return`"${e.split(`,`)[t].trim()}" at position #${t}`}function composeErrorMessage(e,t,n=` `){return[e,...t.message.split(`
`).map(e=>n+e)].join(`
`)}function formatErrorCtor(e,t,n){const[,r=null]=e.toString().match(/constructor\(([\w, ]+)\)/)||[];return composeErrorMessage(`Cannot inject the dependency ${formatDependency(r,t)} of "${e.name}" constructor. Reason:`,n)}e.formatErrorCtor=formatErrorCtor}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/types/disposable.js
var require_disposable=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.isDisposable=void 0;function isDisposable(e){if(typeof e.dispose!==`function`)return false;if(e.dispose.length>0)return false;return true}e.isDisposable=isDisposable}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/interceptors.js
var require_interceptors=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.PostResolutionInterceptors=e.PreResolutionInterceptors=void 0;const t=require_registry_base();var PreResolutionInterceptors=class extends t.default{};e.PreResolutionInterceptors=PreResolutionInterceptors;var PostResolutionInterceptors=class extends t.default{};e.PostResolutionInterceptors=PostResolutionInterceptors;var Interceptors=class{constructor(){this.preResolution=new PreResolutionInterceptors;this.postResolution=new PostResolutionInterceptors}};e.default=Interceptors}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/dependency-container.js
var require_dependency_container=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.instance=e.typeInfo=void 0;const t=(init_tslib_es6(),__toCommonJS(tslib_es6_exports));const n=require_providers();const r=require_provider();const i=require_injection_token();const a=require_registry$1();const o=require_lifecycle();const s=require_resolution_context();const c=require_error_helpers();const u=require_lazy_helpers();const d=require_disposable();const f=require_interceptors();e.typeInfo=/* @__PURE__ */ new Map;var p=class InternalDependencyContainer{constructor(e){this.parent=e;this._registry=new a.default;this.interceptors=new f.default;this.disposed=false;this.disposables=/* @__PURE__ */ new Set}register(e,t,i={lifecycle:o.default.Transient}){this.ensureNotDisposed();let a;if(!r.isProvider(t))a={useClass:t};else a=t;if(n.isTokenProvider(a)){const t=[e];let r=a;while(r!=null){const e=r.useToken;if(t.includes(e))throw new Error(`Token registration cycle detected! ${[...t,e].join(` -> `)}`);t.push(e);const i=this._registry.get(e);if(i&&n.isTokenProvider(i.provider))r=i.provider;else r=null}}if(i.lifecycle===o.default.Singleton||i.lifecycle==o.default.ContainerScoped||i.lifecycle==o.default.ResolutionScoped){if(n.isValueProvider(a)||n.isFactoryProvider(a))throw new Error(`Cannot use lifecycle "${o.default[i.lifecycle]}" with ValueProviders or FactoryProviders`)}this._registry.set(e,{provider:a,options:i});return this}registerType(e,t){this.ensureNotDisposed();if(n.isNormalToken(t))return this.register(e,{useToken:t});return this.register(e,{useClass:t})}registerInstance(e,t){this.ensureNotDisposed();return this.register(e,{useValue:t})}registerSingleton(e,t){this.ensureNotDisposed();if(n.isNormalToken(e)){if(n.isNormalToken(t))return this.register(e,{useToken:t},{lifecycle:o.default.Singleton});else if(t)return this.register(e,{useClass:t},{lifecycle:o.default.Singleton});throw new Error(`Cannot register a type name as a singleton without a "to" token`)}let r=e;if(t&&!n.isNormalToken(t))r=t;return this.register(e,{useClass:r},{lifecycle:o.default.Singleton})}resolve(e,t=new s.default,r=false){this.ensureNotDisposed();const a=this.getRegistration(e);if(!a&&n.isNormalToken(e)){if(r)return;throw new Error(`Attempted to resolve unregistered dependency token: "${e.toString()}"`)}this.executePreResolutionInterceptor(e,`Single`);if(a){const n=this.resolveRegistration(a,t);this.executePostResolutionInterceptor(e,n,`Single`);return n}if(i.isConstructorToken(e)){const n=this.construct(e,t);this.executePostResolutionInterceptor(e,n,`Single`);return n}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")}executePreResolutionInterceptor(e,t){if(this.interceptors.preResolution.has(e)){const n=[];for(const r of this.interceptors.preResolution.getAll(e)){if(r.options.frequency!=`Once`)n.push(r);r.callback(e,t)}this.interceptors.preResolution.setAll(e,n)}}executePostResolutionInterceptor(e,t,n){if(this.interceptors.postResolution.has(e)){const r=[];for(const i of this.interceptors.postResolution.getAll(e)){if(i.options.frequency!=`Once`)r.push(i);i.callback(e,t,n)}this.interceptors.postResolution.setAll(e,r)}}resolveRegistration(e,t){this.ensureNotDisposed();if(e.options.lifecycle===o.default.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);const r=e.options.lifecycle===o.default.Singleton;const i=e.options.lifecycle===o.default.ContainerScoped;const a=r||i;let s;if(n.isValueProvider(e.provider))s=e.provider.useValue;else if(n.isTokenProvider(e.provider))s=a?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t);else if(n.isClassProvider(e.provider))s=a?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t);else if(n.isFactoryProvider(e.provider))s=e.provider.useFactory(this);else s=this.construct(e.provider,t);if(e.options.lifecycle===o.default.ResolutionScoped)t.scopedResolutions.set(e,s);return s}resolveAll(e,t=new s.default,r=false){this.ensureNotDisposed();const i=this.getAllRegistrations(e);if(!i&&n.isNormalToken(e)){if(r)return[];throw new Error(`Attempted to resolve unregistered dependency token: "${e.toString()}"`)}this.executePreResolutionInterceptor(e,`All`);if(i){const n=i.map(e=>this.resolveRegistration(e,t));this.executePostResolutionInterceptor(e,n,`All`);return n}const a=[this.construct(e,t)];this.executePostResolutionInterceptor(e,a,`All`);return a}isRegistered(e,t=false){this.ensureNotDisposed();return this._registry.has(e)||t&&(this.parent||false)&&this.parent.isRegistered(e,true)}reset(){this.ensureNotDisposed();this._registry.clear();this.interceptors.preResolution.clear();this.interceptors.postResolution.clear()}clearInstances(){this.ensureNotDisposed();for(const[e,t]of this._registry.entries())this._registry.setAll(e,t.filter(e=>!n.isValueProvider(e.provider)).map(e=>{e.instance=void 0;return e}))}createChildContainer(){this.ensureNotDisposed();const e=new InternalDependencyContainer(this);for(const[t,n]of this._registry.entries())if(n.some(({options:e})=>e.lifecycle===o.default.ContainerScoped))e._registry.setAll(t,n.map(e=>{if(e.options.lifecycle===o.default.ContainerScoped)return{provider:e.provider,options:e.options};return e}));return e}beforeResolution(e,t,n={frequency:`Always`}){this.interceptors.preResolution.set(e,{callback:t,options:n})}afterResolution(e,t,n={frequency:`Always`}){this.interceptors.postResolution.set(e,{callback:t,options:n})}dispose(){return t.__awaiter(this,void 0,void 0,function*(){this.disposed=true;const e=[];this.disposables.forEach(t=>{const n=t.dispose();if(n)e.push(n)});yield Promise.all(e)})}getRegistration(e){if(this.isRegistered(e))return this._registry.get(e);if(this.parent)return this.parent.getRegistration(e);return null}getAllRegistrations(e){if(this.isRegistered(e))return this._registry.getAll(e);if(this.parent)return this.parent.getAllRegistrations(e);return null}construct(t,n){if(t instanceof u.DelayedConstructor)return t.createProxy(e=>this.resolve(e,n));const r=(()=>{const r=e.typeInfo.get(t);if(!r||r.length===0){if(t.length===0)return new t;else throw new Error(`TypeInfo not known for "${t.name}"`)}return new t(...r.map(this.resolveParams(n,t)))})();if(d.isDisposable(r))this.disposables.add(r);return r}resolveParams(e,t){return(n,r)=>{try{if(i.isTokenDescriptor(n)){if(i.isTransformDescriptor(n))return n.multiple?this.resolve(n.transform).transform(this.resolveAll(n.token,new s.default,n.isOptional),...n.transformArgs):this.resolve(n.transform).transform(this.resolve(n.token,e,n.isOptional),...n.transformArgs);else return n.multiple?this.resolveAll(n.token,new s.default,n.isOptional):this.resolve(n.token,e,n.isOptional)}else if(i.isTransformDescriptor(n))return this.resolve(n.transform,e).transform(this.resolve(n.token,e),...n.transformArgs);return this.resolve(n,e)}catch(e){throw new Error(c.formatErrorCtor(t,r,e))}}}ensureNotDisposed(){if(this.disposed)throw new Error(`This container has been disposed, you cannot interact with a disposed container`)}};e.instance=new p;e.default=e.instance}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/auto-injectable.js
var require_auto_injectable=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=require_reflection_helpers();const n=require_dependency_container();const r=require_injection_token();const i=require_error_helpers();function autoInjectable(){return function(e){const a=t.getParamInfo(e);return class extends e{constructor(...t){super(...t.concat(a.slice(t.length).map((a,o)=>{try{if(r.isTokenDescriptor(a)){if(r.isTransformDescriptor(a))return a.multiple?n.instance.resolve(a.transform).transform(n.instance.resolveAll(a.token),...a.transformArgs):n.instance.resolve(a.transform).transform(n.instance.resolve(a.token),...a.transformArgs);else return a.multiple?n.instance.resolveAll(a.token):n.instance.resolve(a.token)}else if(r.isTransformDescriptor(a))return n.instance.resolve(a.transform).transform(n.instance.resolve(a.token),...a.transformArgs);return n.instance.resolve(a)}catch(n){const r=o+t.length;throw new Error(i.formatErrorCtor(e,r,n))}})))}}}}e.default=autoInjectable}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/inject.js
var require_inject=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=require_reflection_helpers();function inject(e,n){const r={token:e,multiple:false,isOptional:n&&n.isOptional};return t.defineInjectionTokenMetadata(r)}e.default=inject}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/injectable.js
var require_injectable=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=require_reflection_helpers();const n=require_dependency_container();const r=require_dependency_container();function injectable(e){return function(i){n.typeInfo.set(i,t.getParamInfo(i));if(e&&e.token){if(!Array.isArray(e.token))r.instance.register(e.token,i);else e.token.forEach(e=>{r.instance.register(e,i)})}}}e.default=injectable}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/registry.js
var require_registry=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6(),__toCommonJS(tslib_es6_exports));const n=require_dependency_container();function registry(e=[]){return function(r){e.forEach(e=>{var{token:r,options:i}=e,a=t.__rest(e,[`token`,`options`]);return n.instance.register(r,a,i)});return r}}e.default=registry}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/singleton.js
var require_singleton=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=require_injectable();const n=require_dependency_container();function singleton(){return function(e){t.default()(e);n.instance.registerSingleton(e)}}e.default=singleton}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/inject-all.js
var require_inject_all=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=require_reflection_helpers();function injectAll(e,n){const r={token:e,multiple:true,isOptional:n&&n.isOptional};return t.defineInjectionTokenMetadata(r)}e.default=injectAll}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/inject-all-with-transform.js
var require_inject_all_with_transform=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=require_reflection_helpers();function injectAllWithTransform(e,n,...r){const i={token:e,multiple:true,transform:n,transformArgs:r};return t.defineInjectionTokenMetadata(i)}e.default=injectAllWithTransform}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/inject-with-transform.js
var require_inject_with_transform=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=require_reflection_helpers();function injectWithTransform(e,n,...r){return t.defineInjectionTokenMetadata(e,{transformToken:n,args:r})}e.default=injectWithTransform}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/scoped.js
var require_scoped=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=require_injectable();const n=require_dependency_container();function scoped(e,r){return function(i){t.default()(i);n.instance.register(r||i,i,{lifecycle:e})}}e.default=scoped}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/index.js
var require_decorators=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});var t=require_auto_injectable();Object.defineProperty(e,"autoInjectable",{enumerable:true,get:function(){return t.default}});var n=require_inject();Object.defineProperty(e,"inject",{enumerable:true,get:function(){return n.default}});var r=require_injectable();Object.defineProperty(e,"injectable",{enumerable:true,get:function(){return r.default}});var i=require_registry();Object.defineProperty(e,"registry",{enumerable:true,get:function(){return i.default}});var a=require_singleton();Object.defineProperty(e,"singleton",{enumerable:true,get:function(){return a.default}});var o=require_inject_all();Object.defineProperty(e,"injectAll",{enumerable:true,get:function(){return o.default}});var s=require_inject_all_with_transform();Object.defineProperty(e,"injectAllWithTransform",{enumerable:true,get:function(){return s.default}});var c=require_inject_with_transform();Object.defineProperty(e,"injectWithTransform",{enumerable:true,get:function(){return c.default}});var u=require_scoped();Object.defineProperty(e,"scoped",{enumerable:true,get:function(){return u.default}})}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/factories/instance-caching-factory.js
var require_instance_caching_factory=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});function instanceCachingFactory(e){let t;return n=>{if(t==void 0)t=e(n);return t}}e.default=instanceCachingFactory}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/factories/instance-per-container-caching-factory.js
var require_instance_per_container_caching_factory=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});function instancePerContainerCachingFactory(e){const t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r==void 0){r=e(n);t.set(n,r)}return r}}e.default=instancePerContainerCachingFactory}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/factories/predicate-aware-class-factory.js
var require_predicate_aware_class_factory=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});function predicateAwareClassFactory(e,t,n,r=true){let i;let a;return o=>{const s=e(o);if(!r||a!==s){if(a=s)i=o.resolve(t);else i=o.resolve(n)}return i}}e.default=predicateAwareClassFactory}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/factories/index.js
var require_factories=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});var t=require_instance_caching_factory();Object.defineProperty(e,"instanceCachingFactory",{enumerable:true,get:function(){return t.default}});var n=require_instance_per_container_caching_factory();Object.defineProperty(e,"instancePerContainerCachingFactory",{enumerable:true,get:function(){return n.default}});var r=require_predicate_aware_class_factory();Object.defineProperty(e,"predicateAwareClassFactory",{enumerable:true,get:function(){return r.default}})}));
//!node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/index.js
var require_cjs$4=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6(),__toCommonJS(tslib_es6_exports));if(typeof Reflect===`undefined`||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var n=require_types$2();Object.defineProperty(e,"Lifecycle",{enumerable:true,get:function(){return n.Lifecycle}});t.__exportStar(require_decorators(),e);t.__exportStar(require_factories(),e);t.__exportStar(require_providers(),e);var r=require_lazy_helpers();Object.defineProperty(e,"delay",{enumerable:true,get:function(){return r.delay}});var i=require_dependency_container();Object.defineProperty(e,"container",{enumerable:true,get:function(){return i.instance}})}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/attribute.js
var require_attribute=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.PKCS12AttrSet=e.PKCS12Attribute=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();var PKCS12Attribute=class{attrId=``;attrValues=[];constructor(e={}){Object.assign(e)}};e.PKCS12Attribute=PKCS12Attribute;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.ObjectIdentifier})],PKCS12Attribute.prototype,`attrId`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Any,repeated:`set`})],PKCS12Attribute.prototype,`attrValues`,void 0);let i=t=class PKCS12AttrSet extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.PKCS12AttrSet=i;e.PKCS12AttrSet=i=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:PKCS12Attribute})],i)}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/authenticated_safe.js
var require_authenticated_safe=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.AuthenticatedSafe=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_cjs$7();let a=t=class AuthenticatedSafe extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.AuthenticatedSafe=a;e.AuthenticatedSafe=a=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:i.ContentInfo})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/object_identifiers.js
var require_object_identifiers=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.id_bagtypes=e.id_pbewithSHAAnd40BitRC2_CBC=e.id_pbeWithSHAAnd128BitRC2_CBC=e.id_pbeWithSHAAnd2_KeyTripleDES_CBC=e.id_pbeWithSHAAnd3_KeyTripleDES_CBC=e.id_pbeWithSHAAnd40BitRC4=e.id_pbeWithSHAAnd128BitRC4=e.id_pkcs_12PbeIds=e.id_pkcs_12=e.id_pkcs=e.id_rsadsi=void 0;e.id_rsadsi=`1.2.840.113549`;e.id_pkcs=`${e.id_rsadsi}.1`;e.id_pkcs_12=`${e.id_pkcs}.12`;e.id_pkcs_12PbeIds=`${e.id_pkcs_12}.1`;e.id_pbeWithSHAAnd128BitRC4=`${e.id_pkcs_12PbeIds}.1`;e.id_pbeWithSHAAnd40BitRC4=`${e.id_pkcs_12PbeIds}.2`;e.id_pbeWithSHAAnd3_KeyTripleDES_CBC=`${e.id_pkcs_12PbeIds}.3`;e.id_pbeWithSHAAnd2_KeyTripleDES_CBC=`${e.id_pkcs_12PbeIds}.4`;e.id_pbeWithSHAAnd128BitRC2_CBC=`${e.id_pkcs_12PbeIds}.5`;e.id_pbewithSHAAnd40BitRC2_CBC=`${e.id_pkcs_12PbeIds}.6`;e.id_bagtypes=`${e.id_pkcs_12}.10.1`}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/bags/types.js
var require_types$1=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.id_pkcs_9=e.id_SafeContents=e.id_SecretBag=e.id_CRLBag=e.id_certBag=e.id_pkcs8ShroudedKeyBag=e.id_keyBag=void 0;const t=require_object_identifiers();e.id_keyBag=`${t.id_bagtypes}.1`;e.id_pkcs8ShroudedKeyBag=`${t.id_bagtypes}.2`;e.id_certBag=`${t.id_bagtypes}.3`;e.id_CRLBag=`${t.id_bagtypes}.4`;e.id_SecretBag=`${t.id_bagtypes}.5`;e.id_SafeContents=`${t.id_bagtypes}.6`;e.id_pkcs_9=`1.2.840.113549.1.9`}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/bags/cert_bag.js
var require_cert_bag=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.id_sdsiCertificate=e.id_x509Certificate=e.id_certTypes=e.CertBag=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_types$1();var CertBag=class{certId=``;certValue=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.CertBag=CertBag;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],CertBag.prototype,`certId`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any,context:0})],CertBag.prototype,`certValue`,void 0);e.id_certTypes=`${r.id_pkcs_9}.22`;e.id_x509Certificate=`${e.id_certTypes}.1`;e.id_sdsiCertificate=`${e.id_certTypes}.2`}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/bags/crl_bag.js
var require_crl_bag=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.id_x509CRL=e.id_crlTypes=e.CRLBag=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_types$1();var CRLBag=class{crlId=``;crltValue=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.CRLBag=CRLBag;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],CRLBag.prototype,`crlId`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any,context:0})],CRLBag.prototype,`crltValue`,void 0);e.id_crlTypes=`${r.id_pkcs_9}.23`;e.id_x509CRL=`${e.id_crlTypes}.1`}));
//!node_modules/.pnpm/@peculiar+asn1-pkcs8@2.11.0/node_modules/@peculiar/asn1-pkcs8/build/cjs/encrypted_private_key_info.js
var require_encrypted_private_key_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.EncryptedPrivateKeyInfo=e.EncryptedData=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();var EncryptedData=class extends n.OctetString{};e.EncryptedData=EncryptedData;var EncryptedPrivateKeyInfo=class{encryptionAlgorithm=new r.AlgorithmIdentifier;encryptedData=new EncryptedData;constructor(e={}){Object.assign(this,e)}};e.EncryptedPrivateKeyInfo=EncryptedPrivateKeyInfo;t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier})],EncryptedPrivateKeyInfo.prototype,`encryptionAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:EncryptedData})],EncryptedPrivateKeyInfo.prototype,`encryptedData`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-pkcs8@2.11.0/node_modules/@peculiar/asn1-pkcs8/build/cjs/private_key_info.js
var require_private_key_info=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.PrivateKeyInfo=e.Attributes=e.PrivateKey=e.Version=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_cjs$9();var a;(function(e){e[e[`v1`]=0]=`v1`})(a||(e.Version=a={}));var PrivateKey=class extends r.OctetString{};e.PrivateKey=PrivateKey;let o=t=class Attributes extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.Attributes=o;e.Attributes=o=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:i.Attribute})],o);var PrivateKeyInfo=class{version=a.v1;privateKeyAlgorithm=new i.AlgorithmIdentifier;privateKey=new PrivateKey;attributes;constructor(e={}){Object.assign(this,e)}};e.PrivateKeyInfo=PrivateKeyInfo;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Integer})],PrivateKeyInfo.prototype,`version`,void 0);n.__decorate([(0,r.AsnProp)({type:i.AlgorithmIdentifier})],PrivateKeyInfo.prototype,`privateKeyAlgorithm`,void 0);n.__decorate([(0,r.AsnProp)({type:PrivateKey})],PrivateKeyInfo.prototype,`privateKey`,void 0);n.__decorate([(0,r.AsnProp)({type:o,implicit:true,context:0,optional:true})],PrivateKeyInfo.prototype,`attributes`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-pkcs8@2.11.0/node_modules/@peculiar/asn1-pkcs8/build/cjs/index.js
var require_cjs$3=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_encrypted_private_key_info(),e);t.__exportStar(require_private_key_info(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/bags/key_bag.js
var require_key_bag=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.KeyBag=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$3();const r=require_cjs$10();let i=class KeyBag extends n.PrivateKeyInfo{};e.KeyBag=i;e.KeyBag=i=t.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence})],i)}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/bags/pkcs8_shrouded_key_bag.js
var require_pkcs8_shrouded_key_bag=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.PKCS8ShroudedKeyBag=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$3();const r=require_cjs$10();let i=class PKCS8ShroudedKeyBag extends n.EncryptedPrivateKeyInfo{};e.PKCS8ShroudedKeyBag=i;e.PKCS8ShroudedKeyBag=i=t.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence})],i)}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/bags/secret_bag.js
var require_secret_bag=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.SecretBag=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();var SecretBag=class{secretTypeId=``;secretValue=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.SecretBag=SecretBag;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.ObjectIdentifier})],SecretBag.prototype,`secretTypeId`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Any,context:0})],SecretBag.prototype,`secretValue`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/bags/index.js
var require_bags=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_cert_bag(),e);t.__exportStar(require_crl_bag(),e);t.__exportStar(require_key_bag(),e);t.__exportStar(require_pkcs8_shrouded_key_bag(),e);t.__exportStar(require_secret_bag(),e);t.__exportStar(require_types$1(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/mac_data.js
var require_mac_data=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.MacData=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$5();const r=require_cjs$10();var MacData=class{mac=new n.DigestInfo;macSalt=new r.OctetString;iterations=1;constructor(e={}){Object.assign(this,e)}};e.MacData=MacData;t.__decorate([(0,r.AsnProp)({type:n.DigestInfo})],MacData.prototype,`mac`,void 0);t.__decorate([(0,r.AsnProp)({type:r.OctetString})],MacData.prototype,`macSalt`,void 0);t.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Integer,defaultValue:1})],MacData.prototype,`iterations`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/pfx.js
var require_pfx=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.PFX=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$7();const i=require_mac_data();var PFX=class{version=3;authSafe=new r.ContentInfo;macData=new i.MacData;constructor(e={}){Object.assign(this,e)}};e.PFX=PFX;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer})],PFX.prototype,`version`,void 0);t.__decorate([(0,n.AsnProp)({type:r.ContentInfo})],PFX.prototype,`authSafe`,void 0);t.__decorate([(0,n.AsnProp)({type:i.MacData,optional:true})],PFX.prototype,`macData`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/safe_bag.js
var require_safe_bag=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.SafeContents=e.SafeBag=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_attribute();var SafeBag=class{bagId=``;bagValue=/* @__PURE__ */ new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}};e.SafeBag=SafeBag;n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.ObjectIdentifier})],SafeBag.prototype,`bagId`,void 0);n.__decorate([(0,r.AsnProp)({type:r.AsnPropTypes.Any,context:0})],SafeBag.prototype,`bagValue`,void 0);n.__decorate([(0,r.AsnProp)({type:i.PKCS12Attribute,repeated:`set`,optional:true})],SafeBag.prototype,`bagAttributes`,void 0);let a=t=class SafeContents extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.SafeContents=a;e.SafeContents=a=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:SafeBag})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-pfx@2.11.0/node_modules/@peculiar/asn1-pfx/build/cjs/index.js
var require_cjs$2=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_attribute(),e);t.__exportStar(require_authenticated_safe(),e);t.__exportStar(require_bags(),e);t.__exportStar(require_mac_data(),e);t.__exportStar(require_object_identifiers(),e);t.__exportStar(require_pfx(),e);t.__exportStar(require_safe_bag(),e)}));
//!node_modules/.pnpm/@peculiar+asn1-pkcs9@2.11.0/node_modules/@peculiar/asn1-pkcs9/build/cjs/index.js
var require_cjs$1=/* @__PURE__ */ __commonJSMin((e=>{var t;var n;var r;Object.defineProperty(e,"__esModule",{value:true});e.DateOfBirth=e.UnstructuredAddress=e.UnstructuredName=e.EmailAddress=e.EncryptedPrivateKeyInfo=e.UserPKCS12=e.Pkcs7PDU=e.PKCS9String=e.id_at_pseudonym=e.crlTypes=e.id_certTypes=e.id_smime=e.id_pkcs9_mr_signingTimeMatch=e.id_pkcs9_mr_caseIgnoreMatch=e.id_pkcs9_sx_signingTime=e.id_pkcs9_sx_pkcs9String=e.id_pkcs9_at_countryOfResidence=e.id_pkcs9_at_countryOfCitizenship=e.id_pkcs9_at_gender=e.id_pkcs9_at_placeOfBirth=e.id_pkcs9_at_dateOfBirth=e.id_ietf_at=e.id_pkcs9_at_pkcs7PDU=e.id_pkcs9_at_sequenceNumber=e.id_pkcs9_at_randomNonce=e.id_pkcs9_at_encryptedPrivateKeyInfo=e.id_pkcs9_at_pkcs15Token=e.id_pkcs9_at_userPKCS12=e.id_pkcs9_at_localKeyId=e.id_pkcs9_at_friendlyName=e.id_pkcs9_at_smimeCapabilities=e.id_pkcs9_at_extensionRequest=e.id_pkcs9_at_signingDescription=e.id_pkcs9_at_extendedCertificateAttributes=e.id_pkcs9_at_unstructuredAddress=e.id_pkcs9_at_challengePassword=e.id_pkcs9_at_counterSignature=e.id_pkcs9_at_signingTime=e.id_pkcs9_at_messageDigest=e.id_pkcs9_at_contentType=e.id_pkcs9_at_unstructuredName=e.id_pkcs9_at_emailAddress=e.id_pkcs9_oc_naturalPerson=e.id_pkcs9_oc_pkcsEntity=e.id_pkcs9_mr=e.id_pkcs9_sx=e.id_pkcs9_at=e.id_pkcs9_oc=e.id_pkcs9_mo=e.id_pkcs9=void 0;e.SMIMECapabilities=e.SMIMECapability=e.SigningDescription=e.LocalKeyId=e.FriendlyName=e.ExtendedCertificateAttributes=e.ExtensionRequest=e.ChallengePassword=e.CounterSignature=e.SequenceNumber=e.RandomNonce=e.SigningTime=e.MessageDigest=e.ContentType=e.Pseudonym=e.CountryOfResidence=e.CountryOfCitizenship=e.Gender=e.PlaceOfBirth=void 0;const i=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const a=require_cjs$10();const o=i.__importStar(require_cjs$7());const s=i.__importStar(require_cjs$2());const c=i.__importStar(require_cjs$3());const u=i.__importStar(require_cjs$9());const d=i.__importStar(require_cjs$8());e.id_pkcs9=`1.2.840.113549.1.9`;e.id_pkcs9_mo=`${e.id_pkcs9}.0`;e.id_pkcs9_oc=`${e.id_pkcs9}.24`;e.id_pkcs9_at=`${e.id_pkcs9}.25`;e.id_pkcs9_sx=`${e.id_pkcs9}.26`;e.id_pkcs9_mr=`${e.id_pkcs9}.27`;e.id_pkcs9_oc_pkcsEntity=`${e.id_pkcs9_oc}.1`;e.id_pkcs9_oc_naturalPerson=`${e.id_pkcs9_oc}.2`;e.id_pkcs9_at_emailAddress=`${e.id_pkcs9}.1`;e.id_pkcs9_at_unstructuredName=`${e.id_pkcs9}.2`;e.id_pkcs9_at_contentType=`${e.id_pkcs9}.3`;e.id_pkcs9_at_messageDigest=`${e.id_pkcs9}.4`;e.id_pkcs9_at_signingTime=`${e.id_pkcs9}.5`;e.id_pkcs9_at_counterSignature=`${e.id_pkcs9}.6`;e.id_pkcs9_at_challengePassword=`${e.id_pkcs9}.7`;e.id_pkcs9_at_unstructuredAddress=`${e.id_pkcs9}.8`;e.id_pkcs9_at_extendedCertificateAttributes=`${e.id_pkcs9}.9`;e.id_pkcs9_at_signingDescription=`${e.id_pkcs9}.13`;e.id_pkcs9_at_extensionRequest=`${e.id_pkcs9}.14`;e.id_pkcs9_at_smimeCapabilities=`${e.id_pkcs9}.15`;e.id_pkcs9_at_friendlyName=`${e.id_pkcs9}.20`;e.id_pkcs9_at_localKeyId=`${e.id_pkcs9}.21`;e.id_pkcs9_at_userPKCS12=`2.16.840.1.113730.3.1.216`;e.id_pkcs9_at_pkcs15Token=`${e.id_pkcs9_at}.1`;e.id_pkcs9_at_encryptedPrivateKeyInfo=`${e.id_pkcs9_at}.2`;e.id_pkcs9_at_randomNonce=`${e.id_pkcs9_at}.3`;e.id_pkcs9_at_sequenceNumber=`${e.id_pkcs9_at}.4`;e.id_pkcs9_at_pkcs7PDU=`${e.id_pkcs9_at}.5`;e.id_ietf_at=`1.3.6.1.5.5.7.9`;e.id_pkcs9_at_dateOfBirth=`${e.id_ietf_at}.1`;e.id_pkcs9_at_placeOfBirth=`${e.id_ietf_at}.2`;e.id_pkcs9_at_gender=`${e.id_ietf_at}.3`;e.id_pkcs9_at_countryOfCitizenship=`${e.id_ietf_at}.4`;e.id_pkcs9_at_countryOfResidence=`${e.id_ietf_at}.5`;e.id_pkcs9_sx_pkcs9String=`${e.id_pkcs9_sx}.1`;e.id_pkcs9_sx_signingTime=`${e.id_pkcs9_sx}.2`;e.id_pkcs9_mr_caseIgnoreMatch=`${e.id_pkcs9_mr}.1`;e.id_pkcs9_mr_signingTimeMatch=`${e.id_pkcs9_mr}.2`;e.id_smime=`${e.id_pkcs9}.16`;e.id_certTypes=`${e.id_pkcs9}.22`;e.crlTypes=`${e.id_pkcs9}.23`;e.id_at_pseudonym=`${d.id_at}.65`;let f=class PKCS9String extends u.DirectoryString{ia5String;constructor(e={}){super(e)}toString(){({}).toString();return this.ia5String||super.toString()}};e.PKCS9String=f;i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.IA5String})],f.prototype,`ia5String`,void 0);e.PKCS9String=f=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],f);let p=class Pkcs7PDU extends o.ContentInfo{};e.Pkcs7PDU=p;e.Pkcs7PDU=p=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Sequence})],p);let m=class UserPKCS12 extends s.PFX{};e.UserPKCS12=m;e.UserPKCS12=m=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Sequence})],m);let g=class EncryptedPrivateKeyInfo extends c.EncryptedPrivateKeyInfo{};e.EncryptedPrivateKeyInfo=g;e.EncryptedPrivateKeyInfo=g=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Sequence})],g);let _=class EmailAddress{value;constructor(e=``){this.value=e}toString(){return this.value}};e.EmailAddress=_;i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.IA5String})],_.prototype,`value`,void 0);e.EmailAddress=_=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],_);let v=class UnstructuredName extends f{};e.UnstructuredName=v;e.UnstructuredName=v=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],v);let y=class UnstructuredAddress extends u.DirectoryString{};e.UnstructuredAddress=y;e.UnstructuredAddress=y=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],y);let b=class DateOfBirth{value;constructor(e=/* @__PURE__ */ new Date){this.value=e}};e.DateOfBirth=b;i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.GeneralizedTime})],b.prototype,`value`,void 0);e.DateOfBirth=b=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],b);let x=class PlaceOfBirth extends u.DirectoryString{};e.PlaceOfBirth=x;e.PlaceOfBirth=x=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],x);let C=class Gender{value;constructor(e=`M`){this.value=e}toString(){return this.value}};e.Gender=C;i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.PrintableString})],C.prototype,`value`,void 0);e.Gender=C=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],C);let w=class CountryOfCitizenship{value;constructor(e=``){this.value=e}toString(){return this.value}};e.CountryOfCitizenship=w;i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.PrintableString})],w.prototype,`value`,void 0);e.CountryOfCitizenship=w=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],w);let T=class CountryOfResidence extends w{};e.CountryOfResidence=T;e.CountryOfResidence=T=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],T);let E=class Pseudonym extends u.DirectoryString{};e.Pseudonym=E;e.Pseudonym=E=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],E);let D=class ContentType{value;constructor(e=``){this.value=e}toString(){return this.value}};e.ContentType=D;i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.ObjectIdentifier})],D.prototype,`value`,void 0);e.ContentType=D=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],D);var MessageDigest=class extends a.OctetString{};e.MessageDigest=MessageDigest;let O=class SigningTime extends u.Time{};e.SigningTime=O;e.SigningTime=O=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],O);var RandomNonce=class extends a.OctetString{};e.RandomNonce=RandomNonce;let k=class SequenceNumber{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};e.SequenceNumber=k;i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.Integer})],k.prototype,`value`,void 0);e.SequenceNumber=k=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],k);let j=class CounterSignature extends o.SignerInfo{};e.CounterSignature=j;e.CounterSignature=j=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Sequence})],j);let N=class ChallengePassword extends u.DirectoryString{};e.ChallengePassword=N;e.ChallengePassword=N=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],N);let P=t=class ExtensionRequest extends u.Extensions{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.ExtensionRequest=P;e.ExtensionRequest=P=t=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Sequence})],P);let F=n=class ExtendedCertificateAttributes extends a.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,n.prototype)}};e.ExtendedCertificateAttributes=F;e.ExtendedCertificateAttributes=F=n=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Set,itemType:o.Attribute})],F);let I=class FriendlyName{value;constructor(e=``){this.value=e}toString(){return this.value}};e.FriendlyName=I;i.__decorate([(0,a.AsnProp)({type:a.AsnPropTypes.BmpString})],I.prototype,`value`,void 0);e.FriendlyName=I=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Choice})],I);var LocalKeyId=class extends a.OctetString{};e.LocalKeyId=LocalKeyId;var SigningDescription=class extends u.DirectoryString{};e.SigningDescription=SigningDescription;let L=class SMIMECapability extends u.AlgorithmIdentifier{};e.SMIMECapability=L;e.SMIMECapability=L=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Sequence})],L);let R=r=class SMIMECapabilities extends a.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,r.prototype)}};e.SMIMECapabilities=R;e.SMIMECapabilities=R=r=i.__decorate([(0,a.AsnType)({type:a.AsnTypeTypes.Sequence,itemType:L})],R)}));
//!node_modules/.pnpm/@peculiar+asn1-csr@2.11.0/node_modules/@peculiar/asn1-csr/build/cjs/attributes.js
var require_attributes=/* @__PURE__ */ __commonJSMin((e=>{var t;Object.defineProperty(e,"__esModule",{value:true});e.Attributes=void 0;const n=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const r=require_cjs$10();const i=require_cjs$9();let a=t=class Attributes extends r.AsnArray{constructor(e){super(e);Object.setPrototypeOf(this,t.prototype)}};e.Attributes=a;e.Attributes=a=t=n.__decorate([(0,r.AsnType)({type:r.AsnTypeTypes.Sequence,itemType:i.Attribute})],a)}));
//!node_modules/.pnpm/@peculiar+asn1-csr@2.11.0/node_modules/@peculiar/asn1-csr/build/cjs/certification_request_info.js
var require_certification_request_info=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.CertificationRequestInfo=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();const i=require_attributes();var CertificationRequestInfo=class{version=0;subject=new r.Name;subjectPKInfo=new r.SubjectPublicKeyInfo;attributes=new i.Attributes;constructor(e={}){Object.assign(this,e)}};e.CertificationRequestInfo=CertificationRequestInfo;t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.Integer})],CertificationRequestInfo.prototype,`version`,void 0);t.__decorate([(0,n.AsnProp)({type:r.Name})],CertificationRequestInfo.prototype,`subject`,void 0);t.__decorate([(0,n.AsnProp)({type:r.SubjectPublicKeyInfo})],CertificationRequestInfo.prototype,`subjectPKInfo`,void 0);t.__decorate([(0,n.AsnProp)({type:i.Attributes,implicit:true,context:0,optional:true})],CertificationRequestInfo.prototype,`attributes`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-csr@2.11.0/node_modules/@peculiar/asn1-csr/build/cjs/certification_request.js
var require_certification_request=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.CertificationRequest=void 0;const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));const n=require_cjs$10();const r=require_cjs$9();const i=require_certification_request_info();var CertificationRequest=class{certificationRequestInfo=new i.CertificationRequestInfo;certificationRequestInfoRaw;signatureAlgorithm=new r.AlgorithmIdentifier;signature=/* @__PURE__ */ new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};e.CertificationRequest=CertificationRequest;t.__decorate([(0,n.AsnProp)({type:i.CertificationRequestInfo,raw:true})],CertificationRequest.prototype,`certificationRequestInfo`,void 0);t.__decorate([(0,n.AsnProp)({type:r.AlgorithmIdentifier})],CertificationRequest.prototype,`signatureAlgorithm`,void 0);t.__decorate([(0,n.AsnProp)({type:n.AsnPropTypes.BitString})],CertificationRequest.prototype,`signature`,void 0)}));
//!node_modules/.pnpm/@peculiar+asn1-csr@2.11.0/node_modules/@peculiar/asn1-csr/build/cjs/index.js
var require_cjs=/* @__PURE__ */ __commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});const t=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));t.__exportStar(require_attributes(),e);t.__exportStar(require_certification_request(),e);t.__exportStar(require_certification_request_info(),e)}));
//!node_modules/.pnpm/@peculiar+x509@1.14.3/node_modules/@peculiar/x509/build/x509.cjs.js
/*!
* MIT License
*
* Copyright (c) Peculiar Ventures. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
var require_x509_cjs=/* @__PURE__ */ __commonJSMin((e=>{require_Reflect();var t=require_cjs$10();var n=require_cjs$9();var r=require_build$3();var i=(init_tslib_es6$1(),__toCommonJS(tslib_es6_exports$1));var a=require_cjs$7();var o=require_cjs$6();var s=require_cjs$5();var c=require_cjs$4();var u=require_cjs$1();var d=require_cjs();function _interopNamespaceDefault(e){var t=Object.create(null);if(e)Object.keys(e).forEach(function(n){if(n!=="default"){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:true,get:function(){return e[n]}})}});t.default=e;return Object.freeze(t)}var f=/*#__PURE__*/ _interopNamespaceDefault(n);var p=/*#__PURE__*/ _interopNamespaceDefault(a);var m=/*#__PURE__*/ _interopNamespaceDefault(o);var g=/*#__PURE__*/ _interopNamespaceDefault(s);var _=/*#__PURE__*/ _interopNamespaceDefault(u);const v=`crypto.algorithm`;var AlgorithmProvider=class{getAlgorithms(){return c.container.resolveAll(v)}toAsnAlgorithm(e){({...e});for(const t of this.getAlgorithms()){const n=t.toAsnAlgorithm(e);if(n)return n}if(/^[0-9.]+$/.test(e.name)){const t=new n.AlgorithmIdentifier({algorithm:e.name});if(`parameters`in e)t.parameters=e.parameters;return t}throw new Error(`Cannot convert WebCrypto algorithm to ASN.1 algorithm`)}toWebAlgorithm(e){for(const t of this.getAlgorithms()){const n=t.toWebAlgorithm(e);if(n)return n}return{name:e.algorithm,parameters:e.parameters}}};const y=`crypto.algorithmProvider`;c.container.registerSingleton(y,AlgorithmProvider);var b;const x=`1.3.36.3.3.2.8.1.1`;const C=`${x}.1`;const w=`${x}.2`;const T=`${x}.3`;const E=`${x}.4`;const D=`${x}.5`;const O=`${x}.6`;const k=`${x}.7`;const j=`${x}.8`;const N=`${x}.9`;const P=`${x}.10`;const F=`${x}.11`;const I=`${x}.12`;const L=`${x}.13`;const R=`${x}.14`;const z=`brainpoolP160r1`;const B=`brainpoolP160t1`;const V=`brainpoolP192r1`;const H=`brainpoolP192t1`;const U=`brainpoolP224r1`;const W=`brainpoolP224t1`;const G=`brainpoolP256r1`;const K=`brainpoolP256t1`;const q=`brainpoolP320r1`;const J=`brainpoolP320t1`;const Y=`brainpoolP384r1`;const X=`brainpoolP384t1`;const ee=`brainpoolP512r1`;const te=`brainpoolP512t1`;const Q=`ECDSA`;e.EcAlgorithm=b=class EcAlgorithm{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case Q.toLowerCase():if(`hash`in e)switch((typeof e.hash===`string`?e.hash:e.hash.name).toLowerCase()){case`sha-1`:return m.ecdsaWithSHA1;case`sha-256`:return m.ecdsaWithSHA256;case`sha-384`:return m.ecdsaWithSHA384;case`sha-512`:return m.ecdsaWithSHA512}else if(`namedCurve`in e){let r=``;switch(e.namedCurve){case`P-256`:r=m.id_secp256r1;break;case`K-256`:r=b.SECP256K1;break;case`P-384`:r=m.id_secp384r1;break;case`P-521`:r=m.id_secp521r1;break;case z:r=C;break;case B:r=w;break;case V:r=T;break;case H:r=E;break;case U:r=D;break;case W:r=O;break;case G:r=k;break;case K:r=j;break;case q:r=N;break;case J:r=P;break;case Y:r=F;break;case X:r=I;break;case ee:r=L;break;case te:r=R}if(r)return new n.AlgorithmIdentifier({algorithm:m.id_ecPublicKey,parameters:t.AsnConvert.serialize(new m.ECParameters({namedCurve:r}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case m.id_ecdsaWithSHA1:return{name:Q,hash:{name:`SHA-1`}};case m.id_ecdsaWithSHA256:return{name:Q,hash:{name:`SHA-256`}};case m.id_ecdsaWithSHA384:return{name:Q,hash:{name:`SHA-384`}};case m.id_ecdsaWithSHA512:return{name:Q,hash:{name:`SHA-512`}};case m.id_ecPublicKey:if(!e.parameters)throw new TypeError(`Cannot get required parameters from EC algorithm`);switch(t.AsnConvert.parse(e.parameters,m.ECParameters).namedCurve){case m.id_secp256r1:return{name:Q,namedCurve:`P-256`};case b.SECP256K1:return{name:Q,namedCurve:`K-256`};case m.id_secp384r1:return{name:Q,namedCurve:`P-384`};case m.id_secp521r1:return{name:Q,namedCurve:`P-521`};case C:return{name:Q,namedCurve:z};case w:return{name:Q,namedCurve:B};case T:return{name:Q,namedCurve:V};case E:return{name:Q,namedCurve:H};case D:return{name:Q,namedCurve:U};case O:return{name:Q,namedCurve:W};case k:return{name:Q,namedCurve:G};case j:return{name:Q,namedCurve:K};case N:return{name:Q,namedCurve:q};case P:return{name:Q,namedCurve:J};case F:return{name:Q,namedCurve:Y};case I:return{name:Q,namedCurve:X};case L:return{name:Q,namedCurve:ee};case R:return{name:Q,namedCurve:te}}}return null}};e.EcAlgorithm.SECP256K1=`1.3.132.0.10`;e.EcAlgorithm=b=i.__decorate([c.injectable()],e.EcAlgorithm);c.container.registerSingleton(v,e.EcAlgorithm);const ne=Symbol(`name`);const re=Symbol(`value`);var TextObject=class{constructor(e,t={},n=``){this[ne]=e;this[re]=n;for(const e in t)this[e]=t[e]}};TextObject.NAME=ne;TextObject.VALUE=re;var DefaultAlgorithmSerializer=class{static toTextObject(t){const n=new TextObject(`Algorithm Identifier`,{},OidSerializer.toString(t.algorithm));if(t.parameters)switch(t.algorithm){case m.id_ecPublicKey:{const r=new e.EcAlgorithm().toWebAlgorithm(t);if(r&&`namedCurve`in r)n[`Named Curve`]=r.namedCurve;else n[`Parameters`]=t.parameters;break}default:n[`Parameters`]=t.parameters}return n}};var OidSerializer=class{static toString(e){const t=this.items[e];if(t)return t;return e}};OidSerializer.items={[g.id_sha1]:`sha1`,[g.id_sha224]:`sha224`,[g.id_sha256]:`sha256`,[g.id_sha384]:`sha384`,[g.id_sha512]:`sha512`,[g.id_rsaEncryption]:`rsaEncryption`,[g.id_sha1WithRSAEncryption]:`sha1WithRSAEncryption`,[g.id_sha224WithRSAEncryption]:`sha224WithRSAEncryption`,[g.id_sha256WithRSAEncryption]:`sha256WithRSAEncryption`,[g.id_sha384WithRSAEncryption]:`sha384WithRSAEncryption`,[g.id_sha512WithRSAEncryption]:`sha512WithRSAEncryption`,[m.id_ecPublicKey]:`ecPublicKey`,[m.id_ecdsaWithSHA1]:`ecdsaWithSHA1`,[m.id_ecdsaWithSHA224]:`ecdsaWithSHA224`,[m.id_ecdsaWithSHA256]:`ecdsaWithSHA256`,[m.id_ecdsaWithSHA384]:`ecdsaWithSHA384`,[m.id_ecdsaWithSHA512]:`ecdsaWithSHA512`,[f.id_kp_serverAuth]:`TLS WWW server authentication`,[f.id_kp_clientAuth]:`TLS WWW client authentication`,[f.id_kp_codeSigning]:`Code Signing`,[f.id_kp_emailProtection]:`E-mail Protection`,[f.id_kp_timeStamping]:`Time Stamping`,[f.id_kp_OCSPSigning]:`OCSP Signing`,[p.id_signedData]:`Signed Data`};var TextConverter=class{static serialize(e){return this.serializeObj(e).join(`
`)}static pad(e=0){return``.padStart(2*e,` `)}static serializeObj(e,t=0){const n=[];let i=this.pad(t++);let a=``;const o=e[TextObject.VALUE];if(o)a=` ${o}`;n.push(`${i}${e[TextObject.NAME]}:${a}`);i=this.pad(t);for(const a in e){if(typeof a===`symbol`)continue;const o=e[a];const s=a?`${a}: `:``;if(typeof o===`string`||typeof o===`number`||typeof o===`boolean`)n.push(`${i}${s}${o}`);else if(o instanceof Date)n.push(`${i}${s}${o.toUTCString()}`);else if(Array.isArray(o))for(const e of o){e[TextObject.NAME]=a;n.push(...this.serializeObj(e,t))}else if(o instanceof TextObject){o[TextObject.NAME]=a;n.push(...this.serializeObj(o,t))}else if(r.BufferSourceConverter.isBufferSource(o)){if(a){n.push(`${i}${s}`);n.push(...this.serializeBufferSource(o,t+1))}else n.push(...this.serializeBufferSource(o,t))}else if(`toTextObject`in o){const e=o.toTextObject();e[TextObject.NAME]=a;n.push(...this.serializeObj(e,t))}else throw new TypeError(`Cannot serialize data in text format. Unsupported type.`)}return n}static serializeBufferSource(e,t=0){const n=this.pad(t);const i=r.BufferSourceConverter.toUint8Array(e);const a=[];for(let e=0;e<i.length;){const t=[];for(let n=0;n<16&&e<i.length;n++){if(n===8)t.push(``);const r=i[e++].toString(16).padStart(2,`0`);t.push(r)}a.push(`${n}${t.join(` `)}`)}return a}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}};TextConverter.oidSerializer=OidSerializer;TextConverter.algorithmSerializer=DefaultAlgorithmSerializer;var ie;var ae=class AsnData{get rawData(){if(!i.__classPrivateFieldGet(this,ie,`f`))i.__classPrivateFieldSet(this,ie,t.AsnConvert.serialize(this.asn),`f`);return i.__classPrivateFieldGet(this,ie,`f`)}constructor(...e){ie.set(this,void 0);if(r.BufferSourceConverter.isBufferSource(e[0])){this.asn=t.AsnConvert.parse(e[0],e[1]);i.__classPrivateFieldSet(this,ie,r.BufferSourceConverter.toArrayBuffer(e[0]),`f`);this.onInit(this.asn)}else{this.asn=e[0];this.onInit(this.asn)}}equal(e){if(e instanceof AsnData)return r.isEqual(e.rawData,this.rawData);return false}toString(e=`text`){switch(e){case`asn`:return t.AsnConvert.toString(this.rawData);case`text`:return TextConverter.serialize(this.toTextObject());case`hex`:return r.Convert.ToHex(this.rawData);case`base64`:return r.Convert.ToBase64(this.rawData);case`base64url`:return r.Convert.ToBase64Url(this.rawData);default:throw TypeError(`Argument 'format' is unsupported value`)}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();e[``]=this.rawData;return e}toTextObjectEmpty(e){return new TextObject(this.getTextName(),{},e)}};ie=/* @__PURE__ */ new WeakMap;ae.NAME=`ASN`;var oe=class Extension extends ae{constructor(...e){let i;if(r.BufferSourceConverter.isBufferSource(e[0]))i=r.BufferSourceConverter.toArrayBuffer(e[0]);else i=t.AsnConvert.serialize(new n.Extension({extnID:e[0],critical:e[1],extnValue:new t.OctetString(r.BufferSourceConverter.toArrayBuffer(e[2]))}));super(i,n.Extension)}onInit(e){this.type=e.extnID;this.critical=e.critical;this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();e[``]=this.value;return e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?`critical`:void 0);if(e[TextObject.NAME]===Extension.NAME)e[TextObject.NAME]=OidSerializer.toString(this.type);return e}};var se;var ce=class CryptoProvider{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=/* @__PURE__ */ new Map;this[se]=`CryptoProvider`;if(typeof self!==`undefined`&&typeof crypto!==`undefined`)this.set(CryptoProvider.DEFAULT,crypto);else if(typeof global!==`undefined`&&global.crypto&&global.crypto.subtle)this.set(CryptoProvider.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=CryptoProvider.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(typeof e===`string`){if(!t)throw new TypeError(`Argument 'value' is required`);this.items.set(e.toLowerCase(),t)}else this.items.set(CryptoProvider.DEFAULT,e);return this}};se=Symbol.toStringTag;ce.DEFAULT=`default`;const $=new ce;const le=/^[0-2](?:\.[1-9][0-9]*)+$/;function isOID(e){return new RegExp(le).test(e)}var NameIdentifier=class{constructor(e={}){this.items={};for(const t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){if(!isOID(e))return this.get(e);return e}register(e,t){this.items[e]=t;this.items[t]=e}};const ue=new NameIdentifier;ue.register(`CN`,`2.5.4.3`);ue.register(`L`,`2.5.4.7`);ue.register(`ST`,`2.5.4.8`);ue.register(`O`,`2.5.4.10`);ue.register(`OU`,`2.5.4.11`);ue.register(`C`,`2.5.4.6`);ue.register(`DC`,`0.9.2342.19200300.100.1.25`);ue.register(`E`,`1.2.840.113549.1.9.1`);ue.register(`G`,`2.5.4.42`);ue.register(`I`,`2.5.4.43`);ue.register(`SN`,`2.5.4.4`);ue.register(`T`,`2.5.4.12`);function replaceUnknownCharacter(e,t){return`\\${r.Convert.ToHex(r.Convert.FromUtf8String(t)).toUpperCase()}`}function escape(e){return e.replace(/([,+"\\<>;])/g,`\\$1`).replace(/^([ #])/,`\\$1`).replace(/([ ]$)/,`\\$1`).replace(/([\r\n\t])/,replaceUnknownCharacter)}var de=class Name{static isASCII(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return false;return true}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,i={}){this.extraNames=new NameIdentifier;this.asn=new n.Name;for(const e in i)if(Object.prototype.hasOwnProperty.call(i,e)){const t=i[e];this.extraNames.register(e,t)}if(typeof e===`string`)this.asn=this.fromString(e);else if(e instanceof n.Name)this.asn=e;else if(r.BufferSourceConverter.isBufferSource(e))this.asn=t.AsnConvert.parse(e,n.Name);else this.asn=this.fromJSON(e)}getField(e){const t=this.extraNames.findId(e)||ue.findId(e);const n=[];for(const e of this.asn)for(const r of e)if(r.type===t)n.push(r.value.toString());return n}getName(e){return this.extraNames.get(e)||ue.get(e)}toString(){return this.asn.map(e=>e.map(e=>{return`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${r.Convert.ToHex(e.value.anyValue)}`:escape(e.value.toString())}`}).join(`+`)).join(`, `)}toJSON(){var e;const t=[];for(const n of this.asn){const i={};for(const t of n){const n=this.getName(t.type)||t.type;(e=i[n])!==null&&e!==void 0||(i[n]=[]);i[n].push(t.value.anyValue?`#${r.Convert.ToHex(t.value.anyValue)}`:t.value.toString())}t.push(i)}return t}fromString(e){const t=new n.Name;const r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let i=null;let a=`,`;while(i=r.exec(`${e},`)){let[,e,r]=i;const o=r[r.length-1];if(o===`,`||o===`+`){r=r.slice(0,r.length-1);i[3]=o}const s=i[3];e=this.getTypeOid(e);const c=this.createAttribute(e,r);if(a===`+`)t[t.length-1].push(c);else t.push(new n.RelativeDistinguishedName([c]));a=s}return t}fromJSON(e){const t=new n.Name;for(const r of e){const e=new n.RelativeDistinguishedName;for(const t in r){const n=this.getTypeOid(t);const i=r[t];for(const t of i){const r=this.createAttribute(n,t);e.push(r)}}t.push(e)}return t}getTypeOid(e){if(!/[\d.]+/.test(e))e=this.getName(e)||``;if(!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,t){const i=new n.AttributeTypeAndValue({type:e});if(typeof t===`object`)for(const e in t)switch(e){case`ia5String`:i.value.ia5String=t[e];break;case`utf8String`:i.value.utf8String=t[e];break;case`universalString`:i.value.universalString=t[e];break;case`bmpString`:i.value.bmpString=t[e];break;case`printableString`:i.value.printableString=t[e]}else if(t[0]===`#`)i.value.anyValue=r.Convert.FromHex(t.slice(1));else{const n=this.processStringValue(t);if(e===this.getName(`E`)||e===this.getName(`DC`))i.value.ia5String=n;else if(Name.isPrintableString(n))i.value.printableString=n;else i.value.utf8String=n}return i}processStringValue(e){const t=/"(.*?[^\\])?"/.exec(e);if(t)e=t[1];return e.replace(/\\0a/gi,`
`).replace(/\\0d/gi,`\r`).replace(/\\0g/gi,` `).replace(/\\(.)/g,`$1`)}toArrayBuffer(){return t.AsnConvert.serialize(this.asn)}async getThumbprint(...e){var t;let n;let r=`SHA-1`;if(e.length>=1&&!((t=e[0])===null||t===void 0?void 0:t.subtle)){r=e[0]||r;n=e[1]||$.get()}else n=e[0]||$.get();return await n.subtle.digest(r,this.toArrayBuffer())}};const fe=`Cannot initialize GeneralName from ASN.1 data.`;const pe=`${fe} Unsupported string format in use.`;const me=`${fe} Value doesn't match to GUID regular expression.`;const he=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i;const ge=`1.3.6.1.4.1.311.25.1`;const _e=`1.3.6.1.4.1.311.20.2.3`;const ve=`dns`;const ye=`dn`;const be=`email`;const xe=`ip`;const Se=`url`;const Ce=`guid`;const we=`upn`;const Te=`id`;var GeneralName=class extends ae{constructor(...e){let n;if(e.length===2)switch(e[0]){case ye:{const r=new de(e[1]).toArrayBuffer();const i=t.AsnConvert.parse(r,f.Name);n=new f.GeneralName({directoryName:i});break}case ve:n=new f.GeneralName({dNSName:e[1]});break;case be:n=new f.GeneralName({rfc822Name:e[1]});break;case Ce:{const i=new RegExp(he,`i`).exec(e[1]);if(!i)throw new Error(`Cannot parse GUID value. Value doesn't match to regular expression`);const a=i.slice(1).map((e,t)=>{if(t<3)return r.Convert.ToHex(new Uint8Array(r.Convert.FromHex(e)).reverse());return e}).join(``);n=new f.GeneralName({otherName:new f.OtherName({typeId:ge,value:t.AsnConvert.serialize(new t.OctetString(r.Convert.FromHex(a)))})});break}case xe:n=new f.GeneralName({iPAddress:e[1]});break;case Te:n=new f.GeneralName({registeredID:e[1]});break;case we:n=new f.GeneralName({otherName:new f.OtherName({typeId:_e,value:t.AsnConvert.serialize(t.AsnUtf8StringConverter.toASN(e[1]))})});break;case Se:n=new f.GeneralName({uniformResourceIdentifier:e[1]});break;default:throw new Error(`Cannot create GeneralName. Unsupported type of the name`)}else if(r.BufferSourceConverter.isBufferSource(e[0]))n=t.AsnConvert.parse(e[0],f.GeneralName);else n=e[0];super(n)}onInit(e){if(e.dNSName!=void 0){this.type=ve;this.value=e.dNSName}else if(e.rfc822Name!=void 0){this.type=be;this.value=e.rfc822Name}else if(e.iPAddress!=void 0){this.type=xe;this.value=e.iPAddress}else if(e.uniformResourceIdentifier!=void 0){this.type=Se;this.value=e.uniformResourceIdentifier}else if(e.registeredID!=void 0){this.type=Te;this.value=e.registeredID}else if(e.directoryName!=void 0){this.type=ye;this.value=new de(e.directoryName).toString()}else if(e.otherName!=void 0){if(e.otherName.typeId===ge){this.type=Ce;const n=t.AsnConvert.parse(e.otherName.value,t.OctetString);const i=new RegExp(he,`i`).exec(r.Convert.ToHex(n));if(!i)throw new Error(me);this.value=i.slice(1).map((e,t)=>{if(t<3)return r.Convert.ToHex(new Uint8Array(r.Convert.FromHex(e)).reverse());return e}).join(`-`)}else if(e.otherName.typeId===_e){this.type=we;this.value=t.AsnConvert.parse(e.otherName.value,f.DirectoryString).toString()}else throw new Error(pe)}else throw new Error(pe)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case ye:case ve:case Ce:case xe:case Te:case we:case Se:e=this.type.toUpperCase();break;case be:e=`Email`;break;default:throw new Error(`Unsupported GeneralName type`)}let t=this.value;if(this.type===Te)t=OidSerializer.toString(t);return new TextObject(e,void 0,t)}};var GeneralNames=class extends ae{constructor(e){let n;if(e instanceof f.GeneralNames)n=e;else if(Array.isArray(e)){const r=[];for(const n of e)if(n instanceof f.GeneralName)r.push(n);else{const e=t.AsnConvert.parse(new GeneralName(n.type,n.value).rawData,f.GeneralName);r.push(e)}n=new f.GeneralNames(r)}else if(r.BufferSourceConverter.isBufferSource(e))n=t.AsnConvert.parse(e,f.GeneralNames);else throw new Error(`Cannot initialize GeneralNames. Incorrect incoming arguments`);super(n)}onInit(e){const t=[];for(const n of e){let e=null;try{e=new GeneralName(n)}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 n=t.toTextObject();let r=e[n[TextObject.NAME]];if(!Array.isArray(r)){r=[];e[n[TextObject.NAME]]=r}r.push(n)}return e}};GeneralNames.NAME=`GeneralNames`;const Ee=`-{5}`;const De=`\\n`;const Oe=`${Ee}BEGIN (${`[^${De}]+`}(?=${Ee}))${Ee}`;const ke=`${Ee}END \\1${Ee}`;const Ae=`\\n`;const je=`${Oe}${Ae}(?:((?:${`[^:${De}]+`}: ${`(?:[^${De}]+${Ae}(?: +[^${De}]+${Ae})*)`})+))?${Ae}?(${`(?:[a-zA-Z0-9=+/]+${Ae})+`})${ke}`;var PemConverter=class{static isPem(e){return typeof e===`string`&&new RegExp(je,`g`).test(e.replace(/\r/g,``))}static decodeWithHeaders(e){e=e.replace(/\r/g,``);const t=new RegExp(je,`g`);const n=[];let i=null;while(i=t.exec(e)){const e=i[3].replace(new RegExp(`[${De}]+`,`g`),``);const t={type:i[1],headers:[],rawData:r.Convert.FromBase64(e)};const a=i[2];if(a){const e=a.split(new RegExp(Ae,`g`));let n=null;for(const r of e){const[e,i]=r.split(/:(.*)/);if(i===void 0){if(!n)throw new Error(`Cannot parse PEM string. Incorrect header value`);n.value+=e.trim()}else{if(n)t.headers.push(n);n={key:e,value:i.trim()}}}if(n)t.headers.push(n)}n.push(t)}return n}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 n=new Array;if(t)e.forEach(e=>{if(!r.BufferSourceConverter.isBufferSource(e))throw new TypeError(`Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource`);n.push(this.encodeStruct({type:t,rawData:r.BufferSourceConverter.toArrayBuffer(e)}))});else 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`);n.push(this.encodeStruct(e))});return n.join(`
`)}else{if(!t)throw new Error(`Required argument 'tag' is missed`);return this.encodeStruct({type:t,rawData:r.BufferSourceConverter.toArrayBuffer(e)})}}static encodeStruct(e){var t;const n=e.type.toLocaleUpperCase();const i=[];i.push(`-----BEGIN ${n}-----`);if((t=e.headers)===null||t===void 0?void 0:t.length){for(const t of e.headers)i.push(`${t.key}: ${t.value}`);i.push(``)}const a=r.Convert.ToBase64(e.rawData);let o;let s=0;const c=Array();while(s<a.length){if(a.length-s<64)o=a.substring(s);else{o=a.substring(s,s+64);s+=64}if(o.length!==0){c.push(o);if(o.length<64)break}else break}i.push(...c);i.push(`-----END ${n}-----`);return i.join(`
`)}};PemConverter.CertificateTag=`CERTIFICATE`;PemConverter.CrlTag=`CRL`;PemConverter.CertificateRequestTag=`CERTIFICATE REQUEST`;PemConverter.PublicKeyTag=`PUBLIC KEY`;PemConverter.PrivateKeyTag=`PRIVATE KEY`;var Me=class PemData extends ae{static isAsnEncoded(e){return r.BufferSourceConverter.isBufferSource(e)||typeof e===`string`}static toArrayBuffer(e){if(typeof e===`string`){if(PemConverter.isPem(e))return PemConverter.decode(e)[0];else if(r.Convert.isHex(e))return r.Convert.FromHex(e);else if(r.Convert.isBase64(e))return r.Convert.FromBase64(e);else if(r.Convert.isBase64Url(e))return r.Convert.FromBase64Url(e);else throw new TypeError(`Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url`)}else{const t=r.BufferSourceConverter.toUint8Array(e);if(t.length>0&&t[0]===48)return r.BufferSourceConverter.toArrayBuffer(e);const n=r.Convert.ToBinary(e);if(PemConverter.isPem(n))return PemConverter.decode(n)[0];else if(r.Convert.isHex(n))return r.Convert.FromHex(n);else if(r.Convert.isBase64(n))return r.Convert.FromBase64(n);else if(r.Convert.isBase64Url(n))return r.Convert.FromBase64Url(n);throw new TypeError(`Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url`)}}constructor(...e){if(PemData.isAsnEncoded(e[0]))super(PemData.toArrayBuffer(e[0]),e[1]);else super(e[0])}toString(e=`pem`){switch(e){case`pem`:return PemConverter.encode(this.rawData,this.tag);default:return super.toString(e)}}};var Ne=class PublicKey extends Me{static async create(e,t=$.get()){if(e instanceof PublicKey)return e;else if(ce.isCryptoKey(e)){if(e.type!==`public`)throw new TypeError(`Public key is required`);const n=await t.subtle.exportKey(`spki`,e);return new PublicKey(n)}else if(e.publicKey)return e.publicKey;else if(r.BufferSourceConverter.isBufferSource(e))return new PublicKey(e);else throw new TypeError(`Unsupported PublicKeyType`)}constructor(e){if(Me.isAsnEncoded(e))super(e,n.SubjectPublicKeyInfo);else super(e);this.tag=PemConverter.PublicKeyTag}async export(...e){let r;let i=[`verify`];let a={hash:`SHA-256`,...this.algorithm};if(e.length>1){a=e[0]||a;i=e[1]||i;r=e[2]||$.get()}else r=e[0]||$.get();let o=this.rawData;const c=t.AsnConvert.parse(this.rawData,n.SubjectPublicKeyInfo);if(c.algorithm.algorithm===s.id_RSASSA_PSS)o=convertSpkiToRsaPkcs1(c,o);return r.subtle.importKey(`spki`,o,a,true,i)}onInit(e){const n=c.container.resolve(y);const i=this.algorithm=n.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case s.id_rsaEncryption:{const n=t.AsnConvert.parse(e.subjectPublicKey,s.RSAPublicKey);const a=r.BufferSourceConverter.toUint8Array(n.modulus);i.publicExponent=r.BufferSourceConverter.toUint8Array(n.publicExponent);i.modulusLength=(!a[0]?a.slice(1):a).byteLength<<3;break}}}async getThumbprint(...e){var t;let n;let r=`SHA-1`;if(e.length>=1&&!((t=e[0])===null||t===void 0?void 0:t.subtle)){r=e[0]||r;n=e[1]||$.get()}else n=e[0]||$.get();return await n.subtle.digest(r,this.rawData)}async getKeyIdentifier(...e){let r;let i=`SHA-1`;if(e.length===1){if(typeof e[0]===`string`){i=e[0];r=$.get()}else r=e[0]}else if(e.length===2){i=e[0];r=e[1]}else r=$.get();const a=t.AsnConvert.parse(this.rawData,n.SubjectPublicKeyInfo);return await r.subtle.digest(i,a.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty();const r=t.AsnConvert.parse(this.rawData,n.SubjectPublicKeyInfo);e[`Algorithm`]=TextConverter.serializeAlgorithm(r.algorithm);switch(r.algorithm.algorithm){case o.id_ecPublicKey:e[`EC Point`]=r.subjectPublicKey;break;case s.id_rsaEncryption:default:e[`Raw Data`]=r.subjectPublicKey}return e}};function convertSpkiToRsaPkcs1(e,r){e.algorithm=new n.AlgorithmIdentifier({algorithm:s.id_rsaEncryption,parameters:null});r=t.AsnConvert.serialize(e);return r}var Pe=class AuthorityKeyIdentifierExtension extends oe{static async create(e,t=false,n=$.get()){if(`name`in e&&`serialNumber`in e)return new AuthorityKeyIdentifierExtension(e,t);const i=await(await Ne.create(e,n)).getKeyIdentifier(n);return new AuthorityKeyIdentifierExtension(r.Convert.ToHex(i),t)}constructor(...e){if(r.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]===`string`){const n=new f.AuthorityKeyIdentifier({keyIdentifier:new f.KeyIdentifier(r.Convert.FromHex(e[0]))});super(f.id_ce_authorityKeyIdentifier,e[1],t.AsnConvert.serialize(n))}else{const n=e[0];const i=n.name instanceof GeneralNames?t.AsnConvert.parse(n.name.rawData,f.GeneralNames):n.name;const a=new f.AuthorityKeyIdentifier({authorityCertIssuer:i,authorityCertSerialNumber:r.Convert.FromHex(n.serialNumber)});super(f.id_ce_authorityKeyIdentifier,e[1],t.AsnConvert.serialize(a))}}onInit(e){super.onInit(e);const n=t.AsnConvert.parse(e.extnValue,f.AuthorityKeyIdentifier);if(n.keyIdentifier)this.keyId=r.Convert.ToHex(n.keyIdentifier);if(n.authorityCertIssuer||n.authorityCertSerialNumber)this.certId={name:n.authorityCertIssuer||[],serialNumber:n.authorityCertSerialNumber?r.Convert.ToHex(n.authorityCertSerialNumber):``}}toTextObject(){const e=this.toTextObjectWithoutValue();const n=t.AsnConvert.parse(this.value,f.AuthorityKeyIdentifier);if(n.authorityCertIssuer)e[`Authority Issuer`]=new GeneralNames(n.authorityCertIssuer).toTextObject();if(n.authorityCertSerialNumber)e[`Authority Serial Number`]=n.authorityCertSerialNumber;if(n.keyIdentifier)e[``]=n.keyIdentifier;return e}};Pe.NAME=`Authority Key Identifier`;var BasicConstraintsExtension=class extends oe{constructor(...e){if(r.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);const r=t.AsnConvert.parse(this.value,n.BasicConstraints);this.ca=r.cA;this.pathLength=r.pathLenConstraint}else{const r=new n.BasicConstraints({cA:e[0],pathLenConstraint:e[1]});super(n.id_ce_basicConstraints,e[2],t.AsnConvert.serialize(r));this.ca=e[0];this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();if(this.ca)e[`CA`]=this.ca;if(this.pathLength!==void 0)e[`Path Length`]=this.pathLength;return e}};BasicConstraintsExtension.NAME=`Basic Constraints`;e.ExtendedKeyUsage=void 0;(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`})(e.ExtendedKeyUsage||(e.ExtendedKeyUsage={}));var ExtendedKeyUsageExtension=class extends oe{constructor(...e){if(r.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);const n=t.AsnConvert.parse(this.value,f.ExtendedKeyUsage);this.usages=n.map(e=>e)}else{const n=new f.ExtendedKeyUsage(e[0]);super(f.id_ce_extKeyUsage,e[1],t.AsnConvert.serialize(n));this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();e[``]=this.usages.map(e=>OidSerializer.toString(e)).join(`, `);return e}};ExtendedKeyUsageExtension.NAME=`Extended Key Usages`;e.KeyUsageFlags=void 0;(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`})(e.KeyUsageFlags||(e.KeyUsageFlags={}));var KeyUsagesExtension=class extends oe{constructor(...e){if(r.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);const r=t.AsnConvert.parse(this.value,n.KeyUsage);this.usages=r.toNumber()}else{const r=new n.KeyUsage(e[0]);super(n.id_ce_keyUsage,e[1],t.AsnConvert.serialize(r));this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();e[``]=t.AsnConvert.parse(this.value,n.KeyUsage).toJSON().join(`, `);return e}};KeyUsagesExtension.NAME=`Key Usages`;var Fe=class SubjectKeyIdentifierExtension extends oe{static async create(e,t=false,n=$.get()){const i=await(await Ne.create(e,n)).getKeyIdentifier(n);return new SubjectKeyIdentifierExtension(r.Convert.ToHex(i),t)}constructor(...e){if(r.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);const n=t.AsnConvert.parse(this.value,f.SubjectKeyIdentifier);this.keyId=r.Convert.ToHex(n)}else{const n=typeof e[0]===`string`?r.Convert.FromHex(e[0]):e[0];const i=new f.SubjectKeyIdentifier(n);super(f.id_ce_subjectKeyIdentifier,e[1],t.AsnConvert.serialize(i));this.keyId=r.Convert.ToHex(n)}}toTextObject(){const e=this.toTextObjectWithoutValue();e[``]=t.AsnConvert.parse(this.value,f.SubjectKeyIdentifier);return e}};Fe.NAME=`Subject Key Identifier`;var SubjectAlternativeNameExtension=class extends oe{constructor(...e){if(r.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else super(f.id_ce_subjectAltName,e[1],new GeneralNames(e[0]||[]).rawData)}onInit(e){super.onInit(e);const n=t.AsnConvert.parse(e.extnValue,f.SubjectAlternativeName);this.names=new GeneralNames(n)}toTextObject(){const e=this.toTextObjectWithoutValue();const t=this.names.toTextObject();for(const n in t)e[n]=t[n];return e}};SubjectAlternativeNameExtension.NAME=`Subject Alternative Name`;var ExtensionFactory=class{static register(e,t){this.items.set(e,t)}static create(e){const t=new oe(e);const n=this.items.get(t.type);if(n)return new n(e);return t}};ExtensionFactory.items=/* @__PURE__ */ new Map;var CertificatePolicyExtension=class extends oe{constructor(...e){var n;if(r.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);const n=t.AsnConvert.parse(this.value,f.CertificatePolicies);this.policies=n.map(e=>e.policyIdentifier)}else{const r=e[0];const i=(n=e[1])!==null&&n!==void 0?n:false;const a=new f.CertificatePolicies(r.map(e=>new f.PolicyInformation({policyIdentifier:e})));super(f.id_ce_certificatePolicies,i,t.AsnConvert.serialize(a));this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();e[`Policy`]=this.policies.map(e=>new TextObject(``,{},OidSerializer.toString(e)));return e}};CertificatePolicyExtension.NAME=`Certificate Policies`;ExtensionFactory.register(f.id_ce_certificatePolicies,CertificatePolicyExtension);var CRLDistributionPointsExtension=class extends oe{constructor(...e){var n;if(r.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]===`string`){const n=e[0].map(e=>{return new f.DistributionPoint({distributionPoint:new f.DistributionPointName({fullName:[new f.GeneralName({uniformResourceIdentifier:e})]})})});const r=new f.CRLDistributionPoints(n);super(f.id_ce_cRLDistributionPoints,e[1],t.AsnConvert.serialize(r))}else{const n=new f.CRLDistributionPoints(e[0]);super(f.id_ce_cRLDistributionPoints,e[1],t.AsnConvert.serialize(n))}(n=this.distributionPoints)!==null&&n!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);const n=t.AsnConvert.parse(e.extnValue,f.CRLDistributionPoints);this.distributionPoints=n}toTextObject(){const e=this.toTextObjectWithoutValue();e[`Distribution Point`]=this.distributionPoints.map(e=>{var t;const n={};if(e.distributionPoint)n[``]=(t=e.distributionPoint.fullName)===null||t===void 0?void 0:t.map(e=>new GeneralName(e).toString()).join(`, `);if(e.reasons)n[`Reasons`]=e.reasons.toString();if(e.cRLIssuer)n[`CRL Issuer`]=e.cRLIssuer.map(e=>e.toString()).join(`, `);return n});return e}};CRLDistributionPointsExtension.NAME=`CRL Distribution Points`;var AuthorityInfoAccessExtension=class extends oe{constructor(...e){var n,i,a,o;if(r.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof f.AuthorityInfoAccessSyntax){const n=new f.AuthorityInfoAccessSyntax(e[0]);super(f.id_pe_authorityInfoAccess,e[1],t.AsnConvert.serialize(n))}else{const n=e[0];const r=new f.AuthorityInfoAccessSyntax;addAccessDescriptions(r,n,f.id_ad_ocsp,`ocsp`);addAccessDescriptions(r,n,f.id_ad_caIssuers,`caIssuers`);addAccessDescriptions(r,n,f.id_ad_timeStamping,`timeStamping`);addAccessDescriptions(r,n,f.id_ad_caRepository,`caRepository`);super(f.id_pe_authorityInfoAccess,e[1],t.AsnConvert.serialize(r))}(n=this.ocsp)!==null&&n!==void 0||(this.ocsp=[]);(i=this.caIssuers)!==null&&i!==void 0||(this.caIssuers=[]);(a=this.timeStamping)!==null&&a!==void 0||(this.timeStamping=[]);(o=this.caRepository)!==null&&o!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e);this.ocsp=[];this.caIssuers=[];this.timeStamping=[];this.caRepository=[];t.AsnConvert.parse(e.extnValue,f.AuthorityInfoAccessSyntax).forEach(e=>{switch(e.accessMethod){case f.id_ad_ocsp:this.ocsp.push(new GeneralName(e.accessLocation));break;case f.id_ad_caIssuers:this.caIssuers.push(new GeneralName(e.accessLocation));break;case f.id_ad_timeStamping:this.timeStamping.push(new GeneralName(e.accessLocation));break;case f.id_ad_caRepository:this.caRepository.push(new GeneralName(e.accessLocation))}})}toTextObject(){const e=this.toTextObjectWithoutValue();if(this.ocsp.length)addUrlsToObject(e,`OCSP`,this.ocsp);if(this.caIssuers.length)addUrlsToObject(e,`CA Issuers`,this.caIssuers);if(this.timeStamping.length)addUrlsToObject(e,`Time Stamping`,this.timeStamping);if(this.caRepository.length)addUrlsToObject(e,`CA Repository`,this.caRepository);return e}};AuthorityInfoAccessExtension.NAME=`Authority Info Access`;function addUrlsToObject(e,t,n){if(n.length===1)e[t]=n[0].toTextObject();else{const r=new TextObject(``);n.forEach((e,t)=>{const n=e.toTextObject();const i=`${n[TextObject.NAME]} ${t+1}`;let a=r[i];if(!Array.isArray(a)){a=[];r[i]=a}a.push(n)});e[t]=r}}function addAccessDescriptions(e,n,r,i){const a=n[i];if(a)(Array.isArray(a)?a:[a]).forEach(n=>{if(typeof n===`string`)n=new GeneralName(`url`,n);e.push(new f.AccessDescription({accessMethod:r,accessLocation:t.AsnConvert.parse(n.rawData,f.GeneralName)}))})}var IssuerAlternativeNameExtension=class extends oe{constructor(...e){if(r.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else super(f.id_ce_issuerAltName,e[1],new GeneralNames(e[0]||[]).rawData)}onInit(e){super.onInit(e);const n=t.AsnConvert.parse(e.extnValue,f.GeneralNames);this.names=new GeneralNames(n)}toTextObject(){const e=this.toTextObjectWithoutValue();const t=this.names.toTextObject();for(const n in t)e[n]=t[n];return e}};IssuerAlternativeNameExtension.NAME=`Issuer Alternative Name`;var Ie=class Attribute extends ae{constructor(...e){let i;if(r.BufferSourceConverter.isBufferSource(e[0]))i=r.BufferSourceConverter.toArrayBuffer(e[0]);else{const a=e[0];const o=Array.isArray(e[1])?e[1].map(e=>r.BufferSourceConverter.toArrayBuffer(e)):[];i=t.AsnConvert.serialize(new n.Attribute({type:a,values:o}))}super(i,n.Attribute)}onInit(e){this.type=e.type;this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();e[`Value`]=this.values.map(e=>new TextObject(``,{"":e}));return e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();if(e[TextObject.NAME]===Attribute.NAME)e[TextObject.NAME]=OidSerializer.toString(this.type);return e}};Ie.NAME=`Attribute`;var ChallengePasswordAttribute=class extends Ie{constructor(...e){var n;if(r.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{const n=new _.ChallengePassword({printableString:e[0]});super(_.id_pkcs9_at_challengePassword,[t.AsnConvert.serialize(n)])}(n=this.password)!==null&&n!==void 0||(this.password=``)}onInit(e){super.onInit(e);if(this.values[0]){const e=t.AsnConvert.parse(this.values[0],_.ChallengePassword);this.password=e.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();e[TextObject.VALUE]=this.password;return e}};ChallengePasswordAttribute.NAME=`Challenge Password`;var ExtensionsAttribute=class extends Ie{constructor(...e){var n;if(r.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{const n=e[0];const r=new f.Extensions;for(const e of n)r.push(t.AsnConvert.parse(e.rawData,f.Extension));super(_.id_pkcs9_at_extensionRequest,[t.AsnConvert.serialize(r)])}(n=this.items)!==null&&n!==void 0||(this.items=[])}onInit(e){super.onInit(e);if(this.values[0]){const e=t.AsnConvert.parse(this.values[0],f.Extensions);this.items=e.map(e=>ExtensionFactory.create(t.AsnConvert.serialize(e)))}}toTextObject(){const e=this.toTextObjectWithoutValue();const t=this.items.map(e=>e.toTextObject());for(const n of t)e[n[TextObject.NAME]]=n;return e}};ExtensionsAttribute.NAME=`Extensions`;var AttributeFactory=class{static register(e,t){this.items.set(e,t)}static create(e){const t=new Ie(e);const n=this.items.get(t.type);if(n)return new n(e);return t}};AttributeFactory.items=/* @__PURE__ */ new Map;const Le=`crypto.signatureFormatter`;var AsnDefaultSignatureFormatter=class{toAsnSignature(e,t){return r.BufferSourceConverter.toArrayBuffer(t)}toWebSignature(e,t){return r.BufferSourceConverter.toArrayBuffer(t)}};var Re;e.RsaAlgorithm=Re=class RsaAlgorithm{static createPssParams(e,r){const i=Re.getHashAlgorithm(e);if(!i)return null;return new g.RsaSaPssParams({hashAlgorithm:i,maskGenAlgorithm:new n.AlgorithmIdentifier({algorithm:g.id_mgf1,parameters:t.AsnConvert.serialize(i)}),saltLength:r})}static getHashAlgorithm(e){const t=c.container.resolve(y);if(typeof e===`string`)return t.toAsnAlgorithm({name:e});if(typeof e===`object`&&e&&`name`in e)return t.toAsnAlgorithm(e);return null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`rsassa-pkcs1-v1_5`:if(`hash`in e){let t;if(typeof e.hash===`string`)t=e.hash;else if(e.hash&&typeof e.hash===`object`&&`name`in e.hash&&typeof e.hash.name===`string`)t=e.hash.name.toUpperCase();else throw new Error(`Cannot get hash algorithm name`);switch(t.toLowerCase()){case`sha-1`:return new n.AlgorithmIdentifier({algorithm:g.id_sha1WithRSAEncryption,parameters:null});case`sha-256`:return new n.AlgorithmIdentifier({algorithm:g.id_sha256WithRSAEncryption,parameters:null});case`sha-384`:return new n.AlgorithmIdentifier({algorithm:g.id_sha384WithRSAEncryption,parameters:null});case`sha-512`:return new n.AlgorithmIdentifier({algorithm:g.id_sha512WithRSAEncryption,parameters:null})}}else return new n.AlgorithmIdentifier({algorithm:g.id_rsaEncryption,parameters:null});break;case`rsa-pss`:if(`hash`in e){if(!(`saltLength`in e&&typeof e.saltLength===`number`))throw new Error(`Cannot get 'saltLength' from 'alg' argument`);const r=Re.createPssParams(e.hash,e.saltLength);if(!r)throw new Error(`Cannot create PSS parameters`);return new n.AlgorithmIdentifier({algorithm:g.id_RSASSA_PSS,parameters:t.AsnConvert.serialize(r)})}else return new n.AlgorithmIdentifier({algorithm:g.id_RSASSA_PSS,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case g.id_rsaEncryption:return{name:`RSASSA-PKCS1-v1_5`};case g.id_sha1WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-1`}};case g.id_sha256WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case g.id_sha384WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-384`}};case g.id_sha512WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-512`}};case g.id_RSASSA_PSS:if(e.parameters){const n=t.AsnConvert.parse(e.parameters,g.RsaSaPssParams);return{name:`RSA-PSS`,hash:c.container.resolve(y).toWebAlgorithm(n.hashAlgorithm),saltLength:n.saltLength}}else return{name:`RSA-PSS`}}return null}};e.RsaAlgorithm=Re=i.__decorate([c.injectable()],e.RsaAlgorithm);c.container.registerSingleton(v,e.RsaAlgorithm);e.ShaAlgorithm=class ShaAlgorithm{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`sha-1`:return new n.AlgorithmIdentifier({algorithm:s.id_sha1});case`sha-256`:return new n.AlgorithmIdentifier({algorithm:s.id_sha256});case`sha-384`:return new n.AlgorithmIdentifier({algorithm:s.id_sha384});case`sha-512`:return new n.AlgorithmIdentifier({algorithm:s.id_sha512})}return null}toWebAlgorithm(e){switch(e.algorithm){case s.id_sha1:return{name:`SHA-1`};case s.id_sha256:return{name:`SHA-256`};case s.id_sha384:return{name:`SHA-384`};case s.id_sha512:return{name:`SHA-512`}}return null}};e.ShaAlgorithm=i.__decorate([c.injectable()],e.ShaAlgorithm);c.container.registerSingleton(v,e.ShaAlgorithm);var ze=class AsnEcSignatureFormatter{addPadding(e,t){const n=r.BufferSourceConverter.toUint8Array(t);const i=new Uint8Array(e);i.set(n,e-n.length);return i.buffer}removePadding(e,t=false){let n=r.BufferSourceConverter.toUint8Array(e);for(let e=0;e<n.length;e++){if(!n[e])continue;n=n.slice(e);break}if(t&&n[0]>127){const e=new Uint8Array(n.length+1);e.set(n,1);return e.buffer}return n.buffer}toAsnSignature(e,n){if(e.name===`ECDSA`){const i=e.namedCurve;const a=AsnEcSignatureFormatter.namedCurveSize.get(i)||AsnEcSignatureFormatter.defaultNamedCurveSize;const s=new o.ECDSASigValue;const c=r.BufferSourceConverter.toUint8Array(n);s.r=this.removePadding(c.slice(0,a),true);s.s=this.removePadding(c.slice(a,a+a),true);return t.AsnConvert.serialize(s)}return null}toWebSignature(e,n){if(e.name===`ECDSA`){const i=t.AsnConvert.parse(n,o.ECDSASigValue);const a=e.namedCurve;const s=AsnEcSignatureFormatter.namedCurveSize.get(a)||AsnEcSignatureFormatter.defaultNamedCurveSize;const c=this.addPadding(s,this.removePadding(i.r));const u=this.addPadding(s,this.removePadding(i.s));return r.combine(c,u)}return null}};ze.namedCurveSize=/* @__PURE__ */ new Map;ze.defaultNamedCurveSize=32;const Be=`1.3.101.110`;const Ve=`1.3.101.111`;const He=`1.3.101.112`;const Ue=`1.3.101.113`;e.EdAlgorithm=class EdAlgorithm{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case`ed25519`:t=He;break;case`x25519`:t=Be;break;case`eddsa`:switch(e.namedCurve.toLowerCase()){case`ed25519`:t=He;break;case`ed448`:t=Ue}break;case`ecdh-es`:switch(e.namedCurve.toLowerCase()){case`x25519`:t=Be;break;case`x448`:t=Ve}}if(t)return new n.AlgorithmIdentifier({algorithm:t});return null}toWebAlgorithm(e){switch(e.algorithm){case He:return{name:`Ed25519`};case Ue:return{name:`EdDSA`,namedCurve:`Ed448`};case Be:return{name:`X25519`};case Ve:return{name:`ECDH-ES`,namedCurve:`X448`}}return null}};e.EdAlgorithm=i.__decorate([c.injectable()],e.EdAlgorithm);c.container.registerSingleton(v,e.EdAlgorithm);var We;var Ge;var Ke;var qe;var Je;var Ye;var Xe;var Ze;var Pkcs10CertificateRequest=class extends Me{get subjectName(){if(!i.__classPrivateFieldGet(this,Ge,`f`))i.__classPrivateFieldSet(this,Ge,new de(this.asn.certificationRequestInfo.subject),`f`);return i.__classPrivateFieldGet(this,Ge,`f`)}get subject(){if(!i.__classPrivateFieldGet(this,Ke,`f`))i.__classPrivateFieldSet(this,Ke,this.subjectName.toString(),`f`);return i.__classPrivateFieldGet(this,Ke,`f`)}get signatureAlgorithm(){if(!i.__classPrivateFieldGet(this,qe,`f`)){const e=c.container.resolve(y);i.__classPrivateFieldSet(this,qe,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return i.__classPrivateFieldGet(this,qe,`f`)}get signature(){if(!i.__classPrivateFieldGet(this,Je,`f`))i.__classPrivateFieldSet(this,Je,this.asn.signature,`f`);return i.__classPrivateFieldGet(this,Je,`f`)}get publicKey(){if(!i.__classPrivateFieldGet(this,Ye,`f`))i.__classPrivateFieldSet(this,Ye,new Ne(this.asn.certificationRequestInfo.subjectPKInfo),`f`);return i.__classPrivateFieldGet(this,Ye,`f`)}get attributes(){if(!i.__classPrivateFieldGet(this,Xe,`f`))i.__classPrivateFieldSet(this,Xe,this.asn.certificationRequestInfo.attributes.map(e=>AttributeFactory.create(t.AsnConvert.serialize(e))),`f`);return i.__classPrivateFieldGet(this,Xe,`f`)}get extensions(){if(!i.__classPrivateFieldGet(this,Ze,`f`)){i.__classPrivateFieldSet(this,Ze,[],`f`);const e=this.getAttribute(u.id_pkcs9_at_extensionRequest);if(e instanceof ExtensionsAttribute)i.__classPrivateFieldSet(this,Ze,e.items,`f`)}return i.__classPrivateFieldGet(this,Ze,`f`)}get tbs(){if(!i.__classPrivateFieldGet(this,We,`f`))i.__classPrivateFieldSet(this,We,this.asn.certificationRequestInfoRaw||t.AsnConvert.serialize(this.asn.certificationRequestInfo),`f`);return i.__classPrivateFieldGet(this,We,`f`)}constructor(e){const t=Me.isAsnEncoded(e)?[e,d.CertificationRequest]:[e];super(t[0],t[1]);We.set(this,void 0);Ge.set(this,void 0);Ke.set(this,void 0);qe.set(this,void 0);Je.set(this,void 0);Ye.set(this,void 0);Xe.set(this,void 0);Ze.set(this,void 0);this.tag=PemConverter.CertificateRequestTag}onInit(e){}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=$.get()){const t={...this.publicKey.algorithm,...this.signatureAlgorithm};const n=await this.publicKey.export(t,[`verify`],e);const r=c.container.resolveAll(Le).reverse();let i=null;for(const e of r){i=e.toWebSignature(t,this.signature);if(i)break}if(!i)throw Error(`Cannot convert WebCrypto signature value to ASN.1 format`);return await e.subtle.verify(this.signatureAlgorithm,n,i,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty();const r=t.AsnConvert.parse(this.rawData,d.CertificationRequest);const i=r.certificationRequestInfo;const a=new TextObject(``,{Version:`${n.Version[i.version]} (${i.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const e=new TextObject(``);for(const t of this.attributes){const n=t.toTextObject();e[n[TextObject.NAME]]=n}a[`Attributes`]=e}e[`Data`]=a;e[`Signature`]=new TextObject(``,{Algorithm:TextConverter.serializeAlgorithm(r.signatureAlgorithm),"":r.signature});return e}};We=/* @__PURE__ */ new WeakMap,Ge=/* @__PURE__ */ new WeakMap,Ke=/* @__PURE__ */ new WeakMap,qe=/* @__PURE__ */ new WeakMap,Je=/* @__PURE__ */ new WeakMap,Ye=/* @__PURE__ */ new WeakMap,Xe=/* @__PURE__ */ new WeakMap,Ze=/* @__PURE__ */ new WeakMap;Pkcs10CertificateRequest.NAME=`PKCS#10 Certificate Request`;var Pkcs10CertificateRequestGenerator=class{static async create(e,r=$.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`);const i=await r.subtle.exportKey(`spki`,e.keys.publicKey);const a=new d.CertificationRequest({certificationRequestInfo:new d.CertificationRequestInfo({subjectPKInfo:t.AsnConvert.parse(i,n.SubjectPublicKeyInfo)})});if(e.name){const r=e.name instanceof de?e.name:new de(e.name);a.certificationRequestInfo.subject=t.AsnConvert.parse(r.toArrayBuffer(),n.Name)}if(e.attributes)for(const r of e.attributes)a.certificationRequestInfo.attributes.push(t.AsnConvert.parse(r.rawData,n.Attribute));if(e.extensions&&e.extensions.length){const r=new n.Attribute({type:u.id_pkcs9_at_extensionRequest});const i=new n.Extensions;for(const r of e.extensions)i.push(t.AsnConvert.parse(r.rawData,n.Extension));r.values.push(t.AsnConvert.serialize(i));a.certificationRequestInfo.attributes.push(r)}const o={...e.signingAlgorithm,...e.keys.privateKey.algorithm};a.signatureAlgorithm=c.container.resolve(y).toAsnAlgorithm(o);const s=t.AsnConvert.serialize(a.certificationRequestInfo);const f=await r.subtle.sign(o,e.keys.privateKey,s);const p=c.container.resolveAll(Le).reverse();let m=null;for(const e of p){m=e.toAsnSignature(o,f);if(m)break}if(!m)throw Error(`Cannot convert WebCrypto signature value to ASN.1 format`);a.signature=m;return new Pkcs10CertificateRequest(t.AsnConvert.serialize(a))}};var Qe;var $e;var et;var tt;var nt;var rt;var it;var at;var ot;var st;var ct;var lt;var X509Certificate=class extends Me{get publicKey(){if(!i.__classPrivateFieldGet(this,lt,`f`))i.__classPrivateFieldSet(this,lt,new Ne(this.asn.tbsCertificate.subjectPublicKeyInfo),`f`);return i.__classPrivateFieldGet(this,lt,`f`)}get serialNumber(){if(!i.__classPrivateFieldGet(this,$e,`f`)){const e=this.asn.tbsCertificate;let t=new Uint8Array(e.serialNumber);if(t.length>1&&t[0]===0&&t[1]>127)t=t.slice(1);i.__classPrivateFieldSet(this,$e,r.Convert.ToHex(t),`f`)}return i.__classPrivateFieldGet(this,$e,`f`)}get subjectName(){if(!i.__classPrivateFieldGet(this,et,`f`))i.__classPrivateFieldSet(this,et,new de(this.asn.tbsCertificate.subject),`f`);return i.__classPrivateFieldGet(this,et,`f`)}get subject(){if(!i.__classPrivateFieldGet(this,tt,`f`))i.__classPrivateFieldSet(this,tt,this.subjectName.toString(),`f`);return i.__classPrivateFieldGet(this,tt,`f`)}get issuerName(){if(!i.__classPrivateFieldGet(this,nt,`f`))i.__classPrivateFieldSet(this,nt,new de(this.asn.tbsCertificate.issuer),`f`);return i.__classPrivateFieldGet(this,nt,`f`)}get issuer(){if(!i.__classPrivateFieldGet(this,rt,`f`))i.__classPrivateFieldSet(this,rt,this.issuerName.toString(),`f`);return i.__classPrivateFieldGet(this,rt,`f`)}get notBefore(){if(!i.__classPrivateFieldGet(this,it,`f`)){const e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error(`Cannot get 'notBefore' value`);i.__classPrivateFieldSet(this,it,e,`f`)}return i.__classPrivateFieldGet(this,it,`f`)}get notAfter(){if(!i.__classPrivateFieldGet(this,at,`f`)){const e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error(`Cannot get 'notAfter' value`);i.__classPrivateFieldSet(this,at,e,`f`)}return i.__classPrivateFieldGet(this,at,`f`)}get signatureAlgorithm(){if(!i.__classPrivateFieldGet(this,ot,`f`)){const e=c.container.resolve(y);i.__classPrivateFieldSet(this,ot,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return i.__classPrivateFieldGet(this,ot,`f`)}get signature(){if(!i.__classPrivateFieldGet(this,st,`f`))i.__classPrivateFieldSet(this,st,this.asn.signatureValue,`f`);return i.__classPrivateFieldGet(this,st,`f`)}get extensions(){if(!i.__classPrivateFieldGet(this,ct,`f`)){i.__classPrivateFieldSet(this,ct,[],`f`);if(this.asn.tbsCertificate.extensions)i.__classPrivateFieldSet(this,ct,this.asn.tbsCertificate.extensions.map(e=>ExtensionFactory.create(t.AsnConvert.serialize(e))),`f`)}return i.__classPrivateFieldGet(this,ct,`f`)}get tbs(){if(!i.__classPrivateFieldGet(this,Qe,`f`))i.__classPrivateFieldSet(this,Qe,this.asn.tbsCertificateRaw||t.AsnConvert.serialize(this.asn.tbsCertificate),`f`);return i.__classPrivateFieldGet(this,Qe,`f`)}constructor(e){const t=Me.isAsnEncoded(e)?[e,n.Certificate]:[e];super(t[0],t[1]);Qe.set(this,void 0);$e.set(this,void 0);et.set(this,void 0);tt.set(this,void 0);nt.set(this,void 0);rt.set(this,void 0);it.set(this,void 0);at.set(this,void 0);ot.set(this,void 0);st.set(this,void 0);ct.set(this,void 0);lt.set(this,void 0);this.tag=PemConverter.CertificateTag}onInit(e){}getExtension(e){for(const t of this.extensions)if(typeof e===`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>{if(typeof e===`string`)return t.type===e;else return t instanceof e})}async verify(e={},t=$.get()){let n;let i;const a=e.publicKey;try{if(!a){n={...this.publicKey.algorithm,...this.signatureAlgorithm};i=await this.publicKey.export(n,[`verify`],t)}else if(`publicKey`in a){n={...a.publicKey.algorithm,...this.signatureAlgorithm};i=await a.publicKey.export(n,[`verify`],t)}else if(a instanceof Ne){n={...a.algorithm,...this.signatureAlgorithm};i=await a.export(n,[`verify`],t)}else if(r.BufferSourceConverter.isBufferSource(a)){const e=new Ne(a);n={...e.algorithm,...this.signatureAlgorithm};i=await e.export(n,[`verify`],t)}else{n={...a.algorithm,...this.signatureAlgorithm};i=a}}catch{return false}const o=c.container.resolveAll(Le).reverse();let s=null;for(const e of o){s=e.toWebSignature(n,this.signature);if(s)break}if(!s)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);const u=await t.subtle.verify(this.signatureAlgorithm,i,s,this.tbs);if(e.signatureOnly)return u;else{const t=(e.date||/* @__PURE__ */ new Date).getTime();return u&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t;let n=`SHA-1`;if(e[0]){if(!e[0].subtle){n=e[0]||n;t=e[1]}else t=e[0]}t!==null&&t!==void 0||(t=$.get());return await t.subtle.digest(n,this.rawData)}async isSelfSigned(e=$.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:true},e)}toTextObject(){const e=this.toTextObjectEmpty();const r=t.AsnConvert.parse(this.rawData,n.Certificate);const i=r.tbsCertificate;const a=new TextObject(``,{Version:`${n.Version[i.version]} (${i.version})`,"Serial Number":i.serialNumber,"Signature Algorithm":TextConverter.serializeAlgorithm(i.signature),Issuer:this.issuer,Validity:new TextObject(``,{"Not Before":i.validity.notBefore.getTime(),"Not After":i.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(i.issuerUniqueID)a[`Issuer Unique ID`]=i.issuerUniqueID;if(i.subjectUniqueID)a[`Subject Unique ID`]=i.subjectUniqueID;if(this.extensions.length){const e=new TextObject(``);for(const t of this.extensions){const n=t.toTextObject();e[n[TextObject.NAME]]=n}a[`Extensions`]=e}e[`Data`]=a;e[`Signature`]=new TextObject(``,{Algorithm:TextConverter.serializeAlgorithm(r.signatureAlgorithm),"":r.signatureValue});return e}};Qe=/* @__PURE__ */ new WeakMap,$e=/* @__PURE__ */ new WeakMap,et=/* @__PURE__ */ new WeakMap,tt=/* @__PURE__ */ new WeakMap,nt=/* @__PURE__ */ new WeakMap,rt=/* @__PURE__ */ new WeakMap,it=/* @__PURE__ */ new WeakMap,at=/* @__PURE__ */ new WeakMap,ot=/* @__PURE__ */ new WeakMap,st=/* @__PURE__ */ new WeakMap,ct=/* @__PURE__ */ new WeakMap,lt=/* @__PURE__ */ new WeakMap;X509Certificate.NAME=`Certificate`;var X509Certificates=class extends Array{constructor(e){super();if(Me.isAsnEncoded(e))this.import(e);else if(e instanceof X509Certificate)this.push(e);else if(Array.isArray(e))for(const t of e)this.push(t)}export(e){const r=new p.SignedData;r.version=1;r.encapContentInfo.eContentType=p.id_data;r.encapContentInfo.eContent=new p.EncapsulatedContent({single:new t.OctetString});r.certificates=new p.CertificateSet(this.map(e=>new p.CertificateChoices({certificate:t.AsnConvert.parse(e.rawData,n.Certificate)})));const i=new p.ContentInfo({contentType:p.id_signedData,content:t.AsnConvert.serialize(r)});const a=t.AsnConvert.serialize(i);if(e===`raw`)return a;return this.toString(e)}import(e){const n=Me.toArrayBuffer(e);const r=t.AsnConvert.parse(n,p.ContentInfo);if(r.contentType!==p.id_signedData)throw new TypeError(`Cannot parse CMS package. Incoming data is not a SignedData object.`);const i=t.AsnConvert.parse(r.content,p.SignedData);this.clear();for(const e of i.certificates||[])if(e.certificate)this.push(new X509Certificate(e.certificate))}clear(){while(this.pop());}toString(e=`pem`){const n=this.export(`raw`);switch(e){case`pem`:return PemConverter.encode(n,`CMS`);case`pem-chain`:return this.map(e=>e.toString(`pem`)).join(`
`);case`asn`:return t.AsnConvert.toString(n);case`hex`:return r.Convert.ToHex(n);case`base64`:return r.Convert.ToBase64(n);case`base64url`:return r.Convert.ToBase64Url(n);case`text`:return TextConverter.serialize(this.toTextObject());default:throw TypeError(`Argument 'format' is unsupported value`)}}toTextObject(){const e=t.AsnConvert.parse(this.export(`raw`),p.ContentInfo);const n=t.AsnConvert.parse(e.content,p.SignedData);return new TextObject(`X509Certificates`,{"Content Type":OidSerializer.toString(e.contentType),Content:new TextObject(``,{Version:`${p.CMSVersion[n.version]} (${n.version})`,Certificates:new TextObject(``,{Certificate:this.map(e=>e.toTextObject())})})})}};var X509ChainBuilder=class{constructor(e={}){this.certificates=[];if(e.certificates)this.certificates=e.certificates}async build(e,t=$.get()){const n=new X509Certificates(e);let i=e;while(i=await this.findIssuer(i,t)){const e=await i.getThumbprint(t);for(const i of n){const n=await i.getThumbprint(t);if(r.isEqual(e,n))throw new Error(`Cannot build a certificate chain. Circular dependency.`)}n.push(i)}return n}async findIssuer(e,n=$.get()){if(!await e.isSelfSigned(n)){const i=e.getExtension(f.id_ce_authorityKeyIdentifier);for(const a of this.certificates){if(a.subject!==e.issuer)continue;if(i){if(i.keyId){const e=a.getExtension(f.id_ce_subjectKeyIdentifier);if(e&&e.keyId!==i.keyId)continue}else if(i.certId){const e=a.getExtension(f.id_ce_subjectAltName);if(e&&!(i.certId.serialNumber===a.serialNumber&&r.isEqual(t.AsnConvert.serialize(i.certId.name),t.AsnConvert.serialize(e))))continue}}try{const t={...a.publicKey.algorithm,...e.signatureAlgorithm};const r=await a.publicKey.export(t,[`verify`],n);if(!await e.verify({publicKey:r,signatureOnly:true},n))continue}catch{continue}return a}}return null}};function generateCertificateSerialNumber(e,t=$.get()){const n=r.BufferSourceConverter.toUint8Array(r.Convert.FromHex(e||``));let i=n&&n.length&&n.some(e=>e>0)?new Uint8Array(n):void 0;if(!i)i=t.getRandomValues(/* @__PURE__ */ new Uint8Array(16));let a=0;while(a<i.length-1&&i[a]===0)a++;i=i.slice(a);if(i[0]>127){const e=new Uint8Array(i.length+1);e[0]=0;e.set(i,1);i=e}return i.buffer}var X509CertificateGenerator=class{static async createSelfSigned(e,t=$.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,n=$.get()){var i;let a;if(e.publicKey instanceof Ne)a=e.publicKey.rawData;else if(`publicKey`in e.publicKey)a=e.publicKey.publicKey.rawData;else if(r.BufferSourceConverter.isBufferSource(e.publicKey))a=e.publicKey;else a=await n.subtle.exportKey(`spki`,e.publicKey);const o=generateCertificateSerialNumber(e.serialNumber,n);const s=e.notBefore||/* @__PURE__ */ new Date;const u=e.notAfter||new Date(s.getTime()+31536e6);const d=new f.Certificate({tbsCertificate:new f.TBSCertificate({version:f.Version.v3,serialNumber:o,validity:new f.Validity({notBefore:s,notAfter:u}),extensions:new f.Extensions(((i=e.extensions)===null||i===void 0?void 0:i.map(e=>t.AsnConvert.parse(e.rawData,f.Extension)))||[]),subjectPublicKeyInfo:t.AsnConvert.parse(a,f.SubjectPublicKeyInfo)})});if(e.subject){const n=e.subject instanceof de?e.subject:new de(e.subject);d.tbsCertificate.subject=t.AsnConvert.parse(n.toArrayBuffer(),f.Name)}if(e.issuer){const n=e.issuer instanceof de?e.issuer:new de(e.issuer);d.tbsCertificate.issuer=t.AsnConvert.parse(n.toArrayBuffer(),f.Name)}const p={hash:`SHA-256`};const m=`signingKey`in e?{...p,...e.signingAlgorithm,...e.signingKey.algorithm}:{...p,...e.signingAlgorithm};const g=c.container.resolve(y);d.tbsCertificate.signature=d.signatureAlgorithm=g.toAsnAlgorithm(m);const _=t.AsnConvert.serialize(d.tbsCertificate);const v=`signingKey`in e?await n.subtle.sign(m,e.signingKey,_):e.signature;const b=c.container.resolveAll(Le).reverse();let x=null;for(const e of b){x=e.toAsnSignature(m,v);if(x)break}if(!x)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);d.signatureValue=x;return new X509Certificate(t.AsnConvert.serialize(d))}};var ut;var dt;var ft;var pt;var mt;e.X509CrlReason=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`})(e.X509CrlReason||(e.X509CrlReason={}));var X509CrlEntry=class extends ae{get serialNumber(){if(!i.__classPrivateFieldGet(this,ut,`f`))i.__classPrivateFieldSet(this,ut,r.Convert.ToHex(this.asn.userCertificate),`f`);return i.__classPrivateFieldGet(this,ut,`f`)}get revocationDate(){if(!i.__classPrivateFieldGet(this,dt,`f`))i.__classPrivateFieldSet(this,dt,this.asn.revocationDate.getTime(),`f`);return i.__classPrivateFieldGet(this,dt,`f`)}get reason(){if(i.__classPrivateFieldGet(this,ft,`f`)===void 0)this.extensions;return i.__classPrivateFieldGet(this,ft,`f`)}get invalidity(){if(i.__classPrivateFieldGet(this,pt,`f`)===void 0)this.extensions;return i.__classPrivateFieldGet(this,pt,`f`)}get extensions(){if(!i.__classPrivateFieldGet(this,mt,`f`)){i.__classPrivateFieldSet(this,mt,[],`f`);if(this.asn.crlEntryExtensions)i.__classPrivateFieldSet(this,mt,this.asn.crlEntryExtensions.map(e=>{const r=ExtensionFactory.create(t.AsnConvert.serialize(e));switch(r.type){case n.id_ce_cRLReasons:if(i.__classPrivateFieldGet(this,ft,`f`)===void 0)i.__classPrivateFieldSet(this,ft,t.AsnConvert.parse(r.value,n.CRLReason).reason,`f`);break;case n.id_ce_invalidityDate:if(i.__classPrivateFieldGet(this,pt,`f`)===void 0)i.__classPrivateFieldSet(this,pt,t.AsnConvert.parse(r.value,n.InvalidityDate).value,`f`)}return r}),`f`)}return i.__classPrivateFieldGet(this,mt,`f`)}constructor(...e){let i;if(r.BufferSourceConverter.isBufferSource(e[0]))i=r.BufferSourceConverter.toArrayBuffer(e[0]);else if(typeof e[0]===`string`)i=t.AsnConvert.serialize(new n.RevokedCertificate({userCertificate:generateCertificateSerialNumber(e[0]),revocationDate:new n.Time(e[1]),crlEntryExtensions:e[2]}));else if(e[0]instanceof n.RevokedCertificate)i=e[0];if(!i)throw new TypeError(`Cannot create X509CrlEntry instance. Wrong constructor arguments.`);super(i,n.RevokedCertificate);ut.set(this,void 0);dt.set(this,void 0);ft.set(this,void 0);pt.set(this,void 0);mt.set(this,void 0)}onInit(e){}};ut=/* @__PURE__ */ new WeakMap,dt=/* @__PURE__ */ new WeakMap,ft=/* @__PURE__ */ new WeakMap,pt=/* @__PURE__ */ new WeakMap,mt=/* @__PURE__ */ new WeakMap;var ht;var gt;var _t;var vt;var yt;var bt;var xt;var X509Crl=class extends Me{get version(){return this.asn.tbsCertList.version}get signatureAlgorithm(){if(!i.__classPrivateFieldGet(this,gt,`f`)){const e=c.container.resolve(y);i.__classPrivateFieldSet(this,gt,e.toWebAlgorithm(this.asn.signatureAlgorithm),`f`)}return i.__classPrivateFieldGet(this,gt,`f`)}get signature(){return this.asn.signature}get issuer(){return this.issuerName.toString()}get issuerName(){if(!i.__classPrivateFieldGet(this,_t,`f`))i.__classPrivateFieldSet(this,_t,new de(this.asn.tbsCertList.issuer),`f`);return i.__classPrivateFieldGet(this,_t,`f`)}get thisUpdate(){if(!i.__classPrivateFieldGet(this,vt,`f`)){const e=this.asn.tbsCertList.thisUpdate.getTime();if(!e)throw new Error(`Cannot get 'thisUpdate' value`);i.__classPrivateFieldSet(this,vt,e,`f`)}return i.__classPrivateFieldGet(this,vt,`f`)}get nextUpdate(){var e;if(i.__classPrivateFieldGet(this,yt,`f`)===void 0)i.__classPrivateFieldSet(this,yt,((e=this.asn.tbsCertList.nextUpdate)===null||e===void 0?void 0:e.getTime())||void 0,`f`);return i.__classPrivateFieldGet(this,yt,`f`)}get entries(){var e;if(!i.__classPrivateFieldGet(this,bt,`f`))i.__classPrivateFieldSet(this,bt,((e=this.asn.tbsCertList.revokedCertificates)===null||e===void 0?void 0:e.map(e=>new X509CrlEntry(e)))||[],`f`);return i.__classPrivateFieldGet(this,bt,`f`)}get extensions(){if(!i.__classPrivateFieldGet(this,xt,`f`)){i.__classPrivateFieldSet(this,xt,[],`f`);if(this.asn.tbsCertList.crlExtensions)i.__classPrivateFieldSet(this,xt,this.asn.tbsCertList.crlExtensions.map(e=>ExtensionFactory.create(t.AsnConvert.serialize(e))),`f`)}return i.__classPrivateFieldGet(this,xt,`f`)}get tbs(){if(!i.__classPrivateFieldGet(this,ht,`f`))i.__classPrivateFieldSet(this,ht,this.asn.tbsCertListRaw||t.AsnConvert.serialize(this.asn.tbsCertList),`f`);return i.__classPrivateFieldGet(this,ht,`f`)}get tbsCertListSignatureAlgorithm(){return this.asn.tbsCertList.signature}get certListSignatureAlgorithm(){return this.asn.signatureAlgorithm}constructor(e){super(e,Me.isAsnEncoded(e)?n.CertificateList:void 0);this.tag=PemConverter.CrlTag;ht.set(this,void 0);gt.set(this,void 0);_t.set(this,void 0);vt.set(this,void 0);yt.set(this,void 0);bt.set(this,void 0);xt.set(this,void 0)}onInit(e){}getExtension(e){for(const t of this.extensions)if(typeof e===`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>{if(typeof e===`string`)return t.type===e;else return t instanceof e})}async verify(e,t=$.get()){if(!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm))throw new Error(`algorithm identifier in the sequence tbsCertList and CertificateList mismatch`);let n;let r;const i=e.publicKey;try{if(i instanceof X509Certificate){n={...i.publicKey.algorithm,...i.signatureAlgorithm};r=await i.publicKey.export(n,[`verify`])}else if(i instanceof Ne){n={...i.algorithm,...this.signatureAlgorithm};r=await i.export(n,[`verify`])}else{n={...i.algorithm,...this.signatureAlgorithm};r=i}}catch{return false}const a=c.container.resolveAll(Le).reverse();let o=null;for(const e of a){o=e.toWebSignature(n,this.signature);if(o)break}if(!o)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return await t.subtle.verify(this.signatureAlgorithm,r,o,this.tbs)}async getThumbprint(...e){let t;let n=`SHA-1`;if(e[0]){if(!e[0].subtle){n=e[0]||n;t=e[1]}else t=e[0]}t!==null&&t!==void 0||(t=$.get());return await t.subtle.digest(n,this.rawData)}findRevoked(e){const n=generateCertificateSerialNumber(typeof e===`string`?e:e.serialNumber);for(const e of this.asn.tbsCertList.revokedCertificates||[])if(r.BufferSourceConverter.isEqual(e.userCertificate,n))return new X509CrlEntry(t.AsnConvert.serialize(e));return null}};ht=/* @__PURE__ */ new WeakMap,gt=/* @__PURE__ */ new WeakMap,_t=/* @__PURE__ */ new WeakMap,vt=/* @__PURE__ */ new WeakMap,yt=/* @__PURE__ */ new WeakMap,bt=/* @__PURE__ */ new WeakMap,xt=/* @__PURE__ */ new WeakMap;var X509CrlGenerator=class{static async create(e,i=$.get()){var a;const o=e.issuer instanceof de?e.issuer:new de(e.issuer);const s=new f.CertificateList({tbsCertList:new f.TBSCertList({version:f.Version.v2,issuer:t.AsnConvert.parse(o.toArrayBuffer(),f.Name),thisUpdate:new n.Time(e.thisUpdate||/* @__PURE__ */ new Date)})});if(e.nextUpdate)s.tbsCertList.nextUpdate=new n.Time(e.nextUpdate);if(e.extensions&&e.extensions.length)s.tbsCertList.crlExtensions=new f.Extensions(e.extensions.map(e=>t.AsnConvert.parse(e.rawData,f.Extension))||[]);if(e.entries&&e.entries.length){s.tbsCertList.revokedCertificates=[];for(const i of e.entries){const o=Me.toArrayBuffer(i.serialNumber);if(s.tbsCertList.revokedCertificates.findIndex(e=>r.isEqual(e.userCertificate,o))>-1)throw new Error(`Certificate serial number ${i.serialNumber} already exists in tbsCertList`);const c=new n.RevokedCertificate({userCertificate:o,revocationDate:new n.Time(i.revocationDate||/* @__PURE__ */ new Date)});if(`extensions`in i&&((a=i.extensions)===null||a===void 0?void 0:a.length))c.crlEntryExtensions=i.extensions.map(e=>t.AsnConvert.parse(e.rawData,f.Extension));else c.crlEntryExtensions=[];if(!(i instanceof X509CrlEntry)){if(i.reason)c.crlEntryExtensions.push(new f.Extension({extnID:f.id_ce_cRLReasons,critical:false,extnValue:new t.OctetString(t.AsnConvert.serialize(new f.CRLReason(i.reason)))}));if(i.invalidity)c.crlEntryExtensions.push(new f.Extension({extnID:f.id_ce_invalidityDate,critical:false,extnValue:new t.OctetString(t.AsnConvert.serialize(new f.InvalidityDate(i.invalidity)))}));if(i.issuer){const n=e.issuer instanceof de?e.issuer:new de(e.issuer);c.crlEntryExtensions.push(new f.Extension({extnID:f.id_ce_certificateIssuer,critical:false,extnValue:new t.OctetString(t.AsnConvert.serialize(t.AsnConvert.parse(n.toArrayBuffer(),f.Name)))}))}}s.tbsCertList.revokedCertificates.push(c)}}const u={...e.signingAlgorithm,...e.signingKey.algorithm};const d=c.container.resolve(y);s.tbsCertList.signature=s.signatureAlgorithm=d.toAsnAlgorithm(u);const p=t.AsnConvert.serialize(s.tbsCertList);const m=await i.subtle.sign(u,e.signingKey,p);const g=c.container.resolveAll(Le).reverse();let _=null;for(const e of g){_=e.toAsnSignature(u,m);if(_)break}if(!_)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);s.signature=_;return new X509Crl(t.AsnConvert.serialize(s))}};ExtensionFactory.register(f.id_ce_basicConstraints,BasicConstraintsExtension);ExtensionFactory.register(f.id_ce_extKeyUsage,ExtendedKeyUsageExtension);ExtensionFactory.register(f.id_ce_keyUsage,KeyUsagesExtension);ExtensionFactory.register(f.id_ce_subjectKeyIdentifier,Fe);ExtensionFactory.register(f.id_ce_authorityKeyIdentifier,Pe);ExtensionFactory.register(f.id_ce_subjectAltName,SubjectAlternativeNameExtension);ExtensionFactory.register(f.id_ce_cRLDistributionPoints,CRLDistributionPointsExtension);ExtensionFactory.register(f.id_pe_authorityInfoAccess,AuthorityInfoAccessExtension);ExtensionFactory.register(f.id_ce_issuerAltName,IssuerAlternativeNameExtension);AttributeFactory.register(_.id_pkcs9_at_challengePassword,ChallengePasswordAttribute);AttributeFactory.register(_.id_pkcs9_at_extensionRequest,ExtensionsAttribute);c.container.registerSingleton(Le,AsnDefaultSignatureFormatter);c.container.registerSingleton(Le,ze);ze.namedCurveSize.set(`P-256`,32);ze.namedCurveSize.set(`K-256`,32);ze.namedCurveSize.set(`P-384`,48);ze.namedCurveSize.set(`P-521`,66);e.AlgorithmProvider=AlgorithmProvider;e.AsnData=ae;e.AsnDefaultSignatureFormatter=AsnDefaultSignatureFormatter;e.AsnEcSignatureFormatter=ze;e.Attribute=Ie;e.AttributeFactory=AttributeFactory;e.AuthorityInfoAccessExtension=AuthorityInfoAccessExtension;e.AuthorityKeyIdentifierExtension=Pe;e.BasicConstraintsExtension=BasicConstraintsExtension;e.CRLDistributionPointsExtension=CRLDistributionPointsExtension;e.CertificatePolicyExtension=CertificatePolicyExtension;e.ChallengePasswordAttribute=ChallengePasswordAttribute;e.CryptoProvider=ce;e.DN=ye;e.DNS=ve;e.DefaultAlgorithmSerializer=DefaultAlgorithmSerializer;e.EMAIL=be;e.ExtendedKeyUsageExtension=ExtendedKeyUsageExtension;e.Extension=oe;e.ExtensionFactory=ExtensionFactory;e.ExtensionsAttribute=ExtensionsAttribute;e.GUID=Ce;e.GeneralName=GeneralName;e.GeneralNames=GeneralNames;e.IP=xe;e.IssuerAlternativeNameExtension=IssuerAlternativeNameExtension;e.KeyUsagesExtension=KeyUsagesExtension;e.Name=de;e.NameIdentifier=NameIdentifier;e.OidSerializer=OidSerializer;e.PemConverter=PemConverter;e.PemData=Me;e.Pkcs10CertificateRequest=Pkcs10CertificateRequest;e.Pkcs10CertificateRequestGenerator=Pkcs10CertificateRequestGenerator;e.PublicKey=Ne;e.REGISTERED_ID=Te;e.SubjectAlternativeNameExtension=SubjectAlternativeNameExtension;e.SubjectKeyIdentifierExtension=Fe;e.TextConverter=TextConverter;e.TextObject=TextObject;e.UPN=we;e.URL=Se;e.X509Certificate=X509Certificate;e.X509CertificateGenerator=X509CertificateGenerator;e.X509Certificates=X509Certificates;e.X509ChainBuilder=X509ChainBuilder;e.X509Crl=X509Crl;e.X509CrlEntry=X509CrlEntry;e.X509CrlGenerator=X509CrlGenerator;e.cryptoProvider=$;e.diAlgorithm=v;e.diAlgorithmProvider=y;e.diAsnSignatureFormatter=Le;e.idEd25519=He;e.idEd448=Ue;e.idX25519=Be;e.idX448=Ve}));
//!node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/cryptoNode.js
var import_src=/* @__PURE__ */ __toESM(require_src(),1);var import_nacl_fast=/* @__PURE__ */ __toESM(require_nacl_fast(),1);var import_build=require_build();var import_x509_cjs=/* @__PURE__ */ __toESM(require_x509_cjs(),1);const crypto$3=nc&&typeof nc===`object`&&`webcrypto`in nc?nc.webcrypto:nc&&typeof nc===`object`&&`randomBytes`in nc?nc:void 0;
//!node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function isBytes(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function anumber(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, got `+e)}function abytes(e,...t){if(!isBytes(e))throw new Error(`Uint8Array expected`);if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length `+t+`, got length=`+e.length)}function ahash(e){if(typeof e!==`function`||typeof e.create!==`function`)throw new Error(`Hash should be wrapped by utils.createHasher`);anumber(e.outputLen);anumber(e.blockLen)}function aexists(e,t=true){if(e.destroyed)throw new Error(`Hash instance has been destroyed`);if(t&&e.finished)throw new Error(`Hash#digest() has already been called`)}function aoutput(e,t){abytes(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least `+n)}function clean(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function createView(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function rotr(e,t){return e<<32-t|e>>>t}const hasHexBuiltin=/* @__PURE__ */ (()=>typeof Uint8Array.from([]).toHex===`function`&&typeof Uint8Array.fromHex===`function`)();const hexes=/* @__PURE__ */ Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function bytesToHex(e){abytes(e);if(hasHexBuiltin)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=hexes[e[n]];return t}const asciis={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16(e){if(e>=asciis._0&&e<=asciis._9)return e-asciis._0;if(e>=asciis.A&&e<=asciis.F)return e-(asciis.A-10);if(e>=asciis.a&&e<=asciis.f)return e-(asciis.a-10)}function hexToBytes(e){if(typeof e!==`string`)throw new Error(`hex string expected, got `+typeof e);if(hasHexBuiltin)return Uint8Array.fromHex(e);const t=e.length;const n=t/2;if(t%2)throw new Error(`hex string expected, got unpadded hex of length `+t);const r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){const n=asciiToBase16(e.charCodeAt(i));const a=asciiToBase16(e.charCodeAt(i+1));if(n===void 0||a===void 0){const t=e[i]+e[i+1];throw new Error(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function utf8ToBytes(e){if(typeof e!==`string`)throw new Error(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function toBytes(e){if(typeof e===`string`)e=utf8ToBytes(e);abytes(e);return e}function concatBytes(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];abytes(r);t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const i=e[t];n.set(i,r);r+=i.length}return n}var Hash=class{};function createHasher(e){const hashC=t=>e().update(toBytes(t)).digest();const t=e();hashC.outputLen=t.outputLen;hashC.blockLen=t.blockLen;hashC.create=()=>e();return hashC}function randomBytes$2(e=32){if(crypto$3&&typeof crypto$3.getRandomValues===`function`)return crypto$3.getRandomValues(new Uint8Array(e));if(crypto$3&&typeof crypto$3.randomBytes===`function`)return Uint8Array.from(crypto$3.randomBytes(e));throw new Error(`crypto.getRandomValues must be defined`)}
//!node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/utils.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$3=/* @__PURE__ */ BigInt(0);const _1n$3=/* @__PURE__ */ BigInt(1);function _abool2(e,t=``){if(typeof e!==`boolean`){const n=t&&`"${t}"`;throw new Error(n+`expected boolean, got type=`+typeof e)}return e}function _abytes2(e,t,n=``){const r=isBytes(e);const i=e?.length;const a=t!==void 0;if(!r||a&&i!==t){const o=n&&`"${n}" `;const s=a?` of length ${t}`:``;const c=r?`length=${i}`:`type=${typeof e}`;throw new Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function numberToHexUnpadded(e){const t=e.toString(16);return t.length&1?`0`+t:t}function hexToNumber(e){if(typeof e!==`string`)throw new Error(`hex string expected, got `+typeof e);return e===``?_0n$3:BigInt(`0x`+e)}function bytesToNumberBE(e){return hexToNumber(bytesToHex(e))}function bytesToNumberLE(e){abytes(e);return hexToNumber(bytesToHex(Uint8Array.from(e).reverse()))}function numberToBytesBE(e,t){return hexToBytes(e.toString(16).padStart(t*2,`0`))}function numberToBytesLE(e,t){return numberToBytesBE(e,t).reverse()}function ensureBytes(e,t,n){let r;if(typeof t===`string`)try{r=hexToBytes(t)}catch(t){throw new Error(e+` must be hex string or Uint8Array, cause: `+t)}else if(isBytes(t))r=Uint8Array.from(t);else throw new Error(e+` must be hex string or Uint8Array`);const i=r.length;if(typeof n===`number`&&i!==n)throw new Error(e+` of length `+n+` expected, got `+i);return r}const isPosBig=e=>typeof e===`bigint`&&_0n$3<=e;function inRange(e,t,n){return isPosBig(e)&&isPosBig(t)&&isPosBig(n)&&t<=e&&e<n}function aInRange(e,t,n,r){if(!inRange(t,n,r))throw new Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function bitLen(e){let t=0;for(;e>_0n$3;e>>=_1n$3,t+=1);return t}const bitMask=e=>(_1n$3<<BigInt(e))-_1n$3;function createHmacDrbg(e,t,n){if(typeof e!==`number`||e<2)throw new Error(`hashLen must be a number`);if(typeof t!==`number`||t<2)throw new Error(`qByteLen must be a number`);if(typeof n!==`function`)throw new Error(`hmacFn must be a function`);const u8n=e=>new Uint8Array(e);const u8of=e=>Uint8Array.of(e);let r=u8n(e);let i=u8n(e);let a=0;const reset=()=>{r.fill(1);i.fill(0);a=0};const h=(...e)=>n(i,r,...e);const reseed=(e=u8n(0))=>{i=h(u8of(0),e);r=h();if(e.length===0)return;i=h(u8of(1),e);r=h()};const gen=()=>{if(a++>=1e3)throw new Error(`drbg: tried 1000 values`);let e=0;const n=[];while(e<t){r=h();const t=r.slice();n.push(t);e+=r.length}return concatBytes(...n)};const genUntil=(e,t)=>{reset();reseed(e);let n=void 0;while(!(n=t(gen())))reseed();reset();return n};return genUntil}function _validateObject(e,t,n={}){if(!e||typeof e!==`object`)throw new Error(`expected valid options object`);function checkField(t,n,r){const i=e[t];if(r&&i===void 0)return;const a=typeof i;if(a!==n||i===null)throw new Error(`param "${t}" is invalid: expected ${n}, got ${a}`)}Object.entries(t).forEach(([e,t])=>checkField(e,t,false));Object.entries(n).forEach(([e,t])=>checkField(e,t,true))}function memoized(e){const t=/* @__PURE__ */ new WeakMap;return(n,...r)=>{const i=t.get(n);if(i!==void 0)return i;const a=e(n,...r);t.set(n,a);return a}}
//!node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$2=BigInt(0);const _1n$2=BigInt(1);const _2n$1=/* @__PURE__ */ BigInt(2);const _3n$1=/* @__PURE__ */ BigInt(3);const _4n$1=/* @__PURE__ */ BigInt(4);const _5n=/* @__PURE__ */ BigInt(5);const _7n=/* @__PURE__ */ BigInt(7);const _8n=/* @__PURE__ */ BigInt(8);const _9n=/* @__PURE__ */ BigInt(9);const _16n=/* @__PURE__ */ BigInt(16);function mod(e,t){const n=e%t;return n>=_0n$2?n:t+n}function invert(e,t){if(e===_0n$2)throw new Error(`invert: expected non-zero number`);if(t<=_0n$2)throw new Error(`invert: expected positive modulus, got `+t);let n=mod(e,t);let r=t;let i=_0n$2,a=_1n$2,o=_1n$2,s=_0n$2;while(n!==_0n$2){const e=r/n;const t=r%n;const c=i-o*e;const u=a-s*e;r=n,n=t,i=o,a=s,o=c,s=u}if(r!==_1n$2)throw new Error(`invert: does not exist`);return mod(i,t)}function assertIsSquare(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error(`Cannot find square root`)}function sqrt3mod4(e,t){const n=(e.ORDER+_1n$2)/_4n$1;const r=e.pow(t,n);assertIsSquare(e,r,t);return r}function sqrt5mod8(e,t){const n=(e.ORDER-_5n)/_8n;const r=e.mul(t,_2n$1);const i=e.pow(r,n);const a=e.mul(t,i);const o=e.mul(e.mul(a,_2n$1),i);const s=e.mul(a,e.sub(o,e.ONE));assertIsSquare(e,s,t);return s}function sqrt9mod16(e){const t=Field(e);const n=tonelliShanks(e);const r=n(t,t.neg(t.ONE));const i=n(t,r);const a=n(t,t.neg(r));const o=(e+_7n)/_16n;return(e,t)=>{let n=e.pow(t,o);let s=e.mul(n,r);const c=e.mul(n,i);const u=e.mul(n,a);const d=e.eql(e.sqr(s),t);const f=e.eql(e.sqr(c),t);n=e.cmov(n,s,d);s=e.cmov(u,c,f);const p=e.eql(e.sqr(s),t);const m=e.cmov(n,s,p);assertIsSquare(e,m,t);return m}}function tonelliShanks(e){if(e<_3n$1)throw new Error(`sqrt is not defined for small field`);let t=e-_1n$2;let n=0;while(t%_2n$1===_0n$2){t/=_2n$1;n++}let r=_2n$1;const i=Field(e);while(FpLegendre(i,r)===1)if(r++>1e3)throw new Error(`Cannot find square root: probably non-prime P`);if(n===1)return sqrt3mod4;let a=i.pow(r,t);const o=(t+_1n$2)/_2n$1;return function tonelliSlow(e,r){if(e.is0(r))return r;if(FpLegendre(e,r)!==1)throw new Error(`Cannot find square root`);let i=n;let s=e.mul(e.ONE,a);let c=e.pow(r,t);let u=e.pow(r,o);while(!e.eql(c,e.ONE)){if(e.is0(c))return e.ZERO;let t=1;let n=e.sqr(c);while(!e.eql(n,e.ONE)){t++;n=e.sqr(n);if(t===i)throw new Error(`Cannot find square root`)}const r=_1n$2<<BigInt(i-t-1);const a=e.pow(s,r);i=t;s=e.sqr(a);c=e.mul(c,s);u=e.mul(u,a)}return u}}function FpSqrt(e){if(e%_4n$1===_3n$1)return sqrt3mod4;if(e%_8n===_5n)return sqrt5mod8;if(e%_16n===_9n)return sqrt9mod16(e);return tonelliShanks(e)}const FIELD_FIELDS=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function validateField(e){const t=FIELD_FIELDS.reduce((e,t)=>{e[t]=`function`;return e},{ORDER:`bigint`,MASK:`bigint`,BYTES:`number`,BITS:`number`});_validateObject(e,t);return e}function FpPow(e,t,n){if(n<_0n$2)throw new Error(`invalid exponent, negatives unsupported`);if(n===_0n$2)return e.ONE;if(n===_1n$2)return t;let r=e.ONE;let i=t;while(n>_0n$2){if(n&_1n$2)r=e.mul(r,i);i=e.sqr(i);n>>=_1n$2}return r}function FpInvertBatch(e,t,n=false){const r=new Array(t.length).fill(n?e.ZERO:void 0);const i=t.reduce((t,n,i)=>{if(e.is0(n))return t;r[i]=t;return e.mul(t,n)},e.ONE);const a=e.inv(i);t.reduceRight((t,n,i)=>{if(e.is0(n))return t;r[i]=e.mul(t,r[i]);return e.mul(t,n)},a);return r}function FpLegendre(e,t){const n=(e.ORDER-_1n$2)/_2n$1;const r=e.pow(t,n);const i=e.eql(r,e.ONE);const a=e.eql(r,e.ZERO);const o=e.eql(r,e.neg(e.ONE));if(!i&&!a&&!o)throw new Error(`invalid Legendre symbol result`);return i?1:a?0:-1}function nLength(e,t){if(t!==void 0)anumber(t);const n=t!==void 0?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Field(e,t,n=false,r={}){if(e<=_0n$2)throw new Error(`invalid field: expected ORDER > 0, got `+e);let i=void 0;let a=void 0;let o=false;let s=void 0;if(typeof t===`object`&&t!=null){if(r.sqrt||n)throw new Error(`cannot specify opts in two arguments`);const e=t;if(e.BITS)i=e.BITS;if(e.sqrt)a=e.sqrt;if(typeof e.isLE===`boolean`)n=e.isLE;if(typeof e.modFromBytes===`boolean`)o=e.modFromBytes;s=e.allowedLengths}else{if(typeof t===`number`)i=t;if(r.sqrt)a=r.sqrt}const{nBitLength:c,nByteLength:u}=nLength(e,i);if(u>2048)throw new Error(`invalid field: expected ORDER of <= 2048 bytes`);let d;const f=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:u,MASK:bitMask(c),ZERO:_0n$2,ONE:_1n$2,allowedLengths:s,create:t=>mod(t,e),isValid:t=>{if(typeof t!==`bigint`)throw new Error(`invalid field element: expected bigint, got `+typeof t);return _0n$2<=t&&t<e},is0:e=>e===_0n$2,isValidNot0:e=>!f.is0(e)&&f.isValid(e),isOdd:e=>(e&_1n$2)===_1n$2,neg:t=>mod(-t,e),eql:(e,t)=>e===t,sqr:t=>mod(t*t,e),add:(t,n)=>mod(t+n,e),sub:(t,n)=>mod(t-n,e),mul:(t,n)=>mod(t*n,e),pow:(e,t)=>FpPow(f,e,t),div:(t,n)=>mod(t*invert(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>invert(t,e),sqrt:a||(t=>{if(!d)d=FpSqrt(e);return d(f,t)}),toBytes:e=>n?numberToBytesLE(e,u):numberToBytesBE(e,u),fromBytes:(t,r=true)=>{if(s){if(!s.includes(t.length)||t.length>u)throw new Error(`Field.fromBytes: expected `+s+` bytes, got `+t.length);const e=new Uint8Array(u);e.set(t,n?0:e.length-t.length);t=e}if(t.length!==u)throw new Error(`Field.fromBytes: expected `+u+` bytes, got `+t.length);let i=n?bytesToNumberLE(t):bytesToNumberBE(t);if(o)i=mod(i,e);if(!r){if(!f.isValid(i))throw new Error(`invalid field element: outside of range 0..ORDER`)}return i},invertBatch:e=>FpInvertBatch(f,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(f)}function getFieldBytesLength(e){if(typeof e!==`bigint`)throw new Error(`field order must be bigint`);const t=e.toString(2).length;return Math.ceil(t/8)}function getMinHashLength(e){const t=getFieldBytesLength(e);return t+Math.ceil(t/2)}function mapHashToField(e,t,n=false){const r=e.length;const i=getFieldBytesLength(t);const a=getMinHashLength(t);if(r<16||r<a||r>1024)throw new Error(`expected `+a+`-1024 bytes of input, got `+r);const o=mod(n?bytesToNumberLE(e):bytesToNumberBE(e),t-_1n$2)+_1n$2;return n?numberToBytesLE(o,i):numberToBytesBE(o,i)}
//!node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
function setBigUint64(e,t,n,r){if(typeof e.setBigUint64===`function`)return e.setBigUint64(t,n,r);const i=BigInt(32);const a=BigInt(4294967295);const o=Number(n>>i&a);const s=Number(n&a);const c=r?4:0;const u=r?0:4;e.setUint32(t+c,o,r);e.setUint32(t+u,s,r)}function Chi(e,t,n){return e&t^~e&n}function Maj(e,t,n){return e&t^e&n^t&n}var HashMD=class extends Hash{constructor(e,t,n,r){super();this.finished=false;this.length=0;this.pos=0;this.destroyed=false;this.blockLen=e;this.outputLen=t;this.padOffset=n;this.isLE=r;this.buffer=new Uint8Array(e);this.view=createView(this.buffer)}update(e){aexists(this);e=toBytes(e);abytes(e);const{view:t,buffer:n,blockLen:r}=this;const i=e.length;for(let a=0;a<i;){const o=Math.min(r-this.pos,i-a);if(o===r){const t=createView(e);for(;r<=i-a;a+=r)this.process(t,a);continue}n.set(e.subarray(a,a+o),this.pos);this.pos+=o;a+=o;if(this.pos===r){this.process(t,0);this.pos=0}}this.length+=e.length;this.roundClean();return this}digestInto(e){aexists(this);aoutput(e,this);this.finished=true;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:a}=this;t[a++]=128;clean(this.buffer.subarray(a));if(this.padOffset>r-a){this.process(n,0);a=0}for(let e=a;e<r;e++)t[e]=0;setBigUint64(n,r-8,BigInt(this.length*8),i);this.process(n,0);const o=createView(e);const s=this.outputLen;if(s%4)throw new Error(`_sha2: outputLen should be aligned to 32bit`);const c=s/4;const u=this.get();if(c>u.length)throw new Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,u[e],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);this.destroy();return n}_cloneInto(e){e||(e=new this.constructor);e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;e.destroyed=a;e.finished=i;e.length=r;e.pos=o;if(r%t)e.buffer.set(n);return e}clone(){return this._cloneInto()}};const SHA256_IV=/* @__PURE__ */ Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);const SHA384_IV=/* @__PURE__ */ Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);const SHA512_IV=/* @__PURE__ */ Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);
//!node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js
const U32_MASK64=/* @__PURE__ */ BigInt(2**32-1);const _32n=/* @__PURE__ */ BigInt(32);function fromBig(e,t=false){if(t)return{h:Number(e&U32_MASK64),l:Number(e>>_32n&U32_MASK64)};return{h:Number(e>>_32n&U32_MASK64)|0,l:Number(e&U32_MASK64)|0}}function split(e,t=false){const n=e.length;let r=new Uint32Array(n);let i=new Uint32Array(n);for(let a=0;a<n;a++){const{h:n,l:o}=fromBig(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}const shrSH=(e,t,n)=>e>>>n;const shrSL=(e,t,n)=>e<<32-n|t>>>n;const rotrSH=(e,t,n)=>e>>>n|t<<32-n;const rotrSL=(e,t,n)=>e<<32-n|t>>>n;const rotrBH=(e,t,n)=>e<<64-n|t>>>n-32;const rotrBL=(e,t,n)=>e>>>n-32|t<<64-n;function add(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}const add3L=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);const add3H=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;const add4L=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);const add4H=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;const add5L=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);const add5H=(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0;
//!node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
const SHA256_K=/* @__PURE__ */ Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);const SHA256_W=/* @__PURE__ */ new Uint32Array(64);var SHA256=class extends HashMD{constructor(e=32){super(64,e,8,false);this.A=SHA256_IV[0]|0;this.B=SHA256_IV[1]|0;this.C=SHA256_IV[2]|0;this.D=SHA256_IV[3]|0;this.E=SHA256_IV[4]|0;this.F=SHA256_IV[5]|0;this.G=SHA256_IV[6]|0;this.H=SHA256_IV[7]|0}get(){const{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0;this.B=t|0;this.C=n|0;this.D=r|0;this.E=i|0;this.F=a|0;this.G=o|0;this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)SHA256_W[n]=e.getUint32(t,false);for(let e=16;e<64;e++){const t=SHA256_W[e-15];const n=SHA256_W[e-2];const r=rotr(t,7)^rotr(t,18)^t>>>3;const i=rotr(n,17)^rotr(n,19)^n>>>10;SHA256_W[e]=i+SHA256_W[e-7]+r+SHA256_W[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:u}=this;for(let e=0;e<64;e++){const t=rotr(o,6)^rotr(o,11)^rotr(o,25);const d=u+t+Chi(o,s,c)+SHA256_K[e]+SHA256_W[e]|0;const f=(rotr(n,2)^rotr(n,13)^rotr(n,22))+Maj(n,r,i)|0;u=c;c=s;s=o;o=a+d|0;a=i;i=r;r=n;n=d+f|0}n=n+this.A|0;r=r+this.B|0;i=i+this.C|0;a=a+this.D|0;o=o+this.E|0;s=s+this.F|0;c=c+this.G|0;u=u+this.H|0;this.set(n,r,i,a,o,s,c,u)}roundClean(){clean(SHA256_W)}destroy(){this.set(0,0,0,0,0,0,0,0);clean(this.buffer)}};const K512=/* @__PURE__ */ (()=>split([`0x428a2f98d728ae22`,`0x7137449123ef65cd`,`0xb5c0fbcfec4d3b2f`,`0xe9b5dba58189dbbc`,`0x3956c25bf348b538`,`0x59f111f1b605d019`,`0x923f82a4af194f9b`,`0xab1c5ed5da6d8118`,`0xd807aa98a3030242`,`0x12835b0145706fbe`,`0x243185be4ee4b28c`,`0x550c7dc3d5ffb4e2`,`0x72be5d74f27b896f`,`0x80deb1fe3b1696b1`,`0x9bdc06a725c71235`,`0xc19bf174cf692694`,`0xe49b69c19ef14ad2`,`0xefbe4786384f25e3`,`0x0fc19dc68b8cd5b5`,`0x240ca1cc77ac9c65`,`0x2de92c6f592b0275`,`0x4a7484aa6ea6e483`,`0x5cb0a9dcbd41fbd4`,`0x76f988da831153b5`,`0x983e5152ee66dfab`,`0xa831c66d2db43210`,`0xb00327c898fb213f`,`0xbf597fc7beef0ee4`,`0xc6e00bf33da88fc2`,`0xd5a79147930aa725`,`0x06ca6351e003826f`,`0x142929670a0e6e70`,`0x27b70a8546d22ffc`,`0x2e1b21385c26c926`,`0x4d2c6dfc5ac42aed`,`0x53380d139d95b3df`,`0x650a73548baf63de`,`0x766a0abb3c77b2a8`,`0x81c2c92e47edaee6`,`0x92722c851482353b`,`0xa2bfe8a14cf10364`,`0xa81a664bbc423001`,`0xc24b8b70d0f89791`,`0xc76c51a30654be30`,`0xd192e819d6ef5218`,`0xd69906245565a910`,`0xf40e35855771202a`,`0x106aa07032bbd1b8`,`0x19a4c116b8d2d0c8`,`0x1e376c085141ab53`,`0x2748774cdf8eeb99`,`0x34b0bcb5e19b48a8`,`0x391c0cb3c5c95a63`,`0x4ed8aa4ae3418acb`,`0x5b9cca4f7763e373`,`0x682e6ff3d6b2b8a3`,`0x748f82ee5defb2fc`,`0x78a5636f43172f60`,`0x84c87814a1f0ab72`,`0x8cc702081a6439ec`,`0x90befffa23631e28`,`0xa4506cebde82bde9`,`0xbef9a3f7b2c67915`,`0xc67178f2e372532b`,`0xca273eceea26619c`,`0xd186b8c721c0c207`,`0xeada7dd6cde0eb1e`,`0xf57d4f7fee6ed178`,`0x06f067aa72176fba`,`0x0a637dc5a2c898a6`,`0x113f9804bef90dae`,`0x1b710b35131c471b`,`0x28db77f523047d84`,`0x32caab7b40c72493`,`0x3c9ebe0a15c9bebc`,`0x431d67c49c100d4c`,`0x4cc5d4becb3e42b6`,`0x597f299cfc657e2a`,`0x5fcb6fab3ad6faec`,`0x6c44198c4a475817`].map(e=>BigInt(e))))();const SHA512_Kh=/* @__PURE__ */ (()=>K512[0])();const SHA512_Kl=/* @__PURE__ */ (()=>K512[1])();const SHA512_W_H=/* @__PURE__ */ new Uint32Array(80);const SHA512_W_L=/* @__PURE__ */ new Uint32Array(80);var SHA512=class extends HashMD{constructor(e=64){super(128,e,16,false);this.Ah=SHA512_IV[0]|0;this.Al=SHA512_IV[1]|0;this.Bh=SHA512_IV[2]|0;this.Bl=SHA512_IV[3]|0;this.Ch=SHA512_IV[4]|0;this.Cl=SHA512_IV[5]|0;this.Dh=SHA512_IV[6]|0;this.Dl=SHA512_IV[7]|0;this.Eh=SHA512_IV[8]|0;this.El=SHA512_IV[9]|0;this.Fh=SHA512_IV[10]|0;this.Fl=SHA512_IV[11]|0;this.Gh=SHA512_IV[12]|0;this.Gl=SHA512_IV[13]|0;this.Hh=SHA512_IV[14]|0;this.Hl=SHA512_IV[15]|0}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:s,Eh:c,El:u,Fh:d,Fl:f,Gh:p,Gl:m,Hh:g,Hl:_}=this;return[e,t,n,r,i,a,o,s,c,u,d,f,p,m,g,_]}set(e,t,n,r,i,a,o,s,c,u,d,f,p,m,g,_){this.Ah=e|0;this.Al=t|0;this.Bh=n|0;this.Bl=r|0;this.Ch=i|0;this.Cl=a|0;this.Dh=o|0;this.Dl=s|0;this.Eh=c|0;this.El=u|0;this.Fh=d|0;this.Fl=f|0;this.Gh=p|0;this.Gl=m|0;this.Hh=g|0;this.Hl=_|0}process(e,t){for(let n=0;n<16;n++,t+=4){SHA512_W_H[n]=e.getUint32(t);SHA512_W_L[n]=e.getUint32(t+=4)}for(let e=16;e<80;e++){const t=SHA512_W_H[e-15]|0;const n=SHA512_W_L[e-15]|0;const r=rotrSH(t,n,1)^rotrSH(t,n,8)^shrSH(t,n,7);const i=rotrSL(t,n,1)^rotrSL(t,n,8)^shrSL(t,n,7);const a=SHA512_W_H[e-2]|0;const o=SHA512_W_L[e-2]|0;const s=rotrSH(a,o,19)^rotrBH(a,o,61)^shrSH(a,o,6);const c=rotrSL(a,o,19)^rotrBL(a,o,61)^shrSL(a,o,6);const u=add4L(i,c,SHA512_W_L[e-7],SHA512_W_L[e-16]);const d=add4H(u,r,s,SHA512_W_H[e-7],SHA512_W_H[e-16]);SHA512_W_H[e]=d|0;SHA512_W_L[e]=u|0}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:s,Dh:c,Dl:u,Eh:d,El:f,Fh:p,Fl:m,Gh:g,Gl:_,Hh:v,Hl:y}=this;for(let e=0;e<80;e++){const t=rotrSH(d,f,14)^rotrSH(d,f,18)^rotrBH(d,f,41);const b=rotrSL(d,f,14)^rotrSL(d,f,18)^rotrBL(d,f,41);const x=d&p^~d&g;const C=f&m^~f&_;const w=add5L(y,b,C,SHA512_Kl[e],SHA512_W_L[e]);const T=add5H(w,v,t,x,SHA512_Kh[e],SHA512_W_H[e]);const E=w|0;const D=rotrSH(n,r,28)^rotrBH(n,r,34)^rotrBH(n,r,39);const O=rotrSL(n,r,28)^rotrBL(n,r,34)^rotrBL(n,r,39);const k=n&i^n&o^i&o;const j=r&a^r&s^a&s;v=g|0;y=_|0;g=p|0;_=m|0;p=d|0;m=f|0;({h:d,l:f}=add(c|0,u|0,T|0,E|0));c=o|0;u=s|0;o=i|0;s=a|0;i=n|0;a=r|0;const N=add3L(E,O,j);n=add3H(N,T,D,k);r=N|0}({h:n,l:r}=add(this.Ah|0,this.Al|0,n|0,r|0));({h:i,l:a}=add(this.Bh|0,this.Bl|0,i|0,a|0));({h:o,l:s}=add(this.Ch|0,this.Cl|0,o|0,s|0));({h:c,l:u}=add(this.Dh|0,this.Dl|0,c|0,u|0));({h:d,l:f}=add(this.Eh|0,this.El|0,d|0,f|0));({h:p,l:m}=add(this.Fh|0,this.Fl|0,p|0,m|0));({h:g,l:_}=add(this.Gh|0,this.Gl|0,g|0,_|0));({h:v,l:y}=add(this.Hh|0,this.Hl|0,v|0,y|0));this.set(n,r,i,a,o,s,c,u,d,f,p,m,g,_,v,y)}roundClean(){clean(SHA512_W_H,SHA512_W_L)}destroy(){clean(this.buffer);this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var SHA384=class extends SHA512{constructor(){super(48);this.Ah=SHA384_IV[0]|0;this.Al=SHA384_IV[1]|0;this.Bh=SHA384_IV[2]|0;this.Bl=SHA384_IV[3]|0;this.Ch=SHA384_IV[4]|0;this.Cl=SHA384_IV[5]|0;this.Dh=SHA384_IV[6]|0;this.Dl=SHA384_IV[7]|0;this.Eh=SHA384_IV[8]|0;this.El=SHA384_IV[9]|0;this.Fh=SHA384_IV[10]|0;this.Fl=SHA384_IV[11]|0;this.Gh=SHA384_IV[12]|0;this.Gl=SHA384_IV[13]|0;this.Hh=SHA384_IV[14]|0;this.Hl=SHA384_IV[15]|0}};const sha256=/* @__PURE__ */ createHasher(()=>new SHA256);const sha512=/* @__PURE__ */ createHasher(()=>new SHA512);const sha384=/* @__PURE__ */ createHasher(()=>new SHA384);
//!node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
var HMAC=class extends Hash{constructor(e,t){super();this.finished=false;this.destroyed=false;ahash(e);const n=toBytes(t);this.iHash=e.create();if(typeof this.iHash.update!==`function`)throw new Error(`Expected instance of class which extends utils.Hash`);this.blockLen=this.iHash.blockLen;this.outputLen=this.iHash.outputLen;const r=this.blockLen;const i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i);this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i);clean(i)}update(e){aexists(this);this.iHash.update(e);return this}digestInto(e){aexists(this);abytes(e,this.outputLen);this.finished=true;this.iHash.digestInto(e);this.oHash.update(e);this.oHash.digestInto(e);this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);this.digestInto(e);return e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o}=this;e=e;e.finished=r;e.destroyed=i;e.blockLen=a;e.outputLen=o;e.oHash=t._cloneInto(e.oHash);e.iHash=n._cloneInto(e.iHash);return e}clone(){return this._cloneInto()}destroy(){this.destroyed=true;this.oHash.destroy();this.iHash.destroy()}};const hmac$1=(e,t,n)=>new HMAC(e,t).update(n).digest();hmac$1.create=(e,t)=>new HMAC(e,t);
//!node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$1=BigInt(0);const _1n$1=BigInt(1);function negateCt(e,t){const n=t.negate();return e?n:t}function normalizeZ(e,t){const n=FpInvertBatch(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function validateW(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function calcWOpts(e,t){validateW(e,t);const n=Math.ceil(t/e)+1;const r=2**(e-1);const i=2**e;return{windows:n,windowSize:r,mask:bitMask(e),maxNumber:i,shiftBy:BigInt(e)}}function calcOffsets(e,t,n){const{windowSize:r,mask:i,maxNumber:a,shiftBy:o}=n;let s=Number(e&i);let c=e>>o;if(s>r){s-=a;c+=_1n$1}const u=t*r;const d=u+Math.abs(s)-1;const f=s===0;const p=s<0;const m=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:m,offsetF:u}}function validateMSMPoints(e,t){if(!Array.isArray(e))throw new Error(`array expected`);e.forEach((e,n)=>{if(!(e instanceof t))throw new Error(`invalid point at index `+n)})}function validateMSMScalars(e,t){if(!Array.isArray(e))throw new Error(`array of scalars expected`);e.forEach((e,n)=>{if(!t.isValid(e))throw new Error(`invalid scalar at index `+n)})}const pointPrecomputes=/* @__PURE__ */ new WeakMap;const pointWindowSizes=/* @__PURE__ */ new WeakMap;function getW(e){return pointWindowSizes.get(e)||1}function assert0(e){if(e!==_0n$1)throw new Error(`invalid wNAF`)}var wNAF=class{constructor(e,t){this.BASE=e.BASE;this.ZERO=e.ZERO;this.Fn=e.Fn;this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;while(t>_0n$1){if(t&_1n$1)n=n.add(r);r=r.double();t>>=_1n$1}return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=calcWOpts(t,this.bits);const i=[];let a=e;let o=a;for(let e=0;e<n;e++){o=a;i.push(o);for(let e=1;e<r;e++){o=o.add(a);i.push(o)}a=o.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error(`invalid scalar`);let r=this.ZERO;let i=this.BASE;const a=calcWOpts(e,this.bits);for(let e=0;e<a.windows;e++){const{nextN:o,offset:s,isZero:c,isNeg:u,isNegF:d,offsetF:f}=calcOffsets(n,e,a);n=o;if(c)i=i.add(negateCt(d,t[f]));else r=r.add(negateCt(u,t[s]))}assert0(n);return{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=calcWOpts(e,this.bits);for(let e=0;e<i.windows;e++){if(n===_0n$1)break;const{nextN:a,offset:o,isZero:s,isNeg:c}=calcOffsets(n,e,i);n=a;if(s)continue;else{const e=t[o];r=r.add(c?e.negate():e)}}assert0(n);return r}getPrecomputes(e,t,n){let r=pointPrecomputes.get(t);if(!r){r=this.precomputeWindow(t,e);if(e!==1){if(typeof n===`function`)r=n(r);pointPrecomputes.set(t,r)}}return r}cached(e,t,n){const r=getW(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=getW(e);if(i===1)return this._unsafeLadder(e,t,r);return this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){validateW(t,this.bits);pointWindowSizes.set(e,t);pointPrecomputes.delete(e)}hasCache(e){return getW(e)!==1}};function mulEndoUnsafe(e,t,n,r){let i=t;let a=e.ZERO;let o=e.ZERO;while(n>_0n$1||r>_0n$1){if(n&_1n$1)a=a.add(i);if(r&_1n$1)o=o.add(i);i=i.double();n>>=_1n$1;r>>=_1n$1}return{p1:a,p2:o}}function pippenger(e,t,n,r){validateMSMPoints(n,e);validateMSMScalars(r,t);const i=n.length;const a=r.length;if(i!==a)throw new Error(`arrays of points and scalars must have equal length`);const o=e.ZERO;const s=bitLen(BigInt(i));let c=1;if(s>12)c=s-3;else if(s>4)c=s-2;else if(s>0)c=2;const u=bitMask(c);const d=new Array(Number(u)+1).fill(o);const f=Math.floor((t.BITS-1)/c)*c;let p=o;for(let e=f;e>=0;e-=c){d.fill(o);for(let t=0;t<a;t++){const i=r[t];const a=Number(i>>BigInt(e)&u);d[a]=d[a].add(n[t])}let t=o;for(let e=d.length-1,n=o;e>0;e--){n=n.add(d[e]);t=t.add(n)}p=p.add(t);if(e!==0)for(let e=0;e<c;e++)p=p.double()}return p}function createField(e,t,n){if(t){if(t.ORDER!==e)throw new Error(`Field.ORDER must match order: Fp == p, Fn == n`);validateField(t);return t}else return Field(e,{isLE:n})}function _createCurveFields(e,t,n={},r){if(r===void 0)r=e===`edwards`;if(!t||typeof t!==`object`)throw new Error(`expected valid ${e} CURVE object`);for(const e of[`p`,`n`,`h`]){const n=t[e];if(!(typeof n===`bigint`&&n>_0n$1))throw new Error(`CURVE.${e} must be positive bigint`)}const i=createField(t.p,n.Fp,r);const a=createField(t.n,n.Fn,r);const o=[`Gx`,`Gy`,`a`,e===`weierstrass`?`b`:`d`];for(const e of o)if(!i.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);t=Object.freeze(Object.assign({},t));return{CURVE:t,Fp:i,Fn:a}}
//!node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/weierstrass.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const divNearest=(e,t)=>(e+(e>=0?t:-t)/_2n)/t;function _splitEndoScalar(e,t,n){const[[r,i],[a,o]]=t;const s=divNearest(o*e,n);const c=divNearest(-i*e,n);let u=e-s*r-c*a;let d=-s*i-c*o;const f=u<_0n;const p=d<_0n;if(f)u=-u;if(p)d=-d;const m=bitMask(Math.ceil(bitLen(n)/2))+_1n;if(u<_0n||u>=m||d<_0n||d>=m)throw new Error(`splitScalar (endomorphism): failed, k=`+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}function validateSigFormat(e){if(![`compact`,`recovered`,`der`].includes(e))throw new Error(`Signature format must be "compact", "recovered", or "der"`);return e}function validateSigOpts(e,t){const n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];_abool2(n.lowS,`lowS`);_abool2(n.prehash,`prehash`);if(n.format!==void 0)validateSigFormat(n.format);return n}var DERErr=class extends Error{constructor(e=``){super(e)}};const DER={Err:DERErr,_tlv:{encode:(e,t)=>{const{Err:n}=DER;if(e<0||e>256)throw new n(`tlv.encode: wrong tag`);if(t.length&1)throw new n(`tlv.encode: unpadded data`);const r=t.length/2;const i=numberToHexUnpadded(r);if(i.length/2&128)throw new n(`tlv.encode: long form length too big`);const a=r>127?numberToHexUnpadded(i.length/2|128):``;return numberToHexUnpadded(e)+a+i+t},decode(e,t){const{Err:n}=DER;let r=0;if(e<0||e>256)throw new n(`tlv.encode: wrong tag`);if(t.length<2||t[r++]!==e)throw new n(`tlv.decode: wrong tlv`);const i=t[r++];const a=!!(i&128);let o=0;if(!a)o=i;else{const e=i&127;if(!e)throw new n(`tlv.decode(long): indefinite length not supported`);if(e>4)throw new n(`tlv.decode(long): byte length is too big`);const a=t.subarray(r,r+e);if(a.length!==e)throw new n(`tlv.decode: length bytes not complete`);if(a[0]===0)throw new n(`tlv.decode(long): zero leftmost byte`);for(const e of a)o=o<<8|e;r+=e;if(o<128)throw new n(`tlv.decode(long): not minimal encoding`)}const s=t.subarray(r,r+o);if(s.length!==o)throw new n(`tlv.decode: wrong value length`);return{v:s,l:t.subarray(r+o)}}},_int:{encode(e){const{Err:t}=DER;if(e<_0n)throw new t(`integer: negative integers are not allowed`);let n=numberToHexUnpadded(e);if(Number.parseInt(n[0],16)&8)n=`00`+n;if(n.length&1)throw new t(`unexpected DER parsing assertion: unpadded hex`);return n},decode(e){const{Err:t}=DER;if(e[0]&128)throw new t(`invalid signature integer: negative`);if(e[0]===0&&!(e[1]&128))throw new t(`invalid signature integer: unnecessary leading zero`);return bytesToNumberBE(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=DER;const i=ensureBytes(`signature`,e);const{v:a,l:o}=r.decode(48,i);if(o.length)throw new t(`invalid signature: left bytes after parsing`);const{v:s,l:c}=r.decode(2,a);const{v:u,l:d}=r.decode(2,c);if(d.length)throw new t(`invalid signature: left bytes after parsing`);return{r:n.decode(s),s:n.decode(u)}},hexFromSig(e){const{_tlv:t,_int:n}=DER;const r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}};const _0n=BigInt(0);const _1n=BigInt(1);const _2n=BigInt(2);const _3n=BigInt(3);const _4n=BigInt(4);function _normFnElement(e,t){const{BYTES:n}=e;let r;if(typeof t===`bigint`)r=t;else{let i=ensureBytes(`private key`,t);try{r=e.fromBytes(i)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error(`invalid private key: out of range [1..N-1]`);return r}function weierstrassN(e,t={}){const n=_createCurveFields(`weierstrass`,e,t);const{Fp:r,Fn:i}=n;let a=n.CURVE;const{h:o,n:s}=a;_validateObject(t,{},{allowInfinityPoint:`boolean`,clearCofactor:`function`,isTorsionFree:`function`,fromBytes:`function`,toBytes:`function`,endo:`object`,wrapPrivateKey:`boolean`});const{endo:c}=t;if(c){if(!r.is0(a.a)||typeof c.beta!==`bigint`||!Array.isArray(c.basises))throw new Error(`invalid endo: expected "beta": bigint and "basises": array`)}const u=getWLengths(r,i);function assertCompressionIsSupported(){if(!r.isOdd)throw new Error(`compression is not supported: Field does not have .isOdd()`)}function pointToBytes(e,t,n){const{x:i,y:a}=t.toAffine();const o=r.toBytes(i);_abool2(n,`isCompressed`);if(n){assertCompressionIsSupported();const e=!r.isOdd(a);return concatBytes(pprefix(e),o)}else return concatBytes(Uint8Array.of(4),o,r.toBytes(a))}function pointFromBytes(e){_abytes2(e,void 0,`Point`);const{publicKey:t,publicKeyUncompressed:n}=u;const i=e.length;const a=e[0];const o=e.subarray(1);if(i===t&&(a===2||a===3)){const e=r.fromBytes(o);if(!r.isValid(e))throw new Error(`bad point: is not on curve, wrong x`);const t=weierstrassEquation(e);let n;try{n=r.sqrt(t)}catch(e){const t=e instanceof Error?`: `+e.message:``;throw new Error(`bad point: is not on curve, sqrt error`+t)}assertCompressionIsSupported();const i=r.isOdd(n);if((a&1)===1!==i)n=r.neg(n);return{x:e,y:n}}else if(i===n&&a===4){const e=r.BYTES;const t=r.fromBytes(o.subarray(0,e));const n=r.fromBytes(o.subarray(e,e*2));if(!isValidXY(t,n))throw new Error(`bad point: is not on curve`);return{x:t,y:n}}else throw new Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${n}`)}const d=t.toBytes||pointToBytes;const f=t.fromBytes||pointFromBytes;function weierstrassEquation(e){const t=r.sqr(e);const n=r.mul(t,e);return r.add(r.add(n,r.mul(e,a.a)),a.b)}function isValidXY(e,t){const n=r.sqr(t);const i=weierstrassEquation(e);return r.eql(n,i)}if(!isValidXY(a.Gx,a.Gy))throw new Error(`bad curve params: generator point`);const p=r.mul(r.pow(a.a,_3n),_4n);const m=r.mul(r.sqr(a.b),BigInt(27));if(r.is0(r.add(p,m)))throw new Error(`bad curve params: a or b`);function acoord(e,t,n=false){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function aprjpoint(e){if(!(e instanceof Point))throw new Error(`ProjectivePoint expected`)}function splitEndoScalarN(e){if(!c||!c.basises)throw new Error(`no endo`);return _splitEndoScalar(e,c.basises,i.ORDER)}const g=memoized((e,t)=>{const{X:n,Y:i,Z:a}=e;if(r.eql(a,r.ONE))return{x:n,y:i};const o=e.is0();if(t==null)t=o?r.ONE:r.inv(a);const s=r.mul(n,t);const c=r.mul(i,t);const u=r.mul(a,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(u,r.ONE))throw new Error(`invZ was invalid`);return{x:s,y:c}});const _=memoized(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error(`bad point: ZERO`)}const{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw new Error(`bad point: x or y not field elements`);if(!isValidXY(n,i))throw new Error(`bad point: equation left != right`);if(!e.isTorsionFree())throw new Error(`bad point: not in prime-order subgroup`);return true});function finishEndo(e,t,n,i,a){n=new Point(r.mul(n.X,e),n.Y,n.Z);t=negateCt(i,t);n=negateCt(a,n);return t.add(n)}class Point{constructor(e,t,n){this.X=acoord(`x`,e);this.Y=acoord(`y`,t,true);this.Z=acoord(`z`,n);Object.freeze(this)}static CURVE(){return a}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error(`invalid affine point`);if(e instanceof Point)throw new Error(`projective point not allowed`);if(r.is0(t)&&r.is0(n))return Point.ZERO;return new Point(t,n,r.ONE)}static fromBytes(e){const t=Point.fromAffine(f(_abytes2(e,void 0,`point`)));t.assertValidity();return t}static fromHex(e){return Point.fromBytes(ensureBytes(`pointHex`,e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=true){y.createCache(this,e);if(!t)this.multiply(_3n);return this}assertValidity(){_(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error(`Field doesn't support isOdd`);return!r.isOdd(e)}equals(e){aprjpoint(e);const{X:t,Y:n,Z:i}=this;const{X:a,Y:o,Z:s}=e;const c=r.eql(r.mul(t,s),r.mul(a,i));const u=r.eql(r.mul(n,s),r.mul(o,i));return c&&u}negate(){return new Point(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=a;const n=r.mul(t,_3n);const{X:i,Y:o,Z:s}=this;let c=r.ZERO,u=r.ZERO,d=r.ZERO;let f=r.mul(i,i);let p=r.mul(o,o);let m=r.mul(s,s);let g=r.mul(i,o);g=r.add(g,g);d=r.mul(i,s);d=r.add(d,d);c=r.mul(e,d);u=r.mul(n,m);u=r.add(c,u);c=r.sub(p,u);u=r.add(p,u);u=r.mul(c,u);c=r.mul(g,c);d=r.mul(n,d);m=r.mul(e,m);g=r.sub(f,m);g=r.mul(e,g);g=r.add(g,d);d=r.add(f,f);f=r.add(d,f);f=r.add(f,m);f=r.mul(f,g);u=r.add(u,f);m=r.mul(o,s);m=r.add(m,m);f=r.mul(m,g);c=r.sub(c,f);d=r.mul(m,p);d=r.add(d,d);d=r.add(d,d);return new Point(c,u,d)}add(e){aprjpoint(e);const{X:t,Y:n,Z:i}=this;const{X:o,Y:s,Z:c}=e;let u=r.ZERO,d=r.ZERO,f=r.ZERO;const p=a.a;const m=r.mul(a.b,_3n);let g=r.mul(t,o);let _=r.mul(n,s);let v=r.mul(i,c);let y=r.add(t,n);let b=r.add(o,s);y=r.mul(y,b);b=r.add(g,_);y=r.sub(y,b);b=r.add(t,i);let x=r.add(o,c);b=r.mul(b,x);x=r.add(g,v);b=r.sub(b,x);x=r.add(n,i);u=r.add(s,c);x=r.mul(x,u);u=r.add(_,v);x=r.sub(x,u);f=r.mul(p,b);u=r.mul(m,v);f=r.add(u,f);u=r.sub(_,f);f=r.add(_,f);d=r.mul(u,f);_=r.add(g,g);_=r.add(_,g);v=r.mul(p,v);b=r.mul(m,b);_=r.add(_,v);v=r.sub(g,v);v=r.mul(p,v);b=r.add(b,v);g=r.mul(_,b);d=r.add(d,g);g=r.mul(x,b);u=r.mul(y,u);u=r.sub(u,g);g=r.mul(y,_);f=r.mul(x,f);f=r.add(f,g);return new Point(u,d,f)}subtract(e){return this.add(e.negate())}is0(){return this.equals(Point.ZERO)}multiply(e){const{endo:n}=t;if(!i.isValidNot0(e))throw new Error(`invalid scalar: out of range`);let r,a;const mul=e=>y.cached(this,e,e=>normalizeZ(Point,e));if(n){const{k1neg:t,k1:i,k2neg:o,k2:s}=splitEndoScalarN(e);const{p:c,f:u}=mul(i);const{p:d,f}=mul(s);a=u.add(f);r=finishEndo(n.beta,c,d,t,o)}else{const{p:t,f:n}=mul(e);r=t;a=n}return normalizeZ(Point,[r,a])[0]}multiplyUnsafe(e){const{endo:n}=t;const r=this;if(!i.isValid(e))throw new Error(`invalid scalar: out of range`);if(e===_0n||r.is0())return Point.ZERO;if(e===_1n)return r;if(y.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:i,k2neg:a,k2:o}=splitEndoScalarN(e);const{p1:s,p2:c}=mulEndoUnsafe(Point,r,i,o);return finishEndo(n.beta,s,c,t,a)}else return y.unsafe(r,e)}multiplyAndAddUnsafe(e,t,n){const r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return g(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;if(o===_1n)return true;if(e)return e(Point,this);return y.unsafe(this,s).is0()}clearCofactor(){const{clearCofactor:e}=t;if(o===_1n)return this;if(e)return e(Point,this);return this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=true){_abool2(e,`isCompressed`);this.assertValidity();return d(Point,this,e)}toHex(e=true){return bytesToHex(this.toBytes(e))}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=true){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return normalizeZ(Point,e)}static msm(e,t){return pippenger(Point,i,e,t)}static fromPrivateKey(e){return Point.BASE.multiply(_normFnElement(i,e))}}Point.BASE=new Point(a.Gx,a.Gy,r.ONE);Point.ZERO=new Point(r.ZERO,r.ONE,r.ZERO);Point.Fp=r;Point.Fn=i;const v=i.BITS;const y=new wNAF(Point,t.endo?Math.ceil(v/2):v);Point.BASE.precompute(8);return Point}function pprefix(e){return Uint8Array.of(e?2:3)}function getWLengths(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:true,signature:2*t.BYTES}}function ecdh(e,t={}){const{Fn:n}=e;const r=t.randomBytes||randomBytes$2;const i=Object.assign(getWLengths(e.Fp,n),{seed:getMinHashLength(n.ORDER)});function isValidSecretKey(e){try{return!!_normFnElement(n,e)}catch(e){return false}}function isValidPublicKey(t,n){const{publicKey:r,publicKeyUncompressed:a}=i;try{const i=t.length;if(n===true&&i!==r)return false;if(n===false&&i!==a)return false;return!!e.fromBytes(t)}catch(e){return false}}function randomSecretKey(e=r(i.seed)){return mapHashToField(_abytes2(e,i.seed,`seed`),n.ORDER)}function getPublicKey(t,r=true){return e.BASE.multiply(_normFnElement(n,t)).toBytes(r)}function keygen(e){const t=randomSecretKey(e);return{secretKey:t,publicKey:getPublicKey(t)}}function isProbPub(t){if(typeof t===`bigint`)return false;if(t instanceof e)return true;const{secretKey:r,publicKey:a,publicKeyUncompressed:o}=i;if(n.allowedLengths||r===a)return void 0;const s=ensureBytes(`key`,t).length;return s===a||s===o}function getSharedSecret(t,r,i=true){if(isProbPub(t)===true)throw new Error(`first arg must be private key`);if(isProbPub(r)===false)throw new Error(`second arg must be public key`);const a=_normFnElement(n,t);return e.fromHex(r).multiply(a).toBytes(i)}return Object.freeze({getPublicKey,getSharedSecret,keygen,Point:e,utils:{isValidSecretKey,isValidPublicKey,randomSecretKey,isValidPrivateKey:isValidSecretKey,randomPrivateKey:randomSecretKey,normPrivateKeyToScalar:e=>_normFnElement(n,e),precompute(t=8,n=e.BASE){return n.precompute(t,false)}},lengths:i})}function ecdsa(e,t,n={}){ahash(t);_validateObject(n,{},{hmac:`function`,lowS:`boolean`,randomBytes:`function`,bits2int:`function`,bits2int_modN:`function`});const r=n.randomBytes||randomBytes$2;const i=n.hmac||((e,...n)=>hmac$1(t,e,concatBytes(...n)));const{Fp:a,Fn:o}=e;const{ORDER:s,BITS:c}=o;const{keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:m}=ecdh(e,n);const g={prehash:false,lowS:typeof n.lowS===`boolean`?n.lowS:false,format:void 0,extraEntropy:false};const _=`compact`;function isBiggerThanHalfOrder(e){return e>s>>_1n}function validateRS(e,t){if(!o.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}function validateSigLength(e,t){validateSigFormat(t);const n=m.signature;const r=t===`compact`?n:t===`recovered`?n+1:void 0;return _abytes2(e,r,`${t} signature`)}class Signature{constructor(e,t,n){this.r=validateRS(`r`,e);this.s=validateRS(`s`,t);if(n!=null)this.recovery=n;Object.freeze(this)}static fromBytes(e,t=_){validateSigLength(e,t);let n;if(t===`der`){const{r:t,s:n}=DER.toSig(_abytes2(e));return new Signature(t,n)}if(t===`recovered`){n=e[0];t=`compact`;e=e.subarray(1)}const r=o.BYTES;const i=e.subarray(0,r);const a=e.subarray(r,r*2);return new Signature(o.fromBytes(i),o.fromBytes(a),n)}static fromHex(e,t){return this.fromBytes(hexToBytes(e),t)}addRecoveryBit(e){return new Signature(this.r,this.s,e)}recoverPublicKey(t){const n=a.ORDER;const{r,s:i,recovery:c}=this;if(c==null||![0,1,2,3].includes(c))throw new Error(`recovery id invalid`);if(s*_2n<n&&c>1)throw new Error(`recovery id is ambiguous for h>1 curve`);const u=c===2||c===3?r+s:r;if(!a.isValid(u))throw new Error(`recovery id 2 or 3 invalid`);const d=a.toBytes(u);const f=e.fromBytes(concatBytes(pprefix((c&1)===0),d));const p=o.inv(u);const m=y(ensureBytes(`msgHash`,t));const g=o.create(-m*p);const _=o.create(i*p);const v=e.BASE.multiplyUnsafe(g).add(f.multiplyUnsafe(_));if(v.is0())throw new Error(`point at infinify`);v.assertValidity();return v}hasHighS(){return isBiggerThanHalfOrder(this.s)}toBytes(e=_){validateSigFormat(e);if(e===`der`)return hexToBytes(DER.hexFromSig(this));const t=o.toBytes(this.r);const n=o.toBytes(this.s);if(e===`recovered`){if(this.recovery==null)throw new Error(`recovery bit must be present`);return concatBytes(Uint8Array.of(this.recovery),t,n)}return concatBytes(t,n)}toHex(e){return bytesToHex(this.toBytes(e))}assertValidity(){}static fromCompact(e){return Signature.fromBytes(ensureBytes(`sig`,e),`compact`)}static fromDER(e){return Signature.fromBytes(ensureBytes(`sig`,e),`der`)}normalizeS(){return this.hasHighS()?new Signature(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes(`der`)}toDERHex(){return bytesToHex(this.toBytes(`der`))}toCompactRawBytes(){return this.toBytes(`compact`)}toCompactHex(){return bytesToHex(this.toBytes(`compact`))}}const v=n.bits2int||function bits2int_def(e){if(e.length>8192)throw new Error(`input is too large`);const t=bytesToNumberBE(e);const n=e.length*8-c;return n>0?t>>BigInt(n):t};const y=n.bits2int_modN||function bits2int_modN_def(e){return o.create(v(e))};const b=bitMask(c);function int2octets(e){aInRange(`num < 2^`+c,e,_0n,b);return o.toBytes(e)}function validateMsgAndHash(e,n){_abytes2(e,void 0,`message`);return n?_abytes2(t(e),void 0,`prehashed message`):e}function prepSig(t,n,i){if([`recovered`,`canonical`].some(e=>e in i))throw new Error(`sign() legacy options not supported`);const{lowS:a,prehash:s,extraEntropy:c}=validateSigOpts(i,g);t=validateMsgAndHash(t,s);const u=y(t);const d=_normFnElement(o,n);const f=[int2octets(d),int2octets(u)];if(c!=null&&c!==false){const e=c===true?r(m.secretKey):c;f.push(ensureBytes(`extraEntropy`,e))}const p=concatBytes(...f);const _=u;function k2sig(t){const n=v(t);if(!o.isValidNot0(n))return;const r=o.inv(n);const i=e.BASE.multiply(n).toAffine();const s=o.create(i.x);if(s===_0n)return;const c=o.create(r*o.create(_+s*d));if(c===_0n)return;let u=(i.x===s?0:2)|Number(i.y&_1n);let f=c;if(a&&isBiggerThanHalfOrder(c)){f=o.neg(c);u^=1}return new Signature(s,f,u)}return{seed:p,k2sig}}function sign(e,n,r={}){e=ensureBytes(`message`,e);const{seed:a,k2sig:s}=prepSig(e,n,r);return createHmacDrbg(t.outputLen,o.BYTES,i)(a,s)}function tryParsingSig(e){let t=void 0;const n=typeof e===`string`||isBytes(e);const r=!n&&e!==null&&typeof e===`object`&&typeof e.r===`bigint`&&typeof e.s===`bigint`;if(!n&&!r)throw new Error(`invalid signature, expected Uint8Array, hex string or Signature instance`);if(r)t=new Signature(e.r,e.s);else if(n){try{t=Signature.fromBytes(ensureBytes(`sig`,e),`der`)}catch(e){if(!(e instanceof DER.Err))throw e}if(!t)try{t=Signature.fromBytes(ensureBytes(`sig`,e),`compact`)}catch(e){return false}}if(!t)return false;return t}function verify(t,n,r,i={}){const{lowS:a,prehash:s,format:c}=validateSigOpts(i,g);r=ensureBytes(`publicKey`,r);n=validateMsgAndHash(ensureBytes(`message`,n),s);if(`strict`in i)throw new Error(`options.strict was renamed to lowS`);const u=c===void 0?tryParsingSig(t):Signature.fromBytes(ensureBytes(`sig`,t),c);if(u===false)return false;try{const t=e.fromBytes(r);if(a&&u.hasHighS())return false;const{r:i,s}=u;const c=y(n);const d=o.inv(s);const f=o.create(c*d);const p=o.create(i*d);const m=e.BASE.multiplyUnsafe(f).add(t.multiplyUnsafe(p));if(m.is0())return false;return o.create(m.x)===i}catch(e){return false}}function recoverPublicKey(e,t,n={}){const{prehash:r}=validateSigOpts(n,g);t=validateMsgAndHash(t,r);return Signature.fromBytes(e,`recovered`).recoverPublicKey(t).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:m,Point:e,sign,verify,recoverPublicKey,Signature,hash:t})}function _weierstrass_legacy_opts_to_new(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy};const n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:Field(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}function _ecdsa_legacy_opts_to_new(e){const{CURVE:t,curveOpts:n}=_weierstrass_legacy_opts_to_new(e);const r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function _ecdsa_new_output_to_legacy(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,nLength(n.Fn.ORDER,n.Fn.BITS))})}function weierstrass(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=_ecdsa_legacy_opts_to_new(e);return _ecdsa_new_output_to_legacy(e,ecdsa(weierstrassN(t,n),r,i))}
//!node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/_shortw_utils.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function createCurve(e,t){const create=t=>weierstrass({...e,hash:t});return{...create(t),create}}
//!node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/nist.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const p256_CURVE={p:BigInt(`0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff`),n:BigInt(`0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551`),h:BigInt(1),a:BigInt(`0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc`),b:BigInt(`0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b`),Gx:BigInt(`0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296`),Gy:BigInt(`0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5`)};const p384_CURVE={p:BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff`),n:BigInt(`0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973`),h:BigInt(1),a:BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc`),b:BigInt(`0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef`),Gx:BigInt(`0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7`),Gy:BigInt(`0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f`)};const p521_CURVE={p:BigInt(`0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),n:BigInt(`0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409`),h:BigInt(1),a:BigInt(`0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc`),b:BigInt(`0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00`),Gx:BigInt(`0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66`),Gy:BigInt(`0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650`)};const Fp256=Field(p256_CURVE.p);const Fp384=Field(p384_CURVE.p);const Fp521=Field(p521_CURVE.p);const p256$1=createCurve({...p256_CURVE,Fp:Fp256,lowS:false},sha256);const p384=createCurve({...p384_CURVE,Fp:Fp384,lowS:false},sha384);const p521=createCurve({...p521_CURVE,Fp:Fp521,lowS:false,allowedPrivateKeyLengths:[130,131,132]},sha512);
//!node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/p256.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const p256=p256$1;
//!node_modules/.pnpm/dns-packet@5.6.1/node_modules/dns-packet/types.js
var require_types=/* @__PURE__ */ __commonJSMin((e=>{e.toString=function(e){switch(e){case 1:return`A`;case 10:return`NULL`;case 28:return`AAAA`;case 18:return`AFSDB`;case 42:return`APL`;case 257:return`CAA`;case 60:return`CDNSKEY`;case 59:return`CDS`;case 37:return`CERT`;case 5:return`CNAME`;case 49:return`DHCID`;case 32769:return`DLV`;case 39:return`DNAME`;case 48:return`DNSKEY`;case 43:return`DS`;case 55:return`HIP`;case 13:return`HINFO`;case 45:return`IPSECKEY`;case 25:return`KEY`;case 36:return`KX`;case 29:return`LOC`;case 15:return`MX`;case 35:return`NAPTR`;case 2:return`NS`;case 47:return`NSEC`;case 50:return`NSEC3`;case 51:return`NSEC3PARAM`;case 12:return`PTR`;case 46:return`RRSIG`;case 17:return`RP`;case 24:return`SIG`;case 6:return`SOA`;case 99:return`SPF`;case 33:return`SRV`;case 44:return`SSHFP`;case 32768:return`TA`;case 249:return`TKEY`;case 52:return`TLSA`;case 250:return`TSIG`;case 16:return`TXT`;case 252:return`AXFR`;case 251:return`IXFR`;case 41:return`OPT`;case 255:return`ANY`}return`UNKNOWN_`+e};e.toType=function(e){switch(e.toUpperCase()){case`A`:return 1;case`NULL`:return 10;case`AAAA`:return 28;case`AFSDB`:return 18;case`APL`:return 42;case`CAA`:return 257;case`CDNSKEY`:return 60;case`CDS`:return 59;case`CERT`:return 37;case`CNAME`:return 5;case`DHCID`:return 49;case`DLV`:return 32769;case`DNAME`:return 39;case`DNSKEY`:return 48;case`DS`:return 43;case`HIP`:return 55;case`HINFO`:return 13;case`IPSECKEY`:return 45;case`KEY`:return 25;case`KX`:return 36;case`LOC`:return 29;case`MX`:return 15;case`NAPTR`:return 35;case`NS`:return 2;case`NSEC`:return 47;case`NSEC3`:return 50;case`NSEC3PARAM`:return 51;case`PTR`:return 12;case`RRSIG`:return 46;case`RP`:return 17;case`SIG`:return 24;case`SOA`:return 6;case`SPF`:return 99;case`SRV`:return 33;case`SSHFP`:return 44;case`TA`:return 32768;case`TKEY`:return 249;case`TLSA`:return 52;case`TSIG`:return 250;case`TXT`:return 16;case`AXFR`:return 252;case`IXFR`:return 251;case`OPT`:return 41;case`ANY`:return 255;case`*`:return 255}if(e.toUpperCase().startsWith(`UNKNOWN_`))return parseInt(e.slice(8));return 0}}));
//!node_modules/.pnpm/dns-packet@5.6.1/node_modules/dns-packet/rcodes.js
var require_rcodes=/* @__PURE__ */ __commonJSMin((e=>{e.toString=function(e){switch(e){case 0:return`NOERROR`;case 1:return`FORMERR`;case 2:return`SERVFAIL`;case 3:return`NXDOMAIN`;case 4:return`NOTIMP`;case 5:return`REFUSED`;case 6:return`YXDOMAIN`;case 7:return`YXRRSET`;case 8:return`NXRRSET`;case 9:return`NOTAUTH`;case 10:return`NOTZONE`;case 11:return`RCODE_11`;case 12:return`RCODE_12`;case 13:return`RCODE_13`;case 14:return`RCODE_14`;case 15:return`RCODE_15`}return`RCODE_`+e};e.toRcode=function(e){switch(e.toUpperCase()){case`NOERROR`:return 0;case`FORMERR`:return 1;case`SERVFAIL`:return 2;case`NXDOMAIN`:return 3;case`NOTIMP`:return 4;case`REFUSED`:return 5;case`YXDOMAIN`:return 6;case`YXRRSET`:return 7;case`NXRRSET`:return 8;case`NOTAUTH`:return 9;case`NOTZONE`:return 10;case`RCODE_11`:return 11;case`RCODE_12`:return 12;case`RCODE_13`:return 13;case`RCODE_14`:return 14;case`RCODE_15`:return 15}return 0}}));
//!node_modules/.pnpm/dns-packet@5.6.1/node_modules/dns-packet/opcodes.js
var require_opcodes=/* @__PURE__ */ __commonJSMin((e=>{e.toString=function(e){switch(e){case 0:return`QUERY`;case 1:return`IQUERY`;case 2:return`STATUS`;case 3:return`OPCODE_3`;case 4:return`NOTIFY`;case 5:return`UPDATE`;case 6:return`OPCODE_6`;case 7:return`OPCODE_7`;case 8:return`OPCODE_8`;case 9:return`OPCODE_9`;case 10:return`OPCODE_10`;case 11:return`OPCODE_11`;case 12:return`OPCODE_12`;case 13:return`OPCODE_13`;case 14:return`OPCODE_14`;case 15:return`OPCODE_15`}return`OPCODE_`+e};e.toOpcode=function(e){switch(e.toUpperCase()){case`QUERY`:return 0;case`IQUERY`:return 1;case`STATUS`:return 2;case`OPCODE_3`:return 3;case`NOTIFY`:return 4;case`UPDATE`:return 5;case`OPCODE_6`:return 6;case`OPCODE_7`:return 7;case`OPCODE_8`:return 8;case`OPCODE_9`:return 9;case`OPCODE_10`:return 10;case`OPCODE_11`:return 11;case`OPCODE_12`:return 12;case`OPCODE_13`:return 13;case`OPCODE_14`:return 14;case`OPCODE_15`:return 15}return 0}}));
//!node_modules/.pnpm/dns-packet@5.6.1/node_modules/dns-packet/classes.js
var require_classes=/* @__PURE__ */ __commonJSMin((e=>{e.toString=function(e){switch(e){case 1:return`IN`;case 2:return`CS`;case 3:return`CH`;case 4:return`HS`;case 255:return`ANY`}return`UNKNOWN_`+e};e.toClass=function(e){switch(e.toUpperCase()){case`IN`:return 1;case`CS`:return 2;case`CH`:return 3;case`HS`:return 4;case`ANY`:return 255}return 0}}));
//!node_modules/.pnpm/dns-packet@5.6.1/node_modules/dns-packet/optioncodes.js
var require_optioncodes=/* @__PURE__ */ __commonJSMin((e=>{e.toString=function(e){switch(e){case 1:return`LLQ`;case 2:return`UL`;case 3:return`NSID`;case 5:return`DAU`;case 6:return`DHU`;case 7:return`N3U`;case 8:return`CLIENT_SUBNET`;case 9:return`EXPIRE`;case 10:return`COOKIE`;case 11:return`TCP_KEEPALIVE`;case 12:return`PADDING`;case 13:return`CHAIN`;case 14:return`KEY_TAG`;case 26946:return`DEVICEID`}if(e<0)return null;return`OPTION_${e}`};e.toCode=function(e){if(typeof e===`number`)return e;if(!e)return-1;switch(e.toUpperCase()){case`OPTION_0`:return 0;case`LLQ`:return 1;case`UL`:return 2;case`NSID`:return 3;case`OPTION_4`:return 4;case`DAU`:return 5;case`DHU`:return 6;case`N3U`:return 7;case`CLIENT_SUBNET`:return 8;case`EXPIRE`:return 9;case`COOKIE`:return 10;case`TCP_KEEPALIVE`:return 11;case`PADDING`:return 12;case`CHAIN`:return 13;case`KEY_TAG`:return 14;case`DEVICEID`:return 26946;case`OPTION_65535`:return 65535}const t=e.match(/_(\d+)$/);if(t)return parseInt(t[1],10);return-1}}));
//!node_modules/.pnpm/@leichtgewicht+ip-codec@2.0.5/node_modules/@leichtgewicht/ip-codec/index.cjs
var require_ip_codec=/* @__PURE__ */ __commonJSMin(((e,t)=>{var n=(function(e){"use strict";Object.defineProperty(e,"__esModule",{value:true});e.decode=decode;e.encode=encode;e.familyOf=familyOf;e.name=void 0;e.sizeOf=sizeOf;e.v6=e.v4=void 0;const t=/^(\d{1,3}\.){3,3}\d{1,3}$/;const n=4;const r=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;const i=16;const a={name:`v4`,size:n,isFormat:e=>t.test(e),encode(e,t,r){r=~~r;t=t||new Uint8Array(r+n);const i=e.length;let a=0;for(let n=0;n<i;){const i=e.charCodeAt(n++);if(i===46){t[r++]=a;a=0}else a=a*10+(i-48)}t[r]=a;return t},decode(e,t){t=~~t;return`${e[t++]}.${e[t++]}.${e[t++]}.${e[t]}`}};e.v4=a;const o={name:`v6`,size:i,isFormat:e=>e.length>0&&r.test(e),encode(e,t,n){n=~~n;let r=n+i;let a=-1;let o=0;let s=0;let c=true;let u=false;t=t||new Uint8Array(n+i);for(let i=0;i<e.length;i++){let d=e.charCodeAt(i);if(d===58){if(c){if(a!==-1){if(n<r)t[n]=0;if(n<r-1)t[n+1]=0;n+=2}else if(n<r)a=n}else{if(u===true){if(n<r)t[n]=s;n++}else{if(n<r)t[n]=o>>8;if(n<r-1)t[n+1]=o&255;n+=2}o=0;s=0}c=true;u=false}else if(d===46){if(n<r)t[n]=s;n++;s=0;o=0;c=false;u=true}else{c=false;if(d>=97)d-=87;else if(d>=65)d-=55;else{d-=48;s=s*10+d}o=(o<<4)+d}}if(c===false){if(u===true){if(n<r)t[n]=s;n++}else{if(n<r)t[n]=o>>8;if(n<r-1)t[n+1]=o&255;n+=2}}else if(a===0){if(n<r)t[n]=0;if(n<r-1)t[n+1]=0;n+=2}else if(a!==-1){n+=2;for(let e=Math.min(n-1,r-1);e>=a+2;e--)t[e]=t[e-2];t[a]=0;t[a+1]=0;a=n}if(a!==n&&a!==-1){if(n>r-2)n=r-2;while(r>a)t[--r]=n<r&&n>a?t[--n]:0}else while(n<r)t[n++]=0;return t},decode(e,t){t=~~t;let n=``;for(let r=0;r<i;r+=2){if(r!==0)n+=`:`;n+=(e[t+r]<<8|e[t+r+1]).toString(16)}return n.replace(/(^|:)0(:0)*:0(:|$)/,`$1::$3`).replace(/:{3,4}/,`::`)}};e.v6=o;e.name=`ip`;function sizeOf(e){if(a.isFormat(e))return a.size;if(o.isFormat(e))return o.size;throw Error(`Invalid ip address: ${e}`)}function familyOf(e){return sizeOf(e)===a.size?1:2}function encode(e,t,n){n=~~n;const r=sizeOf(e);if(typeof t===`function`)t=t(n+r);if(r===a.size)return a.encode(e,t,n);return o.encode(e,t,n)}function decode(e,t,n){t=~~t;n=n||e.length-t;if(n===a.size)return a.decode(e,t,n);if(n===o.size)return o.decode(e,t,n);throw Error(`Invalid buffer size needs to be ${a.size} for v4 or ${o.size} for v6.`)}return`default`in e?e.default:e})({});if(typeof define===`function`&&define.amd)define([],function(){return n});else if(typeof t===`object`&&typeof e===`object`)t.exports=n}));
//!node_modules/.pnpm/dns-packet@5.6.1/node_modules/dns-packet/index.js
var require_dns_packet=/* @__PURE__ */ __commonJSMin((e=>{const t=__require(`buffer`).Buffer;const n=require_types();const r=require_rcodes();const i=require_opcodes();const a=require_classes();const o=require_optioncodes();const s=require_ip_codec();const c=0;const u=32768;const d=32768;const f=-32769;const p=32768;const m=-32769;const g=e.name={};g.encode=function(e,n,r,{mail:i=false}={}){if(!n)n=t.alloc(g.encodingLength(e));if(!r)r=0;const a=r;const o=e.replace(/^\.|\.$/gm,``);if(o.length){let e=[];if(i){let t=``;o.split(`.`).forEach(n=>{if(n.endsWith(`\\`))t+=(t.length?`.`:``)+n.slice(0,-1);else if(e.length===0&&t.length)e.push(t+`.`+n);else e.push(n)})}else e=o.split(`.`);for(let t=0;t<e.length;t++){const i=n.write(e[t],r+1);n[r]=i;r+=i+1}}n[r++]=0;g.encode.bytes=r-a;return n};g.encode.bytes=0;g.decode=function(e,t,{mail:n=false}={}){if(!t)t=0;const r=[];let i=t;let a=0;let o=0;let s=false;while(true){if(t>=e.length)throw new Error(`Cannot decode name (buffer overflow)`);const c=e[t++];o+=s?0:1;if(c===0)break;else if((c&192)===0){if(t+c>e.length)throw new Error(`Cannot decode name (buffer overflow)`);a+=c+1;if(a>254)throw new Error(`Cannot decode name (name too long)`);let i=e.toString(`utf-8`,t,t+c);if(n)i=i.replace(/\./g,`\\.`);r.push(i);t+=c;o+=s?0:c}else if((c&192)===192){if(t+1>e.length)throw new Error(`Cannot decode name (buffer overflow)`);const n=e.readUInt16BE(t-1)-49152;if(n>=i)throw new Error(`Cannot decode name (bad pointer)`);t=n;i=n;o+=s?0:1;s=true}else throw new Error(`Cannot decode name (bad label)`)}g.decode.bytes=o;return r.length===0?`.`:r.join(`.`)};g.decode.bytes=0;g.encodingLength=function(e){if(e===`.`||e===`..`)return 1;return t.byteLength(e.replace(/^\.|\.$/gm,``))+2};const _={};_.encode=function(e,n,r){if(!n)n=t.alloc(_.encodingLength(e));if(!r)r=0;const i=n.write(e,r+1);n[r]=i;_.encode.bytes=i+1;return n};_.encode.bytes=0;_.decode=function(e,t){if(!t)t=0;const n=e[t];const r=e.toString(`utf-8`,t+1,t+1+n);_.decode.bytes=n+1;return r};_.decode.bytes=0;_.encodingLength=function(e){return t.byteLength(e)+1};const v={};v.encode=function(e,t,n){if(!t)t=v.encodingLength(e);if(!n)n=0;const r=(e.flags||0)&32767;const i=e.type===`response`?u:c;t.writeUInt16BE(e.id||0,n);t.writeUInt16BE(r|i,n+2);t.writeUInt16BE(e.questions.length,n+4);t.writeUInt16BE(e.answers.length,n+6);t.writeUInt16BE(e.authorities.length,n+8);t.writeUInt16BE(e.additionals.length,n+10);return t};v.encode.bytes=12;v.decode=function(e,t){if(!t)t=0;if(e.length<12)throw new Error(`Header must be 12 bytes`);const n=e.readUInt16BE(t+2);return{id:e.readUInt16BE(t),type:n&u?`response`:`query`,flags:n&32767,flag_qr:(n>>15&1)===1,opcode:i.toString(n>>11&15),flag_aa:(n>>10&1)===1,flag_tc:(n>>9&1)===1,flag_rd:(n>>8&1)===1,flag_ra:(n>>7&1)===1,flag_z:(n>>6&1)===1,flag_ad:(n>>5&1)===1,flag_cd:(n>>4&1)===1,rcode:r.toString(n&15),questions:new Array(e.readUInt16BE(t+4)),answers:new Array(e.readUInt16BE(t+6)),authorities:new Array(e.readUInt16BE(t+8)),additionals:new Array(e.readUInt16BE(t+10))}};v.decode.bytes=12;v.encodingLength=function(){return 12};const y=e.unknown={};y.encode=function(e,n,r){if(!n)n=t.alloc(y.encodingLength(e));if(!r)r=0;n.writeUInt16BE(e.length,r);e.copy(n,r+2);y.encode.bytes=e.length+2;return n};y.encode.bytes=0;y.decode=function(e,t){if(!t)t=0;const n=e.readUInt16BE(t);const r=e.slice(t+2,t+2+n);y.decode.bytes=n+2;return r};y.decode.bytes=0;y.encodingLength=function(e){return e.length+2};const b=e.ns={};b.encode=function(e,n,r){if(!n)n=t.alloc(b.encodingLength(e));if(!r)r=0;g.encode(e,n,r+2);n.writeUInt16BE(g.encode.bytes,r);b.encode.bytes=g.encode.bytes+2;return n};b.encode.bytes=0;b.decode=function(e,t){if(!t)t=0;const n=e.readUInt16BE(t);const r=g.decode(e,t+2);b.decode.bytes=n+2;return r};b.decode.bytes=0;b.encodingLength=function(e){return g.encodingLength(e)+2};const x=e.soa={};x.encode=function(e,n,r){if(!n)n=t.alloc(x.encodingLength(e));if(!r)r=0;const i=r;r+=2;g.encode(e.mname,n,r);r+=g.encode.bytes;g.encode(e.rname,n,r,{mail:true});r+=g.encode.bytes;n.writeUInt32BE(e.serial||0,r);r+=4;n.writeUInt32BE(e.refresh||0,r);r+=4;n.writeUInt32BE(e.retry||0,r);r+=4;n.writeUInt32BE(e.expire||0,r);r+=4;n.writeUInt32BE(e.minimum||0,r);r+=4;n.writeUInt16BE(r-i-2,i);x.encode.bytes=r-i;return n};x.encode.bytes=0;x.decode=function(e,t){if(!t)t=0;const n=t;const r={};t+=2;r.mname=g.decode(e,t);t+=g.decode.bytes;r.rname=g.decode(e,t,{mail:true});t+=g.decode.bytes;r.serial=e.readUInt32BE(t);t+=4;r.refresh=e.readUInt32BE(t);t+=4;r.retry=e.readUInt32BE(t);t+=4;r.expire=e.readUInt32BE(t);t+=4;r.minimum=e.readUInt32BE(t);t+=4;x.decode.bytes=t-n;return r};x.decode.bytes=0;x.encodingLength=function(e){return 22+g.encodingLength(e.mname)+g.encodingLength(e.rname)};const C=e.txt={};C.encode=function(e,n,r){if(!Array.isArray(e))e=[e];for(let n=0;n<e.length;n++){if(typeof e[n]===`string`)e[n]=t.from(e[n]);if(!t.isBuffer(e[n]))throw new Error(`Must be a Buffer`)}if(!n)n=t.alloc(C.encodingLength(e));if(!r)r=0;const i=r;r+=2;e.forEach(function(e){n[r++]=e.length;e.copy(n,r,0,e.length);r+=e.length});n.writeUInt16BE(r-i-2,i);C.encode.bytes=r-i;return n};C.encode.bytes=0;C.decode=function(e,t){if(!t)t=0;const n=t;let r=e.readUInt16BE(t);t+=2;let i=[];while(r>0){const n=e[t++];--r;if(r<n)throw new Error(`Buffer overflow`);i.push(e.slice(t,t+n));t+=n;r-=n}C.decode.bytes=t-n;return i};C.decode.bytes=0;C.encodingLength=function(e){if(!Array.isArray(e))e=[e];let n=2;e.forEach(function(e){if(typeof e===`string`)n+=t.byteLength(e)+1;else n+=e.length+1});return n};const w=e.null={};w.encode=function(e,n,r){if(!n)n=t.alloc(w.encodingLength(e));if(!r)r=0;if(typeof e===`string`)e=t.from(e);if(!e)e=t.alloc(0);const i=r;r+=2;const a=e.length;e.copy(n,r,0,a);r+=a;n.writeUInt16BE(r-i-2,i);w.encode.bytes=r-i;return n};w.encode.bytes=0;w.decode=function(e,t){if(!t)t=0;const n=t;const r=e.readUInt16BE(t);t+=2;const i=e.slice(t,t+r);t+=r;w.decode.bytes=t-n;return i};w.decode.bytes=0;w.encodingLength=function(e){if(!e)return 2;return(t.isBuffer(e)?e.length:t.byteLength(e))+2};const T=e.hinfo={};T.encode=function(e,n,r){if(!n)n=t.alloc(T.encodingLength(e));if(!r)r=0;const i=r;r+=2;_.encode(e.cpu,n,r);r+=_.encode.bytes;_.encode(e.os,n,r);r+=_.encode.bytes;n.writeUInt16BE(r-i-2,i);T.encode.bytes=r-i;return n};T.encode.bytes=0;T.decode=function(e,t){if(!t)t=0;const n=t;const r={};t+=2;r.cpu=_.decode(e,t);t+=_.decode.bytes;r.os=_.decode(e,t);t+=_.decode.bytes;T.decode.bytes=t-n;return r};T.decode.bytes=0;T.encodingLength=function(e){return _.encodingLength(e.cpu)+_.encodingLength(e.os)+2};const E=e.ptr={};const D=e.cname=E;const O=e.dname=E;E.encode=function(e,n,r){if(!n)n=t.alloc(E.encodingLength(e));if(!r)r=0;g.encode(e,n,r+2);n.writeUInt16BE(g.encode.bytes,r);E.encode.bytes=g.encode.bytes+2;return n};E.encode.bytes=0;E.decode=function(e,t){if(!t)t=0;const n=g.decode(e,t+2);E.decode.bytes=g.decode.bytes+2;return n};E.decode.bytes=0;E.encodingLength=function(e){return g.encodingLength(e)+2};const k=e.srv={};k.encode=function(e,n,r){if(!n)n=t.alloc(k.encodingLength(e));if(!r)r=0;n.writeUInt16BE(e.priority||0,r+2);n.writeUInt16BE(e.weight||0,r+4);n.writeUInt16BE(e.port||0,r+6);g.encode(e.target,n,r+8);const i=g.encode.bytes+6;n.writeUInt16BE(i,r);k.encode.bytes=i+2;return n};k.encode.bytes=0;k.decode=function(e,t){if(!t)t=0;const n=e.readUInt16BE(t);const r={};r.priority=e.readUInt16BE(t+2);r.weight=e.readUInt16BE(t+4);r.port=e.readUInt16BE(t+6);r.target=g.decode(e,t+8);k.decode.bytes=n+2;return r};k.decode.bytes=0;k.encodingLength=function(e){return 8+g.encodingLength(e.target)};const j=e.caa={};j.ISSUER_CRITICAL=128;j.encode=function(e,n,r){const i=j.encodingLength(e);if(!n)n=t.alloc(j.encodingLength(e));if(!r)r=0;if(e.issuerCritical)e.flags=j.ISSUER_CRITICAL;n.writeUInt16BE(i-2,r);r+=2;n.writeUInt8(e.flags||0,r);r+=1;_.encode(e.tag,n,r);r+=_.encode.bytes;n.write(e.value,r);r+=t.byteLength(e.value);j.encode.bytes=i;return n};j.encode.bytes=0;j.decode=function(e,t){if(!t)t=0;const n=e.readUInt16BE(t);t+=2;const r=t;const i={};i.flags=e.readUInt8(t);t+=1;i.tag=_.decode(e,t);t+=_.decode.bytes;i.value=e.toString(`utf-8`,t,r+n);i.issuerCritical=!!(i.flags&j.ISSUER_CRITICAL);j.decode.bytes=n+2;return i};j.decode.bytes=0;j.encodingLength=function(e){return _.encodingLength(e.tag)+_.encodingLength(e.value)+2};const N=e.mx={};N.encode=function(e,n,r){if(!n)n=t.alloc(N.encodingLength(e));if(!r)r=0;const i=r;r+=2;n.writeUInt16BE(e.preference||0,r);r+=2;g.encode(e.exchange,n,r);r+=g.encode.bytes;n.writeUInt16BE(r-i-2,i);N.encode.bytes=r-i;return n};N.encode.bytes=0;N.decode=function(e,t){if(!t)t=0;const n=t;const r={};t+=2;r.preference=e.readUInt16BE(t);t+=2;r.exchange=g.decode(e,t);t+=g.decode.bytes;N.decode.bytes=t-n;return r};N.encodingLength=function(e){return 4+g.encodingLength(e.exchange)};const P=e.a={};P.encode=function(e,n,r){if(!n)n=t.alloc(P.encodingLength(e));if(!r)r=0;n.writeUInt16BE(4,r);r+=2;s.v4.encode(e,n,r);P.encode.bytes=6;return n};P.encode.bytes=0;P.decode=function(e,t){if(!t)t=0;t+=2;const n=s.v4.decode(e,t);P.decode.bytes=6;return n};P.decode.bytes=0;P.encodingLength=function(){return 6};const F=e.aaaa={};F.encode=function(e,n,r){if(!n)n=t.alloc(F.encodingLength(e));if(!r)r=0;n.writeUInt16BE(16,r);r+=2;s.v6.encode(e,n,r);F.encode.bytes=18;return n};F.encode.bytes=0;F.decode=function(e,t){if(!t)t=0;t+=2;const n=s.v6.decode(e,t);F.decode.bytes=18;return n};F.decode.bytes=0;F.encodingLength=function(){return 18};const I=e.option={};I.encode=function(e,n,r){if(!n)n=t.alloc(I.encodingLength(e));if(!r)r=0;const i=r;const a=o.toCode(e.code);n.writeUInt16BE(a,r);r+=2;if(e.data){n.writeUInt16BE(e.data.length,r);r+=2;e.data.copy(n,r);r+=e.data.length}else switch(a){case 8:const i=e.sourcePrefixLength||0;const a=e.family||s.familyOf(e.ip);const o=s.encode(e.ip,t.alloc);const c=Math.ceil(i/8);n.writeUInt16BE(c+4,r);r+=2;n.writeUInt16BE(a,r);r+=2;n.writeUInt8(i,r++);n.writeUInt8(e.scopePrefixLength||0,r++);o.copy(n,r,0,c);r+=c;break;case 11:if(e.timeout){n.writeUInt16BE(2,r);r+=2;n.writeUInt16BE(e.timeout,r);r+=2}else{n.writeUInt16BE(0,r);r+=2}break;case 12:const u=e.length||0;n.writeUInt16BE(u,r);r+=2;n.fill(0,r,r+u);r+=u;break;case 14:const d=e.tags.length*2;n.writeUInt16BE(d,r);r+=2;for(const t of e.tags){n.writeUInt16BE(t,r);r+=2}break;default:throw new Error(`Unknown roption code: ${e.code}`)}I.encode.bytes=r-i;return n};I.encode.bytes=0;I.decode=function(e,n){if(!n)n=0;const r={};r.code=e.readUInt16BE(n);r.type=o.toString(r.code);n+=2;const i=e.readUInt16BE(n);n+=2;r.data=e.slice(n,n+i);switch(r.code){case 8:r.family=e.readUInt16BE(n);n+=2;r.sourcePrefixLength=e.readUInt8(n++);r.scopePrefixLength=e.readUInt8(n++);const a=t.alloc(r.family===1?4:16);e.copy(a,0,n,n+i-4);r.ip=s.decode(a);break;case 11:if(i>0){r.timeout=e.readUInt16BE(n);n+=2}break;case 14:r.tags=[];for(let t=0;t<i;t+=2){r.tags.push(e.readUInt16BE(n));n+=2}}I.decode.bytes=i+4;return r};I.decode.bytes=0;I.encodingLength=function(e){if(e.data)return e.data.length+4;switch(o.toCode(e.code)){case 8:const t=e.sourcePrefixLength||0;return Math.ceil(t/8)+8;case 11:return typeof e.timeout===`number`?6:4;case 12:return e.length+4;case 14:return 4+e.tags.length*2}throw new Error(`Unknown roption code: ${e.code}`)};const L=e.opt={};L.encode=function(e,n,r){if(!n)n=t.alloc(L.encodingLength(e));if(!r)r=0;const i=r;const a=encodingLengthList(e,I);n.writeUInt16BE(a,r);r=encodeList(e,I,n,r+2);L.encode.bytes=r-i;return n};L.encode.bytes=0;L.decode=function(e,t){if(!t)t=0;const n=t;const r=[];let i=e.readUInt16BE(t);t+=2;let a=0;while(i>0){r[a++]=I.decode(e,t);t+=I.decode.bytes;i-=I.decode.bytes}L.decode.bytes=t-n;return r};L.decode.bytes=0;L.encodingLength=function(e){return 2+encodingLengthList(e||[],I)};const R=e.dnskey={};R.PROTOCOL_DNSSEC=3;R.ZONE_KEY=128;R.SECURE_ENTRYPOINT=32768;R.encode=function(e,n,r){if(!n)n=t.alloc(R.encodingLength(e));if(!r)r=0;const i=r;const a=e.key;if(!t.isBuffer(a))throw new Error(`Key must be a Buffer`);r+=2;n.writeUInt16BE(e.flags,r);r+=2;n.writeUInt8(R.PROTOCOL_DNSSEC,r);r+=1;n.writeUInt8(e.algorithm,r);r+=1;a.copy(n,r,0,a.length);r+=a.length;R.encode.bytes=r-i;n.writeUInt16BE(R.encode.bytes-2,i);return n};R.encode.bytes=0;R.decode=function(e,t){if(!t)t=0;const n=t;var r={};var i=e.readUInt16BE(t);t+=2;r.flags=e.readUInt16BE(t);t+=2;if(e.readUInt8(t)!==R.PROTOCOL_DNSSEC)throw new Error(`Protocol must be 3`);t+=1;r.algorithm=e.readUInt8(t);t+=1;r.key=e.slice(t,n+i+2);t+=r.key.length;R.decode.bytes=t-n;return r};R.decode.bytes=0;R.encodingLength=function(e){return 6+t.byteLength(e.key)};const z=e.rrsig={};z.encode=function(e,r,i){if(!r)r=t.alloc(z.encodingLength(e));if(!i)i=0;const a=i;const o=e.signature;if(!t.isBuffer(o))throw new Error(`Signature must be a Buffer`);i+=2;r.writeUInt16BE(n.toType(e.typeCovered),i);i+=2;r.writeUInt8(e.algorithm,i);i+=1;r.writeUInt8(e.labels,i);i+=1;r.writeUInt32BE(e.originalTTL,i);i+=4;r.writeUInt32BE(e.expiration,i);i+=4;r.writeUInt32BE(e.inception,i);i+=4;r.writeUInt16BE(e.keyTag,i);i+=2;g.encode(e.signersName,r,i);i+=g.encode.bytes;o.copy(r,i,0,o.length);i+=o.length;z.encode.bytes=i-a;r.writeUInt16BE(z.encode.bytes-2,a);return r};z.encode.bytes=0;z.decode=function(e,t){if(!t)t=0;const r=t;var i={};var a=e.readUInt16BE(t);t+=2;i.typeCovered=n.toString(e.readUInt16BE(t));t+=2;i.algorithm=e.readUInt8(t);t+=1;i.labels=e.readUInt8(t);t+=1;i.originalTTL=e.readUInt32BE(t);t+=4;i.expiration=e.readUInt32BE(t);t+=4;i.inception=e.readUInt32BE(t);t+=4;i.keyTag=e.readUInt16BE(t);t+=2;i.signersName=g.decode(e,t);t+=g.decode.bytes;i.signature=e.slice(t,r+a+2);t+=i.signature.length;z.decode.bytes=t-r;return i};z.decode.bytes=0;z.encodingLength=function(e){return 20+g.encodingLength(e.signersName)+t.byteLength(e.signature)};const B=e.rp={};B.encode=function(e,n,r){if(!n)n=t.alloc(B.encodingLength(e));if(!r)r=0;const i=r;r+=2;g.encode(e.mbox||`.`,n,r,{mail:true});r+=g.encode.bytes;g.encode(e.txt||`.`,n,r);r+=g.encode.bytes;B.encode.bytes=r-i;n.writeUInt16BE(B.encode.bytes-2,i);return n};B.encode.bytes=0;B.decode=function(e,t){if(!t)t=0;const n=t;const r={};t+=2;r.mbox=g.decode(e,t,{mail:true})||`.`;t+=g.decode.bytes;r.txt=g.decode(e,t)||`.`;t+=g.decode.bytes;B.decode.bytes=t-n;return r};B.decode.bytes=0;B.encodingLength=function(e){return 2+g.encodingLength(e.mbox||`.`)+g.encodingLength(e.txt||`.`)};const V={};V.encode=function(e,r,i){if(!r)r=t.alloc(V.encodingLength(e));if(!i)i=0;const a=i;var o=[];for(var s=0;s<e.length;s++){var c=n.toType(e[s]);if(o[c>>8]===void 0)o[c>>8]=[];o[c>>8][c>>3&31]|=1<<7-(c&7)}for(s=0;s<o.length;s++)if(o[s]!==void 0){var u=t.from(o[s]);r.writeUInt8(s,i);i+=1;r.writeUInt8(u.length,i);i+=1;u.copy(r,i);i+=u.length}V.encode.bytes=i-a;return r};V.encode.bytes=0;V.decode=function(e,t,r){if(!t)t=0;const i=t;var a=[];while(t-i<r){var o=e.readUInt8(t);t+=1;var s=e.readUInt8(t);t+=1;for(var c=0;c<s;c++){var u=e.readUInt8(t+c);for(var d=0;d<8;d++)if(u&1<<7-d){var f=n.toString(o<<8|c<<3|d);a.push(f)}}t+=s}V.decode.bytes=t-i;return a};V.decode.bytes=0;V.encodingLength=function(e){var t=[];for(var r=0;r<e.length;r++){var i=n.toType(e[r]);t[i>>8]=Math.max(t[i>>8]||0,i&255)}var a=0;for(r=0;r<t.length;r++)if(t[r]!==void 0)a+=2+Math.ceil((t[r]+1)/8);return a};const H=e.nsec={};H.encode=function(e,n,r){if(!n)n=t.alloc(H.encodingLength(e));if(!r)r=0;const i=r;r+=2;g.encode(e.nextDomain,n,r);r+=g.encode.bytes;V.encode(e.rrtypes,n,r);r+=V.encode.bytes;H.encode.bytes=r-i;n.writeUInt16BE(H.encode.bytes-2,i);return n};H.encode.bytes=0;H.decode=function(e,t){if(!t)t=0;const n=t;var r={};var i=e.readUInt16BE(t);t+=2;r.nextDomain=g.decode(e,t);t+=g.decode.bytes;r.rrtypes=V.decode(e,t,i-(t-n));t+=V.decode.bytes;H.decode.bytes=t-n;return r};H.decode.bytes=0;H.encodingLength=function(e){return 2+g.encodingLength(e.nextDomain)+V.encodingLength(e.rrtypes)};const U=e.nsec3={};U.encode=function(e,n,r){if(!n)n=t.alloc(U.encodingLength(e));if(!r)r=0;const i=r;const a=e.salt;if(!t.isBuffer(a))throw new Error(`salt must be a Buffer`);const o=e.nextDomain;if(!t.isBuffer(o))throw new Error(`nextDomain must be a Buffer`);r+=2;n.writeUInt8(e.algorithm,r);r+=1;n.writeUInt8(e.flags,r);r+=1;n.writeUInt16BE(e.iterations,r);r+=2;n.writeUInt8(a.length,r);r+=1;a.copy(n,r,0,a.length);r+=a.length;n.writeUInt8(o.length,r);r+=1;o.copy(n,r,0,o.length);r+=o.length;V.encode(e.rrtypes,n,r);r+=V.encode.bytes;U.encode.bytes=r-i;n.writeUInt16BE(U.encode.bytes-2,i);return n};U.encode.bytes=0;U.decode=function(e,t){if(!t)t=0;const n=t;var r={};var i=e.readUInt16BE(t);t+=2;r.algorithm=e.readUInt8(t);t+=1;r.flags=e.readUInt8(t);t+=1;r.iterations=e.readUInt16BE(t);t+=2;const a=e.readUInt8(t);t+=1;r.salt=e.slice(t,t+a);t+=a;const o=e.readUInt8(t);t+=1;r.nextDomain=e.slice(t,t+o);t+=o;r.rrtypes=V.decode(e,t,i-(t-n));t+=V.decode.bytes;U.decode.bytes=t-n;return r};U.decode.bytes=0;U.encodingLength=function(e){return 8+e.salt.length+e.nextDomain.length+V.encodingLength(e.rrtypes)};const W=e.ds={};W.encode=function(e,n,r){if(!n)n=t.alloc(W.encodingLength(e));if(!r)r=0;const i=r;const a=e.digest;if(!t.isBuffer(a))throw new Error(`Digest must be a Buffer`);r+=2;n.writeUInt16BE(e.keyTag,r);r+=2;n.writeUInt8(e.algorithm,r);r+=1;n.writeUInt8(e.digestType,r);r+=1;a.copy(n,r,0,a.length);r+=a.length;W.encode.bytes=r-i;n.writeUInt16BE(W.encode.bytes-2,i);return n};W.encode.bytes=0;W.decode=function(e,t){if(!t)t=0;const n=t;var r={};var i=e.readUInt16BE(t);t+=2;r.keyTag=e.readUInt16BE(t);t+=2;r.algorithm=e.readUInt8(t);t+=1;r.digestType=e.readUInt8(t);t+=1;r.digest=e.slice(t,n+i+2);t+=r.digest.length;W.decode.bytes=t-n;return r};W.decode.bytes=0;W.encodingLength=function(e){return 6+t.byteLength(e.digest)};const G=e.sshfp={};G.getFingerprintLengthForHashType=function getFingerprintLengthForHashType(e){switch(e){case 1:return 20;case 2:return 32}};G.encode=function encode(e,n,r){if(!n)n=t.alloc(G.encodingLength(e));if(!r)r=0;const i=r;r+=2;n[r]=e.algorithm;r+=1;n[r]=e.hash;r+=1;const a=t.from(e.fingerprint.toUpperCase(),`hex`);if(a.length!==G.getFingerprintLengthForHashType(e.hash))throw new Error(`Invalid fingerprint length`);a.copy(n,r);r+=a.byteLength;G.encode.bytes=r-i;n.writeUInt16BE(G.encode.bytes-2,i);return n};G.encode.bytes=0;G.decode=function decode(e,t){if(!t)t=0;const n=t;const r={};t+=2;r.algorithm=e[t];t+=1;r.hash=e[t];t+=1;const i=G.getFingerprintLengthForHashType(r.hash);r.fingerprint=e.slice(t,t+i).toString(`hex`).toUpperCase();t+=i;G.decode.bytes=t-n;return r};G.decode.bytes=0;G.encodingLength=function(e){return 4+t.from(e.fingerprint,`hex`).byteLength};const K=e.naptr={};K.encode=function(e,n,r){if(!n)n=t.alloc(K.encodingLength(e));if(!r)r=0;const i=r;r+=2;n.writeUInt16BE(e.order||0,r);r+=2;n.writeUInt16BE(e.preference||0,r);r+=2;_.encode(e.flags,n,r);r+=_.encode.bytes;_.encode(e.services,n,r);r+=_.encode.bytes;_.encode(e.regexp,n,r);r+=_.encode.bytes;g.encode(e.replacement,n,r);r+=g.encode.bytes;K.encode.bytes=r-i;n.writeUInt16BE(K.encode.bytes-2,i);return n};K.encode.bytes=0;K.decode=function(e,t){if(!t)t=0;const n=t;const r={};t+=2;r.order=e.readUInt16BE(t);t+=2;r.preference=e.readUInt16BE(t);t+=2;r.flags=_.decode(e,t);t+=_.decode.bytes;r.services=_.decode(e,t);t+=_.decode.bytes;r.regexp=_.decode(e,t);t+=_.decode.bytes;r.replacement=g.decode(e,t);t+=g.decode.bytes;K.decode.bytes=t-n;return r};K.decode.bytes=0;K.encodingLength=function(e){return _.encodingLength(e.flags)+_.encodingLength(e.services)+_.encodingLength(e.regexp)+g.encodingLength(e.replacement)+6};const q=e.tlsa={};q.encode=function(e,n,r){if(!n)n=t.alloc(q.encodingLength(e));if(!r)r=0;const i=r;const a=e.certificate;if(!t.isBuffer(a))throw new Error(`Certificate must be a Buffer`);r+=2;n.writeUInt8(e.usage,r);r+=1;n.writeUInt8(e.selector,r);r+=1;n.writeUInt8(e.matchingType,r);r+=1;a.copy(n,r,0,a.length);r+=a.length;q.encode.bytes=r-i;n.writeUInt16BE(q.encode.bytes-2,i);return n};q.encode.bytes=0;q.decode=function(e,t){if(!t)t=0;const n=t;const r={};const i=e.readUInt16BE(t);t+=2;r.usage=e.readUInt8(t);t+=1;r.selector=e.readUInt8(t);t+=1;r.matchingType=e.readUInt8(t);t+=1;r.certificate=e.slice(t,n+i+2);t+=r.certificate.length;q.decode.bytes=t-n;return r};q.decode.bytes=0;q.encodingLength=function(e){return 5+t.byteLength(e.certificate)};const J=e.record=function(e){switch(e.toUpperCase()){case`A`:return P;case`PTR`:return E;case`CNAME`:return D;case`DNAME`:return O;case`TXT`:return C;case`NULL`:return w;case`AAAA`:return F;case`SRV`:return k;case`HINFO`:return T;case`CAA`:return j;case`NS`:return b;case`SOA`:return x;case`MX`:return N;case`OPT`:return L;case`DNSKEY`:return R;case`RRSIG`:return z;case`RP`:return B;case`NSEC`:return H;case`NSEC3`:return U;case`SSHFP`:return G;case`DS`:return W;case`NAPTR`:return K;case`TLSA`:return q}return y};const Y=e.answer={};Y.encode=function(e,r,i){if(!r)r=t.alloc(Y.encodingLength(e));if(!i)i=0;const o=i;g.encode(e.name,r,i);i+=g.encode.bytes;r.writeUInt16BE(n.toType(e.type),i);if(e.type.toUpperCase()===`OPT`){if(e.name!==`.`)throw new Error(`OPT name must be root.`);r.writeUInt16BE(e.udpPayloadSize||4096,i+2);r.writeUInt8(e.extendedRcode||0,i+4);r.writeUInt8(e.ednsVersion||0,i+5);r.writeUInt16BE(e.flags||0,i+6);i+=8;L.encode(e.options||[],r,i);i+=L.encode.bytes}else{let t=a.toClass(e.class===void 0?`IN`:e.class);if(e.flush)t|=d;r.writeUInt16BE(t,i+2);r.writeUInt32BE(e.ttl||0,i+4);i+=8;const n=J(e.type);n.encode(e.data,r,i);i+=n.encode.bytes}Y.encode.bytes=i-o;return r};Y.encode.bytes=0;Y.decode=function(e,t){if(!t)t=0;const r={};const i=t;r.name=g.decode(e,t);t+=g.decode.bytes;r.type=n.toString(e.readUInt16BE(t));if(r.type===`OPT`){r.udpPayloadSize=e.readUInt16BE(t+2);r.extendedRcode=e.readUInt8(t+4);r.ednsVersion=e.readUInt8(t+5);r.flags=e.readUInt16BE(t+6);r.flag_do=(r.flags>>15&1)===1;r.options=L.decode(e,t+8);t+=8+L.decode.bytes}else{const n=e.readUInt16BE(t+2);r.ttl=e.readUInt32BE(t+4);r.class=a.toString(n&f);r.flush=!!(n&d);const i=J(r.type);r.data=i.decode(e,t+8);t+=8+i.decode.bytes}Y.decode.bytes=t-i;return r};Y.decode.bytes=0;Y.encodingLength=function(e){const t=e.data!==null&&e.data!==void 0?e.data:e.options;return g.encodingLength(e.name)+8+J(e.type).encodingLength(t)};const X=e.question={};X.encode=function(e,r,i){if(!r)r=t.alloc(X.encodingLength(e));if(!i)i=0;const o=i;g.encode(e.name,r,i);i+=g.encode.bytes;r.writeUInt16BE(n.toType(e.type),i);i+=2;r.writeUInt16BE(a.toClass(e.class===void 0?`IN`:e.class),i);i+=2;X.encode.bytes=i-o;return e};X.encode.bytes=0;X.decode=function(e,t){if(!t)t=0;const r=t;const i={};i.name=g.decode(e,t);t+=g.decode.bytes;i.type=n.toString(e.readUInt16BE(t));t+=2;i.class=a.toString(e.readUInt16BE(t));t+=2;if(!!(i.class&p))i.class&=m;X.decode.bytes=t-r;return i};X.decode.bytes=0;X.encodingLength=function(e){return g.encodingLength(e.name)+4};e.AUTHORITATIVE_ANSWER=1024;e.TRUNCATED_RESPONSE=512;e.RECURSION_DESIRED=256;e.RECURSION_AVAILABLE=128;e.AUTHENTIC_DATA=32;e.CHECKING_DISABLED=16;e.DNSSEC_OK=32768;e.encode=function(n,r,i){const a=!r;if(a)r=t.alloc(e.encodingLength(n));if(!i)i=0;const o=i;if(!n.questions)n.questions=[];if(!n.answers)n.answers=[];if(!n.authorities)n.authorities=[];if(!n.additionals)n.additionals=[];v.encode(n,r,i);i+=v.encode.bytes;i=encodeList(n.questions,X,r,i);i=encodeList(n.answers,Y,r,i);i=encodeList(n.authorities,Y,r,i);i=encodeList(n.additionals,Y,r,i);e.encode.bytes=i-o;if(a&&e.encode.bytes!==r.length)return r.slice(0,e.encode.bytes);return r};e.encode.bytes=0;e.decode=function(t,n){if(!n)n=0;const r=n;const i=v.decode(t,n);n+=v.decode.bytes;n=decodeList(i.questions,X,t,n);n=decodeList(i.answers,Y,t,n);n=decodeList(i.authorities,Y,t,n);n=decodeList(i.additionals,Y,t,n);e.decode.bytes=n-r;return i};e.decode.bytes=0;e.encodingLength=function(e){return v.encodingLength(e)+encodingLengthList(e.questions||[],X)+encodingLengthList(e.answers||[],Y)+encodingLengthList(e.authorities||[],Y)+encodingLengthList(e.additionals||[],Y)};e.streamEncode=function(n){const r=e.encode(n);const i=t.alloc(2);i.writeUInt16BE(r.byteLength);const a=t.concat([i,r]);e.streamEncode.bytes=a.byteLength;return a};e.streamEncode.bytes=0;e.streamDecode=function(t){const n=t.readUInt16BE(0);if(t.byteLength<n+2)return null;const r=e.decode(t.slice(2));e.streamDecode.bytes=e.decode.bytes;return r};e.streamDecode.bytes=0;function encodingLengthList(e,t){let n=0;for(let r=0;r<e.length;r++)n+=t.encodingLength(e[r]);return n}function encodeList(e,t,n,r){for(let i=0;i<e.length;i++){t.encode(e[i],n,r);r+=t.encode.bytes}return r}function decodeList(e,t,n,r){for(let i=0;i<e.length;i++){e[i]=t.decode(n,r);r+=t.decode.bytes}return r}}));
//!node_modules/.pnpm/thunky@1.1.0/node_modules/thunky/index.js
var require_thunky=/* @__PURE__ */ __commonJSMin(((e,t)=>{var n=nextTickArgs;process.nextTick(upgrade,42);t.exports=thunky;function thunky(e){var t=run;return thunk;function thunk(e){t(e||noop)}function run(r){var i=[r];t=wait;e(done);function wait(e){i.push(e)}function done(e){var r=arguments;t=isError(e)?run:finished;while(i.length)finished(i.shift());function finished(e){n(apply,e,r)}}}}function isError(e){return Object.prototype.toString.call(e)===`[object Error]`}function noop(){}function apply(e,t){e.apply(null,t)}function upgrade(e){if(e===42)n=process.nextTick}function nextTickArgs(e,t,n){process.nextTick(function(){e(t,n)})}}));
//!node_modules/.pnpm/multicast-dns@7.2.5/node_modules/multicast-dns/index.js
var require_multicast_dns=/* @__PURE__ */ __commonJSMin(((e,t)=>{var n=require_dns_packet();var r=__require(`dgram`);var i=require_thunky();var a=__require(`events`);var o=__require(`os`);var noop=function(){};t.exports=function(e){if(!e)e={};var t=new a.EventEmitter;var o=typeof e.port===`number`?e.port:5353;var s=e.type||`udp4`;var c=e.ip||e.host||(s===`udp4`?`224.0.0.251`:null);var u={address:c,port:o};var d={};var f=false;var p=null;if(s===`udp6`&&(!c||!e.interface))throw new Error("For IPv6 multicast you must specify `ip` and `interface`");var m=e.socket||r.createSocket({type:s,reuseAddr:e.reuseAddr!==false,toString:function(){return s}});m.on(`error`,function(e){if(e.code===`EACCES`||e.code===`EADDRINUSE`)t.emit(`error`,e);else t.emit(`warning`,e)});m.on(`message`,function(e,r){try{e=n.decode(e)}catch(e){t.emit(`warning`,e);return}t.emit(`packet`,e,r);if(e.type===`query`)t.emit(`query`,e,r);if(e.type===`response`)t.emit(`response`,e,r)});m.on(`listening`,function(){if(!o)o=u.port=m.address().port;if(e.multicast!==false){t.update();p=setInterval(t.update,5e3);m.setMulticastTTL(e.ttl||255);m.setMulticastLoopback(e.loopback!==false)}});var g=i(function(t){if(!o||e.bind===false)return t(null);m.once(`error`,t);m.bind(o,e.bind||e.interface,function(){m.removeListener(`error`,t);t(null)})});g(function(e){if(e)return t.emit(`error`,e);t.emit(`ready`)});t.send=function(e,r,i){if(typeof r===`function`)return t.send(e,null,r);if(!i)i=noop;if(!r)r=u;else if(!r.host&&!r.address)r.address=u.address;g(onbind);function onbind(t){if(f)return i();if(t)return i(t);var a=n.encode(e);m.send(a,0,a.length,r.port,r.address||r.host,i)}};t.response=t.respond=function(e,r,i){if(Array.isArray(e))e={answers:e};e.type=`response`;e.flags=(e.flags||0)|n.AUTHORITATIVE_ANSWER;t.send(e,r,i)};t.query=function(e,n,r,i){if(typeof n===`function`)return t.query(e,null,null,n);if(typeof n===`object`&&n&&n.port)return t.query(e,null,n,r);if(typeof r===`function`)return t.query(e,n,null,r);if(!i)i=noop;if(typeof e===`string`)e=[{name:e,type:n||`ANY`}];if(Array.isArray(e))e={type:`query`,questions:e};e.type=`query`;t.send(e,r,i)};t.destroy=function(e){if(!e)e=noop;if(f)return process.nextTick(e);f=true;clearInterval(p);for(var t in d)try{m.dropMembership(c,t)}catch(e){}d={};m.close(e)};t.update=function(){var n=e.interface?[].concat(e.interface):allInterfaces();var r=false;for(var i=0;i<n.length;i++){var a=n[i];if(d[a])continue;try{m.addMembership(c,a);d[a]=true;r=true}catch(e){t.emit(`warning`,e)}}if(r){if(m.setMulticastInterface)try{m.setMulticastInterface(e.interface||defaultInterface())}catch(e){t.emit(`warning`,e)}t.emit(`networkInterface`)}};return t};function defaultInterface(){var e=o.networkInterfaces();var t=Object.keys(e);for(var n=0;n<t.length;n++){var r=e[t[n]];for(var i=0;i<r.length;i++){var a=r[i];if(isIPv4(a.family)&&!a.internal){if(o.platform()===`darwin`&&t[n]===`en0`)return a.address;return`0.0.0.0`}}}return`127.0.0.1`}function allInterfaces(){var e=o.networkInterfaces();var t=Object.keys(e);var n=[];for(var r=0;r<t.length;r++){var i=e[t[r]];for(var a=0;a<i.length;a++){var s=i[a];if(isIPv4(s.family)){n.push(s.address);break}}}return n}function isIPv4(e){return e===4||e===`IPv4`}}));
//!node_modules/.pnpm/werift@0.25.2_supports-color@10.2.2/node_modules/werift/lib/index.mjs
var import_multicast_dns=/* @__PURE__ */ __toESM(require_multicast_dns(),1);var __defProp=Object.defineProperty;var __export=(e,t)=>{for(var n in t)__defProp(e,n,{get:t[n],enumerable:true})};function random16(){return randomBytes$1(2).readUInt16BE(0)}function random32(){return randomBytes$1(4).readUInt32BE(0)}function bufferXor(e,t){if(e.length!==t.length)throw new TypeError(`[webrtc-stun] You can not XOR buffers which length are different`);const n=e.length;const r=Buffer.allocUnsafe(n);for(let i=0;i<n;i++)r[i]=e[i]^t[i];return r}function bufferArrayXor(e){const t=[...e].sort((e,t)=>e.length-t.length).reverse()[0].length;const n=Buffer.allocUnsafe(t);for(let r=0;r<t;r++){n[r]=0;e.forEach(e=>{n[r]^=e[r]??0})}return n}var BitWriter=class{constructor(e){this.bitLength=e}value=0;set(e,t,n){n&=(1<<e)-1;this.value|=n<<this.bitLength-e-t;return this}get buffer(){const e=Math.ceil(this.bitLength/8);const t=Buffer.alloc(e);t.writeUIntBE(this.value,0,e);return t}};var BitWriter2=class{constructor(e){this.bitLength=e;if(e>32)throw new Error}_value=0n;offset=0n;set(e,t=1){let n=BigInt(e);const r=BigInt(t);n&=(1n<<r)-1n;this._value|=n<<BigInt(this.bitLength)-r-this.offset;this.offset+=r;return this}get value(){return Number(this._value)}get buffer(){const e=Math.ceil(this.bitLength/8);const t=Buffer.alloc(e);t.writeUIntBE(this.value,0,e);return t}};function getBit(e,t,n=1){let r=e.toString(2).split(``);r=[...Array(8-r.length).fill(`0`),...r];const i=r.slice(t,t+n).join(``);return Number.parseInt(i,2)}function paddingByte(e){const t=e.toString(2).split(``);return[...[...Array(8-t.length)].map(()=>`0`),...t].join(``)}function paddingBits(e,t){const n=e.toString(2);return[...[...Array(t-n.length)].map(()=>`0`),...n].join(``)}function bufferWriter(e,t){return createBufferWriter(e)(t)}function createBufferWriter(e,t){const n=e.reduce((e,t)=>e+t,0);const r=t?Buffer.alloc(n):void 0;return t=>{const i=r||Buffer.alloc(n);let a=0;t.forEach((t,n)=>{const r=e[n];if(r===8)i.writeBigUInt64BE(t,a);else i.writeUIntBE(t,a,r);a+=r});return i}}function bufferWriterLE(e,t){const n=e.reduce((e,t)=>e+t,0);const r=Buffer.alloc(n);let i=0;t.forEach((t,n)=>{const a=e[n];if(a===8)r.writeBigUInt64LE(t,i);else r.writeUIntLE(t,i,a);i+=a});return r}function bufferReader(e,t){let n=0;return t.map(t=>{let r;if(t===8)r=e.readBigUInt64BE(n);else r=e.readUIntBE(n,t);n+=t;return r})}var BufferChain=class{buffer;constructor(e){this.buffer=Buffer.alloc(e)}writeInt16BE(e,t){this.buffer.writeInt16BE(e,t);return this}writeUInt8(e,t){this.buffer.writeUInt8(e,t);return this}};var dumpBuffer=e=>`0x`+e.toString(`hex`).replace(/(.)(.)/g,`$1$2 `).split(` `).filter(e=>e!=void 0&&e.length>0).join(`,0x`);function buffer2ArrayBuffer(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}var BitStream=class{constructor(e){this.uint8Array=e}position=0;bitsPending=0;writeBits(e,t){if(e==0)return this;t&=4294967295>>>32-e;let n;if(this.bitsPending>0){if(this.bitsPending>e){this.uint8Array[this.position-1]|=t<<this.bitsPending-e;n=e;this.bitsPending-=e}else if(this.bitsPending==e){this.uint8Array[this.position-1]|=t;n=e;this.bitsPending=0}else{this.uint8Array[this.position-1]|=t>>e-this.bitsPending;n=this.bitsPending;this.bitsPending=0}}else{n=Math.min(8,e);this.bitsPending=8-n;this.uint8Array[this.position++]=t>>e-n<<this.bitsPending}e-=n;if(e>0)this.writeBits(e,t);return this}readBits(e){return this._readBits(e)}_readBits(e,t){if(typeof t==`undefined`)t=0;if(e==0)return t;let n;let r;if(this.bitsPending>0){const t=this.uint8Array[this.position-1]&255>>8-this.bitsPending;r=Math.min(this.bitsPending,e);this.bitsPending-=r;n=t>>this.bitsPending}else{r=Math.min(8,e);this.bitsPending=8-r;n=this.uint8Array[this.position++]>>this.bitsPending}e-=r;t=t<<r|n;return e>0?this._readBits(e,t):t}seekTo(e){this.position=e/8|0;this.bitsPending=e%8;if(this.bitsPending>0){this.bitsPending=8-this.bitsPending;this.position++}}};var POLY_CRC32=3988292384;var POLY_CRC32C=2197175160;function isBufferLike(e){return typeof e!==`string`}function generateCRCTable(e){const t=new Array(256);let n=0;for(let r=0;r<256;++r){n=r;n=n&1?e^n>>>1:n>>>1;n=n&1?e^n>>>1:n>>>1;n=n&1?e^n>>>1:n>>>1;n=n&1?e^n>>>1:n>>>1;n=n&1?e^n>>>1:n>>>1;n=n&1?e^n>>>1:n>>>1;n=n&1?e^n>>>1:n>>>1;n=n&1?e^n>>>1:n>>>1;t[r]=n}return new Int32Array(t)}function generateSliceBy16Tables(e){const t=/* @__PURE__ */ new Int32Array(4096);let n=0;let r=0;let i=0;for(i=0;i<256;++i)t[i]=e[i];for(i=0;i<256;++i){r=e[i];for(n=256+i;n<4096;n+=256)r=t[n]=r>>>8^e[r&255]}const a=[];for(i=1;i<16;++i)a[i-1]=t.subarray(i*256,i*256+256);return a}function crcGenericString(e,t,n){let r=t^-1;let i=0;const a=e.length;let o=0;let s=0;while(i<a){o=e.charCodeAt(i++);if(o<128)r=r>>>8^n[(r^o)&255];else if(o<2048){r=r>>>8^n[(r^(192|o>>6&31))&255];r=r>>>8^n[(r^(128|o&63))&255]}else if(o>=55296&&o<57344){o=(o&1023)+64;s=e.charCodeAt(i++)&1023;r=r>>>8^n[(r^(240|o>>8&7))&255];r=r>>>8^n[(r^(128|o>>2&63))&255];r=r>>>8^n[(r^(128|s>>6&15|(o&3)<<4))&255];r=r>>>8^n[(r^(128|s&63))&255]}else{r=r>>>8^n[(r^(224|o>>12&15))&255];r=r>>>8^n[(r^(128|o>>6&63))&255];r=r>>>8^n[(r^(128|o&63))&255]}}return~r>>>0}function crcBuffer(e,t,n,r){const[i,a,o,s,c,u,d,f,p,m,g,_,v,y,b]=r;let x=t^-1;let C=0;let w=e.length-15;while(C<w)x=b[e[C++]^x&255]^y[e[C++]^x>>>8&255]^v[e[C++]^x>>>16&255]^_[e[C++]^x>>>24]^g[e[C++]]^m[e[C++]]^p[e[C++]]^f[e[C++]]^d[e[C++]]^u[e[C++]]^c[e[C++]]^s[e[C++]]^o[e[C++]]^a[e[C++]]^i[e[C++]]^n[e[C++]];for(w+=15;C<w;)x=x>>>8^n[(x^e[C++])&255];return~x>>>0}var table32=generateCRCTable(POLY_CRC32);var tables32By16=generateSliceBy16Tables(table32);var table32c=generateCRCTable(POLY_CRC32C);var tables32cBy16=generateSliceBy16Tables(table32c);function crc32(e,t=0){if(isBufferLike(e))return crcBuffer(e,t,table32,tables32By16);return crcGenericString(e,t,table32)}function crc32c(e,t=0){if(isBufferLike(e))return crcBuffer(e,t,table32c,tables32cBy16);return crcGenericString(e,t,table32c)}function uint8Add(e,t){return e+t&255}function uint16Add(e,t){return e+t&65535}function uint32Add(e,t){return Number(BigInt(e)+BigInt(t)&4294967295n)}function uint24(e){return e&16777215}function uint16Gt(e,t){const n=32768;return e<t&&t-e>n||e>t&&e-t<n}function uint16Gte(e,t){return e===t||uint16Gt(e,t)}function uint32Gt(e,t){const n=2147483648;return e<t&&t-e>n||e>t&&e-t<n}function uint32Gte(e,t){return e===t||uint32Gt(e,t)}var int=e=>Number.parseInt(e,10);var PromiseQueue=class{queue=[];running=false;push=e=>new Promise((t,n)=>{this.queue.push({promise:e,done:t,failed:n});if(!this.running)this.run()});async run(){const e=this.queue.shift();if(e){this.running=true;try{const t=await e.promise();e.done(t)}catch(t){e.failed(t)}this.run()}else this.running=false}cancel(){this.queue=[]}};var interfaceAddress=(e,t)=>t?t[e]:void 0;async function randomPort(e=`udp4`,t){const n=createSocket(e);setImmediate(()=>n.bind({port:0,address:interfaceAddress(e,t)}));await new Promise(e=>{n.once(`error`,e);n.once(`listening`,e)});const r=n.address()?.port;await new Promise(e=>n.close(()=>e()));return r}async function randomPorts(e,t=`udp4`,n){return Promise.all([...Array(e)].map(()=>randomPort(t,n)))}async function findPort(e,t,n=`udp4`,r){let i;for(let a=e;a<=t;a++){const o=createSocket(n);setImmediate(()=>o.bind({port:a,address:interfaceAddress(n,r)}));if(await new Promise(e=>{o.once(`error`,t=>e(t));o.once(`listening`,()=>e())})){await new Promise(e=>o.close(()=>e()));continue}i=o.address()?.port;await new Promise(e=>o.close(()=>e()));if(e<=i&&i<=t)break}if(!i)throw new Error(`port not found`);return i}function normalizeFamilyNodeV18(e){if(e===`IPv4`)return 4;if(e===`IPv6`)return 6;return e}var WeriftError=class extends Error{message;payload;path;constructor(e){super(e.message)}toJSON(){return{message:this.message,payload:JSON.parse(JSON.stringify(this.payload)),path:this.path}}};var debug=import_src.default.debug;var Event2=class{event={stack:[],promiseStack:[],eventId:0};ended=false;onended;onerror=e=>{};execute=(...e)=>{if(this.ended)return;for(const t of this.event.stack)t.execute(...e);(async()=>{for(const t of this.event.promiseStack)await t.execute(...e)})().catch(e=>{this.onerror(e)})};complete=()=>{if(this.ended)return;for(const e of this.event.stack)if(e.complete)e.complete();this.allUnsubscribe();this.ended=true;if(this.onended){this.onended();this.onended=void 0}};error=e=>{if(this.ended)return;for(const t of this.event.stack)if(t.error)t.error(e);this.allUnsubscribe()};allUnsubscribe=()=>{if(this.ended)return;this.event={stack:[],promiseStack:[],eventId:0}};subscribe=(e,t,n)=>{const r=this.event.eventId;this.event.stack.push({execute:e,id:r,complete:t,error:n});this.event.eventId++;const unSubscribe=()=>{this.event.stack=this.event.stack.filter(e=>e.id!==r&&e)};const disposer=e=>{e.push(unSubscribe)};return{unSubscribe,disposer}};pipe(e){this.subscribe((...t)=>{e.execute(...t)})}queuingSubscribe=(e,t,n)=>{if(this.ended)throw new Error(`event completed`);const r=this.event.eventId;this.event.promiseStack.push({execute:e,id:r,complete:t,error:n});this.event.eventId++;const unSubscribe=()=>{this.event.stack=this.event.stack.filter(e=>e.id!==r&&e)};const disposer=e=>{e.push(unSubscribe)};return{unSubscribe,disposer}};once=(e,t,n)=>{const r=this.subscribe((...t)=>{r.unSubscribe();e(...t)},t,n)};watch=(e,t)=>new Promise((n,r)=>{const i=t&&setTimeout(()=>{r(`Event watch timeout`)},t);const{unSubscribe:a}=this.subscribe((...t)=>{if(e(...t)){if(i)clearTimeout(i);a();n(t)}})});asPromise=e=>new Promise((t,n)=>{const r=e&&setTimeout(()=>{n(`Event asPromise timeout`)},e);this.once((...e)=>{if(r)clearTimeout(r);t(e)},()=>{if(r)clearTimeout(r);t([])},e=>{if(r)clearTimeout(r);n(e)})});get returnTrigger(){const{execute:e,error:t,complete:n}=this;return{execute:e,error:t,complete:n}}get returnListener(){const{subscribe:e,once:t,asPromise:n}=this;return{subscribe:e,once:t,asPromise:n}}get length(){return this.event.stack.length}};var EventDisposer=class{_disposer=[];push(e){this._disposer.push(e)}dispose(){this._disposer.forEach(e=>e());this._disposer=[]}};var log=debug(`werift-ice:packages/ice/src/transport.ts`);var DEFAULT_CONNECT_TIMEOUT_MS=8e3;var UdpTransport=class _UdpTransport{constructor(e,t={}){this.socketType=e;this.options=t;this.socket=createSocket(e);this.socket.on(`message`,(e,t)=>{if(normalizeFamilyNodeV18(t.family)===6)[t.address]=t.address.split(`%`);this.rinfo=t;try{this.onData(e,[t.address,t.port])}catch(e){log(`onData error`,e)}})}type=`udp`;socket;rinfo;onData=()=>{};closed=false;static async init(e,t={}){const n=new _UdpTransport(e,t);await n.init();return n}async init(){const e=interfaceAddress(this.socketType,this.options.interfaceAddresses);if(this.options.port)this.socket.bind({port:this.options.port,address:e});else if(this.options.portRange){const t=await findPort(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:t,address:e})}else this.socket.bind({address:e});await new Promise(e=>this.socket.once(`listening`,e))}send=async(e,t)=>{if(t&&!net$1.isIP(t[0]))return new Promise((n,r)=>{this.socket.send(e,t[1],t[0],i=>{if(i){log(`send error`,t,e);r(i)}else n()})});else{t=t??[this.rinfo?.address,this.rinfo?.port];this.socket.send(e,t[1],t[0])}};get address(){return this.socket.address()}get addressFamily(){return this.socketType===`udp6`?6:4}get host(){return this.socket.address().address}get port(){return this.socket.address().port}close=()=>new Promise(e=>{this.closed=true;this.socket.once(`close`,e);try{this.socket.close()}catch(t){e()}})};var TcpTransport=class _TcpTransport{type=`tcp`;stream;constructor(e,t={}){this.stream=new StreamTransport(`tcp`,()=>connect({port:e[1],host:e[0]}),void 0,t.connectTimeoutMs)}static async init(e,t={}){const n=new _TcpTransport(e,t);try{await n.init();return n}catch(e){await n.close();throw e}}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get remoteAddress(){return this.stream.remoteAddress}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}send=async(e,t)=>{await this.stream.send(e,t)};close=async()=>{await this.stream.close()}};var TlsTransport=class _TlsTransport{type=`tls`;stream;constructor(e,t={},n={}){this.stream=new StreamTransport(`tls`,()=>tls$1.connect({...t,host:e[0],port:e[1]}),void 0,n.connectTimeoutMs)}static async init(e,t={},n={}){const r=new _TlsTransport(e,t,n);try{await r.init();return r}catch(e){await r.close();throw e}}async init(){await this.stream.waitForConnect()}get address(){return this.stream.address}get remoteAddress(){return this.stream.remoteAddress}get closed(){return this.stream.closed}get onData(){return this.stream.onData}set onData(e){this.stream.onData=e}send=async(e,t)=>{await this.stream.send(e,t)};close=async()=>{await this.stream.close()}};var StreamTransport=class{constructor(e,t,n=e===`tls`?`secureConnect`:`connect`,r=DEFAULT_CONNECT_TIMEOUT_MS){this.createClient=t;this.connectEvent=n;this.connectTimeoutMs=r;this.type=e;this.connect()}type;connecting;client;onData=()=>{};closed=false;rejectConnecting;connect(){if(this.closed)return;if(this.client)this.client.destroy();const e=this.createClient();this.client=e;this.connecting=new Promise((t,n)=>{let r=false;const settle=a=>{if(r)return;r=true;clearTimeout(i);e.off(this.connectEvent,onConnect);e.off(`error`,onConnectError);this.rejectConnecting=void 0;a?n(a):t()};const onConnect=()=>{settle()};const onConnectError=t=>{this.closed=true;settle(t);e.destroy()};const i=setTimeout(()=>{this.closed=true;settle(/* @__PURE__ */ new Error(`${this.type} connect timed out after ${this.connectTimeoutMs}ms`));e.destroy()},this.connectTimeoutMs);this.rejectConnecting=e=>settle(e);e.once(this.connectEvent,onConnect);e.once(`error`,onConnectError)});e.on(`data`,e=>{this.onData(e,this.remoteAddress)});e.on(`error`,e=>{log(`${this.type} transport error`,e)})}async waitForConnect(){await this.connecting}get address(){return{}}get remoteAddress(){const{remoteAddress:e,remotePort:t}=this.client;if(!e||!t)return;return[stripZoneId(e),t]}send=async(e,t)=>{await this.connecting;await new Promise((t,n)=>{this.client.write(e,e=>{if(e){n(e);return}t()})})};close=async()=>{this.closed=true;this.rejectConnecting?.(/* @__PURE__ */ new Error(`${this.type} transport closed`));this.client?.destroy()}};function stripZoneId(e){return e.split(`%`)[0]}var binaryData_exports={};__export(binaryData_exports,{BinaryReader:()=>BinaryReader,BinaryWriter:()=>BinaryWriter,NotEnoughDataError:()=>NotEnoughDataError,decode:()=>decode,encode:()=>encode,types:()=>types});var NotEnoughDataError=class extends Error{constructor(e,t){super(`requested ${e} bytes but only ${t} available`);this.name=`NotEnoughDataError`}};var BinaryReader=class{constructor(e){this.buf=e}offset=0;get length(){return this.buf.length-this.offset}get bytes(){return this.offset}readBuffer(e){this.assertSize(e);const t=this.buf.subarray(this.offset,this.offset+e);this.offset+=e;return t}readUIntBE(e){this.assertSize(e);const t=this.buf.readUIntBE(this.offset,e);this.offset+=e;return t}assertSize(e){if(e>this.length)throw new NotEnoughDataError(e,this.length)}};var BinaryWriter=class{chunks=[];written=0;get bytes(){return this.written}writeBuffer(e){this.chunks.push(e);this.written+=e.length}writeUIntBE(e,t){const n=Buffer.allocUnsafe(t);switch(t){case 1:n.writeUInt8(e,0);break;case 2:n.writeUInt16BE(e,0);break;case 4:n.writeUInt32BE(e,0);break;default:n.writeUIntBE(e,0,t)}this.writeBuffer(n)}toBuffer(){return Buffer.concat(this.chunks,this.written)}};var isObject=e=>typeof e===`object`&&e!==null;var isType=e=>isObject(e)&&typeof e.encode===`function`&&typeof e.decode===`function`;var isPlainObject=e=>{if(!isObject(e))return false;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null};var createContext=()=>({node:void 0,current:void 0});var cloneContext=e=>({node:e.node,current:e.current});var assertSchema=(e,t)=>{if(!isPlainObject(e))throw new TypeError(t)};var encodeCommon=(e,t,n,r)=>{if(isType(t))t.encode(e,n,r);else encodeSchema(e,t,n,r)};var encodeSchema=(e,t,n,r)=>{assertSchema(t,"Argument `schema` should be a plain object.");if(r.node===void 0)r.node=e;r.current=e;for(const i of Object.keys(t)){const a=t[i];const o=e[i];if(isType(a))a.encode(o,n,r);else{encodeSchema(o,a,n,r);r.current=e}}};var decodeCommon=(e,t,n)=>{if(isType(t))return t.decode(e,n);return decodeSchema(e,t,n)};var decodeSchema=(e,t,n)=>{assertSchema(t,`Argument #2 should be a plain object.`);const r=/* @__PURE__ */ Object.create(null);if(n.node===void 0)n.node=r;n.current=r;for(const i of Object.keys(t)){const a=t[i];if(isType(a))r[i]=a.decode(e,n);else{r[i]=decodeSchema(e,a,n);n.current=r}}return r};function encode(e,t){const n=new BinaryWriter;encodeCommon(e,t,n,createContext());return n.toBuffer()}function decode(e,t){return decodeCommon(new BinaryReader(e),t,createContext())}var createUIntBE=e=>({encode:(t,n)=>n.writeUIntBE(t,e),decode:t=>t.readUIntBE(e)});var assertLengthSpec=e=>{if(typeof e!==`number`&&!isType(e)&&typeof e!==`function`)throw new TypeError(`Unknown type of argument #1.`)};var checkLength=(e,t,n)=>{if(e!==t)throw new Error(`${n} required length ${e} instead of ${t}`)};var checkLengthType=(e,t)=>{if(typeof e!==`number`)throw new TypeError(t)};function buffer(e){assertLengthSpec(e);const t=`Length of a buffer should be a number.`;return{encode(n,r,i){if(!Buffer.isBuffer(n))throw new TypeError(`Argument 1 should be a Buffer or a BinaryStream.`);if(typeof e===`number`)checkLength(e,n.length,`Buffer`);else if(isType(e))e.encode(n.length,r,i);else{const r=e(i);checkLengthType(r,t);checkLength(r,n.length,`Buffer`)}r.writeBuffer(n)},decode(n,r){let i;if(typeof e===`number`)i=e;else if(isType(e))i=e.decode(n,r);else i=e(r);checkLengthType(i,t);return n.readBuffer(i)}}}function array(e,t,n=`count`){if(!isType(e)&&!isPlainObject(e))throw new TypeError(`Argument #1 should be a valid type.`);assertLengthSpec(t);const r=n===`bytes`;const i=`Length of an array should be a number.`;return{encode(n,a,o){if(!Array.isArray(n))throw new TypeError(`Argument #1 should be an Array.`);const s=cloneContext(o);let c=0;if(typeof t===`number`)c=t;else if(isType(t))c=n.length;else{c=t(s);checkLengthType(c,i)}const u=new BinaryWriter;for(const t of n)encodeCommon(t,e,u,s);if(r){if(isType(t))c=u.bytes;checkLength(u.bytes,c,`Argument #1`)}else checkLength(c,n.length,`Argument #1`);if(isType(t))t.encode(c,a,s);a.writeBuffer(u.toBuffer())},decode(n,a){const o=cloneContext(a);let s;if(typeof t===`number`)s=t;else if(isType(t))s=t.decode(n,o);else s=t(o);checkLengthType(s,i);const c=[];if(r){const t=n.bytes;let r=0;while(r<s){c.push(decodeCommon(n,e,o));r=n.bytes-t}if(r>s)throw new Error(`Incorrect length of an array.`)}else for(let t=0;t<s;t++)c.push(decodeCommon(n,e,o));return c}}}function string(e,t=`ascii`){if(!Buffer.isEncoding(t))throw new Error(`Argument #2 should be an encoding name.`);assertLengthSpec(e);const n=`Length of a buffer should be a number.`;return{encode(r,i,a){const o=Buffer.from(r.toString(),t);if(typeof e===`number`){if(o.length!==e)throw new Error(`Size of string should be ${e} in bytes.`)}else if(isType(e))e.encode(o.length,i,a);else{const t=e(a);checkLengthType(t,n);checkLength(t,o.length,`Buffer`)}i.writeBuffer(o)},decode(r,i){let a;if(typeof e===`number`)a=e;else if(isType(e)){a=e.decode(r,i);checkLengthType(a,`Size of a string should be a number.`)}else{a=e(i);checkLengthType(a,n)}return r.readBuffer(a).toString(t)}}}var types={uint8:createUIntBE(1),uint16be:createUIntBE(2),uint24be:createUIntBE(3),uint32be:createUIntBE(4),uint48be:createUIntBE(6),buffer,array,string};var SignatureAlgorithm={rsa_1:1,ecdsa_3:3};var HashAlgorithm={sha256_4:4};var CipherSuite={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199};var CipherSuiteList=Object.values(CipherSuite);var NamedCurveAlgorithm={x25519_29:29,secp256r1_23:23};var NamedCurveAlgorithmList=Object.values(NamedCurveAlgorithm);var CurveType={named_curve_3:3};var SignatureScheme={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027};var certificateTypes=[1,64];var signatures=[{hash:HashAlgorithm.sha256_4,signature:SignatureAlgorithm.rsa_1},{hash:HashAlgorithm.sha256_4,signature:SignatureAlgorithm.ecdsa_3}];var p256Keypair=()=>{const e=p256.utils.randomPrivateKey();const t=p256.getPublicKey(e,false);return{privateKey:Buffer.from(e),publicKey:Buffer.from(t)}};var p256PreMasterSecret=({publicKey:e,privateKey:t})=>{const n=p256.getSharedSecret(t,e);return Buffer.from(n).subarray(1)};function prfPreMasterSecret(e,t,n){switch(n){case NamedCurveAlgorithm.secp256r1_23:return p256PreMasterSecret({publicKey:e,privateKey:t});case NamedCurveAlgorithm.x25519_29:return Buffer.from(import_nacl_fast.default.scalarMult(t,e));default:throw new Error}}function hmac(e,t,n){const r=createHmac$1(e,t);r.update(n);return r.digest()}function prfPHash(e,t,n,r=`sha256`){const i=n;const a=[];let o=t;do{o=hmac(r,e,o);const i=hmac(r,e,Buffer.concat([o,t]));a.push(i);n-=i.length}while(n>0);return Buffer.concat(a,i)}function prfMasterSecret(e,t,n){return prfPHash(e,Buffer.concat([Buffer.from(`master secret`),t,n]),48)}function prfExtendedMasterSecret(e,t){const n=hash$1(`sha256`,t);return prfPHash(e,Buffer.concat([Buffer.from(`extended master secret`),n]),48)}function exportKeyingMaterial(e,t,n,r,i,a){const o=a?r:i;const s=a?i:r;return prfPHash(n,Buffer.concat([Buffer.from(e),o,s]),t)}function hash$1(e,t){return createHash$1(e).update(t).digest()}function prfVerifyData(e,t,n,r=12){const i=hash$1(`sha256`,t);return prfPHash(e,Buffer.concat([Buffer.from(n),i]),r)}function prfVerifyDataClient(e,t){return prfVerifyData(e,t,`client finished`)}function prfVerifyDataServer(e,t){return prfVerifyData(e,t,`server finished`)}function prfEncryptionKeys(e,t,n,r,i,a,o=`sha256`){const s=r*2+i*2;const c=e;const u=Buffer.concat([n,t]);const d=prfPHash(c,Buffer.concat([Buffer.from(`key expansion`),u]),s,o);const f=new binaryData_exports.BinaryReader(d);const p=f.readBuffer(r);const m=f.readBuffer(r);const g=f.readBuffer(i);const _=f.readBuffer(i);const v=Buffer.alloc(a,0);const y=Buffer.alloc(a,0);g.copy(v,0);_.copy(y,0);return{clientWriteKey:p,serverWriteKey:m,clientNonce:v,serverNonce:y}}var SessionType={CLIENT:1,SERVER:2};var AbstractCipher=class{id=0;name;hashAlgorithm;verifyDataLength=12;blockAlgorithm;kx;init(...e){throw new Error(`not implemented`)}encrypt(...e){throw new Error(`not implemented`)}decrypt(...e){throw new Error(`not implemented`)}toString(){return this.name}};var{encode:encode2,types:types2}=binaryData_exports;var crypto$2=webcrypto;import_x509_cjs.cryptoProvider.set(crypto$2);var CipherContext=class{constructor(e,t,n,r){this.sessionType=e;this.certPem=t;this.keyPem=n;if(t&&n&&r)this.parseX509(t,n,r)}localRandom;remoteRandom;cipherSuite;remoteCertificate;remoteKeyPair;localKeyPair;masterSecret;cipher;namedCurve;signatureHashAlgorithm;localCert;localPrivateKey;static createSelfSignedCertificateWithKey=async(e,t)=>{const n=(()=>{switch(e.signature){case SignatureAlgorithm.rsa_1:return`RSASSA-PKCS1-v1_5`;case SignatureAlgorithm.ecdsa_3:return`ECDSA`}})();const r=(()=>{switch(e.hash){case HashAlgorithm.sha256_4:return`SHA-256`}})();const i=(()=>{switch(t){case NamedCurveAlgorithm.secp256r1_23:return`P-256`;case NamedCurveAlgorithm.x25519_29:if(n===`ECDSA`)return`P-256`;return`X25519`;default:if(n===`ECDSA`)return`P-256`;if(n===`RSASSA-PKCS1-v1_5`)return`X25519`}})();const a=(()=>{switch(n){case`ECDSA`:return{name:n,hash:r,namedCurve:i};case`RSASSA-PKCS1-v1_5`:return{name:n,hash:r,publicExponent:new Uint8Array([1,0,1]),modulusLength:2048}}})();const o=await crypto$2.subtle.generateKey(a,true,[`sign`,`verify`]);return{certPem:(await import_x509_cjs.X509CertificateGenerator.createSelfSigned({serialNumber:randomBytes$1(8).toString(`hex`),name:`C=AU, ST=Some-State, O=Internet Widgits Pty Ltd`,notBefore:/* @__PURE__ */ new Date,notAfter:new Date(Date.now()+31536e7),signingAlgorithm:a,keys:o})).toString(`pem`),keyPem:import_x509_cjs.PemConverter.encode(await crypto$2.subtle.exportKey(`pkcs8`,o.privateKey),`private key`),signatureHash:e}};encryptPacket(e){const t=e.recordLayerHeader;const n=t.protocolVersion.major<<8|t.protocolVersion.minor;const r=this.cipher.encrypt(this.sessionType,e.fragment,{type:t.contentType,version:n,epoch:t.epoch,sequenceNumber:t.sequenceNumber});e.fragment=r;e.recordLayerHeader.contentLen=r.length;return e}decryptPacket(e){const t=e.recordLayerHeader;const n=t.protocolVersion.major<<8|t.protocolVersion.minor;return this.cipher.decrypt(this.sessionType,e.fragment,{type:t.contentType,version:n,epoch:t.epoch,sequenceNumber:t.sequenceNumber})}verifyData(e){if(this.sessionType===SessionType.CLIENT)return prfVerifyDataClient(this.masterSecret,e);else return prfVerifyDataServer(this.masterSecret,e)}signatureData(e,t){const n=createSign$1(t).update(e);const r=this.localPrivateKey.toPEM().toString();return n.sign(r)}generateKeySignature(e){const t=this.sessionType===SessionType.CLIENT?this.localRandom:this.remoteRandom;const n=this.sessionType===SessionType.SERVER?this.localRandom:this.remoteRandom;const r=this.valueKeySignature(t.serialize(),n.serialize(),this.localKeyPair.publicKey,this.namedCurve);return this.localPrivateKey.sign(r,e)}parseX509(e,t,n){const r=import_build.Certificate.fromPEM(Buffer.from(e));const i=import_build.PrivateKey.fromPEM(Buffer.from(t));this.localCert=r.raw;this.localPrivateKey=i;this.signatureHashAlgorithm=n}valueKeySignature(e,t,n,r){const i=encode2({type:CurveType.named_curve_3,curve:r,len:n.length},{type:types2.uint8,curve:types2.uint16be,len:types2.uint8});return Buffer.concat([e,t,i,n])}};var SrtpContext=class{srtpProfile;static findMatchingSRTPProfile(e,t){for(const n of t)if(e.includes(n))return n}};var dumpBuffer2=e=>`0x`+e.toString(`hex`).replace(/(.)(.)/g,`$1$2 `).split(` `).filter(e=>e!=void 0&&e.length>0).join(`,0x`);var getObjectSummary=e=>Object.entries({...e}).reduce((e,[t,n])=>{if(typeof n===`number`||typeof n===`string`)e[t]=n;if(Buffer.isBuffer(n))e[t]=dumpBuffer2(n);return e},{});var{decode:decode2,encode:encode3,types:types3}=binaryData_exports;var FragmentedHandshake=class _FragmentedHandshake{constructor(e,t,n,r,i,a){this.msg_type=e;this.length=t;this.message_seq=n;this.fragment_offset=r;this.fragment_length=i;this.fragment=a}static spec={msg_type:types3.uint8,length:types3.uint24be,message_seq:types3.uint16be,fragment_offset:types3.uint24be,fragment_length:types3.uint24be,fragment:types3.buffer(e=>e.current.fragment_length)};get summary(){return getObjectSummary(this)}static createEmpty(){return new _FragmentedHandshake(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new _FragmentedHandshake(...Object.values(decode2(e,_FragmentedHandshake.spec)))}serialize(){return encode3(this,_FragmentedHandshake.spec)}chunk(e){let t=0;const n=this.fragment.length;if(n===0)return[new _FragmentedHandshake(this.msg_type,n,this.message_seq,t,0,this.fragment)];const r=[];if(!e)e=1240;while(t<n){const i=Math.min(e,n-t);const a=Buffer.from(this.fragment.slice(t,t+i));if(a.length<=0)throw new Error(`Zero or less bytes processed while fragmenting handshake message.`);r.push(new _FragmentedHandshake(this.msg_type,n,this.message_seq,t,a.length,a));t+=a.length}return r}static assemble(e){if(!e?.length)throw new Error(`cannot reassemble handshake from empty array`);e=e.sort((e,t)=>e.fragment_offset-t.fragment_offset);const t=Buffer.alloc(e[0].length);for(const n of e)n.fragment.copy(t,n.fragment_offset);return new _FragmentedHandshake(e[0].msg_type,e[0].length,e[0].message_seq,0,t.length,t)}static findAllFragments(e,t){const n=e.find(e=>e.msg_type===t);if(!n)return[];if(!e?.length)return[];return e.filter(e=>{return e.msg_type===n.msg_type&&e.message_seq===n.message_seq&&e.length===n.length})}};var{types:types4}=binaryData_exports;var{uint16be,uint24be,buffer:buffer2,array:array2,uint8,string:string2}=types4;var ExtensionList=array2({type:uint16be,data:buffer2(uint16be)},uint16be,`bytes`);var ASN11Cert=buffer2(uint24be);var ClientCertificateType=uint8;var DistinguishedName=string2(uint16be);var SignatureHashAlgorithm={hash:uint8,signature:uint8};var ProtocolVersion={major:uint8,minor:uint8};var{decode:decode3,encode:encode4,types:types5}=binaryData_exports;var DtlsRandom=class _DtlsRandom{constructor(e=Math.floor(Date.now()/1e3),t=randomBytes$1(28)){this.gmt_unix_time=e;this.random_bytes=t}static spec={gmt_unix_time:types5.uint32be,random_bytes:types5.buffer(28)};static deSerialize(e){return new _DtlsRandom(...Object.values(decode3(e,_DtlsRandom.spec)))}static from(e){return new _DtlsRandom(...Object.values(e))}serialize(){return encode4(this,_DtlsRandom.spec)}};var{decode:decode4,encode:encode5,types:types6}=binaryData_exports;var ClientHello=class _ClientHello{constructor(e,t,n,r,i,a,o){this.clientVersion=e;this.random=t;this.sessionId=n;this.cookie=r;this.cipherSuites=i;this.compressionMethods=a;this.extensions=o}msgType=1;messageSeq=0;static spec={clientVersion:{major:types6.uint8,minor:types6.uint8},random:DtlsRandom.spec,sessionId:types6.buffer(types6.uint8),cookie:types6.buffer(types6.uint8),cipherSuites:types6.array(types6.uint16be,types6.uint16be,`bytes`),compressionMethods:types6.array(types6.uint8,types6.uint8,`bytes`),extensions:ExtensionList};static createEmpty(){return new _ClientHello(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new _ClientHello(...Object.values(decode4(e,_ClientHello.spec)))}serialize(){return encode5(this,_ClientHello.spec)}toFragment(){const e=this.serialize();return new FragmentedHandshake(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:decode5,encode:encode6,types:types7}=binaryData_exports;var MACHeader=class _MACHeader{constructor(e,t,n,r,i){this.epoch=e;this.sequenceNumber=t;this.contentType=n;this.protocolVersion=r;this.contentLen=i}static spec={epoch:types7.uint16be,sequenceNumber:types7.uint48be,contentType:types7.uint8,protocolVersion:ProtocolVersion,contentLen:types7.uint16be};static createEmpty(){return new _MACHeader(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new _MACHeader(...Object.values(decode5(e,_MACHeader.spec)))}serialize(){return encode6(this,_MACHeader.spec)}};var DtlsPlaintext=class _DtlsPlaintext{constructor(e,t){this.recordLayerHeader=e;this.fragment=t}get summary(){return{header:this.recordLayerHeader,fragment:dumpBuffer2(this.fragment)}}static createEmpty(){return new _DtlsPlaintext(void 0,void 0)}static deSerialize(e){if(e.length<13)throw new Error(`Invalid DTLS record: buffer is too short`);const t=e.readUInt8(0);const n=e.readUInt8(1);const r=e.readUInt8(2);const i=e.readUInt16BE(3);const a=e.slice(5,11).readUIntBE(0,6);const o=e.readUInt16BE(11);if(e.length<13+o)throw new Error(`Invalid DTLS record: fragment length exceeds buffer`);const s=e.slice(13,13+o);return new _DtlsPlaintext({contentType:t,protocolVersion:{major:n,minor:r},epoch:i,sequenceNumber:a,contentLen:o},s)}serialize(){const e=this.fragment.length;const t=13+e;const n=Buffer.alloc(t);n.writeUInt8(this.recordLayerHeader.contentType,0);n.writeUInt8(this.recordLayerHeader.protocolVersion.major,1);n.writeUInt8(this.recordLayerHeader.protocolVersion.minor,2);n.writeUInt16BE(this.recordLayerHeader.epoch,3);n.writeUIntBE(this.recordLayerHeader.sequenceNumber,5,6);n.writeUInt16BE(e,11);this.fragment.copy(n,13);return n}computeMACHeader(){return new MACHeader(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}};var createFragments=e=>t=>{e.lastFlight=t;return t.flatMap(t=>{t.messageSeq=e.sequenceNumber++;return t.toFragment().chunk()})};var createPlaintext=e=>(t,n)=>{return t.map(t=>{return new DtlsPlaintext({contentType:t.type,protocolVersion:e.version,epoch:e.epoch,sequenceNumber:n,contentLen:t.fragment.length},t.fragment)})};var AlertDesc=/* @__PURE__ */ (e=>{e[e[`CloseNotify`]=0]=`CloseNotify`;e[e[`UnexpectedMessage`]=10]=`UnexpectedMessage`;e[e[`BadRecordMac`]=20]=`BadRecordMac`;e[e[`DecryptionFailed`]=21]=`DecryptionFailed`;e[e[`RecordOverflow`]=22]=`RecordOverflow`;e[e[`DecompressionFailure`]=30]=`DecompressionFailure`;e[e[`HandshakeFailure`]=40]=`HandshakeFailure`;e[e[`NoCertificate`]=41]=`NoCertificate`;e[e[`BadCertificate`]=42]=`BadCertificate`;e[e[`UnsupportedCertificate`]=43]=`UnsupportedCertificate`;e[e[`CertificateRevoked`]=44]=`CertificateRevoked`;e[e[`CertificateExpired`]=45]=`CertificateExpired`;e[e[`CertificateUnknown`]=46]=`CertificateUnknown`;e[e[`IllegalParameter`]=47]=`IllegalParameter`;e[e[`UnknownCa`]=48]=`UnknownCa`;e[e[`AccessDenied`]=49]=`AccessDenied`;e[e[`DecodeError`]=50]=`DecodeError`;e[e[`DecryptError`]=51]=`DecryptError`;e[e[`ExportRestriction`]=60]=`ExportRestriction`;e[e[`ProtocolVersion`]=70]=`ProtocolVersion`;e[e[`InsufficientSecurity`]=71]=`InsufficientSecurity`;e[e[`InternalError`]=80]=`InternalError`;e[e[`UserCanceled`]=90]=`UserCanceled`;e[e[`NoRenegotiation`]=100]=`NoRenegotiation`;e[e[`UnsupportedExtension`]=110]=`UnsupportedExtension`;return e})(AlertDesc||{});var warn=debug(`werift-dtls : packages/dtls/src/flight/flight.ts : warn`);var err=debug(`werift-dtls : packages/dtls/src/flight/flight.ts : err`);var Flight=class _Flight{constructor(e,t,n,r){this.transport=e;this.dtls=t;this.flight=n;this.nextFlight=r}state=`PREPARING`;static RetransmitCount=10;createPacket(e){const t=createFragments(this.dtls)(e);this.dtls.bufferHandshakeCache(t,true,this.flight);return createPlaintext(this.dtls)(t.map(e=>({type:22,fragment:e.serialize()})),++this.dtls.recordSequenceNumber)}async transmit(e){let t=0;for(;t<=_Flight.RetransmitCount;t++){this.setState(`SENDING`);this.send(e).catch(e=>{err(`fail to send`,err)});this.setState(`WAITING`);if(this.nextFlight===void 0){this.setState(`FINISHED`);break}await setTimeout$2(1e3*((t+1)/2));if(this.dtls.flight>=this.nextFlight){this.setState(`FINISHED`);break}else warn(this.dtls.sessionId,`retransmit`,t,this.dtls.flight)}if(t>_Flight.RetransmitCount){err(this.dtls.sessionId,`retransmit failed`,t);throw new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}}send=e=>Promise.all(e.map(e=>this.transport.send(e)));setState(e){this.state=e}};var Flight1=class extends Flight{constructor(e,t,n){super(e,t,1,3);this.cipher=n}async exec(e){if(this.dtls.flight===1)throw new Error;this.dtls.flight=1;const t=new ClientHello({major:254,minor:253},new DtlsRandom,Buffer.from([]),Buffer.from([]),CipherSuiteList,[0],e);this.dtls.version=t.clientVersion;this.cipher.localRandom=DtlsRandom.from(t.random);const n=this.createPacket([t]);const r=Buffer.concat(n.map(e=>e.serialize()));await this.transmit([r])}};var log2=debug(`werift-dtls : packages/dtls/src/flight/client/flight3.ts : log`);var Flight3=class extends Flight{constructor(e,t){super(e,t,3,5)}async exec(e){if(this.dtls.flight===3)throw new Error;this.dtls.flight=3;this.dtls.handshakeCache=[];const[t]=this.dtls.lastFlight;log2(`dtls version`,t.clientVersion);t.cookie=e.cookie;this.dtls.cookie=e.cookie;const n=this.createPacket([t]);const r=Buffer.concat(n.map(e=>e.serialize()));await this.transmit([r])}};var signTypes={NULL:0,ECDHE:1};var keyTypes={NULL:0,RSA:1,ECDSA:2,PSK:3};var kxTypes={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5};var KeyExchange=class{id=0;name;signType;keyType;toString(){return this.name}};function createRSAKeyExchange(){const e=new KeyExchange;e.id=kxTypes.RSA;e.name=`RSA`;e.keyType=keyTypes.RSA;return e}function createECDHERSAKeyExchange(){const e=new KeyExchange;e.id=kxTypes.ECDHE_RSA;e.name=`ECDHE_RSA`;e.signType=signTypes.ECDHE;e.keyType=keyTypes.RSA;return e}function createECDHEECDSAKeyExchange(){const e=new KeyExchange;e.id=kxTypes.ECDHE_ECDSA;e.name=`ECDHE_ECDSA`;e.signType=signTypes.ECDHE;e.keyType=keyTypes.ECDSA;return e}function createPSKKeyExchange(){const e=new KeyExchange;e.id=kxTypes.PSK;e.name=`PSK`;e.signType=signTypes.NULL;e.keyType=keyTypes.PSK;return e}function createECDHEPSKKeyExchange(){const e=new KeyExchange;e.id=kxTypes.ECDHE_PSK;e.name=`ECDHE_PSK`;e.signType=signTypes.ECDHE;e.keyType=keyTypes.PSK;return e}var err2=debug(`werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err`);var AEADCipher=class extends AbstractCipher{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return getObjectSummary(this)}init(e,t,n){const r=prfEncryptionKeys(e,n,t,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=r.clientWriteKey;this.serverWriteKey=r.serverWriteKey;this.clientNonce=r.clientNonce;this.serverNonce=r.serverNonce}encrypt(e,t,n){const r=e===SessionType.CLIENT;const i=r?this.clientNonce:this.serverNonce;const a=r?this.clientWriteKey:this.serverWriteKey;if(!i||!a)throw new Error;i.writeUInt16BE(n.epoch,this.nonceImplicitLength);i.writeUIntBE(n.sequenceNumber,this.nonceImplicitLength+2,6);const o=i.slice(this.nonceImplicitLength);const s=this.encodeAdditionalBuffer(n,t.length);const c=createCipheriv$1(this.blockAlgorithm,a,i,{authTagLength:this.authTagLength});c.setAAD(s,{plaintextLength:t.length});const u=c.update(t);const d=c.final();const f=c.getAuthTag();return Buffer.concat([o,u,d,f])}encodeAdditionalBuffer(e,t){const n=Buffer.alloc(13);n.writeUInt16BE(e.epoch,0);n.writeUintBE(e.sequenceNumber,2,6);n.writeUInt8(e.type,8);n.writeUInt16BE(e.version,9);n.writeUInt16BE(t,11);return n}decrypt(e,t,n){const r=e===SessionType.CLIENT;const i=r?this.serverNonce:this.clientNonce;const a=r?this.serverWriteKey:this.clientWriteKey;if(!i||!a)throw new Error;t.subarray(0,this.nonceExplicitLength).copy(i,this.nonceImplicitLength);const o=t.subarray(this.nonceExplicitLength,t.length-this.authTagLength);const s=t.subarray(t.length-this.authTagLength);const c=this.encodeAdditionalBuffer(n,o.length);const u=createDecipheriv$1(this.blockAlgorithm,a,i,{authTagLength:this.authTagLength});u.setAuthTag(s);u.setAAD(c,{plaintextLength:o.length});const d=u.update(o);try{const e=u.final();return e.length>0?Buffer.concat([d,e]):d}catch(r){err2(`decrypt failed`,r,e,dumpBuffer2(t),n,this.summary);throw r}}};var cipherSuites={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:49195,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:49196,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:49199,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:49200,TLS_RSA_WITH_AES_128_GCM_SHA256:156,TLS_RSA_WITH_AES_256_GCM_SHA384:157,TLS_PSK_WITH_AES_128_GCM_SHA256:168,TLS_PSK_WITH_AES_256_GCM_SHA384:169,TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:53249,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:53250,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:52396,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:52393,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:52392,TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:52395};var AEAD_AES_128_GCM={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15};var AEAD_AES_256_GCM={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15};var RSA_KEY_EXCHANGE=createRSAKeyExchange();var ECDHE_RSA_KEY_EXCHANGE=createECDHERSAKeyExchange();var ECDHE_ECDSA_KEY_EXCHANGE=createECDHEECDSAKeyExchange();var PSK_KEY_EXCHANGE=createPSKKeyExchange();var ECDHE_PSK_KEY_EXCHANGE=createECDHEPSKKeyExchange();function createCipher(e){switch(e){case cipherSuites.TLS_RSA_WITH_AES_128_GCM_SHA256:return createAEADCipher(cipherSuites.TLS_RSA_WITH_AES_128_GCM_SHA256,`TLS_RSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,RSA_KEY_EXCHANGE,AEAD_AES_128_GCM);case cipherSuites.TLS_RSA_WITH_AES_256_GCM_SHA384:return createAEADCipher(cipherSuites.TLS_RSA_WITH_AES_256_GCM_SHA384,`TLS_RSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,RSA_KEY_EXCHANGE,AEAD_AES_256_GCM,`sha384`);case cipherSuites.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return createAEADCipher(cipherSuites.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,ECDHE_RSA_KEY_EXCHANGE,AEAD_AES_128_GCM);case cipherSuites.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return createAEADCipher(cipherSuites.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,ECDHE_RSA_KEY_EXCHANGE,AEAD_AES_256_GCM,`sha384`);case cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return createAEADCipher(cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,ECDHE_ECDSA_KEY_EXCHANGE,AEAD_AES_128_GCM);case cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return createAEADCipher(cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,ECDHE_ECDSA_KEY_EXCHANGE,AEAD_AES_256_GCM,`sha384`);case cipherSuites.TLS_PSK_WITH_AES_128_GCM_SHA256:return createAEADCipher(cipherSuites.TLS_PSK_WITH_AES_128_GCM_SHA256,`TLS_PSK_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,PSK_KEY_EXCHANGE,AEAD_AES_128_GCM,`sha256`);case cipherSuites.TLS_PSK_WITH_AES_256_GCM_SHA384:return createAEADCipher(cipherSuites.TLS_PSK_WITH_AES_256_GCM_SHA384,`TLS_PSK_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,PSK_KEY_EXCHANGE,AEAD_AES_256_GCM,`sha384`);case cipherSuites.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return createAEADCipher(cipherSuites.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,`TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256`,`aes-128-gcm`,ECDHE_PSK_KEY_EXCHANGE,AEAD_AES_128_GCM,`sha256`);case cipherSuites.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return createAEADCipher(cipherSuites.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,`TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384`,`aes-256-gcm`,ECDHE_PSK_KEY_EXCHANGE,AEAD_AES_256_GCM,`sha384`)}return null}function createAEADCipher(e,t,n,r,i,a=`sha256`){const o=new AEADCipher;o.id=e;o.name=t;o.blockAlgorithm=n;o.kx=r;o.hashAlgorithm=a;o.keyLength=i.K_LEN;o.nonceLength=i.N_MAX;o.nonceImplicitLength=4;o.nonceExplicitLength=8;o.ivLength=o.nonceImplicitLength;o.authTagLength=16;return o}function generateKeyPair(e){switch(e){case NamedCurveAlgorithm.secp256r1_23:{const{privateKey:t,publicKey:n}=p256Keypair();return{curve:e,privateKey:t,publicKey:n}}case NamedCurveAlgorithm.x25519_29:{const t=import_nacl_fast.default.box.keyPair();return{curve:e,privateKey:Buffer.from(t.secretKey.buffer),publicKey:Buffer.from(t.publicKey.buffer)}}default:throw new Error}}var ExtendedMasterSecret=class{static type=23};var{decode:decode6,encode:encode7,types:types8}=binaryData_exports;var RenegotiationIndication=class _RenegotiationIndication{static type=65281;static spec={type:types8.uint16be,data:types8.uint8};type=_RenegotiationIndication.type;data=0;constructor(e={}){Object.assign(this,e)}static createEmpty(){return new _RenegotiationIndication}static deSerialize(e){return new _RenegotiationIndication(decode6(e,_RenegotiationIndication.spec))}serialize(){return encode7(this,_RenegotiationIndication.spec)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:decode7,encode:encode8,types:types9}=binaryData_exports;var UseSRTP=class _UseSRTP{static type=14;static spec={type:types9.uint16be,data:types9.buffer(types9.uint16be)};type=_UseSRTP.type;data=Buffer.from([]);profiles=[];mki=Buffer.from([0]);constructor(e={}){Object.assign(this,e)}static create(e,t){return new _UseSRTP({profiles:e,mki:t})}static deSerialize(e){const t=new _UseSRTP(decode7(e,_UseSRTP.spec));const n=t.data.readUInt16BE();const r=new Array(n/2);for(let e=0;e<r.length;e++)r[e]=t.data.readUInt16BE(e*2+2);t.profiles=r;t.mki=t.data.slice(n+2);return t}serialize(){const e=Buffer.alloc(2);e.writeUInt16BE(this.profiles.length*2);const t=Buffer.concat([e,...this.profiles.map(e=>{const t=Buffer.alloc(2);t.writeUInt16BE(e);return t}),this.mki]);this.data=t;return encode8(this,_UseSRTP.spec)}static fromData(e){const t=Buffer.alloc(4);t.writeUInt16BE(_UseSRTP.type);t.writeUInt16BE(e.length,2);return _UseSRTP.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}};var{decode:decode8,encode:encode9,types:types10}=binaryData_exports;var Certificate2=class _Certificate{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:types10.array(ASN11Cert,types10.uint24be,`bytes`)};static createEmpty(){return new _Certificate(void 0)}static deSerialize(e){return new _Certificate(...Object.values(decode8(e,_Certificate.spec)))}serialize(){return encode9(this,_Certificate.spec)}toFragment(){const e=this.serialize();return new FragmentedHandshake(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:decode9,encode:encode10,types:types11}=binaryData_exports;var ChangeCipherSpec=class _ChangeCipherSpec{constructor(e=1){this.type=e}static spec={type:types11.uint8};static createEmpty(){return new _ChangeCipherSpec}static deSerialize(e){return new _ChangeCipherSpec(...Object.values(decode9(e,_ChangeCipherSpec.spec)))}serialize(){return encode10(this,_ChangeCipherSpec.spec)}};var{decode:decode10,encode:encode11,types:types12}=binaryData_exports;var CertificateVerify=class _CertificateVerify{constructor(e,t){this.algorithm=e;this.signature=t}msgType=15;messageSeq;static spec={algorithm:types12.uint16be,signature:types12.buffer(types12.uint16be)};static createEmpty(){return new _CertificateVerify(void 0,void 0)}static deSerialize(e){const t=decode10(e,_CertificateVerify.spec);return new _CertificateVerify(...Object.values(t))}serialize(){return encode11(this,_CertificateVerify.spec)}toFragment(){const e=this.serialize();return new FragmentedHandshake(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:decode11,encode:encode12,types:types13}=binaryData_exports;var ClientKeyExchange=class _ClientKeyExchange{constructor(e){this.publicKey=e}msgType=16;messageSeq;static spec={publicKey:types13.buffer(types13.uint8)};static createEmpty(){return new _ClientKeyExchange(void 0)}static deSerialize(e){const t=decode11(e,_ClientKeyExchange.spec);return new _ClientKeyExchange(...Object.values(t))}serialize(){return encode12(this,_ClientKeyExchange.spec)}toFragment(){const e=this.serialize();return new FragmentedHandshake(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var Finished=class _Finished{constructor(e){this.verifyData=e}msgType=20;messageSeq;static createEmpty(){return new _Finished(void 0)}static deSerialize(e){return new _Finished(e)}serialize(){return this.verifyData}toFragment(){const e=this.serialize();return new FragmentedHandshake(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:decode12,encode:encode13,types:types14}=binaryData_exports;var ServerCertificateRequest=class _ServerCertificateRequest{constructor(e,t,n){this.certificateTypes=e;this.signatures=t;this.authorities=n}msgType=13;messageSeq;static spec={certificateTypes:types14.array(ClientCertificateType,types14.uint8,`bytes`),signatures:types14.array(SignatureHashAlgorithm,types14.uint16be,`bytes`),authorities:types14.array(DistinguishedName,types14.uint16be,`bytes`)};static createEmpty(){return new _ServerCertificateRequest(void 0,void 0,void 0)}static deSerialize(e){return new _ServerCertificateRequest(...Object.values(decode12(e,_ServerCertificateRequest.spec)))}serialize(){return encode13(this,_ServerCertificateRequest.spec)}toFragment(){const e=this.serialize();return new FragmentedHandshake(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:decode13,encode:encode14,types:types15}=binaryData_exports;var ServerHello=class _ServerHello{constructor(e,t,n,r,i,a){this.serverVersion=e;this.random=t;this.sessionId=n;this.cipherSuite=r;this.compressionMethod=i;this.extensions=a}msgType=2;messageSeq;static spec={serverVersion:ProtocolVersion,random:DtlsRandom.spec,sessionId:types15.buffer(types15.uint8),cipherSuite:types15.uint16be,compressionMethod:types15.uint8};static createEmpty(){return new _ServerHello(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){const t=decode13(e,_ServerHello.spec);const n=new _ServerHello(...Object.values(t));if(n.serialize().length<e.length)return new _ServerHello(...Object.values(decode13(e,{..._ServerHello.spec,extensions:ExtensionList})));return n}serialize(){return this.extensions===void 0?encode14(this,_ServerHello.spec):encode14(this,{..._ServerHello.spec,extensions:ExtensionList})}toFragment(){const e=this.serialize();return new FragmentedHandshake(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{decode:decode14,encode:encode15}=binaryData_exports;var ServerHelloDone=class _ServerHelloDone{msgType=14;messageSeq;static spec={};static createEmpty(){return new _ServerHelloDone}static deSerialize(e){return new _ServerHelloDone(...Object.values(decode14(e,_ServerHelloDone.spec)))}serialize(){return encode15(this,_ServerHelloDone.spec)}toFragment(){const e=this.serialize();return new FragmentedHandshake(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var{encode:encode16}=binaryData_exports;function encodeBuffer(e,t){return encode16(e,t)}var{decode:decode15,types:types16}=binaryData_exports;var ServerKeyExchange=class _ServerKeyExchange{constructor(e,t,n,r,i,a,o,s){this.ellipticCurveType=e;this.namedCurve=t;this.publicKeyLength=n;this.publicKey=r;this.hashAlgorithm=i;this.signatureAlgorithm=a;this.signatureLength=o;this.signature=s}msgType=12;messageSeq;static spec={ellipticCurveType:types16.uint8,namedCurve:types16.uint16be,publicKeyLength:types16.uint8,publicKey:types16.buffer(e=>e.current.publicKeyLength),hashAlgorithm:types16.uint8,signatureAlgorithm:types16.uint8,signatureLength:types16.uint16be,signature:types16.buffer(e=>e.current.signatureLength)};static createEmpty(){return new _ServerKeyExchange(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){const t=decode15(e,_ServerKeyExchange.spec);return new _ServerKeyExchange(...Object.values(t))}serialize(){return encodeBuffer(this,_ServerKeyExchange.spec)}toFragment(){const e=this.serialize();return new FragmentedHandshake(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var ProtectionProfileAes128CmHmacSha1_80=1;var ProtectionProfileAeadAes128Gcm=7;var Profiles=[1,7];var keyLength=e=>{switch(e){case 1:case 7:return 16}};var saltLength=e=>{switch(e){case 1:return 14;case 7:return 12}};var MTU=1200;var ExtensionProfiles={OneByte:48862,TwoByte:4096};var seqNumOffset=2;var timestampOffset=4;var ssrcOffset=8;var csrcOffset=12;var csrcSize=4;var RtpHeader=class _RtpHeader{version=2;padding=false;paddingSize=0;extension=false;marker=false;payloadOffset=0;payloadType=0;sequenceNumber=0;timestamp=0;ssrc=0;csrcLength=0;csrc=[];extensionProfile=ExtensionProfiles.OneByte;extensionLength;extensions=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){const t=new _RtpHeader;let n=0;const r=e[n++];t.version=getBit(r,0,2);t.padding=getBit(r,2)>0;t.extension=getBit(r,3)>0;t.csrcLength=getBit(r,4,4);t.csrc=[...Array(t.csrcLength)].map(()=>{const t=e.readUInt32BE(n);n+=4;return t});n+=csrcOffset-1;const i=e[1];t.marker=getBit(i,0)>0;t.payloadType=getBit(i,1,7);t.sequenceNumber=e.readUInt16BE(seqNumOffset);t.timestamp=e.readUInt32BE(timestampOffset);t.ssrc=e.readUInt32BE(ssrcOffset);for(let n=0;n<t.csrc.length;n++){const r=csrcOffset+n*csrcSize;t.csrc[n]=e.subarray(r).readUInt32BE()}if(t.extension){t.extensionProfile=e.subarray(n).readUInt16BE();n+=2;const r=e.subarray(n).readUInt16BE()*4;t.extensionLength=r;n+=2;switch(t.extensionProfile){case ExtensionProfiles.OneByte:{const i=n+r;while(n<i){if(e[n]===0){n++;continue}const r=e[n]>>4;const i=(e[n]&(e[n]^240))+1;n++;if(r===15)break;const a={id:r,payload:e.subarray(n,n+i)};t.extensions=[...t.extensions,a];n+=i}}break;case ExtensionProfiles.TwoByte:{const i=n+r;while(n<i){if(e[n]===0){n++;continue}const r=e[n];n++;const i=e[n];n++;const a={id:r,payload:e.subarray(n,n+i)};t.extensions=[...t.extensions,a];n+=i}}break;default:{const i={id:0,payload:e.subarray(n,n+r)};t.extensions=[...t.extensions,i];n+=t.extensions[0].payload.length}}}t.payloadOffset=n;if(t.padding)t.paddingSize=e[e.length-1];return t}get serializeSize(){const{csrc:e,extensionProfile:t,extensions:n}=this;let r=12+e.length*csrcSize;if(n.length>0||this.extension===true){let e=4;switch(t){case ExtensionProfiles.OneByte:for(const t of n)e+=1+t.payload.length;break;case ExtensionProfiles.TwoByte:for(const t of n)e+=2+t.payload.length;break;default:e+=n[0].payload.length}r+=Math.floor((e+3)/4)*4}return r}serialize(e){const t=Buffer.alloc(e);let n=0;const r=new BitWriter(8);r.set(2,0,this.version);if(this.padding)r.set(1,2,1);if(this.extensions.length>0)this.extension=true;if(this.extension)r.set(1,3,1);r.set(4,4,this.csrc.length);t.writeUInt8(r.value,n++);const i=new BitWriter(8);if(this.marker)i.set(1,0,1);i.set(7,1,this.payloadType);t.writeUInt8(i.value,n++);t.writeUInt16BE(this.sequenceNumber,seqNumOffset);n+=2;t.writeUInt32BE(this.timestamp,timestampOffset);n+=4;t.writeUInt32BE(this.ssrc,ssrcOffset);n+=4;for(const e of this.csrc){t.writeUInt32BE(e,n);n+=4}if(this.extension){const e=n;t.writeUInt16BE(this.extensionProfile,n);n+=4;const r=n;switch(this.extensionProfile){case ExtensionProfiles.OneByte:for(const e of this.extensions){t.writeUInt8(e.id<<4|e.payload.length-1,n++);e.payload.copy(t,n);n+=e.payload.length}break;case ExtensionProfiles.TwoByte:for(const e of this.extensions){t.writeUInt8(e.id,n++);t.writeUInt8(e.payload.length,n++);e.payload.copy(t,n);n+=e.payload.length}break;default:{const e=this.extensions[0].payload.length;if(e%4!=0)throw new Error;this.extensions[0].payload.copy(t,n);n+=e}}const i=n-r;const a=Math.trunc((i+3)/4)*4;t.writeUInt16BE(Math.trunc(a/4),e+2);for(let e=0;e<a-i;e++){t.writeUInt8(0,n);n++}}this.payloadOffset=n;return t}};var RtpPacket=class _RtpPacket{constructor(e,t){this.header=e;this.payload=t}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new _RtpPacket(new RtpHeader({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length);const{payloadOffset:t}=this.header;this.payload.copy(e,t);if(this.header.padding){const t=Buffer.alloc(this.header.paddingSize);t.writeUInt8(this.header.paddingSize,this.header.paddingSize-1);e=Buffer.concat([e,t])}return e}static deSerialize(e){const t=RtpHeader.deSerialize(e);return new _RtpPacket(t,e.subarray(t.payloadOffset,e.length-t.paddingSize))}clear(){this.payload=null}};var DePacketizerBase=class{payload;fragment;static deSerialize(e,t){return{}}static isDetectedFinalPacketInSequence(e){return true}get isKeyframe(){return true}};var PacketizerBase=class{sequenceNumber;maxPayloadSize;payloadType;ssrc;constructor(e={}){const t=e.maxPayloadSize??MTU;if(!Number.isInteger(t)||t<=0)throw new Error(`PacketizerBase: maxPayloadSize must be a positive integer, got ${t}`);this.maxPayloadSize=t;this.payloadType=e.payloadType??96;this.sequenceNumber=e.sequenceNumber??random16();this.ssrc=e.ssrc??0}talkspurtPending=true;startTalkspurt(){this.talkspurtPending=true}takeTalkspurtMarker(){const e=this.talkspurtPending;this.talkspurtPending=false;return e}buildPacket(e,t,n){const r=new RtpPacket(new RtpHeader({payloadType:this.payloadType,sequenceNumber:this.sequenceNumber,timestamp:t,marker:n,ssrc:this.ssrc}),e);this.sequenceNumber=this.sequenceNumber+1&65535;return r}};function leb128encode(e){if(!Number.isInteger(e)||e<0||!Number.isSafeInteger(e))throw new Error(`LEB128 encode requires a non-negative safe integer`);const t=[];let n=e;do{let e=n&127;n=Math.floor(n/128);if(n!==0)e|=128;t.push(e)}while(n!==0);return Buffer.from(t)}var log3=debug(`werift-rtp : packages/rtp/src/codec/av1.ts`);var AV1RtpPayload=class _AV1RtpPayload{zBit_RtpStartsWithFragment;yBit_RtpEndsWithFragment;w_RtpNumObus;nBit_RtpStartsNewCodedVideoSequence;obu_or_fragment=[];static deSerialize=e=>{const t=new _AV1RtpPayload;let n=0;t.zBit_RtpStartsWithFragment=getBit(e[n],0);t.yBit_RtpEndsWithFragment=getBit(e[n],1);t.w_RtpNumObus=getBit(e[n],2,2);t.nBit_RtpStartsNewCodedVideoSequence=getBit(e[n],4);n++;if(t.nBit_RtpStartsNewCodedVideoSequence&&t.zBit_RtpStartsWithFragment)throw new Error;if(t.w_RtpNumObus===0){let r=0;while(n<e.length){const[i,a]=leb128decode(e.subarray(n));const o=n+a;const s=o+i;if(s>e.length)throw new Error(`AV1 OBU element length exceeds payload`);const c=r===0;const u=s>=e.length;const d=c&&!!t.zBit_RtpStartsWithFragment||u&&!!t.yBit_RtpEndsWithFragment;t.obu_or_fragment.push({data:e.subarray(o,s),isFragment:d,continues:u&&!!t.yBit_RtpEndsWithFragment,isContinuation:c&&!!t.zBit_RtpStartsWithFragment});n=s;r++}return t}[...Array(t.w_RtpNumObus-1).keys()].forEach(r=>{const[i,a]=leb128decode(e.subarray(n));const o=n+a;const s=o+i;let c=false;if(t.zBit_RtpStartsWithFragment&&r===0)c=true;t.obu_or_fragment.push({data:e.subarray(o,s),isFragment:c,continues:false,isContinuation:c});n+=a+i});let r=false;if(t.yBit_RtpEndsWithFragment||t.w_RtpNumObus===1&&t.zBit_RtpStartsWithFragment)r=true;t.obu_or_fragment.push({data:e.subarray(n),isFragment:r,continues:!!t.yBit_RtpEndsWithFragment,isContinuation:!!t.zBit_RtpStartsWithFragment&&t.w_RtpNumObus===1});return t};static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nBit_RtpStartsNewCodedVideoSequence===1}static getFrame(e){const t=[];let n=[];const flushLost=()=>{if(n.length>0){log3(`fragment lost, maybe packet lost`);n=[]}};for(const{data:r,isFragment:i,continues:a,isContinuation:o}of e.flatMap(e=>e.obu_or_fragment)){if(!i){flushLost();t.push(r);continue}if(!o){flushLost();n=[r]}else if(n.length===0){log3(`fragment lost, maybe packet lost`);continue}else n.push(r);if(!a){if(n.length>1)t.push(Buffer.concat(n));else log3(`fragment lost, maybe packet lost`);n=[]}}flushLost();const r=t.map(e=>AV1Obu.deSerialize(e));if(r.length===0)return Buffer.alloc(0);const i=r.pop();return Buffer.concat([...r.map(e=>{e.obu_has_size_field=1;return e.serialize()}),i.serialize()])}};var AV1Obu=class _AV1Obu{obu_forbidden_bit;obu_type;obu_extension_flag;obu_has_size_field;obu_reserved_1bit;extension_header;payload;static deSerialize(e){if(e.length<1)throw new Error(`AV1 OBU too short: expected at least 1 header byte`);const t=new _AV1Obu;let n=0;t.obu_forbidden_bit=getBit(e[n],0);t.obu_type=OBU_TYPES[getBit(e[n],1,4)];t.obu_extension_flag=getBit(e[n],5);t.obu_has_size_field=getBit(e[n],6);t.obu_reserved_1bit=getBit(e[n],7);n++;if(t.obu_extension_flag){if(n>=e.length)throw new Error(`AV1 OBU: extension flag set but extension byte missing`);t.extension_header=e[n];n++}if(t.obu_has_size_field){const[r,i]=leb128decode(e.subarray(n));n+=i;const a=n+r;if(a>e.length)throw new Error(`AV1 OBU size field ${r} exceeds remaining buffer ${e.length-n}`);t.payload=e.subarray(n,a)}else t.payload=e.subarray(n);return t}serialize(){const e=new BitWriter2(8).set(this.obu_forbidden_bit).set(OBU_TYPE_IDS[this.obu_type],4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer;const t=this.obu_extension_flag&&this.extension_header!==void 0?Buffer.from([this.extension_header&255]):Buffer.alloc(0);let n=Buffer.alloc(0);if(this.obu_has_size_field)n=leb128encode(this.payload.length);return Buffer.concat([e,t,n,this.payload])}};function leb128decode(e){let t=0;let n=0;for(let r=0;r<8;r++){if(r>=e.length)throw new Error(`LEB128 decode incomplete`);const i=e.readUInt8(r);t+=(i&127)*128**r;n++;if(!(i&128)){if(!Number.isSafeInteger(t))throw new Error(`LEB128 value exceeds safe integer`);return[t,n]}}throw new Error(`LEB128 decode incomplete`)}var OBU_TYPES={0:`Reserved`,1:`OBU_SEQUENCE_HEADER`,2:`OBU_TEMPORAL_DELIMITER`,3:`OBU_FRAME_HEADER`,4:`OBU_TILE_GROUP`,5:`OBU_METADATA`,6:`OBU_FRAME`,7:`OBU_REDUNDANT_FRAME_HEADER`,8:`OBU_TILE_LIST`,15:`OBU_PADDING`};var OBU_TYPE_IDS=Object.entries(OBU_TYPES).reduce((e,[t,n])=>{e[n]=Number(t);return e},{});function createAv1AggregationHeader({startsWithFragment:e,endsWithFragment:t,startsNewCodedVideoSequence:n,obuCount:r=1}){if(e&&n)throw new Error(`AV1 aggregation header: N=1 and Z=1 must not both be set (AV1 RTP §4.4)`);if(!Number.isInteger(r)||r<1||r>3)throw new Error(`AV1 aggregation header: invalid W=${r}`);return new BitWriter(8).set(1,0,e?1:0).set(1,1,t?1:0).set(2,2,r).set(1,4,n?1:0).set(3,5,0).buffer}function splitAv1Obus(e){const t=[];let n=0;while(n<e.length){const r=n;const i=e[n];n+=1;if(i==void 0)break;const a=getBit(i,5);const o=getBit(i,6);if(a){if(n>=e.length)throw new Error(`invalid AV1 OBU: extension flag set but buffer ends`);n+=1}if(!o){t.push(e.subarray(r));break}const[s,c]=leb128decode(e.subarray(n));n+=c;const u=n+s;if(u>e.length)throw new Error(`invalid AV1 OBU size`);t.push(e.subarray(r,u));n=u}return t}var MAX_W_ELEMENTS=3;var OBU_SEQUENCE_HEADER=1;var OBU_TEMPORAL_DELIMITER=2;function toRtpObuElement(e){const t=e[0];if(!getBit(t,6))return e;const n=getBit(t,5)?2:1;const[,r]=leb128decode(e.subarray(n));const i=Buffer.concat([e.subarray(0,n),e.subarray(n+r)]);i[0]=t&-3;return i}function getAv1ObuLayerId(e){if(!getBit(e[0],5)||e.length<2)return void 0;return e[1]&248}var Av1Packetizer=class extends PacketizerBase{defaultIsKeyframe;constructor(e={}){super(e);this.defaultIsKeyframe=e.isKeyframe??false}packetize(e,t,n={}){if(e.length===0)return[];let r=this.defaultIsKeyframe;if(n.frameType===`key`)r=true;else if(n.frameType===`delta`)r=false;else if(n.isKeyframe!==void 0)r=n.isKeyframe;const i=splitAv1Obus(e);if(i.length===0)throw new Error(`AV1 sample did not contain any OBU data`);const a=n.startsNewCodedVideoSequence??(r&&i.some(e=>(e[0]>>3&15)===OBU_SEQUENCE_HEADER));const o=i.filter(e=>(e[0]>>3&15)!==OBU_TEMPORAL_DELIMITER).map(toRtpObuElement);if(o.length===0)return[];const s=this.maxPayloadSize-1;if(s<=0)throw new Error(`Av1Packetizer: maxPayloadSize ${this.maxPayloadSize} too small for aggregation header`);const c=[];let u=0;let d=0;while(u<o.length){const e=d>0;const n=[];let r=0;let i=false;let f;while(u<o.length&&n.length<MAX_W_ELEMENTS){const e=o[u];const t=getAv1ObuLayerId(e);if(t!==void 0&&f!==void 0&&t!==f)break;const a=e.subarray(d);const c=n.length>0?leb128encode(n.at(-1).length).length:0;const p=s-r-c;if(p<=0)break;r+=c;if(a.length<=p){n.push(a);r+=a.length;if(t!==void 0)f=t;u++;d=0;continue}n.push(a.subarray(0,p));r+=p;if(t!==void 0)f=t;d+=p;i=true;break}const p=createAv1AggregationHeader({startsWithFragment:e,endsWithFragment:i,startsNewCodedVideoSequence:c.length===0&&a,obuCount:n.length});const m=n.flatMap((e,t)=>t<n.length-1?[leb128encode(e.length),e]:[e]);c.push(this.buildPacket(Buffer.concat([p,...m]),t,false))}c.at(-1).header.marker=true;return c}};var PCMU_PAYLOAD_TYPE=0;var PCMA_PAYLOAD_TYPE=8;var G711_CLOCK_RATE=8e3;var DEFAULT_FRAME_DURATION_MS=20;var PcmuRtpPayload=class _PcmuRtpPayload{payload;static deSerialize(e){const t=new _PcmuRtpPayload;t.payload=e;return t}static isDetectedFinalPacketInSequence(e){return true}get isKeyframe(){return true}};var PcmaRtpPayload=class _PcmaRtpPayload{payload;static deSerialize(e){const t=new _PcmaRtpPayload;t.payload=e;return t}static isDetectedFinalPacketInSequence(e){return true}get isKeyframe(){return true}};var G711Packetizer=class extends PacketizerBase{frameBytes;constructor(e={}){super(e);const t=e.frameDurationInMs??DEFAULT_FRAME_DURATION_MS;this.frameBytes=Math.max(1,Math.floor(G711_CLOCK_RATE*t/1e3))}packetize(e,t){if(e.length===0)return[];const n=Math.min(this.maxPayloadSize,this.frameBytes);const r=[];let i=t>>>0;for(let t=0;t<e.length;t+=n){const a=Math.min(e.length,t+n);const o=e.subarray(t,a);r.push(this.buildPacket(o,i,this.takeTalkspurtMarker()));i=i+o.length>>>0}return r}};var PcmuPacketizer=class extends G711Packetizer{constructor(e={}){super({...e,payloadType:e.payloadType??0})}};var PcmaPacketizer=class extends G711Packetizer{constructor(e={}){super({...e,payloadType:e.payloadType??8})}};var G722_PAYLOAD_TYPE=9;var G722_CLOCK_RATE=8e3;var G722_OCTET_RATE=8e3;var DEFAULT_FRAME_DURATION_MS2=20;var G722RtpPayload=class _G722RtpPayload{payload;static deSerialize(e){const t=new _G722RtpPayload;t.payload=e;return t}static isDetectedFinalPacketInSequence(e){return true}get isKeyframe(){return true}};var G722Packetizer=class extends PacketizerBase{frameBytes;constructor(e={}){super({...e,payloadType:e.payloadType??9});const t=e.frameDurationInMs??DEFAULT_FRAME_DURATION_MS2;this.frameBytes=Math.max(1,Math.floor(G722_OCTET_RATE*t/1e3))}packetize(e,t){if(e.length===0)return[];const n=Math.min(this.maxPayloadSize,this.frameBytes);const r=[];let i=t>>>0;for(let t=0;t<e.length;t+=n){const a=Math.min(e.length,t+n);const o=e.subarray(t,a);r.push(this.buildPacket(o,i,this.takeTalkspurtMarker()));i=i+o.length>>>0}return r}};var H265_PAYLOAD_TYPE_AP=48;var H265_PAYLOAD_TYPE_FU=49;var H265_PAYLOAD_TYPE_PACI=50;var H265_IRAP_NAL_TYPES={BLA_W_LP:16,BLA_W_RADL:17,BLA_N_LP:18,IDR_W_RADL:19,IDR_N_LP:20,CRA_NUT:21};var H265_NAL_TYPE={VPS:32,SPS:33,PPS:34,AUD:35,...H265_IRAP_NAL_TYPES,AP:48,FU:49};var annexBStartCode=Buffer.from([0,0,0,1]);function parseH265PayloadHeader(e){if(e.length<2)throw new Error(`H.265 payload header too short: expected 2 bytes, got ${e.length}`);const t=e[0];const n=e[1];return{f:getBit(t,0,1),type:getBit(t,1,6),layerId:getBit(t,7,1)<<5|getBit(n,0,5),tid:getBit(n,5,3)}}function writeH265PayloadHeader(e){const t=(e.f&1)<<7|(e.type&63)<<1|e.layerId>>5&1;const n=(e.layerId&31)<<3|e.tid&7;return Buffer.from([t,n])}function isIrapType(e){return e>=16&&e<=21}function packageAnnexB(e){return Buffer.concat([annexBStartCode,e])}var H265RtpPayload=class _H265RtpPayload{f=0;type=0;layerId=0;tid=0;s=0;e=0;fuType=0;apContainsIrap=false;payload;fragment;static deSerialize(e,t,n={}){const r=new _H265RtpPayload;if(e.length<2)throw new Error(`H.265 RTP payload too short: expected at least 2 bytes, got ${e.length}`);const i=parseH265PayloadHeader(e);r.f=i.f;r.type=i.type;r.layerId=i.layerId;r.tid=i.tid;if(i.type===48){let t=2;if(n.hasDonl){if(t+2>e.length)throw new Error(`H.265 AP: DONL exceeds buffer`);t+=2}const i=[];let a=true;while(t<e.length){if(!a&&n.hasDonl){if(t+1>e.length)throw new Error(`H.265 AP: DOND exceeds buffer`);t+=1}if(t+2>e.length)throw new Error(`H.265 AP: NALU size field exceeds buffer`);const o=e.readUInt16BE(t);t+=2;if(o<2)throw new Error(`H.265 AP: NALU size ${o} too small for header`);if(t+o>e.length)throw new Error(`H.265 AP: NALU size ${o} at offset ${t} exceeds buffer ${e.length}`);const s=e.subarray(t,t+o);if(isIrapType(nalTypeOf(s)))r.apContainsIrap=true;i.push(packageAnnexB(s));t+=o;a=false}if(i.length===0)throw new Error(`H.265 AP: no aggregation units in payload`);r.payload=Buffer.concat(i);return r}if(i.type===49){if(e.length<3)throw new Error(`H.265 FU: payload shorter than PayloadHdr+FU header`);const i=e[2];r.s=getBit(i,0,1);r.e=getBit(i,1,1);r.fuType=getBit(i,2,6);if(r.s&&r.e)throw new Error(`H.265 FU: S and E must not both be set (RFC 7798 §4.4.3)`);let a=3;if(n.hasDonl&&r.s){if(a+2>e.length)throw new Error(`H.265 FU: DONL exceeds buffer`);a+=2}const o=e.subarray(a);if(o.length===0)throw new Error(`H.265 FU: empty FU payload (RFC 7798 forbids empty)`);let s;if(r.s){const e=writeH265PayloadHeader({f:r.f,type:r.fuType,layerId:r.layerId,tid:r.tid});s=Buffer.concat([e,o])}else{if(!t||t.length===0)throw new Error(`H.265 FU: received non-start fragment (S=0) without prior FU start (S=1)`);s=Buffer.concat([t,o])}if(r.e){r.fragment=void 0;r.payload=packageAnnexB(s)}else r.fragment=s;return r}if(i.type===50)throw new Error(`H.265 PACI (type 50) is not supported`);let a=2;if(n.hasDonl){if(e.length<4)throw new Error(`H.265 single NAL: DONL exceeds buffer`);a=4}r.payload=packageAnnexB(Buffer.concat([e.subarray(0,2),e.subarray(a)]));return r}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){if(this.type===49)return isIrapType(this.fuType);if(this.type===48)return this.apContainsIrap;return isIrapType(this.type)}get isPartitionHead(){if(this.type===49)return this.s!==0;return true}};var H265AnnexBParser=class{data;currentStartcodeOffset=0;eof=false;constructor(e){this.data=e;this.currentStartcodeOffset=this.findNextStartCodeOffset(0)}findNextStartCodeOffset(e){const t=this.data;let n=e;for(;;){if(n+3>=t.length){this.eof=true;return t.length}const e=t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3];const r=t[n]<<16|t[n+1]<<8|t[n+2];if(e===1||r===1)return n;n++}}readNextNalu(){if(this.eof)return null;let e=this.currentStartcodeOffset;const t=this.data[e]<<24|this.data[e+1]<<16|this.data[e+2]<<8|this.data[e+3];e+=t===1?4:3;const n=this.findNextStartCodeOffset(e);this.currentStartcodeOffset=n;if(e>=n)return this.eof?null:this.readNextNalu();return this.data.subarray(e,n)}readAll(){const e=[];let t=this.readNextNalu();while(t){e.push(t);t=this.readNextNalu()}return e}};function looksLikeAnnexB(e){if(e.length<4)return false;return e[0]===0&&e[1]===0&&e[2]===0&&e[3]===1||e[0]===0&&e[1]===0&&e[2]===1}function readUintLength(e,t,n){if(n===1)return e[t];if(n===2)return e.readUInt16BE(t);if(n===3)return e[t]<<16|e[t+1]<<8|e[t+2];return e.readUInt32BE(t)}function splitH265NalUnits(e,t=4,n=`auto`){if(t<1||t>4||!Number.isInteger(t))throw new Error(`H.265 naluLengthSize must be an integer 1\u20134, got ${t}`);if(e.length===0)return[];if((n===`auto`?looksLikeAnnexB(e)?`annexb`:`length-prefixed`:n)===`annexb`){if(!looksLikeAnnexB(e))throw new Error(`H.265 inputFormat annexb: sample does not start with a start code`);return new H265AnnexBParser(e).readAll()}const r=parseLengthPrefixed(e,t);if(r.nalus)return r.nalus;throw new Error(r.error)}function parseLengthPrefixed(e,t){const n=[];let r=0;while(r<e.length){if(r+t>e.length)return{error:`H.265 length-prefixed sample truncated (length field)`};const i=readUintLength(e,r,t);r+=t;if(i===0)return{error:`H.265 length-prefixed sample: NAL length 0 is invalid`};if(r+i>e.length)return{error:`H.265 length-prefixed sample: NAL length ${i} exceeds buffer`};n.push(e.subarray(r,r+i));r+=i}return{nalus:n,error:``}}function nalTypeOf(e){if(e.length<2)return 0;return parseH265PayloadHeader(e).type}var H265Packetizer=class extends PacketizerBase{naluLengthSize;inputFormat;parameterSets;constructor(e={}){super(e);const t=e.naluLengthSize??4;if(t<1||t>4||!Number.isInteger(t))throw new Error(`H265Packetizer: naluLengthSize must be an integer 1\u20134, got ${t}`);this.naluLengthSize=t;this.inputFormat=e.inputFormat??`auto`;this.parameterSets=e.parameterSets??[]}packetize(e,t){let n=splitH265NalUnits(e,this.naluLengthSize,this.inputFormat);if(n.length===0)return[];if(n.some(e=>isIrapType(nalTypeOf(e)))&&this.parameterSets.length>0&&!containsParameterSets(n)){const e=n.findIndex(e=>nalTypeOf(e)!==35);const t=e===-1?n.length:e;n=[...n.slice(0,t),...this.parameterSets,...n.slice(t)]}const r=[];let i=0;if(n.length>=2&&isParameterSet(nalTypeOf(n[0]))){const e=[];let a=2;while(i<n.length&&isParameterSet(nalTypeOf(n[i]))){const t=n[i];const r=2+t.length;if(e.length>0&&a+r>this.maxPayloadSize)break;if(e.length===0&&a+r>this.maxPayloadSize)break;e.push(t);a+=r;i++}if(e.length>=2){const a=i>=n.length;r.push(this.buildPacket(buildAggregationPacket(e),t,a))}else i=0}for(;i<n.length;i++){const e=n[i];const a=i===n.length-1;if(e.length<=this.maxPayloadSize){r.push(this.buildPacket(e,t,a));continue}if(e.length<3)throw new Error(`H.265 NAL too short to fragment`);const o=parseH265PayloadHeader(e);const s=writeH265PayloadHeader({f:o.f,type:49,layerId:o.layerId,tid:o.tid});const c=e.subarray(2);const u=this.maxPayloadSize-3;if(u<=0)throw new Error(`invalid H.265 RTP maxPayloadSize for FU`);for(let e=0;e<c.length;e+=u){const n=c.subarray(e,Math.min(c.length,e+u));const i=e===0;const d=e+n.length>=c.length;const f=Buffer.from([(i?128:0)|(d?64:0)|o.type&63]);r.push(this.buildPacket(Buffer.concat([s,f,n]),t,a&&d))}}return r}};function isParameterSet(e){return e===H265_NAL_TYPE.VPS||e===H265_NAL_TYPE.SPS||e===H265_NAL_TYPE.PPS}function containsParameterSets(e){const t=new Set(e.map(nalTypeOf));return t.has(H265_NAL_TYPE.VPS)&&t.has(H265_NAL_TYPE.SPS)&&t.has(H265_NAL_TYPE.PPS)}function buildAggregationPacket(e){if(e.length<2)throw new Error(`H.265 AP requires at least two NAL units`);const t=e.map(e=>{if(e.length<2)throw new Error(`H.265 AP: NAL unit shorter than 2-byte header`);return parseH265PayloadHeader(e)});let n=0;let r=t[0].layerId;let i=t[0].tid;for(const e of t){n|=e.f;if(e.layerId<r)r=e.layerId;if(e.tid<i)i=e.tid}const a=[writeH265PayloadHeader({f:n,type:48,layerId:r,tid:i})];for(const t of e){if(t.length>65535)throw new Error(`H.265 NAL unit too large for AP size field`);const e=Buffer.alloc(2);e.writeUInt16BE(t.length,0);a.push(e,t)}return Buffer.concat(a)}var H264RtpPayload=class _H264RtpPayload{f;nri;nalUnitType;s;e;r;nalUnitPayloadType;aggregatedNalUnitTypes=[];payload;fragment;static deSerialize(e,t){const n=new _H264RtpPayload;if(e.length<1)throw new Error(`H.264 RTP payload too short: expected at least 1 byte (NAL/FU indicator)`);let r=0;const i=e[r];n.f=getBit(i,0);n.nri=getBit(i,1,2);n.nalUnitType=getBit(i,3,5);r++;if(0<n.nalUnitType&&n.nalUnitType<NalUnitType.stap_a){n.payload=this.packaging(e);return n}if(e.length<2)throw new Error(`H.264 RTP payload too short for type ${n.nalUnitType}: expected at least 2 bytes, got ${e.length}`);if(n.nalUnitType===NalUnitType.fu_a||n.nalUnitType===NalUnitType.fu_b){n.s=getBit(e[r],0);n.e=getBit(e[r],1);n.r=getBit(e[r],2);n.nalUnitPayloadType=getBit(e[r],3,5);r++}if(n.nalUnitType===NalUnitType.stap_a){let t=stap_aHeaderSize;let r=Buffer.alloc(0);while(t<e.length){if(t+stap_aNALULengthSize>e.length)throw new Error(`H.264 STAP-A: NALU size field exceeds buffer`);const i=e.readUInt16BE(t);t+=stap_aNALULengthSize;if(t+i>e.length)throw new Error(`H.264 STAP-A: NALU size ${i} exceeds buffer`);if(i>0)n.aggregatedNalUnitTypes.push(getBit(e[t],3,5));r=Buffer.concat([r,this.packaging(e.subarray(t,t+i))]);t+=i}n.payload=r}else if(n.nalUnitType===NalUnitType.fu_a){if(!t)t=Buffer.alloc(0);const i=e.subarray(r);n.fragment=Buffer.concat([t,i]);if(n.e&&n.nalUnitPayloadType!==void 0){const e=new BitStream(Buffer.alloc(1)).writeBits(1,0).writeBits(2,n.nri).writeBits(5,n.nalUnitPayloadType);const t=Buffer.concat([e.uint8Array,n.fragment]);n.fragment=void 0;n.payload=this.packaging(t)}}return n}static packaging(e){return Buffer.concat([annex_bNALUStartCode,e])}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){switch(this.nalUnitType){case NalUnitType.idrSlice:return true;case NalUnitType.fu_a:case NalUnitType.fu_b:return this.nalUnitPayloadType===NalUnitType.idrSlice;case NalUnitType.stap_a:return this.aggregatedNalUnitTypes.includes(NalUnitType.idrSlice);default:return false}}get isPartitionHead(){if(this.nalUnitType===NalUnitType.fu_a||this.nalUnitType===NalUnitType.fu_b)return this.s!==0;return true}};var NalUnitType={idrSlice:5,sps:7,pps:8,stap_a:24,stap_b:25,mtap16:26,mtap24:27,fu_a:28,fu_b:29};var annex_bNALUStartCode=Buffer.from([0,0,0,1]);var stap_aHeaderSize=1;var stap_aNALULengthSize=2;function looksLikeAnnexB2(e){if(e.length<3)return false;return e[0]===0&&e[1]===0&&e[2]===0&&e[3]===1||e[0]===0&&e[1]===0&&e[2]===1}function readUintLength2(e,t,n){if(n===1)return e[t];if(n===2)return e.readUInt16BE(t);if(n===3)return e[t]<<16|e[t+1]<<8|e[t+2];return e.readUInt32BE(t)}function splitH264NalUnits(e,t=4,n=`auto`){if(t<1||t>4||!Number.isInteger(t))throw new Error(`H.264 naluLengthSize must be an integer 1\u20134, got ${t}`);if(e.length===0)return[];if((n===`auto`?looksLikeAnnexB2(e)?`annexb`:`length-prefixed`:n)===`annexb`){if(!looksLikeAnnexB2(e))throw new Error(`H.264 inputFormat annexb: sample does not start with a start code`);return new H265AnnexBParser(e).readAll()}const r=parseLengthPrefixed2(e,t);if(r.nalus)return r.nalus;throw new Error(r.error)}function parseLengthPrefixed2(e,t){const n=[];let r=0;while(r<e.length){if(r+t>e.length)return{error:`H.264 length-prefixed sample truncated (length field)`};const i=readUintLength2(e,r,t);r+=t;if(i===0)return{error:`H.264 length-prefixed sample: NAL length 0 is invalid`};if(r+i>e.length)return{error:`H.264 length-prefixed sample: NAL length ${i} exceeds buffer`};n.push(e.subarray(r,r+i));r+=i}return{nalus:n,error:``}}function h264NalType(e){if(e.length<1)return 0;return e[0]&31}function isH264ParameterSet(e){return e===NalUnitType.sps||e===NalUnitType.pps}function selectMissingH264ParameterSets(e,t){const n=t.some(e=>h264NalType(e)===NalUnitType.sps);const r=t.some(e=>h264NalType(e)===NalUnitType.pps);return e.filter(e=>{const t=h264NalType(e);if(t===NalUnitType.sps)return!n;if(t===NalUnitType.pps)return!r;return false})}var H264_MIN_NAL_LENGTH=2;function minH264NalLength(e){const t=e.length>0?e[0]&31:0;return t===10||t===11?1:2}function buildH264StapA(e){if(e.length<2)throw new Error(`H.264 STAP-A requires at least two NAL units`);let t=0;let n=0;for(const r of e){if(r.length<minH264NalLength(r))throw new Error(`H.264 STAP-A: NAL unit too short (need \u2265${minH264NalLength(r)} bytes, got ${r.length})`);if(r.length>65535)throw new Error(`H.264 NAL unit too large for STAP-A size field`);t|=r[0]>>7&1;const e=r[0]>>5&3;if(e>n)n=e}const r=[Buffer.from([t<<7|n<<5|NalUnitType.stap_a])];for(const t of e){const e=Buffer.alloc(2);e.writeUInt16BE(t.length,0);r.push(e,t)}return Buffer.concat(r)}var H264Packetizer=class extends PacketizerBase{naluLengthSize;inputFormat;parameterSets;defaultIsKeyframe;constructor(e={}){super(e);const t=e.naluLengthSize??4;if(t<1||t>4||!Number.isInteger(t))throw new Error(`H264Packetizer: naluLengthSize must be an integer 1\u20134, got ${t}`);this.naluLengthSize=t;this.inputFormat=e.inputFormat??`auto`;this.parameterSets=e.parameterSets??[];this.defaultIsKeyframe=e.isKeyframe}packetize(e,t,n={}){let r=splitH264NalUnits(e,this.naluLengthSize,this.inputFormat);if(r.length===0)return[];const i=r.some(e=>h264NalType(e)===NalUnitType.idrSlice);if((n.isKeyframe??this.defaultIsKeyframe??i)&&this.parameterSets.length>0){const e=selectMissingH264ParameterSets(this.parameterSets,r);if(e.length>0){const t=r.findIndex(e=>h264NalType(e)!==9);const n=t===-1?r.length:t;r=[...r.slice(0,n),...e,...r.slice(n)]}}const a=[];let o=0;if(r.length>=2&&isH264ParameterSet(h264NalType(r[0]))){const e=[];let n=1;while(o<r.length&&isH264ParameterSet(h264NalType(r[o]))){const t=r[o];const i=2+t.length;if(n+i>this.maxPayloadSize)break;e.push(t);n+=i;o++}if(e.length>=2){const n=o>=r.length;a.push(this.buildPacket(buildH264StapA(e),t,n))}else o=0}for(;o<r.length;o++){const e=r[o];const n=o===r.length-1;if(e.length<minH264NalLength(e))throw new Error(`H.264 NAL unit too short: expected at least ${minH264NalLength(e)} bytes (NAL header + data), got ${e.length}`);if(e.length<=this.maxPayloadSize){a.push(this.buildPacket(e,t,n));continue}const i=e[0];const s=e.subarray(1);const c=this.maxPayloadSize-2;if(c<=0)throw new Error(`invalid H.264 RTP maxPayloadSize for FU-A`);const u=i&224|NalUnitType.fu_a;const d=i&31;for(let e=0;e<s.length;e+=c){const r=s.subarray(e,Math.min(s.length,e+c));const i=e===0;const o=e+r.length>=s.length;const f=Buffer.from([(i?128:0)|(o?64:0)|d]);a.push(this.buildPacket(Buffer.concat([Buffer.from([u]),f,r]),t,n&&o))}}return a}};function parseAvcDecoderConfigurationRecord(e){const t=ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);if(t.length<7)throw new Error(`invalid H.264 avcC: expected at least 7 bytes, got ${t.length}`);const n=(t[4]&3)+1;let r=5;const readSets=e=>{const n=[];for(let i=0;i<e;i++){if(r+2>t.length)throw new Error(`invalid H.264 avcC: truncated parameter set length`);const e=t.readUInt16BE(r);r+=2;if(r+e>t.length)throw new Error(`invalid H.264 avcC: truncated parameter set`);n.push(t.subarray(r,r+e));r+=e}return n};const i=readSets(t[r++]&31);const a=r<t.length?readSets(t[r++]):[];return{naluLengthSize:n,sps:i,pps:a,parameterSets:[...i,...a]}}var MPEG4_GENERIC_ENCODING_NAME=`MPEG4-GENERIC`;var AAC_HBR_SIZE_LENGTH=13;var AAC_HBR_INDEX_LENGTH=3;var AAC_HBR_INDEX_DELTA_LENGTH=3;var AAC_HBR_AU_HEADER_BITS=13+3;var FRAG_SIZE_PREFIX=4;var AacHbrRtpPayload=class _AacHbrRtpPayload{payload;fragment;auHeaders=[];isContinuationFragment=false;optionalAuHeaderFieldsDetected=false;static deSerialize(e,t,n={}){const r=new _AacHbrRtpPayload;if(e.length<2)throw new Error(`AAC AU Header Section too short: expected at least 2 bytes, got ${e.length}`);const i=e.readUInt16BE(0);if(i<16)throw new Error(`AAC AU-headers-length too small: ${i} bits (minimum 16 for hbr)`);if(!n.ctsDtsPresent&&i%16!==0)throw new Error(`AAC AU-headers-length must be a multiple of 16, got ${i}`);const a=2+Math.ceil(i/8);if(a>e.length)throw new Error(`AAC AU Header Section exceeds buffer: need ${a}, have ${e.length}`);const{headers:o,optionalFieldsDetected:s}=parseAuHeaders(e.subarray(2,a),i,n);r.auHeaders=o;r.optionalAuHeaderFieldsDetected=s;const c=e.subarray(a);let u=0;for(const e of o)u+=e.size;const d=t&&t.length>=FRAG_SIZE_PREFIX?t.readUInt32BE(0):void 0;if(d!==void 0&&o.length===1&&o[0].size===d&&c.length>0&&t.length-FRAG_SIZE_PREFIX+c.length<=d){r.isContinuationFragment=true;const e=Buffer.concat([t.subarray(FRAG_SIZE_PREFIX),c]);if(e.length===d)r.payload=e;else r.fragment=packFragment(d,e);return r}if(o.length===1&&c.length<o[0].size){if(c.length===0)throw new Error(`AAC fragmented AU with empty data section`);r.fragment=packFragment(o[0].size,c);return r}if(u>c.length)throw new Error(`AAC AU sizes exceed data section: headers sum ${u}, data ${c.length}`);if(u<c.length)throw new Error(`AAC data section has surplus bytes: headers sum ${u}, data ${c.length}`);if(o.length===1)r.payload=Buffer.from(c.subarray(0,o[0].size));else{const e=[];let t=0;for(const n of o){e.push(c.subarray(t,t+n.size));t+=n.size}r.payload=Buffer.concat(e)}return r}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return true}};function packFragment(e,t){const n=Buffer.alloc(FRAG_SIZE_PREFIX);n.writeUInt32BE(e,0);return Buffer.concat([n,t])}function parseAuHeaders(e,t,n){const r=[];let i=0;let a=true;let o=false;if(n.ctsDtsPresent){while(i+16+2<=t){const s=readBits(e,i,13);i+=13;const c=a?3:3;const u=readBits(e,i,c);i+=c;const d={size:s,index:u};const f=readBits(e,i,1);i+=1;d.hasCts=f===1;if(f===1){const r=n.ctsDeltaLength??14;if(i+r>t)throw new Error(`AAC AU-header CTS-delta exceeds AU-headers-length`);d.ctsDelta=readBits(e,i,r);i+=r}if(i>=t)throw new Error(`AAC AU-header missing DTS-flag after CTS fields`);const p=readBits(e,i,1);i+=1;d.hasDts=p===1;if(p===1){const r=n.dtsDeltaLength??14;if(i+r>t)throw new Error(`AAC AU-header DTS-delta exceeds AU-headers-length`);d.dtsDelta=readBits(e,i,r);i+=r}r.push(d);a=false;o=true}if(i!==t)throw new Error(`AAC AU-headers-length ${t} does not match parsed AU-headers (${i} bits)`)}else{while(i+16<=t){const t=readBits(e,i,13);i+=13;const n=readBits(e,i,a?3:3);i+=a?3:3;r.push({size:t,index:n});a=false}const n=t-i;if(n>7)o=true;else if(n>0){if(readBits(e,i,n)!==0)o=true}}if(r.length===0)throw new Error(`AAC AU Header Section contained no AU-headers`);return{headers:r,optionalFieldsDetected:o}}function readBits(e,t,n){let r=0;for(let i=0;i<n;i++){const n=t+i;const a=n>>3;const o=7-(n&7);if(a>=e.length)throw new Error(`AAC AU-header bit read past end of buffer`);const s=e[a]>>o&1;r=r<<1|s}return r}function writeBits(e,t,n,r){for(let i=0;i<n;i++){const a=t+i;const o=a>>3;const s=7-(a&7);if(r>>n-1-i&1)e[o]|=1<<s}}var AacHbrPacketizer=class extends PacketizerBase{auDurationInSamples;constructor(e={}){super(e);const t=e.auDurationInSamples??1024;if(!Number.isInteger(t)||t<=0)throw new Error(`AacHbrPacketizer: auDurationInSamples must be a positive integer, got ${t}`);this.auDurationInSamples=t}packetize(e,t){return this.packetizeAccessUnits([e],t)}packetizeAccessUnits(e,t){const n=[];let r=[];let i=0;const flush=()=>{if(r.length>0){n.push(this.buildPacket(buildAuPayload(r),this.tsOf(t,i),true));r=[]}};const groupSize=e=>2+Math.ceil(e.length*16/8)+e.reduce((e,t)=>e+t.length,0);e.forEach((e,a)=>{if(e.length===0)throw new Error(`AAC AU must not be empty`);if(groupSize([e])>this.maxPayloadSize){flush();n.push(...this.fragmentAu(e,this.tsOf(t,a)));return}if(r.length>0&&groupSize([...r,e])>this.maxPayloadSize)flush();if(r.length===0)i=a;r.push(e)});flush();return n}tsOf(e,t){return(e>>>0)+t*this.auDurationInSamples>>>0}fragmentAu(e,t){const n=this.maxPayloadSize-4;if(n<=0)throw new Error(`invalid AAC RTP maxPayloadSize for fragmentation`);const r=[];for(let i=0;i<e.length;i+=n){const a=e.subarray(i,Math.min(e.length,i+n));r.push(this.buildPacket(buildAuPayload([e],a),t,i+a.length>=e.length))}return r}};function buildAuPayload(e,t){const n=e.length*16;const r=Math.ceil(n/8);const i=Buffer.alloc(r);let a=0;e.forEach((e,t)=>{if(e.length>8191)throw new Error(`AAC AU size ${e.length} exceeds AAC-hbr maximum 8191 octets (RFC 3640 \xA73.3.6)`);writeBits(i,a,13,e.length);a+=13;writeBits(i,a,t===0?3:3,0);a+=t===0?3:3});const o=Buffer.alloc(2);o.writeUInt16BE(n,0);const s=t??(e.length===1?e[0]:Buffer.concat(e));return Buffer.concat([o,i,s])}var OPUS_CLOCK_RATE=48e3;var OpusRtpPayload=class _OpusRtpPayload{payload;static deSerialize(e){const t=new _OpusRtpPayload;t.payload=e;return t}static isDetectedFinalPacketInSequence(e){return true}get isKeyframe(){return true}static createCodecPrivate(e=48e3){return Buffer.concat([Buffer.from(`OpusHead`),bufferWriter([1,1],[1,2]),bufferWriterLE([2,4,2,1],[312,e,0,0])])}};var OpusPacketizer=class extends PacketizerBase{constructor(e={}){super(e)}packetize(e,t){if(e.length===0)return[];if(e.length>this.maxPayloadSize)throw new Error(`OpusPacketizer: Opus packet length ${e.length} exceeds maxPayloadSize ${this.maxPayloadSize} (RFC 7587 forbids blind MTU fragmentation of the TOC)`);return[this.buildPacket(e,t,this.takeTalkspurtMarker())]}};var Vp8RtpPayload=class _Vp8RtpPayload{xBit;nBit;sBit;pid;iBit;lBit;tBit;kBit;mBit;pictureId;payload;size0=0;hBit;ver;pBit;size1=0;size2=0;static deSerialize(e){const t=new _Vp8RtpPayload;let n=0;t.xBit=getBit(e[n],0);t.nBit=getBit(e[n],2);t.sBit=getBit(e[n],3);t.pid=getBit(e[n],5,3);n++;if(t.xBit){t.iBit=getBit(e[n],0);t.lBit=getBit(e[n],1);t.tBit=getBit(e[n],2);t.kBit=getBit(e[n],3);n++}if(t.iBit){t.mBit=getBit(e[n],0);if(t.mBit){const r=paddingByte(getBit(e[n],1,7));const i=paddingByte(e[n+1]);t.pictureId=Number.parseInt(r+i,2);n+=2}else{t.pictureId=getBit(e[n],1,7);n++}}if(t.lBit)n++;if(t.lBit||t.kBit){if(t.tBit){}if(t.kBit){}n++}t.payload=e.subarray(n);if(t.payloadHeaderExist){t.size0=getBit(e[n],0,3);t.hBit=getBit(e[n],3);t.ver=getBit(e[n],4,3);t.pBit=getBit(e[n],7);n++;t.size1=e[n];n++;t.size2=e[n]}return t}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.pBit===0}get isPartitionHead(){return this.sBit===1}get payloadHeaderExist(){return this.sBit===1&&this.pid===0}get size(){if(this.payloadHeaderExist)return this.size0+8*this.size1+2048*this.size2;return 0}};var VP8_PAYLOAD_DESCRIPTOR_LENGTH=4;var VP8_PICTURE_ID_MASK=32767;function createVp8PayloadDescriptor({start:e,pictureId:t}){const n=t&VP8_PICTURE_ID_MASK;return Buffer.from([128|(e?16:0),128,128|n>>8,n&255])}var Vp8Packetizer=class extends PacketizerBase{pictureId;constructor(e={}){super(e);this.pictureId=(e.pictureId??random16())&VP8_PICTURE_ID_MASK}packetize(e,t){if(e.length===0)return[];const n=this.maxPayloadSize-4;if(n<=0)throw new Error(`Vp8Packetizer: maxPayloadSize ${this.maxPayloadSize} too small for VP8 descriptor`);const r=this.pictureId;this.pictureId=this.pictureId+1&VP8_PICTURE_ID_MASK;const i=[];for(let a=0;a<e.length;a+=n){const o=e.subarray(a,Math.min(e.length,a+n));const s=createVp8PayloadDescriptor({start:a===0,pictureId:r});const c=a+o.length>=e.length;i.push(this.buildPacket(Buffer.concat([s,o]),t,c))}return i}};var Vp9RtpPayload=class _Vp9RtpPayload{iBit;pBit;lBit;fBit;bBit;eBit;vBit;zBit;m;pictureId;tid;u;sid;d;tl0PicIdx;pDiff=[];n_s;y;g;width=[];height=[];n_g=0;pgT=[];pgU=[];pgP_Diff=[];payload;static deSerialize(e){const{p:t,offset:n}=this.parseRtpPayload(e);t.payload=e.subarray(n);return t}static parseRtpPayload(e){const t=new _Vp9RtpPayload;let n=0;t.iBit=getBit(e[n],0);t.pBit=getBit(e[n],1);t.lBit=getBit(e[n],2);t.fBit=getBit(e[n],3);t.bBit=getBit(e[n],4);t.eBit=getBit(e[n],5);t.vBit=getBit(e[n],6);t.zBit=getBit(e[n],7);n++;if(t.iBit){t.m=getBit(e[n],0);if(t.m){const r=paddingByte(getBit(e[n],1,7));const i=paddingByte(e[n+1]);t.pictureId=Number.parseInt(r+i,2);n+=2}else{t.pictureId=getBit(e[n],1,7);n++}}if(t.lBit){t.tid=getBit(e[n],0,3);t.u=getBit(e[n],3);t.sid=getBit(e[n],4,3);t.d=getBit(e[n],7);n++;if(t.fBit===0){t.tl0PicIdx=e[n];n++}}if(t.fBit&&t.pBit)for(;;){t.pDiff=[...t.pDiff,getBit(e[n],0,7)];const r=getBit(e[n],7);n++;if(r===0)break}if(t.vBit){t.n_s=getBit(e[n],0,3);t.y=getBit(e[n],3);t.g=getBit(e[n],4);n++;if(t.y)[...Array(t.n_s+1)].forEach(()=>{t.width.push(e.readUInt16BE(n));n+=2;t.height.push(e.readUInt16BE(n));n+=2});if(t.g){t.n_g=e[n];n++}if(t.n_g>0)[...Array(t.n_g).keys()].forEach(r=>{t.pgT.push(getBit(e[n],0,3));t.pgU.push(getBit(e[n],3));const i=getBit(e[n],4,2);n++;t.pgP_Diff[r]=[];if(i>0)[...Array(i)].forEach(()=>{t.pgP_Diff[r].push(e[n]);n++})})}return{offset:n,p:t}}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return!!(!this.pBit&&this.bBit&&(!this.sid||!this.lBit))}get isPartitionHead(){return this.bBit&&(!this.lBit||!this.d)}};var Vp9Packetizer=class extends PacketizerBase{defaultIsKeyframe;constructor(e={}){super(e);this.defaultIsKeyframe=e.isKeyframe??false}packetize(e,t,n={}){if(e.length===0)return[];const r=this.maxPayloadSize-1;if(r<=0)throw new Error(`Vp9Packetizer: maxPayloadSize ${this.maxPayloadSize} too small for VP9 descriptor`);let i=this.defaultIsKeyframe;if(n.frameType===`key`)i=true;else if(n.frameType===`delta`)i=false;else if(n.isKeyframe!==void 0)i=n.isKeyframe;const a=i?0:1;const o=[];for(let n=0;n<e.length;n+=r){const i=e.subarray(n,Math.min(e.length,n+r));const s=n===0;const c=n+i.length>=e.length;const u=new BitWriter(8).set(1,0,0).set(1,1,a).set(1,2,0).set(1,3,0).set(1,4,s?1:0).set(1,5,c?1:0).set(1,6,0).set(1,7,0).buffer;o.push(this.buildPacket(Buffer.concat([u,i]),t,c))}return o}};var TELEPHONE_EVENT_DEFAULT_PAYLOAD_TYPE=101;var TELEPHONE_EVENT_DEFAULT_CLOCK_RATE=8e3;var PAYLOAD_SIZE=4;function assertUintRange(e,t,n){if(!Number.isInteger(t)||t<0||t>n)throw new RangeError(`telephone-event ${e} must be an integer in 0..${n}, got ${t}`)}var TelephoneEventRtpPayload=class _TelephoneEventRtpPayload{event=0;end=false;reserved=false;volume=0;duration=0;constructor(e={}){Object.assign(this,e)}static deSerialize(e){if(e.length<PAYLOAD_SIZE)throw new Error(`telephone-event payload too short: expected ${PAYLOAD_SIZE}, got ${e.length}`);const t=new _TelephoneEventRtpPayload;t.event=e[0];t.end=(e[1]&128)!==0;t.reserved=(e[1]&64)!==0;t.volume=e[1]&63;t.duration=e.readUInt16BE(2);return t}serialize(){assertUintRange(`event`,this.event,255);assertUintRange(`volume`,this.volume,63);assertUintRange(`duration`,this.duration,65535);const e=Buffer.alloc(PAYLOAD_SIZE);e[0]=this.event&255;e[1]=(this.end?128:0)|(this.reserved?64:0)|this.volume&63;e.writeUInt16BE(this.duration,2);return e}static isDetectedFinalPacketInSequence(e){return true}get isKeyframe(){return true}get payload(){return this.serialize()}};var TelephoneEventPacketizer=class extends PacketizerBase{constructor(e={}){super({...e,payloadType:e.payloadType??101})}packetize(e,t){if(Buffer.isBuffer(e))return[this.packetizeBuffer(e,t,false)];return[this.packetizeEvent(e,t)]}packetizeBuffer(e,t,n=false){if(e.length<PAYLOAD_SIZE)throw new Error(`telephone-event packetize: payload must be at least ${PAYLOAD_SIZE} bytes`);return this.buildPacket(e.subarray(0,PAYLOAD_SIZE),t,n)}packetizeEvent(e,t){const n=new TelephoneEventRtpPayload({event:e.event,volume:e.volume,duration:e.duration,end:!!e.end}).serialize();return this.buildPacket(n,t,!!e.start)}packetizeStart(e,t,n,r){return this.packetizeEvent({event:e,volume:t,duration:n,start:true,end:false},r)}packetizeContinue(e,t,n,r){return this.packetizeEvent({event:e,volume:t,duration:n,start:false,end:false},r)}packetizeEnd(e,t,n,r){return this.packetizeEvent({event:e,volume:t,duration:n,start:false,end:true},r)}};function dePacketizeRtpPackets(e,t,n){const basicCodecParser=e=>{const r=[];for(const i of t){const t=e.deSerialize(i.payload,n);if(t.fragment){n??=Buffer.alloc(0);n=t.fragment}else if(t.payload)n=void 0;r.push(t)}return{isKeyframe:!!r.find(e=>e.isKeyframe),data:Buffer.concat(r.map(e=>e.payload).filter(e=>e)),sequence:t.at(-1)?.header.sequenceNumber??0,timestamp:t.at(-1)?.header.timestamp??0,frameFragmentBuffer:n}};switch(e.toUpperCase()){case`AV1`:{const e=t.map(e=>AV1RtpPayload.deSerialize(e.payload));return{isKeyframe:!!e.find(e=>e.isKeyframe),data:AV1RtpPayload.getFrame(e),sequence:t.at(-1)?.header.sequenceNumber??0,timestamp:t.at(-1)?.header.timestamp??0}}case`MPEG4/ISO/AVC`:return basicCodecParser(H264RtpPayload);case`H265`:case`HEVC`:return basicCodecParser(H265RtpPayload);case`VP8`:return basicCodecParser(Vp8RtpPayload);case`VP9`:return basicCodecParser(Vp9RtpPayload);case`OPUS`:return basicCodecParser(OpusRtpPayload);case`PCMU`:return basicCodecParser(PcmuRtpPayload);case`PCMA`:return basicCodecParser(PcmaRtpPayload);case`G722`:return basicCodecParser(G722RtpPayload);case`MPEG4-GENERIC`:return basicCodecParser(AacHbrRtpPayload);default:throw new Error}}var depacketizerCodecs=[`MPEG4/ISO/AVC`,`H265`,`VP8`,`VP9`,`OPUS`,`AV1`,`PCMU`,`PCMA`,`G722`,`MPEG4-GENERIC`];function enumerate(e){return e.map((e,t)=>[t,e])}function growBufferSize(e,t){const n=Buffer.alloc(t);e.copy(n);return n}function Int(e){return Number.parseInt(e.toString(),10)}var timer={setTimeout:(...e)=>{const t=setTimeout(...e);return()=>clearTimeout(t)},setInterval:(...e)=>{const t=setInterval(()=>{e[0]()},...e.slice(1));return()=>clearInterval(t)}};function isMedia(e){const t=e[0];return t>127&&t<192}var RTCP_HEADER_SIZE=4;var RtcpHeader=class _RtcpHeader{version=2;padding=false;count=0;type=0;length=0;constructor(e={}){Object.assign(this,e)}static serialize(e,t,n,r){const i=new _RtcpHeader({type:e,count:t,version:2,length:r}).serialize();return Buffer.concat([i,n])}serialize(){const e=new BitWriter(8);e.set(2,0,this.version);if(this.padding)e.set(1,2,1);e.set(5,3,this.count);return bufferWriter([1,1,2],[e.value,this.type,this.length])}static deSerialize(e){const[t,n,r]=bufferReader(e,[1,1,2]);const i=getBit(t,0,2);const a=getBit(t,2,1)>0;const o=getBit(t,3,5);return new _RtcpHeader({version:i,padding:a,count:o,type:n,length:r})}};var FullIntraRequest=class _FullIntraRequest{static count=4;count=_FullIntraRequest.count;senderSsrc;mediaSsrc;fir=[];constructor(e={}){Object.assign(this,e)}get length(){return Math.floor(this.serialize().length/4-1)}static deSerialize(e){const[t,n]=bufferReader(e,[4,4]);const r=[];for(let t=8;t<e.length;t+=8)r.push({ssrc:e.readUInt32BE(t),sequenceNumber:e[t+4]});return new _FullIntraRequest({senderSsrc:t,mediaSsrc:n,fir:r})}serialize(){const e=bufferWriter([4,4],[this.senderSsrc,this.mediaSsrc]);const t=Buffer.alloc(this.fir.length*8);this.fir.forEach(({ssrc:e,sequenceNumber:n},r)=>{t.writeUInt32BE(e,r*8);t[r*8+4]=n});return Buffer.concat([e,t])}};var PictureLossIndication=class _PictureLossIndication{static count=1;count=_PictureLossIndication.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(e){const[t,n]=bufferReader(e,[4,4]);return new _PictureLossIndication({senderSsrc:t,mediaSsrc:n})}serialize(){return bufferWriter([4,4],[this.senderSsrc,this.mediaSsrc])}};var ReceiverEstimatedMaxBitrate=class _ReceiverEstimatedMaxBitrate{static count=15;length;count=_ReceiverEstimatedMaxBitrate.count;senderSsrc;mediaSsrc;uniqueID=`REMB`;ssrcNum=0;brExp;brMantissa;bitrate;ssrcFeedbacks=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){const[t,n,r,i,a]=bufferReader(e,[4,4,4,1,1]);const o=getBit(a,0,6);const s=(getBit(a,6,2)<<16)+(e[14]<<8)+e[15];const c=o>46?18446744073709551615n:BigInt(s)<<BigInt(o);const u=[];for(let t=16;t<e.length;t+=4){const n=e.slice(t).readUIntBE(0,4);u.push(n)}return new _ReceiverEstimatedMaxBitrate({senderSsrc:t,mediaSsrc:n,uniqueID:bufferWriter([4],[r]).toString(),ssrcNum:i,brExp:o,brMantissa:s,ssrcFeedbacks:u,bitrate:c})}serialize(){const e=Buffer.concat([bufferWriter([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),bufferWriter([1],[this.ssrcNum])]);const t=new BitWriter(24);t.set(6,0,this.brExp).set(18,6,this.brMantissa);const n=Buffer.concat(this.ssrcFeedbacks.map(e=>bufferWriter([4],[e])));const r=Buffer.concat([e,bufferWriter([3],[t.value]),n]);this.length=r.length/4;return r}};var log4=debug(`werift-rtp: /rtcp/psfb/index`);var RtcpPayloadSpecificFeedback=class _RtcpPayloadSpecificFeedback{static type=206;type=_RtcpPayloadSpecificFeedback.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){const e=this.feedback.serialize();return RtcpHeader.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(e,t){let n;switch(t.count){case FullIntraRequest.count:n=FullIntraRequest.deSerialize(e);break;case PictureLossIndication.count:n=PictureLossIndication.deSerialize(e);break;case ReceiverEstimatedMaxBitrate.count:n=ReceiverEstimatedMaxBitrate.deSerialize(e);break;default:log4(`unknown psfb packet`,t.count)}return new _RtcpPayloadSpecificFeedback({feedback:n})}};var RtcpRrPacket=class _RtcpRrPacket{ssrc=0;reports=[];static type=201;type=_RtcpRrPacket.type;constructor(e={}){Object.assign(this,e)}serialize(){let e=bufferWriter([4],[this.ssrc]);e=Buffer.concat([e,...this.reports.map(e=>e.serialize())]);return RtcpHeader.serialize(_RtcpRrPacket.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){const[n]=bufferReader(e,[4]);let r=4;const i=[];for(let n=0;n<t;n++){i.push(RtcpReceiverInfo.deSerialize(e.slice(r,r+24)));r+=24}return new _RtcpRrPacket({ssrc:n,reports:i})}};var RtcpReceiverInfo=class _RtcpReceiverInfo{ssrc;fractionLost;packetsLost;highestSequence;jitter;lsr;dlsr;constructor(e={}){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,fractionLost:this.fractionLost,packetsLost:this.packetsLost,highestSequence:this.highestSequence,jitter:this.jitter,lsr:this.lsr,dlsr:this.dlsr}}serialize(){return bufferWriter([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(e){const[t,n,r,i,a,o,s]=bufferReader(e,[4,1,3,4,4,4,4]);return new _RtcpReceiverInfo({ssrc:t,fractionLost:n,packetsLost:r,highestSequence:i,jitter:a,lsr:o,dlsr:s})}};var RtcpTransportLayerFeedbackType=205;var GenericNack=class _GenericNack{static count=1;count=_GenericNack.count;header;senderSsrc;mediaSourceSsrc;lost=[];toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){Object.assign(this,e);if(!this.header)this.header=new RtcpHeader({type:RtcpTransportLayerFeedbackType,count:this.count,version:2})}static deSerialize(e,t){const[n,r]=bufferReader(e,[4,4]);const i=[];for(let t=8;t<e.length;t+=4){const[n,r]=bufferReader(e.subarray(t),[2,2]);i.push(n);for(let e=0;e<16;e++)if(r>>e&1)i.push(n+e+1)}return new _GenericNack({header:t,senderSsrc:n,mediaSourceSsrc:r,lost:i})}serialize(){const e=bufferWriter([4,4],[this.senderSsrc,this.mediaSourceSsrc]);const t=[];if(this.lost.length>0){let e=this.lost[0],n=0;this.lost.slice(1).forEach(r=>{const i=r-e-1;if(i>=0&&i<16)n|=1<<i;else{t.push(bufferWriter([2,2],[e,n]));e=r;n=0}});t.push(bufferWriter([2,2],[e,n]))}const n=Buffer.concat([e,Buffer.concat(t)]);this.header.length=n.length/4;return Buffer.concat([this.header.serialize(),n])}};var log5=debug(`werift/rtp/rtcp/rtpfb/twcc`);var TransportWideCC=class _TransportWideCC{static count=15;count=_TransportWideCC.count;length=2;senderSsrc;mediaSourceSsrc;baseSequenceNumber;packetStatusCount;referenceTime;fbPktCount;packetChunks=[];recvDeltas=[];header;constructor(e={}){Object.assign(this,e);if(!this.header)this.header=new RtcpHeader({type:205,count:this.count,version:2})}static deSerialize(e,t){const[n,r,i,a,o,s]=bufferReader(e,[4,4,2,2,3,1]);const c=[];const u=[];let d=16;for(let t=0;t<a;){const n=getBit(e.slice(d,d+1)[0],0,1);let r;switch(n){case 0:{const n=RunLengthChunk.deSerialize(e.slice(d,d+2));r=n;const i=Math.min(a-t,n.runLength);if(n.packetStatus===1||n.packetStatus===2)for(let e=0;e<i;e++)u.push(new RecvDelta({type:n.packetStatus}));t+=i}break;case 1:{const n=StatusVectorChunk.deSerialize(e.slice(d,d+2));r=n;if(n.symbolSize===0)n.symbolList.forEach(e=>{if(e===1)u.push(new RecvDelta({type:1}))});if(n.symbolSize===1)n.symbolList.forEach(e=>{if(e===1||e===2)u.push(new RecvDelta({type:e}))});t+=n.symbolList.length}}if(!r)throw new Error;d+=2;c.push(r)}let f=d;u.forEach(t=>{if(t.type===1){t.deSerialize(e.slice(f,f+1));f++}if(t.type===2){t.deSerialize(e.slice(f,f+2));f+=2}});return new _TransportWideCC({senderSsrc:n,mediaSourceSsrc:r,baseSequenceNumber:i,packetStatusCount:a,referenceTime:o,fbPktCount:s,recvDeltas:u,packetChunks:c,header:t})}serialize(){const e=bufferWriter([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]);const t=Buffer.concat(this.packetChunks.map(e=>e.serialize()));const n=Buffer.concat(this.recvDeltas.map(e=>{try{return e.serialize()}catch(e){log5(e?.message);return}}).filter(e=>e));const r=Buffer.concat([e,t,n]);if(this.header.padding&&r.length%4!==0){const e=4-r.length%4;const t=Buffer.alloc(e);t[t.length-1]=t.length;this.header.length=Math.floor((r.length+t.length)/4);return Buffer.concat([this.header.serialize(),r,t])}this.header.length=Math.floor(r.length/4);return Buffer.concat([this.header.serialize(),r])}get packetResults(){const e=this.baseSequenceNumber-1;const t=this.packetChunks.filter(e=>e instanceof RunLengthChunk).flatMap(t=>t.results(e));let n=0;let r=BigInt(this.referenceTime)*64n;for(const e of t){const t=this.recvDeltas[n];if(!e.received||!t)continue;r+=BigInt(t.delta)/1000n;e.delta=t.delta;e.receivedAtMs=Number(r);n++}return t}};var RunLengthChunk=class _RunLengthChunk{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e);this.type=0}static deSerialize(e){const t=getBit(e[0],1,2);const n=(getBit(e[0],3,5)<<8)+e[1];return new _RunLengthChunk({type:0,packetStatus:t,runLength:n})}serialize(){return new BitWriter2(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer}results(e){const t=this.packetStatus===1||this.packetStatus===2;const n=[];for(let r=0;r<=this.runLength;++r)n.push(new PacketResult({sequenceNumber:++e,received:t}));return n}};var StatusVectorChunk=class _StatusVectorChunk{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){const t=1;let n=getBit(e[0],1,1);const r=[];function range(e,t){for(let n=0;n<e;n++)t(n)}switch(n){case 0:range(6,t=>r.push(getBit(e[0],2+t,1)));range(8,t=>r.push(getBit(e[1],t,1)));break;case 1:range(3,t=>r.push(getBit(e[0],2+t*2,2)));range(4,t=>r.push(getBit(e[1],t*2,2)));break;default:n=(getBit(e[0],2,6)<<8)+e[1]}return new _StatusVectorChunk({type:t,symbolSize:n,symbolList:r})}serialize(){const e=Buffer.alloc(2);const t=new BitWriter2(16).set(1).set(this.symbolSize);const n=this.symbolSize===0?1:2;this.symbolList.forEach(e=>{t.set(e,n)});e.writeUInt16BE(t.value);return e}};var RecvDelta=class _RecvDelta{type;delta;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let t;let n;if(e.length===1){t=1;n=250*e[0]}else if(e.length===2){t=2;n=250*e.readInt16BE()}if(t===void 0||n===void 0)throw new Error;return new _RecvDelta({type:t,delta:n})}deSerialize(e){const t=_RecvDelta.deSerialize(e);this.delta=t.delta}parsed=false;parseDelta(){this.delta=Math.floor(this.delta/250);if(this.delta<0||this.delta>255){if(this.delta>32767)this.delta=32767;if(this.delta<-32768)this.delta=-32768;if(!this.type)this.type=2}else if(!this.type)this.type=1;this.parsed=true}serialize(){if(!this.parsed)this.parseDelta();if(this.type===1){const e=Buffer.alloc(1);e.writeUInt8(this.delta);return e}else if(this.type===2){const e=Buffer.alloc(2);e.writeInt16BE(this.delta);return e}throw new Error(`errDeltaExceedLimit `+this.delta+` `+this.type)}};var PacketChunk=/* @__PURE__ */ (e=>{e[e[`TypeTCCRunLengthChunk`]=0]=`TypeTCCRunLengthChunk`;e[e[`TypeTCCStatusVectorChunk`]=1]=`TypeTCCStatusVectorChunk`;e[e[`packetStatusChunkLength`]=2]=`packetStatusChunkLength`;return e})(PacketChunk||{});var PacketStatus=/* @__PURE__ */ (e=>{e[e[`TypeTCCPacketNotReceived`]=0]=`TypeTCCPacketNotReceived`;e[e[`TypeTCCPacketReceivedSmallDelta`]=1]=`TypeTCCPacketReceivedSmallDelta`;e[e[`TypeTCCPacketReceivedLargeDelta`]=2]=`TypeTCCPacketReceivedLargeDelta`;e[e[`TypeTCCPacketReceivedWithoutDelta`]=3]=`TypeTCCPacketReceivedWithoutDelta`;return e})(PacketStatus||{});var PacketResult=class{sequenceNumber=0;delta=0;received=false;receivedAtMs=0;constructor(e){Object.assign(this,e)}};var log6=debug(`werift-rtp:packages/rtp/rtcp/rtpfb/index`);var RtcpTransportLayerFeedback=class _RtcpTransportLayerFeedback{static type=RtcpTransportLayerFeedbackType;type=_RtcpTransportLayerFeedback.type;feedback;header;constructor(e={}){Object.assign(this,e)}serialize(){return this.feedback.serialize()}static deSerialize(e,t){let n;switch(t.count){case GenericNack.count:n=GenericNack.deSerialize(e,t);break;case TransportWideCC.count:n=TransportWideCC.deSerialize(e,t);break;default:log6(`unknown rtpfb packet`,t.count)}return new _RtcpTransportLayerFeedback({feedback:n,header:t})}};var RtcpSourceDescriptionPacket=class _RtcpSourceDescriptionPacket{static type=202;type=_RtcpSourceDescriptionPacket.type;chunks=[];constructor(e){Object.assign(this,e)}get length(){let e=0;this.chunks.forEach(t=>e+=t.length);return e}serialize(){let e=Buffer.concat(this.chunks.map(e=>e.serialize()));while(e.length%4)e=Buffer.concat([e,Buffer.from([0])]);return RtcpHeader.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(e,t){const n=[];for(let t=0;t<e.length;){const r=SourceDescriptionChunk.deSerialize(e.slice(t));n.push(r);t+=r.length}return new _RtcpSourceDescriptionPacket({chunks:n})}};var SourceDescriptionChunk=class _SourceDescriptionChunk{source;items=[];constructor(e={}){Object.assign(this,e)}get length(){let e=4;this.items.forEach(t=>e+=t.length);e+=1;e+=getPadding(e);return e}serialize(){const e=Buffer.concat([bufferWriter([4],[this.source]),Buffer.concat(this.items.map(e=>e.serialize()))]);return Buffer.concat([e,Buffer.alloc(getPadding(e.length))])}static deSerialize(e){const t=e.readUInt32BE();const n=[];for(let t=4;t<e.length;){if(e[t]===0)break;const r=SourceDescriptionItem.deSerialize(e.slice(t));n.push(r);t+=r.length}return new _SourceDescriptionChunk({source:t,items:n})}};var SourceDescriptionItem=class _SourceDescriptionItem{type;text;constructor(e){Object.assign(this,e)}get length(){return 2+Buffer.from(this.text).length}serialize(){const e=Buffer.from(this.text);return Buffer.concat([bufferWriter([1,1],[this.type,e.length]),e])}static deSerialize(e){const t=e[0];const n=e[1];const r=e.slice(2,2+n).toString();return new _SourceDescriptionItem({type:t,text:r})}};function getPadding(e){if(e%4==0)return 0;return 4-e%4}var RtcpSrPacket=class _RtcpSrPacket{ssrc=0;senderInfo;reports=[];static type=200;type=_RtcpSrPacket.type;constructor(e){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,senderInfo:this.senderInfo.toJSON(),reports:this.reports.map(e=>e.toJSON())}}serialize(){let e=Buffer.alloc(4);e.writeUInt32BE(this.ssrc);e=Buffer.concat([e,this.senderInfo.serialize()]);e=Buffer.concat([e,...this.reports.map(e=>e.serialize())]);return RtcpHeader.serialize(_RtcpSrPacket.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,t){const n=e.readUInt32BE();const r=RtcpSenderInfo.deSerialize(e.subarray(4,24));let i=24;const a=[];for(let n=0;n<t;n++){a.push(RtcpReceiverInfo.deSerialize(e.subarray(i,i+24)));i+=24}return new _RtcpSrPacket({ssrc:n,senderInfo:r,reports:a})}};var RtcpSenderInfo=class _RtcpSenderInfo{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:ntpTime2Sec(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return bufferWriter([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(e){const[t,n,r,i]=bufferReader(e,[8,4,4,4]);return new _RtcpSenderInfo({ntpTimestamp:t,rtpTimestamp:n,packetCount:r,octetCount:i})}};var ntpTime2Sec=e=>{const[t,n]=bufferReader(bufferWriter([8],[e]),[4,4]);return Number(`${t}.${n}`)};var log7=debug(`werift-rtp:packages/rtp/src/rtcp/rtcp.ts`);var RtcpPacketConverter=class{static deSerialize(e){let t=0;const n=[];while(t<e.length){const r=RtcpHeader.deSerialize(e.subarray(t,t+4));t+=4;let i=e.subarray(t);t+=r.length*4;if(r.padding)i=i.subarray(0,i.length-i.subarray(-1)[0]);try{switch(r.type){case RtcpSrPacket.type:n.push(RtcpSrPacket.deSerialize(i,r.count));break;case RtcpRrPacket.type:n.push(RtcpRrPacket.deSerialize(i,r.count));break;case RtcpSourceDescriptionPacket.type:n.push(RtcpSourceDescriptionPacket.deSerialize(i,r));break;case RtcpTransportLayerFeedback.type:n.push(RtcpTransportLayerFeedback.deSerialize(i,r));break;case RtcpPayloadSpecificFeedback.type:n.push(RtcpPayloadSpecificFeedback.deSerialize(i,r))}}catch(e){log7(`deSerialize RTCP`,e)}}return n}};function isRtcp(e){return e.length>=2&&e[1]>=192&&e[1]<=208}var RTP_EXTENSION_URI={sdesMid:`urn:ietf:params:rtp-hdrext:sdes:mid`,sdesRTPStreamID:`urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id`,repairedRtpStreamId:`urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id`,transportWideCC:`http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01`,absSendTime:`http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time`,dependencyDescriptor:`https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension`,audioLevelIndication:`urn:ietf:params:rtp-hdrext:ssrc-audio-level`,videoOrientation:`urn:3gpp:video-orientation`};function rtpHeaderExtensionsParser(e,t){return e.map(e=>{const n=t[e.id];if(!n)return{uri:`unknown`,value:e.payload};switch(n){case RTP_EXTENSION_URI.sdesMid:case RTP_EXTENSION_URI.sdesRTPStreamID:case RTP_EXTENSION_URI.repairedRtpStreamId:return{uri:n,value:deserializeString(e.payload)};case RTP_EXTENSION_URI.transportWideCC:return{uri:n,value:deserializeUint16BE(e.payload)};case RTP_EXTENSION_URI.absSendTime:return{uri:n,value:deserializeAbsSendTime(e.payload)};case RTP_EXTENSION_URI.audioLevelIndication:return{uri:n,value:deserializeAudioLevelIndication(e.payload)};case RTP_EXTENSION_URI.videoOrientation:return{uri:n,value:deserializeVideoOrientation(e.payload)};default:return{uri:n,value:e.payload}}}).reduce((e,t)=>{if(t)e[t.uri]=t.value;return e},{})}function serializeSdesMid(e){return Buffer.from(e)}function serializeSdesRTPStreamID(e){return Buffer.from(e)}function serializeRepairedRtpStreamId(e){return Buffer.from(e)}function serializeTransportWideCC(e){return bufferWriter([2],[e])}function serializeAbsSendTime(e){const t=Buffer.alloc(3);const n=e>>14n&16777215n;t.writeUIntBE(Number(n),0,3);return t}function serializeAudioLevelIndication(e){const t=new BitStream(Buffer.alloc(1));t.writeBits(1,1);t.writeBits(7,e);return t.uint8Array}function deserializeString(e){return e.toString()}function deserializeUint16BE(e){return e.readUInt16BE()}function deserializeAbsSendTime(e){return bufferReader(e,[3])[0]}function deserializeAudioLevelIndication(e){const t=new BitStream(e);return{v:t.readBits(1)===1,level:t.readBits(7)}}function deserializeVideoOrientation(e){const t=new BitStream(e);t.readBits(4);return{c:t.readBits(1),f:t.readBits(1),r1:t.readBits(1),r0:t.readBits(1)}}var UINT32_MODULO=4294967296;var SLOT_EPSILON=1e-9;var RtpMediaTimeline=class{clockRate;frameSamples;frameDurationMs;initialTimestamp;constructor(e){const{clockRate:t,frameSamples:n,frameDurationMs:r}=e;assertPositive(`clockRate`,t);if(n===void 0===(r===void 0))throw new TypeError(`exactly one of frameSamples or frameDurationMs must be specified`);this.clockRate=t;if(n!==void 0){assertPositive(`frameSamples`,n);this.frameSamples=n;this.frameDurationMs=n*1e3/t}else{assertPositive(`frameDurationMs`,r);this.frameDurationMs=r;this.frameSamples=r*t/1e3}this.initialTimestamp=toUint32(Math.round(e.initialTimestamp??random32()))}elapsedSamples(e){return Math.round(e*this.frameSamples)}timestamp(e){return toUint32(this.initialTimestamp+this.elapsedSamples(e))}deadline(e,t){return e.time+(t-e.frameIndex)*this.frameDurationMs}latestFrameIndex(e,t){return e.frameIndex+Math.floor((t-e.time)/this.frameDurationMs+SLOT_EPSILON)}resolveTick({anchor:e,nextFrameIndex:t,lastFrameIndex:n,baseFrameIndex:r=t,now:i,stallPolicy:a=`skip`}){const o=this.latestFrameIndex(e,i);if(o<t)return;const s=a===`delay`?t:o;const c=this.deadline(e,s);return{frameIndex:s,timestamp:this.timestamp(s),elapsedSamples:this.elapsedSamples(s)-this.elapsedSamples(n??r),skippedFrames:s-(n!==void 0?n+1:r),deadline:c,lateness:i-c}}};var defaultScheduler={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};var RtpMediaClock=class{timeline;onTick=new Event2;stallPolicy;now;scheduler;unref;signal;_state=`idle`;anchor={time:0,frameIndex:0};nextFrameIndex=0;_lastTick;timerHandle;constructor(e){this.timeline=new RtpMediaTimeline(e);this.stallPolicy=e.stallPolicy??`skip`;this.now=e.now??(()=>performance.now());this.scheduler=e.scheduler??defaultScheduler;this.unref=e.unref??false;this.signal=e.signal}get state(){return this._state}get clockRate(){return this.timeline.clockRate}get lastTick(){return this._lastTick}get timestamp(){return this._lastTick?.timestamp??this.timeline.timestamp(0)}start(e){if(this._state!==`idle`)throw new Error(`RtpMediaClock cannot start from state ${this._state}`);if(e)this.onTick.subscribe(e);if(this.signal?.aborted){this.stop();return}this.signal?.addEventListener(`abort`,this.handleAbort);this._state=`running`;this.anchor={time:this.now(),frameIndex:0};this.nextFrameIndex=0;this.schedule(0)}pause(){if(this._state!==`running`)return;this._state=`paused`;this.clearTimer()}resume(e={}){if(this._state!==`paused`)return;const t=this.now();const n=e.continuous??this.stallPolicy===`delay`?this.nextFrameIndex:Math.max(this.nextFrameIndex,this.timeline.latestFrameIndex(this.anchor,t));this.anchor={time:t,frameIndex:n};this.nextFrameIndex=n;this._state=`running`;this.schedule(0)}stop(){if(this._state===`stopped`)return;this._state=`stopped`;this.clearTimer();this.signal?.removeEventListener(`abort`,this.handleAbort);this.onTick.complete()}handleAbort=()=>{this.stop()};schedule(e){const t=this.scheduler.setTimeout(this.handleTimer,e);if(this.unref)t?.unref?.();this.timerHandle=t}clearTimer(){if(this.timerHandle!==void 0){this.scheduler.clearTimeout(this.timerHandle);this.timerHandle=void 0}}handleTimer=()=>{this.timerHandle=void 0;if(this._state!==`running`)return;const e=this.now();const t=this.timeline.resolveTick({anchor:this.anchor,nextFrameIndex:this.nextFrameIndex,lastFrameIndex:this._lastTick?.frameIndex,baseFrameIndex:0,now:e,stallPolicy:this.stallPolicy});if(!t){this.schedule(Math.max(0,this.timeline.deadline(this.anchor,this.nextFrameIndex)-e));return}if(this.stallPolicy===`delay`&&t.lateness>=this.timeline.frameDurationMs)this.anchor={time:e,frameIndex:t.frameIndex};this._lastTick=t;this.nextFrameIndex=t.frameIndex+1;this.schedule(Math.max(0,this.timeline.deadline(this.anchor,this.nextFrameIndex)-e));this.onTick.execute(t)}};var RtpMediaPacer=class{clockRate;initialTimestamp;onTick=new Event2;now;scheduler;unref;signal;latencyMs;_state=`idle`;queue=[];firstPts;lastPushedDts;anchor;frameIndex=0;_delay=0;_lastTick;timerHandle;constructor(e){assertPositive(`clockRate`,e.clockRate);this.clockRate=e.clockRate;this.initialTimestamp=toUint32(Math.round(e.initialTimestamp??random32()));this.latencyMs=e.latencyMs??0;if(!Number.isFinite(this.latencyMs)||this.latencyMs<0)throw new RangeError(`latencyMs must be a non-negative finite number`);this.now=e.now??(()=>performance.now());this.scheduler=e.scheduler??defaultScheduler;this.unref=e.unref??false;this.signal=e.signal}get state(){return this._state}get queueLength(){return this.queue.length}get lastTick(){return this._lastTick}get delay(){return this._delay}push(e,t){if(this._state===`stopped`)throw new Error(`RtpMediaPacer is stopped`);const n=t.pts;const r=t.dts??n;if(!Number.isFinite(n)||!Number.isFinite(r))throw new RangeError(`pts and dts must be finite numbers`);if(this.lastPushedDts!==void 0&&r<this.lastPushedDts)throw new RangeError(`frames must be pushed in non-decreasing dts order`);this.lastPushedDts=r;this.firstPts??=n;this.queue.push({frame:e,pts:n,dts:r});if(this._state===`running`&&this.timerHandle===void 0)this.scheduleNext(this.now())}start(e){if(this._state!==`idle`)throw new Error(`RtpMediaPacer cannot start from state ${this._state}`);if(e)this.onTick.subscribe(e);if(this.signal?.aborted){this.stop();return}this.signal?.addEventListener(`abort`,this.handleAbort);this._state=`running`;if(this.queue.length>0)this.scheduleNext(this.now())}pause(){if(this._state!==`running`)return;this._state=`paused`;this.clearTimer()}resume(){if(this._state!==`paused`)return;this._state=`running`;const e=this.now();const t=this.queue[0];if(t&&this.anchor&&this.deadline(t.dts)<e)this.reanchor(e,t.dts);this.scheduleNext(e)}stop(){if(this._state===`stopped`)return;this._state=`stopped`;this.clearTimer();this.queue=[];this.signal?.removeEventListener(`abort`,this.handleAbort);this.onTick.complete()}handleAbort=()=>{this.stop()};deadline(e){const t=this.anchor;return t.time+(e-t.dts)*1e3/this.clockRate}reanchor(e,t){if(this.anchor)this._delay+=e-this.deadline(t);this.anchor={time:e,dts:t}}scheduleNext(e){const t=this.queue[0];if(!t)return;this.anchor??={time:e+this.latencyMs,dts:t.dts};const n=Math.max(0,this.deadline(t.dts)-e);const r=this.scheduler.setTimeout(this.handleTimer,n);if(this.unref)r?.unref?.();this.timerHandle=r}clearTimer(){if(this.timerHandle!==void 0){this.scheduler.clearTimeout(this.timerHandle);this.timerHandle=void 0}}handleTimer=()=>{this.timerHandle=void 0;const e=this.queue[0];if(this._state!==`running`||!e)return;const t=this.now();const n=this.deadline(e.dts);if(t<n-SLOT_EPSILON){this.scheduleNext(t);return}this.queue.shift();const r=this.queue[0];const i=r!==void 0&&this.deadline(r.dts)<=t;const a={frame:e.frame,frameIndex:this.frameIndex,timestamp:toUint32(this.initialTimestamp+Math.round(e.pts-this.firstPts)),pts:e.pts,dts:e.dts,deadline:n,lateness:t-n,delay:0};if(i)this.reanchor(t,e.dts);a.delay=this._delay;this.frameIndex++;this._lastTick=a;this.scheduleNext(t);this.onTick.execute(a)}};function toUint32(e){const t=e%UINT32_MODULO;return t<0?t+UINT32_MODULO:t}function assertPositive(e,t){if(!Number.isFinite(t)||t<=0)throw new RangeError(`${e} must be a positive finite number`)}var log8=debug(`packages/rtp/src/rtp/red/packet.ts`);var Red=class _Red{header;blocks=[];static deSerialize(e){const t=e instanceof ArrayBuffer?Buffer.from(e):e;const n=new _Red;let r=0;[n.header,r]=RedHeader.deSerialize(t);n.header.fields.forEach(({blockLength:e,timestampOffset:i,blockPT:a})=>{if(e&&i){const o=t.subarray(r,r+e);n.blocks.push({block:o,blockPT:a,timestampOffset:i});r+=e}else{const e=t.subarray(r);n.blocks.push({block:e,blockPT:a})}});return n}serialize(){this.header=new RedHeader;for(const{timestampOffset:e,blockPT:t,block:n}of this.blocks)if(e)this.header.fields.push({fBit:1,blockPT:t,blockLength:n.length,timestampOffset:e});else this.header.fields.push({fBit:0,blockPT:t});let e=this.header.serialize();for(const{block:t}of this.blocks)e=Buffer.concat([e,t]);return e}};var RedHeader=class _RedHeader{fields=[];static deSerialize(e){let t=0;const n=new _RedHeader;for(;;){const r={};n.fields.push(r);const i=new BitStream(e.subarray(t));r.fBit=i.readBits(1);r.blockPT=i.readBits(7);t++;if(r.fBit===0)break;r.timestampOffset=i.readBits(14);r.blockLength=i.readBits(10);t+=3}return[n,t]}serialize(){let e=Buffer.alloc(0);for(const t of this.fields)try{if(t.timestampOffset&&t.blockLength){const n=new BitStream(Buffer.alloc(4)).writeBits(1,t.fBit).writeBits(7,t.blockPT).writeBits(14,t.timestampOffset).writeBits(10,t.blockLength);e=Buffer.concat([e,n.uint8Array])}else{const n=new BitStream(Buffer.alloc(1)).writeBits(1,0).writeBits(7,t.blockPT);e=Buffer.concat([e,n.uint8Array])}}catch(e){log8(e?.message)}return e}};var RedEncoder=class{constructor(e=1){this.distance=e}cache=[];cacheSize=10;push(e){this.cache.push(e);if(this.cache.length>this.cacheSize)this.cache.shift()}build(){const e=new Red;const t=this.cache.slice(-(this.distance+1));const n=t.pop();if(!n)return e;t.forEach(t=>{const r=uint32Add(n.timestamp,-t.timestamp);if(r>Max14Uint)return;e.blocks.push({block:t.block,blockPT:t.blockPT,timestampOffset:r})});e.blocks.push({block:n.block,blockPT:n.blockPT});return e}};var Max14Uint=16383;var RedHandler=class{size=150;sequenceNumbers=[];push(e,t){const n=[];e.blocks.forEach(({blockPT:r,timestampOffset:i,block:a},o)=>{const s=uint16Add(t.header.sequenceNumber,-(e.blocks.length-(o+1)));if(i)n.push(new RtpPacket(new RtpHeader({timestamp:uint32Add(t.header.timestamp,-i),payloadType:r,ssrc:t.header.ssrc,sequenceNumber:s,marker:true}),a));else n.push(new RtpPacket(new RtpHeader({timestamp:t.header.timestamp,payloadType:r,ssrc:t.header.ssrc,sequenceNumber:s,marker:true}),a))});return n.filter(e=>{if(this.sequenceNumbers.includes(e.header.sequenceNumber))return false;else{if(this.sequenceNumbers.length>this.size)this.sequenceNumbers.shift();this.sequenceNumbers.push(e.header.sequenceNumber);return true}})}};function unwrapRtx(e,t,n){return new RtpPacket(new RtpHeader({payloadType:t,marker:e.header.marker,sequenceNumber:e.payload.readUInt16BE(0),timestamp:e.header.timestamp,ssrc:n}),e.payload.subarray(2))}function wrapRtx(e,t,n,r){const i=Buffer.allocUnsafe(2);i.writeUInt16BE(e.header.sequenceNumber,0);return new RtpPacket(new RtpHeader({payloadType:t,marker:e.header.marker,sequenceNumber:n,timestamp:e.header.timestamp,ssrc:r,csrc:e.header.csrc,extensions:e.header.extensions}),Buffer.concat([i,e.payload]))}var CipherAesBase=class{constructor(e,t,n,r){this.srtpSessionKey=e;this.srtpSessionSalt=t;this.srtcpSessionKey=n;this.srtcpSessionSalt=r}encryptRtp(e,t,n){return Buffer.from([])}decryptRtp(e,t,n){return[]}encryptRTCP(e,t){return Buffer.from([])}decryptRTCP(e){return[]}};var SrtpAuthenticationError=class extends Error{constructor(e){super(e);this.name=`SrtpAuthenticationError`}};var minRtpHeaderSize=12;var minRtcpPacketSize=8;function parseSrtpRtpHeader(e,t,n=`Failed to authenticate SRTP packet`){const r=e.length-t;assertAuthenticatedPacketLength(e.length>=minRtpHeaderSize+t,n);const i=wrapAuthenticationError(()=>RtpHeader.deSerialize(e.subarray(0,r)),n);i.paddingSize=0;assertAuthenticatedPacketLength(i.payloadOffset>=minRtpHeaderSize&&i.payloadOffset<=r,n);return i}function parseSrtcpHeader(e,t,n,r=`Failed to authenticate SRTCP packet`){assertAuthenticatedPacketLength(e.length>=minRtcpPacketSize+t+n,r);return wrapAuthenticationError(()=>RtcpHeader.deSerialize(e.subarray(0,4)),r)}function assertAuthenticatedPacketLength(e,t){if(!e)throw new SrtpAuthenticationError(t)}function wrapAuthenticationError(e,t){try{return e()}catch{throw new SrtpAuthenticationError(t)}}function finalizeSrtpRtpHeader(e,t,n=`Failed to authenticate SRTP packet`){if(!e.padding){e.paddingSize=0;return e}assertAuthenticatedPacketLength(t.length>e.payloadOffset,n);const r=t[t.length-1];assertAuthenticatedPacketLength(r>0&&r<=t.length-e.payloadOffset,n);e.paddingSize=r;return e}var CipherAesCtr=class extends CipherAesBase{constructor(e,t,n,r,i,a){super(e,t,n,r);this.srtpSessionAuthTag=i;this.srtcpSessionAuthTag=a}authTagLength=10;encryptRtp(e,t,n){const r=e.serialize(e.serializeSize);const i=this.generateCounter(e.sequenceNumber,n,e.ssrc,this.srtpSessionSalt);const a=createCipheriv$1(`aes-128-ctr`,this.srtpSessionKey,i).update(t);const o=this.generateSrtpAuthTag(n,r,a);return Buffer.concat([r,a,o])}decryptRtp(e,t,n=parseSrtpRtpHeader(e,this.authTagLength)){const r=e.length-this.authTagLength;const i=e.subarray(0,r);assertAuthTag(e.subarray(r),this.generateSrtpAuthTag(t,i.subarray(0,n.payloadOffset),i.subarray(n.payloadOffset)),`Failed to authenticate SRTP packet`);const a=this.generateCounter(n.sequenceNumber,t,n.ssrc,this.srtpSessionSalt);const o=createDecipheriv$1(`aes-128-ctr`,this.srtpSessionKey,a);const s=i.subarray(n.payloadOffset);const c=o.update(s);const u=Buffer.concat([i.subarray(0,n.payloadOffset),c]);return[u,finalizeSrtpRtpHeader(n,u,`Failed to authenticate SRTP packet`)]}encryptRTCP(e,t){let n=Buffer.from(e);const r=n.readUInt32BE(4);const i=this.generateCounter(t&65535,t>>16,r,this.srtcpSessionSalt);createCipheriv$1(`aes-128-ctr`,this.srtcpSessionKey,i).update(n.slice(8)).copy(n,8);n=Buffer.concat([n,Buffer.alloc(4)]);n.writeUInt32BE(t,n.length-4);n[n.length-4]|=128;const a=this.generateSrtcpAuthTag(n);n=Buffer.concat([n,a]);return n}decryptRTCP(e){const t=parseSrtcpHeader(e,this.authTagLength,srtcpIndexSize);const n=e.length-(this.authTagLength+srtcpIndexSize);const r=e.subarray(0,e.length-this.authTagLength);assertAuthTag(e.subarray(e.length-this.authTagLength),this.generateSrtcpAuthTag(r),`Failed to authenticate SRTCP packet`);const i=Buffer.from(e).slice(0,n);if(e[n]>>>7===0)return[i,t];let a=e.readUInt32BE(n);a&=2147483647;const o=e.readUInt32BE(4);const s=this.generateCounter(a&65535,a>>16,o,this.srtcpSessionSalt);createDecipheriv$1(`aes-128-ctr`,this.srtcpSessionKey,s).update(i.subarray(8)).copy(i,8);return[i,t]}generateSrtcpAuthTag(e){return createHmac$1(`sha1`,this.srtcpSessionAuthTag).update(e).digest().slice(0,10)}generateCounter(e,t,n,r){const i=Buffer.alloc(16);i.writeUInt32BE(n,4);i.writeUInt32BE(t,8);i.writeUInt32BE(Number(BigInt(e)<<16n),12);for(let e=0;e<r.length;e++)i[e]^=r[e];return i}generateSrtpAuthTag(e,...t){const n=createHmac$1(`sha1`,this.srtpSessionAuthTag);const r=Buffer.alloc(4);r.writeUInt32BE(e);for(const e of t)n.update(e);return n.update(r).digest().subarray(0,10)}};var srtcpIndexSize=4;function assertAuthTag(e,t,n){if(e.length!==t.length||!timingSafeEqual$1(e,t))throw new SrtpAuthenticationError(n)}var CipherAesGcm=class extends CipherAesBase{aeadAuthTagLen=16;rtpIvWriter=createBufferWriter([2,4,4,2],true);rtcpIvWriter=createBufferWriter([2,4,2,4],true);aadWriter=createBufferWriter([4],true);constructor(e,t,n,r){super(e,t,n,r)}encryptRtp(e,t,n){const r=e.serialize(e.serializeSize);const i=this.rtpInitializationVector(e,n);const a=createCipheriv$1(`aes-128-gcm`,this.srtpSessionKey,i);a.setAAD(r);const o=a.update(t);a.final();const s=a.getAuthTag();return Buffer.concat([r,o,s])}decryptRtp(e,t,n=parseSrtpRtpHeader(e,this.aeadAuthTagLen)){const r=e.subarray(0,n.payloadOffset);const i=e.length-this.aeadAuthTagLen;const a=e.subarray(i);let o=Buffer.from([]);o=growBufferSize(o,e.length-this.aeadAuthTagLen);r.copy(o);const s=this.rtpInitializationVector(n,t);const c=e.slice(n.payloadOffset,i);const u=createDecipheriv$1(`aes-128-gcm`,this.srtpSessionKey,s);u.setAAD(r);u.setAuthTag(a);const d=u.update(c);finalizeAuthenticatedDecryption(u,`SRTP`);d.copy(o,n.payloadOffset);return[o,finalizeSrtpRtpHeader(n,o,`Failed to authenticate SRTP packet`)]}encryptRTCP(e,t){const n=e.readUInt32BE(4);const r=e.length+this.aeadAuthTagLen;let i=Buffer.from([]);i=growBufferSize(i,r+srtcpIndexSize2);e.slice(0,8).copy(i);const a=this.rtcpInitializationVector(n,t);const o=this.rtcpAdditionalAuthenticatedData(e,t);const s=createCipheriv$1(`aes-128-gcm`,this.srtcpSessionKey,a);s.setAAD(o);const c=s.update(e.slice(8));s.final();c.copy(i,8);s.getAuthTag().copy(i,8+c.length);o.slice(8,12).copy(i,r);return i}decryptRTCP(e){const t=parseSrtcpHeader(e,this.aeadAuthTagLen,srtcpIndexSize2);const n=e.length-srtcpIndexSize2;const r=n-this.aeadAuthTagLen;const i=e.readUInt32BE(4);const a=e.readUInt32BE(n);const o=a>>>31===1;const s=a&~(rtcpEncryptionFlag<<24);const c=this.rtcpInitializationVector(i,s);const u=o?Buffer.concat([e.subarray(0,8),e.subarray(n)]):Buffer.concat([e.subarray(0,r),e.subarray(n)]);const d=o?e.slice(8,r):Buffer.alloc(0);const f=o?Buffer.alloc(r):Buffer.from(e.subarray(0,r));if(o)e.slice(0,8).copy(f);const p=createDecipheriv$1(`aes-128-gcm`,this.srtcpSessionKey,c);p.setAAD(u);p.setAuthTag(e.subarray(r,n));const m=p.update(d);finalizeAuthenticatedDecryption(p,`SRTCP`);if(o)m.copy(f,8);return[f,t]}rtpInitializationVector(e,t){const n=this.rtpIvWriter([0,e.ssrc,t,e.sequenceNumber]);for(let e=0;e<n.length;e++)n[e]^=this.srtpSessionSalt[e];return n}rtcpInitializationVector(e,t){const n=this.rtcpIvWriter([0,e,0,t]);for(let e=0;e<n.length;e++)n[e]^=this.srtcpSessionSalt[e];return n}rtcpAdditionalAuthenticatedData(e,t){const n=Buffer.concat([e.subarray(0,8),this.aadWriter([t])]);n[8]|=rtcpEncryptionFlag;return n}};var srtcpIndexSize2=4;var rtcpEncryptionFlag=128;function finalizeAuthenticatedDecryption(e,t){try{e.final()}catch{throw new SrtpAuthenticationError(`Failed to authenticate ${t} packet`)}}function aes128EcbEncrypt(e,t){const n=createCipheriv$1(`aes-128-ecb`,e,null);n.setAutoPadding(false);return Buffer.concat([n.update(t),n.final()])}var Context=class{constructor(e,t,n){this.masterKey=e;this.masterSalt=t;this.profile=n;{const e=14-t.length;if(e>0)this.masterSalt=Buffer.concat([t,Buffer.alloc(e)])}this.srtpSessionKey=this.generateSessionKey(0);this.srtpSessionSalt=this.generateSessionSalt(2);this.srtpSessionAuthTag=this.generateSessionAuthTag(1);this.srtpSessionAuth=createHmac$1(`sha1`,this.srtpSessionAuthTag);this.srtcpSessionKey=this.generateSessionKey(3);this.srtcpSessionSalt=this.generateSessionSalt(5);this.srtcpSessionAuthTag=this.generateSessionAuthTag(4);this.srtcpSessionAuth=createHmac$1(`sha1`,this.srtcpSessionAuthTag);switch(n){case 1:this.cipher=new CipherAesCtr(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case 7:this.cipher=new CipherAesGcm(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt)}}srtpSSRCStates={};srtpSessionKey;srtpSessionSalt;srtpSessionAuthTag;srtpSessionAuth;srtcpSSRCStates={};srtcpSessionKey;srtcpSessionSalt;srtcpSessionAuthTag;srtcpSessionAuth;cipher;generateSessionKey(e){let t=Buffer.from(this.masterSalt);const n=Buffer.from([e,0,0,0,0,0,0]);for(let e=n.length-1,r=t.length-1;e>=0;e--,r--)t[r]=t[r]^n[e];t=Buffer.concat([t,Buffer.from([0,0])]);return aes128EcbEncrypt(this.masterKey,t)}generateSessionSalt(e){let t=Buffer.from(this.masterSalt);const n=Buffer.from([e,0,0,0,0,0,0]);for(let e=n.length-1,r=t.length-1;e>=0;e--,r--)t[r]=t[r]^n[e];t=Buffer.concat([t,Buffer.from([0,0])]);t=aes128EcbEncrypt(this.masterKey,t);return t.subarray(0,14)}generateSessionAuthTag(e){const t=Buffer.from(this.masterSalt);const n=Buffer.from([e,0,0,0,0,0,0]);for(let e=n.length-1,r=t.length-1;e>=0;e--,r--)t[r]=t[r]^n[e];let r=Buffer.concat([t,Buffer.from([0,0])]);let i=Buffer.concat([t,Buffer.from([0,1])]);r=aes128EcbEncrypt(this.masterKey,r);i=aes128EcbEncrypt(this.masterKey,i);return Buffer.concat([r,i.subarray(0,4)])}getSrtpSsrcState(e){let t=this.srtpSSRCStates[e];if(t)return t;t={ssrc:e,rolloverCounter:0,lastSequenceNumber:0};this.srtpSSRCStates[e]=t;return t}getSrtcpSsrcState(e){let t=this.srtcpSSRCStates[e];if(t)return t;t={srtcpIndex:0,ssrc:e};this.srtcpSSRCStates[e]=t;return t}updateRolloverCount(e,t){if(!t.rolloverHasProcessed)t.rolloverHasProcessed=true;else if(e===0){if(t.lastSequenceNumber>MaxROCDisorder)t.rolloverCounter++}else if(t.lastSequenceNumber<MaxROCDisorder&&e>MaxSequenceNumber-MaxROCDisorder){if(t.rolloverCounter>0)t.rolloverCounter--}else if(e<MaxROCDisorder&&t.lastSequenceNumber>MaxSequenceNumber-MaxROCDisorder)t.rolloverCounter++;t.lastSequenceNumber=e}generateSrtpAuthTag(e,t){this.srtpSessionAuth=createHmac$1(`sha1`,this.srtpSessionAuthTag);const n=Buffer.alloc(4);n.writeUInt32BE(t);return this.srtpSessionAuth.update(e).update(n).digest().slice(0,10)}index(e){const t=this.srtcpSSRCStates[e];if(!t)return 0;return t.srtcpIndex}setIndex(e,t){const n=this.getSrtcpSsrcState(e);n.srtcpIndex=t%2147483647}};var MaxROCDisorder=100;var MaxSequenceNumber=65535;var SrtcpContext=class extends Context{constructor(e,t,n){super(e,t,n)}encryptRTCP(e){const t=e.readUInt32BE(4);const n=this.getSrtcpSsrcState(t);n.srtcpIndex++;if(n.srtcpIndex>>maxSRTCPIndex)n.srtcpIndex=0;return this.cipher.encryptRTCP(e,n.srtcpIndex)}decryptRTCP(e){return this.cipher.decryptRTCP(e)}};var maxSRTCPIndex=2147483647;var Session=class{constructor(e){this.ContextCls=e}localContext;remoteContext;onData;start(e,t,n,r,i){this.localContext=new this.ContextCls(e,t,i);this.remoteContext=new this.ContextCls(n,r,i)}};var SrtcpSession=class extends Session{constructor(e){super(SrtcpContext);this.config=e;this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}decrypt=e=>{const[t]=this.remoteContext.decryptRTCP(e);return t};encrypt(e){return this.localContext.encryptRTCP(e)}};var SrtpContext2=class extends Context{constructor(e,t,n){super(e,t,n)}encryptRtp(e,t){const n=this.getSrtpSsrcState(t.ssrc);this.updateRolloverCount(t.sequenceNumber,n);return this.cipher.encryptRtp(t,e,n.rolloverCounter)}decryptRtp(e){const t=parseSrtpRtpHeader(e,this.rtpAuthTagLength);const n=this.srtpSSRCStates[t.ssrc];const r=n?{...n}:{ssrc:t.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(t.sequenceNumber,r);const i=this.cipher.decryptRtp(e,r.rolloverCounter,t);if(n)Object.assign(n,r);else this.srtpSSRCStates[t.ssrc]=r;return i}get rtpAuthTagLength(){return this.profile===7?16:10}};var SrtpSession=class extends Session{constructor(e){super(SrtpContext2);this.config=e;this.start(e.keys.localMasterKey,e.keys.localMasterSalt,e.keys.remoteMasterKey,e.keys.remoteMasterSalt,e.profile)}decrypt=e=>{const[t]=this.remoteContext.decryptRtp(e);return t};encrypt(e,t){return this.localContext.encryptRtp(e,t)}};var UINT32_MODULO2=4294967296;var RtpBuilder=class{constructor(e){this.props=e;this.sequenceNumber=e.initialSequenceNumber!==void 0?uint16Add(e.initialSequenceNumber,-1):random16();this.baseTimestamp=toUint322(Math.round(e.initialTimestamp??random32()));if(e.between!==void 0){this.betweenSamples=e.between*e.clockRate/1e3;if(!Number.isFinite(this.betweenSamples)||this.betweenSamples<0)throw new RangeError(`between * clockRate must be a finite number`)}}sequenceNumber;baseTimestamp;betweenCount=0;advancedSamples=0;betweenSamples;get timestamp(){const e=this.betweenCount*(this.betweenSamples??0)+this.advancedSamples;return toUint322(this.baseTimestamp+Math.round(e))}set timestamp(e){this.baseTimestamp=toUint322(Math.round(e));this.betweenCount=0;this.advancedSamples=0}advanceSamples(e){if(!Number.isFinite(e)||e<0)throw new RangeError(`samples must be a non-negative finite number`);this.advancedSamples+=e;return this.timestamp}create(e,t={}){if([t.elapsedSamples,t.timestamp,t.tick].filter(e=>e!==void 0).length>1)throw new TypeError(`elapsedSamples, timestamp and tick are mutually exclusive`);if(t.tick)this.timestamp=t.tick.timestamp;else if(t.timestamp!==void 0)this.timestamp=t.timestamp;else if(t.elapsedSamples!==void 0)this.advanceSamples(t.elapsedSamples);else if(this.props.clock)this.timestamp=this.props.clock.timestamp;else if(this.betweenSamples!==void 0)this.betweenCount++;this.sequenceNumber=uint16Add(this.sequenceNumber,1);return new RtpPacket(new RtpHeader({sequenceNumber:this.sequenceNumber,timestamp:this.timestamp,payloadType:this.props.payloadType??96,ssrc:this.props.ssrc??0,extension:this.props.extension??true,marker:t.marker??this.props.marker??false,padding:false}),e)}};function toUint322(e){const t=e%UINT32_MODULO2;return t<0?t+UINT32_MODULO2:t}var log9=debug(`werift-dtls : packages/dtls/src/flight/client/flight5.ts : log`);var Flight5=class extends Flight{constructor(e,t,n,r){super(e,t,5,7);this.cipher=n;this.srtp=r}handleHandshake(e){this.dtls.bufferHandshakeCache([e],false,4);const t=(()=>{switch(e.msg_type){case 2:return ServerHello.deSerialize(e.fragment);case 11:return Certificate2.deSerialize(e.fragment);case 12:return ServerKeyExchange.deSerialize(e.fragment);case 13:return ServerCertificateRequest.deSerialize(e.fragment);case 14:return ServerHelloDone.deSerialize(e.fragment)}})();if(t)handlers[t.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(t)}async exec(){if(this.dtls.flight===5){log9(this.dtls.sessionId,`flight5 twice`);this.send(this.dtls.lastMessage);return}this.dtls.flight=5;const e=this.dtls.requestedCertificateTypes.length>0;log9(this.dtls.sessionId,`send flight5`,e);const t=[e&&this.sendCertificate(),this.sendClientKeyExchange(),e&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(e=>e);this.dtls.lastMessage=t;await this.transmit(t)}sendCertificate(){const e=new Certificate2([Buffer.from(this.cipher.localCert)]);const t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw new Error;const e=new ClientKeyExchange(this.cipher.localKeyPair.publicKey);const t=this.createPacket([e]);const n=Buffer.concat(t.map(e=>e.serialize()));const r=this.cipher.localKeyPair;const i=this.cipher.remoteKeyPair;if(!i.publicKey)throw new Error(`not exist`);const a=prfPreMasterSecret(i.publicKey,r.privateKey,r.curve);log9(this.dtls.sessionId,`extendedMasterSecret`,this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);const o=Buffer.concat(this.dtls.sortedHandshakeCache.map(e=>e.serialize()));this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?prfExtendedMasterSecret(a,o):prfMasterSecret(a,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize());this.cipher.cipher=createCipher(this.cipher.cipherSuite);this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize());log9(this.dtls.sessionId,`cipher`,this.cipher.cipher.summary);return n}sendCertificateVerify(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(e=>e.serialize()));const t=this.cipher.signatureData(e,`sha256`);const n=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case SignatureAlgorithm.ecdsa_3:return SignatureScheme.ecdsa_secp256r1_sha256;case SignatureAlgorithm.rsa_1:return SignatureScheme.rsa_pkcs1_sha256}})();if(!n)throw new Error;log9(this.dtls.sessionId,`signatureScheme`,this.cipher.signatureHashAlgorithm?.signature,n);const r=new CertificateVerify(n,t);const i=this.createPacket([r]);return Buffer.concat(i.map(e=>e.serialize()))}sendChangeCipherSpec(){const e=ChangeCipherSpec.createEmpty().serialize();const t=createPlaintext(this.dtls)([{type:20,fragment:e}],++this.dtls.recordSequenceNumber);return Buffer.concat(t.map(e=>e.serialize()))}sendFinished(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(e=>e.serialize()));const t=new Finished(this.cipher.verifyData(e));this.dtls.epoch=1;const[n]=this.createPacket([t]);this.dtls.recordSequenceNumber=0;const r=this.cipher.encryptPacket(n).serialize();log9(this.dtls.sessionId,`finished`,this.cipher.cipher.summary);return r}};var handlers={};handlers[2]=({cipher:e,srtp:t,dtls:n})=>r=>{log9(n.sessionId,`serverHello`,r.cipherSuite);e.remoteRandom=DtlsRandom.from(r.random);e.cipherSuite=r.cipherSuite;log9(n.sessionId,`selected cipherSuite`,e.cipherSuite);if(r.extensions)r.extensions.forEach(e=>{switch(e.type){case UseSRTP.type:{const r=UseSRTP.fromData(e.data);const i=SrtpContext.findMatchingSRTPProfile(r.profiles,n.options.srtpProfiles||[]);log9(n.sessionId,`selected srtp profile`,i);if(i==void 0)return;t.srtpProfile=i}break;case ExtendedMasterSecret.type:n.remoteExtendedMasterSecret=true;break;case RenegotiationIndication.type:log9(n.sessionId,`RenegotiationIndication`)}})};handlers[11]=({cipher:e,dtls:t})=>n=>{log9(t.sessionId,`handshake certificate`,n);e.remoteCertificate=n.certificateList[0]};handlers[12]=({cipher:e,dtls:t})=>n=>{if(!e.localRandom||!e.remoteRandom)throw new Error;log9(t.sessionId,`ServerKeyExchange`,n);log9(t.sessionId,`selected curve`,n.namedCurve);e.remoteKeyPair={curve:n.namedCurve,publicKey:n.publicKey};e.localKeyPair=generateKeyPair(n.namedCurve)};handlers[13]=({dtls:e})=>t=>{log9(e.sessionId,`certificate_request`,t);e.requestedCertificateTypes=t.certificateTypes;e.requestedSignatureAlgorithms=t.signatures};handlers[14]=({dtls:e})=>t=>{log9(e.sessionId,`server_hello_done`,t)};var{decode:decode16,encode:encode17,types:types17}=binaryData_exports;var ServerHelloVerifyRequest=class _ServerHelloVerifyRequest{constructor(e,t){this.serverVersion=e;this.cookie=t}msgType=3;messageSeq;static spec={serverVersion:ProtocolVersion,cookie:types17.buffer(types17.uint8)};static createEmpty(){return new _ServerHelloVerifyRequest(void 0,void 0)}static deSerialize(e){return new _ServerHelloVerifyRequest(...Object.values(decode16(e,_ServerHelloVerifyRequest.spec)))}serialize(){return encode17(this,_ServerHelloVerifyRequest.spec)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){const e=this.serialize();return new FragmentedHandshake(this.msgType,e.length,this.messageSeq,0,e.length,e)}};var log10=debug(`werift-dtls : packages/dtls/src/context/dtls.ts : log`);var DtlsContext=class{constructor(e,t){this.options=e;this.sessionType=t}version={major:254,minor:253};lastFlight=[];lastMessage=[];recordSequenceNumber=0;sequenceNumber=0;epoch=0;flight=0;handshakeCache={};cookie;requestedCertificateTypes=[];requestedSignatureAlgorithms=[];remoteExtendedMasterSecret=false;get sessionId(){return this.cookie?this.cookie.toString(`hex`).slice(0,10):``}get sortedHandshakeCache(){return Object.entries(this.handshakeCache).sort(([e],[t])=>Number(e)-Number(t)).flatMap(([,{data:e}])=>e.sort((e,t)=>e.message_seq-t.message_seq))}checkHandshakesExist=e=>!e.find(e=>this.sortedHandshakeCache.find(t=>t.msg_type===e)==void 0);bufferHandshakeCache(e,t,n){if(!this.handshakeCache[n])this.handshakeCache[n]={data:[],isLocal:t,flight:n};const r=e.filter(e=>{const r=this.handshakeCache[n].data.find(t=>t.msg_type===e.msg_type);if(r){log10(this.sessionId,`exist`,r.summary,t,n);return false}return true});this.handshakeCache[n].data=[...this.handshakeCache[n].data,...r]}};var TransportContext=class{constructor(e){this.socket=e}send=(e,t)=>{return this.socket.send(e,t)}};var{decode:decode17,encode:encode18,types:types18}=binaryData_exports;var EllipticCurves=class _EllipticCurves{static type=10;static spec={type:types18.uint16be,data:types18.array(types18.uint16be,types18.uint16be,`bytes`)};type=_EllipticCurves.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new _EllipticCurves}static fromData(e){return new _EllipticCurves({type:_EllipticCurves.type,data:decode17(e,_EllipticCurves.spec.data)})}static deSerialize(e){return new _EllipticCurves(decode17(e,_EllipticCurves.spec))}serialize(){return encode18(this,_EllipticCurves.spec)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:decode18,encode:encode19,types:types19}=binaryData_exports;var Signature=class _Signature{static type=13;static spec={type:types19.uint16be,data:types19.array({hash:types19.uint8,signature:types19.uint8},types19.uint16be,`bytes`)};type=_Signature.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new _Signature}static deSerialize(e){return new _Signature(decode18(e,_Signature.spec))}serialize(){return encode19(this,_Signature.spec)}static fromData(e){const t=Buffer.alloc(2);t.writeUInt16BE(_Signature.type);return _Signature.deSerialize(Buffer.concat([t,e]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}};var{decode:decode19,encode:encode20,types:types20}=binaryData_exports;var Alert=class _Alert{constructor(e,t){this.level=e;this.description=t}static spec={level:types20.uint8,description:types20.uint8};static deSerialize(e){return new _Alert(...Object.values(decode19(e,_Alert.spec)))}serialize(){return encode20(this,_Alert.spec)}};var log11=debug(`werift-dtls : packages/dtls/record/receive.ts : log`);var err3=debug(`werift-dtls : packages/dtls/record/receive.ts : err`);var parsePacket=e=>{let t=0;const n=[];while(e.length>t){const r=e.readUInt16BE(t+11);if(e.length<t+(12+r))break;const i=DtlsPlaintext.deSerialize(e.subarray(t));n.push(i);t+=13+r}return n};var parsePlainText=(e,t)=>n=>{switch(n.recordLayerHeader.contentType){case 20:log11(e.sessionId,`change cipher spec`);return[{type:20,data:void 0}];case 22:{let r=n.fragment;try{if(n.recordLayerHeader.epoch>0){log11(e.sessionId,`decrypt handshake`);r=t.decryptPacket(n)}}catch(t){err3(e.sessionId,`decrypt failed`,t);throw t}try{let e=0;const t=[];while(r.length>e){const n=FragmentedHandshake.deSerialize(r.subarray(e));t.push({type:22,data:n});e+=n.fragment_length+12}return t}catch(t){err3(e.sessionId,`decSerialize failed`,t,r);throw t}}case 23:return[{type:23,data:t.decryptPacket(n)}];case 21:{let r=Alert.deSerialize(n.fragment);if(AlertDesc[r.description]==void 0){const e=t.decryptPacket(n);r=Alert.deSerialize(e)}err3(e.sessionId,`ContentType.alert`,r,AlertDesc[r.description],`flight`,e.flight,`lastFlight`,e.lastFlight);if(r.level>1)throw new Error(`alert fatal error`);return[{type:21,data:void 0}]}default:return[{type:21,data:void 0}]}};var{decode:decode20,types:types21}=binaryData_exports;var log12=debug(`werift-dtls : packages/dtls/src/socket.ts : log`);var err4=debug(`werift-dtls : packages/dtls/src/socket.ts : err`);var DtlsSocket=class{constructor(e,t){this.options=e;this.sessionType=t;this.dtls=new DtlsContext(this.options,this.sessionType);this.cipher=new CipherContext(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash);this.transport=new TransportContext(this.options.transport);this.setupExtensions();this.transport.socket.onData=this.udpOnMessage}onConnect=new Event2;onData=new Event2;onError=new Event2;onClose=new Event2;transport;cipher;dtls;srtp=new SrtpContext;connected=false;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){log12(`renegotiation`,this.sessionType);this.connected=false;this.cipher=new CipherContext(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash);this.dtls=new DtlsContext(this.options,this.sessionType);this.srtp=new SrtpContext;this.extensions=[];this.bufferFragmentedHandshakes=[]}udpOnMessage=e=>{const t=parsePacket(e);for(const e of t)try{const t=parsePlainText(this.dtls,this.cipher)(e);for(const e of t)switch(e.type){case 22:{const t=e.data;const n=this.handleFragmentHandshake([t]);const r=Object.values(n.reduce((e,t)=>{if(!e[t.msg_type])e[t.msg_type]=[];e[t.msg_type].push(t);return e},{})).map(e=>FragmentedHandshake.assemble(e)).sort((e,t)=>e.msg_type-t.msg_type);this.onHandleHandshakes(r).catch(e=>{err4(this.dtls.sessionId,`onHandleHandshakes error`,e);this.onError.execute(e)})}break;case 23:this.onData.execute(e.data);break;case 21:this.onClose.execute()}}catch(e){err4(this.dtls.sessionId,`catch udpOnMessage error`,e)}};setupExtensions(){log12(this.dtls.sessionId,`support srtpProfiles`,this.options.srtpProfiles);if(this.options.srtpProfiles&&this.options.srtpProfiles.length>0){const e=UseSRTP.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(e.extension)}{const e=EllipticCurves.createEmpty();e.data=NamedCurveAlgorithmList;this.extensions.push(e.extension)}{const e=Signature.createEmpty();e.data=signatures;this.extensions.push(e.extension)}if(this.options.extendedMasterSecret)this.extensions.push({type:ExtendedMasterSecret.type,data:Buffer.alloc(0)});{const e=RenegotiationIndication.createEmpty();this.extensions.push(e.extension)}}waitForReady=e=>new Promise(async(t,n)=>{for(let n=0;n<10;n++)if(e()){t();break}else await setTimeout$2(100*n);n(`waitForReady timeout`)});handleFragmentHandshake(e){let t=e.filter(e=>{if(e.fragment_length!==e.length){this.bufferFragmentedHandshakes.push(e);return false}return true});if(this.bufferFragmentedHandshakes.length>1){const[e]=this.bufferFragmentedHandshakes.slice(-1);if(e.fragment_offset+e.fragment_length===e.length){t=[...this.bufferFragmentedHandshakes,...t];this.bufferFragmentedHandshakes=[]}}return t}send=async(e,t)=>{const n=createPlaintext(this.dtls)([{type:23,fragment:e}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(n).serialize(),t)};close(){this.transport.socket.close()}extractSessionKeys(e,t){const{clientKey:n,serverKey:r,clientSalt:i,serverSalt:a}=decode20(this.exportKeyingMaterial(`EXTRACTOR-dtls_srtp`,e*2+t*2),{clientKey:types21.buffer(e),serverKey:types21.buffer(e),clientSalt:types21.buffer(t),serverSalt:types21.buffer(t)});if(this.sessionType===SessionType.CLIENT)return{localKey:n,localSalt:i,remoteKey:r,remoteSalt:a};else return{localKey:r,localSalt:a,remoteKey:n,remoteSalt:i}}exportKeyingMaterial(e,t){return exportKeyingMaterial(e,t,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===SessionType.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}};var log13=debug(`werift-dtls : packages/dtls/src/client.ts : log`);var DtlsClient=class extends DtlsSocket{constructor(e){super(e,SessionType.CLIENT);this.onHandleHandshakes=this.handleHandshakes;log13(this.dtls.sessionId,`start client`)}async connect(){await new Flight1(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async e=>{log13(this.dtls.sessionId,`handleHandshakes`,e.map(e=>e.msg_type));for(const t of e)switch(t.msg_type){case 3:{const e=ServerHelloVerifyRequest.deSerialize(t.fragment);await new Flight3(this.transport,this.dtls).exec(e)}break;case 2:if(this.connected)return;this.flight5=new Flight5(this.transport,this.dtls,this.cipher,this.srtp);this.flight5.handleHandshake(t);break;case 11:case 12:case 13:await this.waitForReady(()=>!!this.flight5);this.flight5?.handleHandshake(t);break;case 14:{await this.waitForReady(()=>!!this.flight5);this.flight5?.handleHandshake(t);const e=[11,12,this.options.certificateRequest&&13].filter(e=>typeof e===`number`);await this.waitForReady(()=>this.dtls.checkHandshakesExist(e));await this.flight5?.exec()}break;case 20:this.dtls.flight=7;this.connected=true;this.onConnect.execute();log13(this.dtls.sessionId,`dtls connected`)}}};var log14=debug(`werift-dtls : packages/dtls/flight/server/flight2.ts : log`);var flight2=(e,t,n,r)=>i=>{log14(`dtls version`,i.clientVersion);t.flight=2;t.recordSequenceNumber=0;t.sequenceNumber=0;i.extensions.forEach(e=>{switch(e.type){case EllipticCurves.type:{const r=EllipticCurves.fromData(e.data).data;log14(t.sessionId,`curves`,r);n.namedCurve=r.filter(e=>NamedCurveAlgorithmList.includes(e))[0];log14(t.sessionId,`curve selected`,n.namedCurve)}break;case Signature.type:{if(!n.signatureHashAlgorithm)throw new Error(`need to set certificate`);const r=Signature.fromData(e.data).data;log14(t.sessionId,`hash,signature`,r);const i=r.find(e=>e.signature===n.signatureHashAlgorithm?.signature)?.signature;const a=r.find(e=>e.hash===n.signatureHashAlgorithm?.hash)?.hash;if(i==void 0||a==void 0)throw new Error(`invalid signatureHash`)}break;case UseSRTP.type:{if(!t.options?.srtpProfiles)return;if(t.options.srtpProfiles.length===0)return;const n=UseSRTP.fromData(e.data);log14(t.sessionId,`srtp profiles`,n.profiles);const i=SrtpContext.findMatchingSRTPProfile(n.profiles,t.options?.srtpProfiles);if(!i)throw new Error;r.srtpProfile=i;log14(t.sessionId,`srtp profile selected`,r.srtpProfile)}break;case ExtendedMasterSecret.type:t.remoteExtendedMasterSecret=true;break;case RenegotiationIndication.type:log14(t.sessionId,`RenegotiationIndication`,e.data);break;case 43:log14(`dtls supported version`,[...e.data.subarray(1)].map(e=>e.toString(10)))}});n.localRandom=new DtlsRandom;n.remoteRandom=DtlsRandom.from(i.random);const a=i.cipherSuites;log14(t.sessionId,`cipher suites`,a);const o=(()=>{switch(n.signatureHashAlgorithm?.signature){case SignatureAlgorithm.ecdsa_3:return CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case SignatureAlgorithm.rsa_1:return CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(o===void 0||!a.includes(o))throw new Error(`dtls cipher suite negotiation failed`);n.cipherSuite=o;log14(t.sessionId,`selected cipherSuite`,n.cipherSuite);n.localKeyPair=generateKeyPair(n.namedCurve);t.cookie||=randomBytes$1(20);const s=new ServerHelloVerifyRequest({major:254,minor:253},t.cookie);const c=createFragments(t)([s]);const u=createPlaintext(t)(c.map(e=>({type:22,fragment:e.serialize()})),++t.recordSequenceNumber).map(e=>e.serialize());for(const t of u)e.send(t)};var log15=debug(`werift-dtls : packages/dtls/flight/server/flight4.ts : log`);var Flight4=class extends Flight{constructor(e,t,n,r){super(e,t,4,6);this.cipher=n;this.srtp=r}async exec(e,t=false){if(this.dtls.flight===4){log15(this.dtls.sessionId,`flight4 twice`);this.send(this.dtls.lastMessage);return}this.dtls.flight=4;this.dtls.sequenceNumber=1;this.dtls.bufferHandshakeCache([e],false,4);const n=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),t&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(e=>e);this.dtls.lastMessage=n;await this.transmit(n)}sendServerHello(){const e=[];if(this.srtp.srtpProfile)e.push(UseSRTP.create([this.srtp.srtpProfile],Buffer.from([0])).extension);if(this.dtls.options.extendedMasterSecret)e.push({type:ExtendedMasterSecret.type,data:Buffer.alloc(0)});const t=RenegotiationIndication.createEmpty();e.push(t.extension);const n=new ServerHello(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,e);const r=this.createPacket([n]);return Buffer.concat(r.map(e=>e.serialize()))}sendCertificate(){const e=new Certificate2([Buffer.from(this.cipher.localCert)]);const t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}sendServerKeyExchange(){const e=this.cipher.generateKeySignature(`sha256`);if(!this.cipher.signatureHashAlgorithm)throw new Error(`not exist`);const t=new ServerKeyExchange(CurveType.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,e.length,e);const n=this.createPacket([t]);return Buffer.concat(n.map(e=>e.serialize()))}sendCertificateRequest(){const e=new ServerCertificateRequest(certificateTypes,signatures,[]);log15(this.dtls.sessionId,`sendCertificateRequest`,e);const t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}sendServerHelloDone(){const e=new ServerHelloDone;const t=this.createPacket([e]);return Buffer.concat(t.map(e=>e.serialize()))}};var log16=debug(`werift-dtls : packages/dtls/flight/server/flight6.ts`);var Flight6=class extends Flight{constructor(e,t,n){super(e,t,6);this.cipher=n}handleHandshake(e){this.dtls.bufferHandshakeCache([e],false,5);const t=(()=>{switch(e.msg_type){case 11:return Certificate2.deSerialize(e.fragment);case 15:return CertificateVerify.deSerialize(e.fragment);case 16:return ClientKeyExchange.deSerialize(e.fragment);case 20:return Finished.deSerialize(e.fragment)}})();if(t){const e=handlers2[t.msgType];if(!e)return;e({dtls:this.dtls,cipher:this.cipher})(t)}}async exec(){if(this.dtls.flight===6){log16(this.dtls.sessionId,`flight6 twice`);this.send(this.dtls.lastMessage);return}this.dtls.flight=6;const e=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=e;await this.transmit(e)}sendChangeCipherSpec(){const e=ChangeCipherSpec.createEmpty().serialize();const t=createPlaintext(this.dtls)([{type:20,fragment:e}],++this.dtls.recordSequenceNumber);return Buffer.concat(t.map(e=>e.serialize()))}sendFinished(){const e=Buffer.concat(this.dtls.sortedHandshakeCache.map(e=>e.serialize()));const t=new Finished(this.cipher.verifyData(e));this.dtls.epoch=1;const[n]=this.createPacket([t]);this.dtls.recordSequenceNumber=0;return this.cipher.encryptPacket(n).serialize()}};var handlers2={};handlers2[16]=({cipher:e,dtls:t})=>n=>{e.remoteKeyPair={curve:e.namedCurve,publicKey:n.publicKey};if(!e.remoteKeyPair.publicKey||!e.localKeyPair||!e.remoteRandom||!e.localRandom)throw new Error(`not exist`);const r=prfPreMasterSecret(e.remoteKeyPair.publicKey,e.localKeyPair.privateKey,e.localKeyPair.curve);log16(t.sessionId,`extendedMasterSecret`,t.options.extendedMasterSecret,t.remoteExtendedMasterSecret);const i=Buffer.concat(t.sortedHandshakeCache.map(e=>e.serialize()));e.masterSecret=t.options.extendedMasterSecret&&t.remoteExtendedMasterSecret?prfExtendedMasterSecret(r,i):prfMasterSecret(r,e.remoteRandom.serialize(),e.localRandom.serialize());e.cipher=createCipher(e.cipherSuite);e.cipher.init(e.masterSecret,e.localRandom.serialize(),e.remoteRandom.serialize());log16(t.sessionId,`setup cipher`,e.cipher.summary)};handlers2[11]=({cipher:e,dtls:t})=>n=>{log16(t.sessionId,`handshake certificate`,n);e.remoteCertificate=n.certificateList[0]};handlers2[15]=({cipher:e,dtls:t})=>n=>{if(!e.remoteCertificate)throw new Error(`client certificate missing before certificate verify`);log16(t.sessionId,`certificate_verify`,n.algorithm)};handlers2[20]=({dtls:e})=>t=>{log16(e.sessionId,`finished`,t)};var log17=debug(`werift-dtls : packages/dtls/src/server.ts : log`);var DtlsServer=class extends DtlsSocket{constructor(e){super(e,SessionType.SERVER);this.onHandleHandshakes=this.handleHandshakes;log17(this.dtls.sessionId,`start server`)}flight6;handleHandshakes=async e=>{log17(this.dtls.sessionId,`handleHandshakes`,e.map(e=>e.msg_type));for(const t of e)switch(t.msg_type){case 1:{if(this.connected)this.renegotiation();const e=ClientHello.deSerialize(t.fragment);if(e.cookie.length===0){log17(this.dtls.sessionId,`send flight2`);flight2(this.transport,this.dtls,this.cipher,this.srtp)(e)}else if(this.dtls.cookie&&e.cookie.equals(this.dtls.cookie)){log17(this.dtls.sessionId,`send flight4`);await new Flight4(this.transport,this.dtls,this.cipher,this.srtp).exec(t,this.options.certificateRequest)}else log17(`wrong state`,{dtlsCookie:this.dtls.cookie?.toString(`hex`).slice(10),helloCookie:e.cookie.toString(`hex`).slice(10)})}break;case 11:case 15:case 16:if(this.connected)return;this.flight6=new Flight6(this.transport,this.dtls,this.cipher);this.flight6.handleHandshake(t);break;case 20:{await this.waitForReady(()=>!!this.flight6);this.flight6?.handleHandshake(t);const e=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(e=>typeof e===`number`);await this.waitForReady(()=>this.dtls.checkHandshakesExist(e));await this.flight6?.exec();this.connected=true;this.onConnect.execute();log17(this.dtls.sessionId,`dtls connected`)}}}};var COOKIE=554869826;var FINGERPRINT_LENGTH=8;var FINGERPRINT_XOR=1398035790;var HEADER_LENGTH=20;var INTEGRITY_LENGTH=24;var IPV4_PROTOCOL=1;var IPV6_PROTOCOL=2;var RETRY_MAX=6;var RETRY_RTO=50;var AttributeKeys=[`FINGERPRINT`,`MESSAGE-INTEGRITY`,`MESSAGE-INTEGRITY-SHA256`,`CHANGE-REQUEST`,`PRIORITY`,`USERNAME`,`USERHASH`,`ICE-CONTROLLING`,`SOURCE-ADDRESS`,`USE-CANDIDATE`,`ICE-CONTROLLED`,`ERROR-CODE`,`UNKNOWN-ATTRIBUTES`,`XOR-MAPPED-ADDRESS`,`CHANGED-ADDRESS`,`LIFETIME`,`REQUESTED-TRANSPORT`,`NONCE`,`REALM`,`REQUESTED-ADDRESS-FAMILY`,`EVEN-PORT`,`PASSWORD-ALGORITHM`,`PASSWORD-ALGORITHMS`,`XOR-RELAYED-ADDRESS`,`RESERVATION-TOKEN`,`CHANNEL-NUMBER`,`XOR-PEER-ADDRESS`,`DATA`,`SOFTWARE`,`MAPPED-ADDRESS`,`ALTERNATE-DOMAIN`,`ALTERNATE-SERVER`,`RESPONSE-ORIGIN`,`OTHER-ADDRESS`];var classes=/* @__PURE__ */ (e=>{e[e[`REQUEST`]=0]=`REQUEST`;e[e[`INDICATION`]=16]=`INDICATION`;e[e[`RESPONSE`]=256]=`RESPONSE`;e[e[`ERROR`]=272]=`ERROR`;return e})(classes||{});var methods=/* @__PURE__ */ (e=>{e[e[`BINDING`]=1]=`BINDING`;e[e[`SHARED_SECRET`]=2]=`SHARED_SECRET`;e[e[`ALLOCATE`]=3]=`ALLOCATE`;e[e[`REFRESH`]=4]=`REFRESH`;e[e[`SEND`]=6]=`SEND`;e[e[`DATA`]=7]=`DATA`;e[e[`CREATE_PERMISSION`]=8]=`CREATE_PERMISSION`;e[e[`CHANNEL_BIND`]=9]=`CHANNEL_BIND`;return e})(methods||{});function isComprehensionRequiredAttribute(e){return e>=0&&e<=32767}function isStunMessage(e){if(e.length<20)return false;if((e[0]&192)!==0)return false;if(e.readUInt32BE(4)!==554869826)return false;const t=e.readUInt16BE(2);if(t%4!==0)return false;return e.length===20+t}var TCP_CHECK_RESPONSE_TIMEOUT_MS=3e3;function encodeTcpFrame(e){const t=Buffer.alloc(2);t.writeUInt16BE(e.length,0);return Buffer.concat([t,e])}function splitTcpFrames(e){const t=[];let n=0;while(e.length-n>=2){const r=e.readUInt16BE(n);if(e.length-n<r+2)break;t.push(e.subarray(n+2,n+2+r));n+=2+r}return{frames:t,rest:e.subarray(n)}}function ipAddressToBuffer(e){if(isIPv4(e)){const t=Buffer.allocUnsafe(4);const n=e.split(`.`);for(let e=0;e<4;e++)t[e]=Number(n[e])&255;return t}if(!isIPv6(e))throw new Error(`Invalid ip address: ${e}`);const t=e.split(`:`,8);for(let e=0;e<t.length;e++){let n;if(isIPv4(t[e])){n=ipAddressToBuffer(t[e]);t[e]=n.subarray(0,2).toString(`hex`)}if(n&&++e<8)t.splice(e,0,n.subarray(2,4).toString(`hex`))}if(t[0]===``)while(t.length<8)t.unshift(`0`);else if(t[t.length-1]===``)while(t.length<8)t.push(`0`);else if(t.length<8){let e=0;for(;e<t.length&&t[e]!==``;e++);const n=[];for(let e=9-t.length;e>0;e--)n.push(`0`);t.splice(e,1,...n)}const n=Buffer.allocUnsafe(16);let r=0;for(const e of t){const t=Number.parseInt(e,16)||0;n[r++]=t>>8&255;n[r++]=t&255}return n}function bufferToIpAddress(e){if(e.length===4)return`${e[0]}.${e[1]}.${e[2]}.${e[3]}`;if(e.length!==16)throw new Error(`Invalid ip address buffer length: ${e.length}`);const t=[];for(let n=0;n<16;n+=2)t.push(e.readUInt16BE(n).toString(16));let n=t.join(`:`);n=n.replace(/(^|:)0(:0)*:0(:|$)/,`$1::$3`);n=n.replace(/:{3,4}/,`::`);return n}function isIpV4Address(e){return isIPv4(e)}function packAddress(e){const[t]=e;const n=isIpV4Address(t)?1:2;const r=Buffer.alloc(4);r.writeUInt8(0,0);r.writeUInt8(n,1);r.writeUInt16BE(e[1],2);return Buffer.concat([r,ipAddressToBuffer(t)])}function unpackErrorCode(e){if(e.length<4)throw new Error(`STUN error code is less than 4 bytes`);const t=e.readUInt8(2);const n=e.readUInt8(3);const r=e.slice(4).toString(`utf8`);return[t*100+n,r]}function unpackAddress(e){if(e.length<4)throw new Error(`STUN address length is less than 4 bytes`);const t=e.readUInt8(1);const n=e.readUInt16BE(2);const r=e.slice(4);switch(t){case 1:if(r.length!==4)throw new Error(`STUN address has invalid length for IPv4`);return[bufferToIpAddress(r),n];case 2:if(r.length!==16)throw new Error(`STUN address has invalid length for IPv6`);return[bufferToIpAddress(r),n];default:throw new Error(`STUN address has unknown protocol`)}}var cookieBuffer=Buffer.alloc(6);cookieBuffer.writeUInt16BE(COOKIE>>16,0);cookieBuffer.writeUInt32BE(COOKIE,2);function xorAddress(e,t){const n=[...cookieBuffer,...t];let r=e.slice(0,2);for(let t=2;t<e.length;t++){const i=e[t]^n[t-2];const a=Buffer.alloc(1);a.writeUIntBE(i,0,1);r=Buffer.concat([r,a])}return r}function unpackXorAddress(e,t){return unpackAddress(xorAddress(e,t))}function packErrorCode(e){const t=Buffer.alloc(4);t.writeUInt16BE(0,0);t.writeUInt8(Math.floor(e[0]/100),2);t.writeUInt8(e[0]%100,3);const n=Buffer.from(e[1],`utf8`);return Buffer.concat([t,n])}function packUnknownAttributes(e){const t=Buffer.alloc(e.length*2);e.forEach((e,n)=>{t.writeUInt16BE(e,n*2)});return t}function unpackUnknownAttributes(e){if(e.length%2!==0)throw new Error(`UNKNOWN-ATTRIBUTES must have an even length`);const t=[];for(let n=0;n<e.length;n+=2)t.push(e.readUInt16BE(n));return t}function packXorAddress(e,t){return xorAddress(packAddress(e),t)}var packUnsigned=e=>{const t=Buffer.alloc(4);t.writeUInt32BE(e,0);return t};var unpackUnsigned=e=>e.readUInt32BE(0);var packUnsignedShort=e=>{const t=Buffer.alloc(4);t.writeUInt16BE(e,0);return t};var unpackUnsignedShort=e=>e.readUInt16BE(0);var packUnsigned64=e=>{const t=Buffer.allocUnsafe(8);t.writeBigUInt64BE(e,0);return t};var unpackUnsigned64=e=>e.readBigUInt64BE(0);var packString=e=>Buffer.from(e,`utf8`);var unpackString=e=>e.toString(`utf8`);var packSoftware=e=>{if([...e].length>=128)throw new Error(`SOFTWARE must be shorter than 128 characters`);return packString(e)};var packBytes=e=>e;var unpackBytes=e=>e;var packNone=()=>Buffer.alloc(0);var unpackNone=()=>null;var ATTRIBUTES=[[1,`MAPPED-ADDRESS`,packAddress,unpackAddress],[3,`CHANGE-REQUEST`,packUnsigned,unpackUnsigned],[4,`SOURCE-ADDRESS`,packAddress,unpackAddress],[5,`CHANGED-ADDRESS`,packAddress,unpackAddress],[6,`USERNAME`,packString,unpackString],[8,`MESSAGE-INTEGRITY`,packBytes,unpackBytes],[9,`ERROR-CODE`,packErrorCode,unpackErrorCode],[10,`UNKNOWN-ATTRIBUTES`,packUnknownAttributes,unpackUnknownAttributes],[12,`CHANNEL-NUMBER`,packUnsignedShort,unpackUnsignedShort],[13,`LIFETIME`,packUnsigned,unpackUnsigned],[18,`XOR-PEER-ADDRESS`,packXorAddress,unpackXorAddress],[19,`DATA`,packBytes,unpackBytes],[20,`REALM`,packString,unpackString],[21,`NONCE`,packBytes,unpackBytes],[22,`XOR-RELAYED-ADDRESS`,packXorAddress,unpackXorAddress],[23,`REQUESTED-ADDRESS-FAMILY`,packUnsigned,unpackUnsigned],[24,`EVEN-PORT`,packBytes,unpackBytes],[25,`REQUESTED-TRANSPORT`,packUnsigned,unpackUnsigned],[28,`MESSAGE-INTEGRITY-SHA256`,packBytes,unpackBytes],[29,`PASSWORD-ALGORITHM`,packBytes,unpackBytes],[30,`USERHASH`,packBytes,unpackBytes],[32,`XOR-MAPPED-ADDRESS`,packXorAddress,unpackXorAddress],[34,`RESERVATION-TOKEN`,packBytes,unpackBytes],[36,`PRIORITY`,packUnsigned,unpackUnsigned],[37,`USE-CANDIDATE`,packNone,unpackNone],[32770,`PASSWORD-ALGORITHMS`,packBytes,unpackBytes],[32771,`ALTERNATE-DOMAIN`,packString,unpackString],[32802,`SOFTWARE`,packSoftware,unpackString],[32803,`ALTERNATE-SERVER`,packAddress,unpackAddress],[32808,`FINGERPRINT`,packUnsigned,unpackUnsigned],[32809,`ICE-CONTROLLED`,packUnsigned64,unpackUnsigned64],[32810,`ICE-CONTROLLING`,packUnsigned64,unpackUnsigned64],[32811,`RESPONSE-ORIGIN`,packAddress,unpackAddress],[32812,`OTHER-ADDRESS`,packAddress,unpackAddress]];var AttributeRepository=class{constructor(e=[]){this.attributes=e}getAttributes(){return this.attributes}setAttribute(e,t){const n=this.attributes.find(t=>t[0]===e);if(n)n[1]=t;else this.attributes.push([e,t]);return this}getAttributeValue(e){return this.attributes.find(t=>t[0]===e)?.[1]}get attributesKeys(){return this.attributes.map(e=>e[0])}clear(){this.attributes=[]}};var ATTRIBUTES_BY_TYPE=ATTRIBUTES.reduce((e,t)=>{e[t[0]]=t;return e},{});var ATTRIBUTES_BY_NAME=ATTRIBUTES.reduce((e,t)=>{e[t[1]]=t;return e},{});function parseMessage(e,t){if(!isStunMessage(e))return;const n=e.readUInt16BE(0);const r=Buffer.from(e.slice(20-12,20));const i=new AttributeRepository;const a=[];let o=false;for(let n=20;n<e.length;){if(n+4>e.length)return;const s=e.readUInt16BE(n);const c=e.readUInt16BE(n+2);const u=n+4;const d=u+c;if(d>e.length)return;const f=e.slice(u,d);const p=paddingLength(c);if(d+p>e.length)return;const m=ATTRIBUTES_BY_TYPE[s];if(m){const[,a,,s]=m;let c;try{c=s.name===unpackXorAddress.name?s(f,r):s(f)}catch{return}i.setAttribute(a,c);if(a===`FINGERPRINT`){const t=messageFingerprint(e.slice(0,n));if(i.getAttributeValue(`FINGERPRINT`)!==t)return}else if(a===`MESSAGE-INTEGRITY`&&t){const r=messageIntegrity(e.slice(0,n),t);const a=i.getAttributeValue(`MESSAGE-INTEGRITY`);if(!r.equals(a))return;o=true}}else a.push({type:s,length:c,value:Buffer.from(f)});n=d+p}if(t&&!o)return;return new Message(n&16111,n&272,r,i.getAttributes(),a)}var Message=class extends AttributeRepository{constructor(e,t,n=randomBytes$1(12),r=[],i=[]){super(r);this.messageMethod=e;this.messageClass=t;this.transactionId=n;this.rawAttributes=i}toJSON(){return this.json}get json(){return{messageMethod:this.messageMethod,messageClass:this.messageClass,attributes:this.attributes,rawAttributes:this.rawAttributes.map(e=>({type:e.type,length:e.value.length}))}}get transactionIdHex(){return this.transactionId.toString(`hex`)}appendRawAttribute(e,t){this.rawAttributes.push({type:e,value:Buffer.from(t)});return this}get unknownAttributeTypes(){return this.rawAttributes.map(e=>e.type)}get bytes(){const e=Buffer.concat(this.serializedAttributes.map(e=>serializeAttribute(e.type,e.value)));const t=Buffer.alloc(8);t.writeUInt16BE(this.messageMethod|this.messageClass,0);t.writeUInt16BE(e.length,2);t.writeUInt32BE(COOKIE,4);return Buffer.concat([t,this.transactionId,e])}addMessageIntegrity(e){this.setAttribute(`MESSAGE-INTEGRITY`,this.messageIntegrity(e));return this}messageIntegrity(e){const t=setBodyLength(this.bytes,this.bytes.length-20+24);return Buffer.from(createHmac$1(`sha1`,e).update(t).digest(`hex`),`hex`)}addFingerprint(){this.setAttribute(`FINGERPRINT`,messageFingerprint(this.bytes));return this}get serializedAttributes(){const e=[];for(const t of this.attributesKeys){const n=this.getAttributeValue(t);const[r,,i]=ATTRIBUTES_BY_NAME[t];const a=i.name===packXorAddress.name?i(n,this.transactionId):i(n);e.push({type:r,value:a})}e.push(...this.rawAttributes.map(e=>({type:e.type,value:Buffer.from(e.value)})));return e}};function serializeAttribute(e,t){const n=t.length;const r=paddingLength(n);const i=Buffer.alloc(4);i.writeUInt16BE(e,0);i.writeUInt16BE(n,2);return Buffer.concat([i,t,Buffer.alloc(r)])}var setBodyLength=(e,t)=>{const n=Buffer.alloc(e.length);e.copy(n,0,0,2);n.writeUInt16BE(t,2);e.copy(n,4,4);return n};function messageFingerprint(e){return(crc32(setBodyLength(e,e.length-20+8))^FINGERPRINT_XOR)>>>0}function messageIntegrity(e,t){const n=setBodyLength(e,e.length-20+24);return Buffer.from(createHmac$1(`sha1`,t).update(n).digest(`hex`),`hex`)}function paddingLength(e){const t=e%4;return t===0?0:4-t}var TransactionError=class extends Error{response;addr};var TransactionFailed=class extends TransactionError{constructor(e,t){super();this.response=e;this.addr=t}get str(){let e=`STUN transaction failed`;const t=this.response.getAttributeValue(`ERROR-CODE`);if(t){const[n,r]=t;e+=` (${n} - ${r})`}return e}};var TransactionTimeout=class extends TransactionError{get str(){return`STUN transaction timed out`}};var AddressFamilyMismatch=class extends Error{constructor(e,t){super(`cannot reach ${e[0]}:${e[1]} from an IPv${t} socket`);this.addr=e;this.socketFamily=t}};var log18=debug(`werift-ice:packages/ice/src/stun/transaction.ts`);async function resolveRequestAddress(e,t=0){const n=isIP(e[0]);if(n){if(t!==0&&n!==t)throw new AddressFamilyMismatch(e,t);return e}return[(await promises.lookup(e[0],{family:t})).address,e[1]]}function normalizeTransactionOptions(e,t){if(e!==null&&typeof e===`object`)return e;return{retransmissions:typeof e===`number`?e:void 0,onRequestSent:t}}function addressEquals(e,t){return e[1]===t[1]&&canonicalHost(e[0])===canonicalHost(t[0])}function canonicalHost(e){return isIP(e)===6?new SocketAddress({address:e,family:`ipv6`}).address:e}var Transaction=class{constructor(e,t,n,r,i){this.request=e;this.addr=t;this.protocol=n;const a=normalizeTransactionOptions(r,i);this.triesMax=1+(a.retransmissions??6);this.timeoutDelay=a.responseTimeout??50;this.onRequestSent=a.onRequestSent;this.signal=a.signal;this.failOnSendError=a.failOnSendError??false;this.expectedAddr=t;this.integrityKey=a.integrityKey}timeoutDelay;ended=false;tries=0;triesMax;onResponse=new Event2;onRequestSent;signal;failOnSendError;expectedAddr;integrityKey;waitTimer;waitResolve;onAbort;responseReceived=(e,t)=>{if(this.ended||this.onResponse.length===0)return;if(!addressEquals(this.expectedAddr,t)){log18(`ignore STUN response from unexpected address`,t,`expected`,this.expectedAddr);return}if(this.integrityKey){if(!(e.attributesKeys.includes(`MESSAGE-INTEGRITY`)||e.attributesKeys.includes(`MESSAGE-INTEGRITY-SHA256`))){log18(`ignore unauthenticated STUN response (MESSAGE-INTEGRITY required)`);return}}if(e.messageClass===256){this.onResponse.execute(e,t);this.onResponse.complete()}else this.onResponse.error(new TransactionFailed(e,t))};run=async()=>{try{if(this.signal?.aborted)throw new TransactionTimeout;this.attachAbortListener();this.retry().catch(e=>{log18(`retry failed`,e)});return await this.onResponse.asPromise()}catch(e){throw e}finally{this.cancel()}};attachAbortListener(){if(!this.signal)return;this.onAbort=()=>{this.failWithTimeout()};this.signal.addEventListener(`abort`,this.onAbort,{once:true})}failWithTimeout(){this.fail(new TransactionTimeout)}fail(e){if(this.ended)return;this.ended=true;this.clearWait();if(this.onResponse.length>0)this.onResponse.error(e)}clearWait(){if(this.waitTimer!==void 0){clearTimeout(this.waitTimer);this.waitTimer=void 0}const e=this.waitResolve;this.waitResolve=void 0;e?.()}wait(e){return new Promise(t=>{if(this.ended||this.signal?.aborted){t();return}this.waitResolve=t;this.waitTimer=setTimeout(()=>{this.waitTimer=void 0;this.waitResolve=void 0;t()},e)})}retry=async()=>{while(this.tries<this.triesMax&&!this.ended){this.onRequestSent?.(this.tries);this.protocol.sendStun(this.request,this.addr).catch(e=>{log18(`send stun failed`,e);if(this.failOnSendError)this.fail(e)});await this.wait(this.timeoutDelay);if(this.ended)break;this.timeoutDelay*=2;this.tries++}if(this.tries>=this.triesMax&&!this.ended){log18(`retry failed times:${this.tries} maxLimit:${this.triesMax}`);this.failWithTimeout()}};cancel(){this.ended=true;this.clearWait();if(this.signal&&this.onAbort){this.signal.removeEventListener(`abort`,this.onAbort);this.onAbort=void 0}}};function buildTransactionOptions(e,t,n){const r=normalizeTransactionOptions(t,n);if(e&&!r.integrityKey)r.integrityKey=e;return r}var log19=debug(`werift-ice:packages/ice/src/stun/tcpProtocol.ts`);function socketKey(e){return`${e[0]}:${e[1]}`}function isSocketClosed(e){return e.destroyed||e.writableEnded}function addressFromSocket(e){if(!e.remoteAddress||!e.remotePort)return;return[e.remoteAddress,e.remotePort]}async function waitForListening(e,t,n){return await new Promise((r,i)=>{const onError=t=>{e.off(`listening`,onListening);i(t)};const onListening=()=>{e.off(`error`,onError);r()};e.once(`error`,onError);e.once(`listening`,onListening);e.listen({host:t,port:n??0,exclusive:true})})}var BaseTcpProtocol=class _BaseTcpProtocol{static type=`tcp`;type=_BaseTcpProtocol.type;transactions={};localCandidate;sentMessage;localIp;onRequestReceived=new Event2;onDataReceived=new Event2;onConnectionClosed=new Event2;sockets=/* @__PURE__ */ new Map;rememberSocket(e){const t=e.remoteAddr;if(!t)return;this.sockets.set(socketKey(t),e)}forgetSocket(e){const t=e.remoteAddr;if(!t)return false;const n=socketKey(t);if(this.sockets.get(n)!==e)return false;this.sockets.delete(n);return true}getOpenSocket(e){const t=this.sockets.get(socketKey(e));if(!t)return;if(isSocketClosed(t.socket)){this.dropSocket(t);return}return t}dropSocket(e){e.socket.destroy();if(this.forgetSocket(e)&&e.remoteAddr)this.onConnectionClosed.execute(e.remoteAddr)}registerSocket(e,t){const n={socket:e,buffer:Buffer.alloc(0),remoteAddr:t};if(t)this.rememberSocket(n);e.on(`data`,t=>{n.buffer=Buffer.concat([n.buffer,t]);const{frames:r,rest:i}=splitTcpFrames(n.buffer);n.buffer=i;const a=n.remoteAddr??addressFromSocket(e);if(!n.remoteAddr&&a){n.remoteAddr=a;this.rememberSocket(n)}if(!a)return;for(const e of r){if(e.length===0)continue;this.handleFrame(e,a)}});e.on(`close`,()=>{if(this.forgetSocket(n)&&n.remoteAddr)this.onConnectionClosed.execute(n.remoteAddr)});e.on(`error`,e=>{log19(`tcp socket error`,e)});return n}handleFrame(e,t){try{const n=parseMessage(e);if(!n){this.onDataReceived.execute(e);return}if((n.messageClass===256||n.messageClass===272)&&this.transactions[n.transactionIdHex]){const r=this.transactions[n.transactionIdHex];const i=r.integrityKey?parseMessage(e,r.integrityKey):n;if(!i){log19(`STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}else if(n.messageClass===0)this.onRequestReceived.execute(n,t,e)}catch(e){log19(`tcp frame parse error`,e)}}async sendFrame(e,t){const n=await this.getSocket(t);try{await new Promise((t,r)=>{n.socket.write(encodeTcpFrame(e),e=>{if(e){r(e);return}t()})})}catch(e){log19(`tcp write failed`,t,e);this.dropSocket(n);throw e}}async sendStun(e,t){await this.sendFrame(e.bytes,t)}async sendData(e,t){await this.sendFrame(e,t)}async request(e,t,n,r,i){if(this.transactions[e.transactionIdHex])throw new Error(`already requested`);if(n){e.addMessageIntegrity(n);e.addFingerprint()}const a=await resolveRequestAddress(t);const o={failOnSendError:true,...buildTransactionOptions(n,r,i)};const s=new Transaction(e,a,this,o);this.transactions[e.transactionIdHex]=s;try{return await s.run()}finally{delete this.transactions[e.transactionIdHex]}}async pruneForSelection(e){for(const[t,n]of this.sockets.entries()){if(e&&t===socketKey(e))continue;n.socket.destroy();this.sockets.delete(t)}}get activeSocketCount(){return this.sockets.size}get address(){return{}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()});await this.pruneForSelection();this.onRequestReceived.complete();this.onDataReceived.complete();this.onConnectionClosed.complete()}};var TcpActiveProtocol=class extends BaseTcpProtocol{pendingSockets=/* @__PURE__ */ new Map;async connectionMade(e){this.localIp=e}async getSocket(e){const t=socketKey(e);const n=this.getOpenSocket(e);if(n)return n;const r=this.pendingSockets.get(t);if(r)return await r;const i=new Promise((t,n)=>{const r=connect({host:e[0],port:e[1],localAddress:this.localIp});const i=this.registerSocket(r,e);const onError=e=>{r.off(`connect`,onConnect);n(e)};const onConnect=()=>{r.off(`error`,onError);t(i)};r.once(`error`,onError);r.once(`connect`,onConnect)});this.pendingSockets.set(t,i);try{return await i}finally{this.pendingSockets.delete(t)}}};var TcpPassiveProtocol=class extends BaseTcpProtocol{server=createServer(e=>{this.registerSocket(e,addressFromSocket(e))});async connectionMade(e,t){this.localIp=e;if(t){let n;for(let r=t[0];r<=t[1];r++)try{await waitForListening(this.server,e,r);return}catch(e){n=e}throw n??/* @__PURE__ */ new Error(`tcp port not found`)}await waitForListening(this.server,e)}async getSocket(e){const t=this.getOpenSocket(e);if(!t)throw new Error(`tcp passive connection not established`);return t}get listeningPort(){const e=this.server.address();if(!e||typeof e===`string`)throw new Error(`tcp passive protocol is not listening`);return e.port}async close(){await super.close();await new Promise(e=>{this.server.close(()=>e())})}};var log20=debug(`werift-ice : packages/ice/src/stun/protocol.ts`);var StunProtocol=class _StunProtocol{static type=`stun`;type=_StunProtocol.type;transport;transactions={};get transactionsKeys(){return Object.keys(this.transactions)}localCandidate;sentMessage;localIp;onRequestReceived=new Event2;onDataReceived=new Event2;constructor(){}connectionMade=async(e,t,n)=>{if(e)this.transport=await UdpTransport.init(`udp4`,{portRange:t,interfaceAddresses:n});else this.transport=await UdpTransport.init(`udp6`,{portRange:t,interfaceAddresses:n});this.transport.onData=(e,t)=>{this.datagramReceived(e,t)}};datagramReceived(e,t){try{const n=parseMessage(e);if(!n){if(this.localCandidate)this.onDataReceived.execute(e);return}if((n.messageClass===256||n.messageClass===272)&&this.transactionsKeys.includes(n.transactionIdHex)){const r=this.transactions[n.transactionIdHex];const i=r.integrityKey?parseMessage(e,r.integrityKey):n;if(!i){log20(`STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}else if(n.messageClass===0)this.onRequestReceived.execute(n,t,e)}catch(e){log20(`datagramReceived error`,e)}}getExtraInfo(){const{address:e,port:t}=this.transport.address;return[e,t]}async sendStun(e,t){if(this.transport.closed)return;const n=e.bytes;await this.transport.send(n,t).catch(()=>{log20(`sendStun failed`,t,e)})}async sendData(e,t){if(this.transport.closed)return;await this.transport.send(e,t)}async request(e,t,n,r,i){if(this.transactionsKeys.includes(e.transactionIdHex))throw new Error(`already request ed`);if(n){e.addMessageIntegrity(n);e.addFingerprint()}const a=await resolveRequestAddress(t,this.transport.addressFamily);const o=buildTransactionOptions(n,r,i);const s=new Transaction(e,a,this,o);this.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(e){throw e}finally{delete this.transactions[e.transactionIdHex]}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()});await this.transport.close();this.onRequestReceived.complete();this.onDataReceived.complete()}};function makeTurnIntegrityKey(e,t,n){return createHash$1(`md5`).update(Buffer.from([e,t,n].join(`:`))).digest()}function randomString(e){return randomBytes$1(e).toString(`hex`).substring(0,e)}function randomTransactionId(){return randomBytes$1(12)}var PQueue=class{queue=[];wait=new Event2;put(e){this.queue.push(e);if(this.queue.length===1)this.wait.execute(e)}get(){const e=this.queue.shift();if(!e)return new Promise(e=>{this.wait.subscribe(t=>{this.queue.shift();e(t)})});return e}};var cancelable=e=>{let t;let n;const r=new Promise((e,r)=>{t=e;n=r});r.then(()=>{i.execute(void 0);i.complete()}).catch(e=>{i.execute(e??/* @__PURE__ */ new Error);i.complete()});const i=new Event2;e(t,n,i).catch(()=>{});return{awaitable:r,resolve:t,reject:n}};function isChannelData(e){return e.length>=4&&(e[0]&192)===64}function encodeChannelData(e,t){const n=Buffer.alloc(4);n.writeUInt16BE(e,0);n.writeUInt16BE(t.length,2);return Buffer.concat([n,t])}function decodeChannelData(e){if(!isChannelData(e)||e.length<4)return;const t=e.readUInt16BE(0);const n=e.readUInt16BE(2);if(e.length<4+n)return;return{channelNumber:t,data:e.subarray(4,4+n)}}function padTurnFrame(e){const t=paddingLength(e.length);return t>0?Buffer.concat([e,Buffer.alloc(t)]):e}function splitTurnTcpFrames(e){const t=[];let n=0;let r=false;while(e.length-n>=4){let i;if(isChannelData(e.subarray(n))){const t=e.readUInt16BE(n+2);i=4+t+paddingLength(t)}else if((e[n]&192)===0){if(e.length-n<20)break;const t=e.readUInt16BE(n+2);i=20+t+paddingLength(t)}else{r=true;break}if(e.length-n<i)break;t.push(e.subarray(n,n+i));n+=i}return{frames:t,malformed:r,rest:e.subarray(n)}}var log21=debug(`werift-ice:packages/ice/src/turn/protocol.ts`);var DEFAULT_CHANNEL_REFRESH_TIME=500;var DEFAULT_ALLOCATION_LIFETIME=600;var UDP_TRANSPORT=285212672;function isStreamTransport(e){return e.type===`tcp`||e.type===`tls`}function permissionKey(e){return e[0]}function channelKey(e){return JSON.stringify(e)}var StunOverTurnProtocol=class _StunOverTurnProtocol{constructor(e){this.turn=e;e.onData.subscribe((e,t)=>{this.handleStunMessage(e,t)}).disposer(this.disposer)}static type=`turn`;type=_StunOverTurnProtocol.type;localCandidate;disposer=new EventDisposer;onRequestReceived=new Event2;onDataReceived=new Event2;handleStunMessage=(e,t)=>{try{const n=parseMessage(e);if(!n){this.onDataReceived.execute(e);return}if(n.messageClass===256||n.messageClass===272){const r=this.turn.transactions[n.transactionIdHex];if(r){const i=r.integrityKey?parseMessage(e,r.integrityKey):n;if(!i){log21(`STUN over TURN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}}else if(n.messageClass===0)this.onRequestReceived.execute(n,t,e)}catch(e){log21(`datagramReceived error`,e)}};async request(e,t,n,r,i){if(this.turn.transactions[e.transactionIdHex])throw new Error(`exist`);if(n){e.addMessageIntegrity(n);e.addFingerprint()}const a=await resolveRequestAddress(t);const o=buildTransactionOptions(n,r,i);const s=new Transaction(e,a,this,o);this.turn.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(e){throw e}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,t){await this.turn.sendData(e,t)}async sendStun(e,t){await this.turn.sendData(e.bytes,t)}async close(){this.disposer.dispose();return this.turn.close()}};var TurnProtocol=class _TurnProtocol{constructor(e,t,n,r,i,a={}){this.server=e;this.username=t;this.password=n;this.lifetime=r;this.transport=i;this.options=a;this.channelRefreshTime=this.options.channelRefreshTime??DEFAULT_CHANNEL_REFRESH_TIME}static type=`turn`;type=_TurnProtocol.type;onData=new Event2;onRequestReceived=new Event2;onDataReceived=new Event2;integrityKey;nonce;realm;relayedAddress;mappedAddress;localCandidate;transactions={};refreshHandle;channelNumber=16384;channelByAddr={};addrByChannel={};channelRefreshTime;channelBindQueue=Promise.resolve();channelBindingByAddr=/* @__PURE__ */ new Map;tcpBuffer=Buffer.alloc(0);permissionByAddr={};permissionQueue=Promise.resolve();creatingPermissionByAddr=/* @__PURE__ */ new Map;pinnedServerEndpoint;serverEndpointSelection;async connectionMade(){this.transport.onData=(e,t)=>{this.dataReceived(e,t)};const e=new Message(3,0);e.setAttribute(`LIFETIME`,this.lifetime).setAttribute(`REQUESTED-TRANSPORT`,UDP_TRANSPORT);const[t]=await this.requestWithRetry(e,this.server).catch(e=>{log21(`connect error`,e);throw e});this.relayedAddress=t.getAttributeValue(`XOR-RELAYED-ADDRESS`);this.mappedAddress=t.getAttributeValue(`XOR-MAPPED-ADDRESS`);const n=t.getAttributeValue(`LIFETIME`);log21(`connect`,this.relayedAddress,this.mappedAddress,{exp:n});this.refresh(n)}handleChannelData(e){const t=decodeChannelData(e);const n=t&&this.addrByChannel[t.channelNumber];if(n&&t)this.onData.execute(t.data,n)}handleSTUNMessage(e,t){try{const n=parseMessage(e);if(!n)throw new Error(`not stun message`);if(n.messageClass===256||n.messageClass===272){const r=this.transactions[n.transactionIdHex];if(r){const i=r.integrityKey?parseMessage(e,r.integrityKey):n;if(!i){log21(`TURN STUN response failed MESSAGE-INTEGRITY check`);return}r.responseReceived(i,t)}}else if(n.messageClass===0)this.onData.execute(e,t);if(n.getAttributeValue(`DATA`)){const e=n.getAttributeValue(`DATA`);const r=n.getAttributeValue(`XOR-PEER-ADDRESS`)??t;this.onData.execute(e,r)}}catch(t){log21(`parse error`,e.toString())}}dataReceived(e,t){const datagramReceived=(e,t)=>{if(e.length>=4&&isChannelData(e))this.handleChannelData(e);else this.handleSTUNMessage(e,t)};if(isStreamTransport(this.transport)){this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);const{frames:n,rest:r}=splitTurnTcpFrames(this.tcpBuffer);this.tcpBuffer=r;for(const e of n)datagramReceived(e,t)}else datagramReceived(e,t)}async send(e,t){if(this.transport.closed)return;await this.transport.send(isStreamTransport(this.transport)?padTurnFrame(e):e,t)}async createPermission(e){const t=new Message(8,0);t.setAttribute(`XOR-PEER-ADDRESS`,e).setAttribute(`USERNAME`,this.username).setAttribute(`REALM`,this.realm).setAttribute(`NONCE`,this.nonce);await this.requestWithRetry(t,this.server)}refresh=e=>{this.refreshHandle=cancelable(async(t,n,r)=>{const i=new AbortController;r.once(()=>{i.abort()});while(!i.signal.aborted){const t=5/6*e*1e3;log21(`refresh delay`,t,{exp:e});try{await setTimeout$2(t,void 0,{signal:i.signal})}catch(e){if(i.signal.aborted)return;throw e}if(i.signal.aborted)return;const n=new Message(4,0);n.setAttribute(`LIFETIME`,e);try{const[t]=await this.requestWithRetry(n,this.server,i.signal);e=t.getAttributeValue(`LIFETIME`);log21(`refresh`,{exp:e})}catch(e){if(i.signal.aborted)return;log21(`refresh error`,e)}}})};async request(e,t,n,r,i){if(this.transactions[e.transactionIdHex])throw new Error(`exist`);if(this.integrityKey)e.setAttribute(`USERNAME`,this.username).setAttribute(`REALM`,this.realm).setAttribute(`NONCE`,this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint();const a=await this.resolveRequestTarget(t);const o=buildTransactionOptions(this.integrityKey,r,i);const s=new Transaction(e,a,this,o);this.transactions[e.transactionIdHex]=s;try{return await s.run()}catch(e){throw e}finally{delete this.transactions[e.transactionIdHex]}}get serverEndpoint(){return this.pinnedServerEndpoint}async resolveRequestTarget(e){if(isStreamTransport(this.transport)||addressEquals(e,this.server))return this.selectServerEndpoint();return resolveRequestAddress(e,this.transport.addressFamily??0)}async serverDestination(){return this.pinnedServerEndpoint??this.selectServerEndpoint()}selectServerEndpoint(){this.serverEndpointSelection??=this.resolveServerEndpoint().then(e=>{this.pinnedServerEndpoint=e;return e},e=>{this.serverEndpointSelection=void 0;throw e});return this.serverEndpointSelection}async resolveServerEndpoint(){const e=this.transport;if(!isStreamTransport(e))return resolveRequestAddress(this.server,e.addressFamily??0);if(e.remoteAddress)return e.remoteAddress;if(e instanceof TcpTransport||e instanceof TlsTransport)throw new Error(`${e.type} transport has no remote address`);return resolveRequestAddress(this.server)}async requestWithRetry(e,t,n){let r,i;try{[r,i]=await this.request(e,t,void 0,{signal:n})}catch(t){if(t instanceof TransactionFailed==false){log21(`requestWithRetry error`,t);throw t}const[a]=t.response.getAttributeValue(`ERROR-CODE`);const o=t.response.getAttributeValue(`NONCE`);const s=t.response.getAttributeValue(`REALM`);if((a===401&&s||a===438&&this.realm)&&o){log21(`retry with nonce`,a);this.nonce=o;if(a===401)this.realm=s;this.integrityKey=makeIntegrityKey(this.username,this.realm,this.password);e.transactionId=randomTransactionId();[r,i]=await this.request(e,this.server,void 0,{signal:n})}else throw t}return[r,i]}async sendData(e,t){let n;try{n=await this.getChannel(t)}catch(e){log21(`channelBind error; falling back to Send Indication`,e)}if(!n){await this.getPermission(t);const n=new Message(6,16).setAttribute(`DATA`,e).setAttribute(`XOR-PEER-ADDRESS`,t);await this.sendStun(n,await this.serverDestination());return}await this.send(encodeChannelData(n.number,e),await this.serverDestination())}async getPermission(e){const t=permissionKey(e);if(this.permissionByAddr[t])return;const n=this.creatingPermissionByAddr.get(t);if(n)return n;const r=this.permissionQueue.then(async()=>{if(this.permissionByAddr[t])return;await this.createPermission(e);this.permissionByAddr[t]=true});this.permissionQueue=r.then(()=>void 0,()=>void 0);this.creatingPermissionByAddr.set(t,r);try{await r}catch(e){log21(`createPermission error`,e);throw e}finally{if(this.creatingPermissionByAddr.get(t)===r)this.creatingPermissionByAddr.delete(t)}}async getChannel(e){const t=channelKey(e);const n=this.channelBindingByAddr.get(t);if(n)return n;const r=this.channelByAddr[t];const i=int(Date.now()/1e3);if(r&&r.refreshAt>i)return r;const a=this.channelBindQueue.then(()=>this.ensureChannel(e));this.channelBindQueue=a.then(()=>void 0,()=>void 0);this.channelBindingByAddr.set(t,a);try{return await a}catch(e){log21(`channelBind error`,e);throw e}finally{if(this.channelBindingByAddr.get(t)===a)this.channelBindingByAddr.delete(t)}}async ensureChannel(e){const t=channelKey(e);const n=int(Date.now()/1e3);let r=this.channelByAddr[t];if(r&&r.refreshAt>n)return r;const i=!r;if(!r){r={number:this.channelNumber++,address:e,refreshAt:0};this.channelByAddr[t]=r;this.addrByChannel[r.number]=e}try{await this.channelBind(r.number,e);r.refreshAt=int(Date.now()/1e3)+this.channelRefreshTime;log21(i?`channelBind`:`channelBind refresh`,r);return r}catch(e){if(i){delete this.channelByAddr[t];delete this.addrByChannel[r.number]}throw e}}async channelBind(e,t){const n=new Message(9,0);n.setAttribute(`CHANNEL-NUMBER`,e).setAttribute(`XOR-PEER-ADDRESS`,t);const[r]=await this.requestWithRetry(n,this.server);if(r.messageMethod!==9)throw new Error(`should be CHANNEL_BIND`)}async sendStun(e,t){await this.send(e.bytes,t)}async close(){this.refreshHandle?.resolve?.();await this.transport.close()}};function selectTurnUdpSocketType(e,t){const n=isIP(e[0]);if(n===4||n===6){if(t&&t!==n)log21(`udpFamily ignored for IP literal TURN server`,{address:e,udpFamily:t,literalFamily:n});return n===6?`udp6`:`udp4`}return(t??4)===6?`udp6`:`udp4`}async function createTurnClient({address:e,username:t,password:n},{lifetime:r,portRange:i,interfaceAddresses:a,ssl:o,tlsOptions:s,transport:c,connectTimeoutMs:u,udpFamily:d}={}){r??=DEFAULT_ALLOCATION_LIFETIME;c??=o?`tls`:`udp`;const f=c===`udp`?await UdpTransport.init(selectTurnUdpSocketType(e,d),{portRange:i,interfaceAddresses:a}):c===`tcp`?await TcpTransport.init(e,{connectTimeoutMs:u}):await TlsTransport.init(e,s,{connectTimeoutMs:u});const p=new TurnProtocol(e,t,n,r,f);try{await p.connectionMade()}catch(e){try{await p.close()}catch(e){log21(`failed to close TURN client after allocation failure`,e)}throw e}return p}async function createStunOverTurnClient(e,t={}){return new StunOverTurnProtocol(await createTurnClient(e,t))}function makeIntegrityKey(e,t,n){return makeTurnIntegrityKey(e,t,n)}var Candidate=class _Candidate{constructor(e,t,n,r,i,a,o,s,c,u,d,f){this.foundation=e;this.component=t;this.transport=n;this.priority=r;this.host=i;this.port=a;this.type=o;this.relatedAddress=s;this.relatedPort=c;this.tcptype=u;this.generation=d;this.ufrag=f}id=randomUUID$1().toString();refreshId(){this.id=randomUUID$1().toString()}static fromSdp(e){const t=e.split(` `);if(t.length<8)throw new Error(`SDP does not have enough properties`);const n={foundation:t[0],component:Number(t[1]),transport:t[2],priority:Number(t[3]),host:t[4],port:Number(t[5]),type:t[7]};for(let e=8,r=t.length-1;e<r;e+=2)if(t[e]===`raddr`)n[`related_address`]=t[e+1];else if(t[e]===`rport`)n[`related_port`]=Number(t[e+1]);else if(t[e]===`tcptype`)n[`tcptype`]=t[e+1];else if(t[e]===`generation`)n[`generation`]=Number(t[e+1]);else if(t[e]===`ufrag`)n[`ufrag`]=t[e+1];const{foundation:r,component:i,transport:a,priority:o,host:s,port:c,type:u}=n;return new _Candidate(r,i,a,o,s,c,u,n[`related_address`],n[`related_port`],n[`tcptype`],n[`generation`],n[`ufrag`])}canPairWith(e){const t=isIPv4$1(this.host);const n=isIPv4$1(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&canPairTcpCandidates(this,e)&&t===n}toSdp(){let e=`${this.foundation} ${this.component} ${this.transport} ${this.priority} ${this.host} ${this.port} typ ${this.type}`;if(this.relatedAddress)e+=` raddr ${this.relatedAddress}`;if(this.relatedPort!=void 0)e+=` rport ${this.relatedPort}`;if(this.tcptype)e+=` tcptype ${this.tcptype}`;if(this.generation!=void 0)e+=` generation ${this.generation}`;if(this.ufrag!=void 0)e+=` ufrag ${this.ufrag}`;return e}};var UDP_TYPE_PREFERENCE={host:126,prflx:110,srflx:100,relay:0};var TCP_TYPE_PREFERENCE={host:105,prflx:90,srflx:80,relay:0};var ACTIVE_PASSIVE_DIRECTION_PREFERENCE={active:6,passive:4,so:2};var REFLEXIVE_DIRECTION_PREFERENCE={active:4,passive:2,so:6};function normalizeTransport(e){return e?.toLowerCase()??`udp`}function normalizeTcpType(e){switch(e){case`active`:case`passive`:case`so`:return e;default:return}}function canPairTcpCandidates(e,t){if(normalizeTransport(e.transport)!==`tcp`)return true;const n=normalizeTcpType(e.tcptype);const r=normalizeTcpType(t.tcptype);if(!n||!r)return false;return n===`active`&&r===`passive`||n===`passive`&&r===`active`||n===`so`&&r===`so`}function candidateLocalPreference({candidateType:e,transport:t=`udp`,tcptype:n,otherPreference:r=8191}){if(normalizeTransport(t)!==`tcp`)return r;const i=normalizeTcpType(n)??`active`;return 8192*(e===`srflx`||e===`prflx`?REFLEXIVE_DIRECTION_PREFERENCE[i]:ACTIVE_PASSIVE_DIRECTION_PREFERENCE[i])+r}function candidateTypePreference(e,t=`udp`){return(normalizeTransport(t)===`tcp`?TCP_TYPE_PREFERENCE:UDP_TYPE_PREFERENCE)[e]??0}function candidateFoundation(e,t,n){const r=`${e}|${t}|${n}`;return createHash$1(`md5`).update(r,`ascii`).digest(`hex`).slice(7)}function candidatePriority(e,t=65535){const n=typeof t===`number`?`udp`:normalizeTransport(t.transport);const r=typeof t===`number`?t:t.localPreference??candidateLocalPreference({candidateType:e,transport:n,tcptype:t.tcptype,otherPreference:t.otherPreference});return(1<<24)*candidateTypePreference(e,n)+256*r+255}function remoteTcpTypeForIncoming(e){switch(e){case`passive`:return`active`;case`active`:return`passive`;default:return`so`}}var MdnsLookup=class{cache=/* @__PURE__ */ new Map;mdnsInstance=(0,import_multicast_dns.default)();constructor(){this.mdnsInstance.setMaxListeners(50)}lookup(e){return new Promise((t,n)=>{const cleanup=()=>{this.mdnsInstance.removeListener(`response`,l);clearTimeout(r)};const r=setTimeout(()=>{cleanup();n(/* @__PURE__ */ new Error(`No mDNS response`))},1e4);const l=n=>{const r=n.answers?.[0];if(r?.type!==`A`)return;if(r.name!==e)return;cleanup();t(r.data)};this.mdnsInstance.on(`response`,l);this.mdnsInstance.query(e,`A`)})}close(){this.mdnsInstance.destroy()}};var log22=debug(`werift-ice : packages/ice/src/ice.ts : log`);var CandidatePair=class{constructor(e,t,n){this.protocol=e;this.remoteCandidate=t;this.iceControlling=n}id=randomUUID$1().toString();handle;nominated=false;remoteNominated=false;_state=0;get state(){return this._state}packetsSent=0;packetsReceived=0;bytesSent=0;bytesReceived=0;rtt;totalRoundTripTime=0;roundTripTimeMeasurements=0;requestsReceived=0;requestsSent=0;responsesReceived=0;responsesSent=0;retransmissionsReceived=0;retransmissionsSent=0;consentRequestsSent=0;requestTransactionIds=/* @__PURE__ */ new Set;toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}updateState(e){this._state=e}get localCandidate(){if(!this.protocol.localCandidate)throw new Error(`localCandidate not exist`);return this.protocol.localCandidate}get remoteAddr(){return[this.remoteCandidate.host,this.remoteCandidate.port]}get component(){return this.localCandidate.component}get priority(){return candidatePairPriority(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}noteIncomingRequest(e){if(!this.requestTransactionIds.has(e)){this.requestTransactionIds.add(e);return false}this.retransmissionsReceived++;return true}};var ICE_COMPLETED=1;var ICE_FAILED=2;var CONSENT_INTERVAL=5;var CONSENT_FAILURES=6;var CONSENT_TIMEOUT=30;var CONSENT_RESPONSE_TIMEOUT=1e3;var CONSENT_RESPONSE_TIMEOUT_MIN=500;function consentResponseTimeoutMs(e){if(e===void 0||!Number.isFinite(e)||e<=0)return CONSENT_RESPONSE_TIMEOUT;return Math.max(500,Math.round(e*1e3*2+200))}var CandidatePairState=/* @__PURE__ */ (e=>{e[e[`FROZEN`]=0]=`FROZEN`;e[e[`WAITING`]=1]=`WAITING`;e[e[`IN_PROGRESS`]=2]=`IN_PROGRESS`;e[e[`SUCCEEDED`]=3]=`SUCCEEDED`;e[e[`FAILED`]=4]=`FAILED`;return e})(CandidatePairState||{});var defaultOptions={iceLite:false,useTcp:false,useIpv4:true,useIpv6:true};function validateRemoteCandidate(e){if(![`host`,`relay`,`srflx`].includes(e.type))throw new Error(`Unexpected candidate type "${e.type}"`);return e}function sortCandidatePairs(e,t){return e.sort((e,n)=>candidatePairPriority(e.localCandidate,e.remoteCandidate,t)-candidatePairPriority(n.localCandidate,n.remoteCandidate,t)).reverse()}function candidatePairPriority(e,t,n){const r=n&&e.priority||t.priority;const i=n&&t.priority||e.priority;return 1*Math.min(r,i)+2*Math.max(r,i)+(r>i?1:0)}async function serverReflexiveCandidate(e,t){const n=new Message(1,0);try{const[r]=await e.request(n,t);const i=e.localCandidate;if(!i)throw new Error(`not exist`);return new Candidate(candidateFoundation(`srflx`,i.transport,i.host),i.component,i.transport,candidatePriority(`srflx`,{transport:i.transport,tcptype:i.tcptype}),r.getAttributeValue(`XOR-MAPPED-ADDRESS`)[0],r.getAttributeValue(`XOR-MAPPED-ADDRESS`)[1],`srflx`,i.host,i.port,i.tcptype)}catch(e){log22(`error serverReflexiveCandidate`,e)}}function validateAddress(e){if(e&&Number.isNaN(e[1]))return[e[0],443];return e}function selectAddressesFromInterfaces(e,t,n={},r){const i=[`ipsec`,`tun`,`utun`,`tap`];const a=[`vmnet`,`veth`];const{useLinkLocalAddress:o}=n;const s=Object.keys(e).map(n=>{for(const e of[...i,...a])if(n.startsWith(e))return{nic:n,addresses:[]};return{nic:n,addresses:(e[n]??[]).filter(e=>normalizeFamilyNodeV18(e.family)===t&&!e.internal&&(o?true:!r(e))).map(e=>e.address)}}).filter(e=>!!e);s.sort((e,t)=>e.nic.localeCompare(t.nic));return Object.values(s).flatMap(e=>e.addresses)}var logger=debug(`werift-ice : packages/ice/src/utils.ts`);async function getGlobalIp(e,t){const n=new StunProtocol;await n.connectionMade(true,void 0,t);const r=new Message(1,0);const[i]=await n.request(r,e??[`stun.l.google.com`,19302]);await n.close();return i.getAttributeValue(`XOR-MAPPED-ADDRESS`)[0]}function isLinkLocalAddress(e){return normalizeFamilyNodeV18(e.family)===4&&e.address?.startsWith(`169.254.`)||normalizeFamilyNodeV18(e.family)===6&&e.address?.startsWith(`fe80::`)}function nodeIpAddress(e,{useLinkLocalAddress:t}={}){const n=os$1.networkInterfaces();logger(n);return selectAddressesFromInterfaces(n,e,{useLinkLocalAddress:t},isLinkLocalAddress)}function getHostAddresses(e,t,n={}){const r=[];if(e)r.push(...nodeIpAddress(4,n));if(t)r.push(...nodeIpAddress(6,n));return r}var url2Address=e=>{if(!e)return;const[t,n]=e.split(`:`);return[t,Number.parseInt(n)]};var log23=debug(`werift-ice : packages/ice/src/ice.ts : log`);var DEFAULT_STUN_SERVER=[`stun.l.google.com`,19302];var Connection=class{constructor(e,t){this._iceControlling=e;this.options={...defaultOptions,...t};if(this.iceLite)this._iceControlling=false;this.applyStunTurnServersFromOptions();this.restart();log23(`new Connection`,this.options)}localUsername=randomString(4);localPassword=randomString(22);remoteIsLite=false;remotePassword=``;remoteUsername=``;checkList=[];localCandidates=[];stunServer;turnServer;options;remoteCandidatesEnd=false;localCandidatesEnd=false;generation=-1;userHistory={};tieBreaker=randomBytes$1(8).readBigUInt64BE(0);state=`new`;lookup;_remoteCandidates=[];nominated;nominating=false;checkListDone=false;checkListState=new PQueue;earlyChecks=[];earlyChecksDone=false;localCandidatesStart=false;protocols=[];queryConsentHandle;consentFresh=false;consentSessionId=0;consentExpiryTimer;consentRequestAbort;onData=new Event2;stateChanged=new Event2;onIceCandidate=new Event2;setIceServers(e){this.options={...this.options,stunServer:e.stunServer,turnServer:e.turnServer,turnUsername:e.turnUsername,turnPassword:e.turnPassword,turnTransport:e.turnTransport};if(e.forceTurn!==void 0)this.options.forceTurn=e.forceTurn;if(e.useTcp!==void 0)this.options.useTcp=e.useTcp;if(e.turnTlsOptions!==void 0)this.options.turnTlsOptions=e.turnTlsOptions;if(e.turnUdpFamily!==void 0)this.options.turnUdpFamily=e.turnUdpFamily;this.applyStunTurnServersFromOptions();log23(`Connection ice servers updated`,this.options)}applyStunTurnServersFromOptions(){this.stunServer=validateAddress(this.options.stunServer)??DEFAULT_STUN_SERVER;this.turnServer=validateAddress(this.options.turnServer)}get iceControlling(){return this._iceControlling}set iceControlling(e){if(this.iceLite)e=false;if(this.nominated)return;this.applyIceControlling(e)}get iceLite(){return this.options.iceLite}async restart(){this.generation++;this.localUsername=randomString(4);this.localPassword=randomString(22);if(this.options.localPasswordPrefix)this.localPassword=this.options.localPasswordPrefix+this.localPassword.slice(this.options.localPasswordPrefix.length);this.userHistory[this.localUsername]=this.localPassword;this.remoteUsername=``;this.remotePassword=``;this.localCandidates=[];this._remoteCandidates=[];this.remoteCandidatesEnd=false;this.localCandidatesEnd=false;this.state=`new`;this.lookup?.close?.();this.lookup=void 0;this.nominated=void 0;this.nominating=false;this.checkList=[];this.checkListDone=false;this.checkListState=new PQueue;this.earlyChecks=[];this.earlyChecksDone=false;this.localCandidatesStart=false;for(const e of this.protocols)if(e.localCandidate){e.localCandidate.refreshId();e.localCandidate.generation=this.generation;e.localCandidate.ufrag=this.localUsername}this.stopConsentLifecycle()}resetNominatedPair(){log23(`resetNominatedPair`);this.nominated=void 0;this.nominating=false;this.stopConsentLifecycle()}setRemoteParams({iceLite:e,usernameFragment:t,password:n}){log23(`setRemoteParams`,{iceLite:e,usernameFragment:t,password:n});this.remoteIsLite=e;this.remoteUsername=t;this.remotePassword=n}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=true;for(const e of this.protocols)if(e.localCandidate){e.localCandidate.generation=this.generation;e.localCandidate.ufrag=this.localUsername;this.appendLocalCandidate(e.localCandidate)}let e=getHostAddresses(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress});const{interfaceAddresses:t}=this.options;if(t){const n=e.filter(e=>Object.values(t).includes(e));if(n.length)e=n}if(this.options.additionalHostAddresses)e=Array.from(/* @__PURE__ */ new Set([...this.options.additionalHostAddresses,...e]));const n=this.getCandidatePromises(e,this.options.stunGatherTimeout);await Promise.allSettled(n);this.localCandidatesEnd=true}this.setState(`completed`)}appendLocalCandidate(e){this.localCandidates.push(e);this.onIceCandidate.execute(e)}ensureProtocol(e){e.onRequestReceived.subscribe((t,n,r)=>{if(t.messageMethod!==1){this.respondError(t,n,e,[400,`Bad Request`]);return}const{remoteUsername:i}=decodeTxUsername(t.getAttributeValue(`USERNAME`));const a=this.userHistory[i]??this.localPassword;const{iceControlling:o}=this;if(o&&t.attributesKeys.includes(`ICE-CONTROLLING`)){if(this.tieBreaker>=t.getAttributeValue(`ICE-CONTROLLING`)){this.respondError(t,n,e,[487,`Role Conflict`]);return}else this.switchRole(false)}else if(!o&&t.attributesKeys.includes(`ICE-CONTROLLED`)){if(this.iceLite||this.tieBreaker<t.getAttributeValue(`ICE-CONTROLLED`)){this.respondError(t,n,e,[487,`Role Conflict`]);return}else{this.switchRole(true);return}}if(this.options.filterStunResponse&&!this.options.filterStunResponse(t,n,e))return;const s=new Message(1,256,t.transactionId);s.setAttribute(`XOR-MAPPED-ADDRESS`,n).addMessageIntegrity(Buffer.from(a,`utf8`)).addFingerprint();e.sendStun(s,n).catch(e=>{log23(`sendStun error`,e)});if(this.checkList.length===0&&!this.earlyChecksDone)this.earlyChecks.push([t,n,e]);else this.checkIncoming(t,n,e)});e.onDataReceived.subscribe(t=>{try{const n=this.nominated;if(n&&n.protocol===e){n.packetsReceived++;n.bytesReceived+=t.length}this.onData.execute(t)}catch(e){log23(`dataReceived`,e)}});e.onConnectionClosed?.subscribe(t=>{this.handleConnectionClosed(e,t)})}handleConnectionClosed(e,t){const n=this.nominated;if(!n||n.protocol!==e||n.remoteAddr[0]!==t[0]||n.remoteAddr[1]!==t[1])return;if(this.state===`closed`||this.state===`failed`)return;log23(`selected tcp connection closed`,n.toJSON());this.stopConsentLifecycle();this.setState(`failed`)}getCandidatePromises(e,t=5){const n=[];const{stunServer:r,turnServer:i}=this;const{turnUsername:a,turnPassword:o}=this.options;const s=this.iceLite;const c=!s&&this.options.forceTurn&&i&&a&&o;e=e.filter(e=>{if(this.protocols.find(t=>t.localIp===e))return false;return true});const u=c?[]:e.map(async e=>{const t=new StunProtocol;this.ensureProtocol(t);try{await t.connectionMade(isIPv4$1(e),this.options.portRange,this.options.interfaceAddresses);t.localIp=e;this.protocols.push(t);log23(`protocol`,t.localIp);const n=[e,t.getExtraInfo()[1]];t.localCandidate=new Candidate(candidateFoundation(`host`,`udp`,n[0]),1,`udp`,candidatePriority(`host`,{transport:`udp`}),n[0],n[1],`host`,void 0,void 0,void 0,this.generation,this.localUsername);this.pairLocalProtocol(t);this.appendLocalCandidate(t.localCandidate);return t}catch(e){log23(`error protocol STUN`,e)}});if(!c)n.push(...u.map(e=>e.then(e=>e?.localCandidate)));if(!c&&this.options.useTcp){const t=e.map(async e=>{if(this.options.tcpPassive!==false){const t=new TcpPassiveProtocol;this.ensureProtocol(t);await t.connectionMade(e,this.options.portRange);t.localIp=e;t.localCandidate=new Candidate(candidateFoundation(`host`,`tcp`,e),1,`tcp`,candidatePriority(`host`,{transport:`tcp`,tcptype:`passive`}),e,t.listeningPort,`host`,void 0,void 0,`passive`,this.generation,this.localUsername);this.protocols.push(t);this.appendLocalCandidate(t.localCandidate)}if(!s){const t=new TcpActiveProtocol;this.ensureProtocol(t);await t.connectionMade(e);t.localIp=e;t.localCandidate=new Candidate(candidateFoundation(`host`,`tcp`,e),1,`tcp`,candidatePriority(`host`,{transport:`tcp`,tcptype:`active`}),e,9,`host`,void 0,void 0,`active`,this.generation,this.localUsername);this.protocols.push(t);this.pairLocalProtocol(t);this.appendLocalCandidate(t.localCandidate)}});n.push(...t)}if(!s&&!c&&r){const e=u.map(async e=>{const n=await e;if(!n)return;return new Promise(async(e,i)=>{const a=setTimeout(i,t*1e3);if(n.localCandidate?.host&&isIPv4$1(n.localCandidate?.host)){const t=await serverReflexiveCandidate(n,r).catch(e=>{log23(`error`,e)});if(t)this.appendLocalCandidate(t);clearTimeout(a);e(t)}else{clearTimeout(a);e()}}).catch(e=>{log23(`query STUN server`,e)})});n.push(...e)}if(!s&&i&&a&&o){const e=(async()=>{const e=this.options.turnTransport??`udp`;const t=await createStunOverTurnClient({address:i,username:a,password:o},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:e,tlsOptions:this.options.turnTlsOptions,connectTimeoutMs:(this.options.turnConnectTimeout??8)*1e3,udpFamily:this.options.turnUdpFamily}).catch(async t=>{if(e===`udp`)return await createStunOverTurnClient({address:i,username:a,password:o},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:`tcp`,connectTimeoutMs:(this.options.turnConnectTimeout??8)*1e3});else throw t});this.ensureProtocol(t);this.protocols.push(t);const n=t.turn.relayedAddress;const r=t.turn.mappedAddress;log23(`turn candidateAddress`,n);t.localCandidate=new Candidate(candidateFoundation(`relay`,`udp`,n[0]),1,`udp`,candidatePriority(`relay`),n[0],n[1],`relay`,r[0],r[1],void 0,this.generation,this.localUsername);this.appendLocalCandidate(t.localCandidate);return t.localCandidate})().catch(e=>{log23(`query TURN server`,e)});n.push(e)}return n}async connect(){log23(`start connect ice`);if(!this.localCandidatesEnd){if(!this.localCandidatesStart)throw new Error(`Local candidates gathering was not performed`)}if(!this.remoteUsername||!this.remotePassword)throw new Error(`Remote username or password is missing`);for(const e of this.remoteCandidates)this.pairRemoteCandidate(e);this.sortCheckList();if(!this.iceLite)this.unfreezeInitial();log23(`earlyChecks`,this.localPassword,this.earlyChecks.length);for(const e of this.earlyChecks)this.checkIncoming(...e);this.earlyChecks=[];this.earlyChecksDone=true;if(this.iceLite){if(!this.nominated){let e=2;while(!this.checkListDone&&this.state!==`closed`){e=await this.checkListState.get();log23(`checkListState`,e);if(e===1)break}if(e!==1&&!this.nominated)throw new Error(`ICE negotiation failed`)}this.setState(`connected`);return}for(;;){if(this.state===`closed`)break;if(!this.schedulingChecks())break;await timers.setTimeout(20)}let e=2;while(this.checkList.length>0&&e===2){e=await this.checkListState.get();log23(`checkListState`,e)}for(const e of this.checkList)e.handle?.resolve?.();if(e!==1)throw new Error(`ICE negotiation failed`);this.queryConsent();this.setState(`connected`)}unfreezeInitial(){const[e]=this.checkList;if(!e)return;if(e.state===0)e.updateState(1);const t=new Set(e.localCandidate.foundation);for(const n of this.checkList)if(n.component===e.component&&!t.has(n.localCandidate.foundation)&&n.state===0){n.updateState(1);t.add(n.localCandidate.foundation)}}schedulingChecks(){{const e=this.checkList.filter(e=>{if(this.options.forceTurn&&e.protocol.type===StunProtocol.type)return false;return true}).find(e=>e.state===1);if(e){e.handle=this.checkStart(e);return true}}{const e=this.checkList.find(e=>e.state===0);if(e){e.handle=this.checkStart(e);return true}}if(!this.remoteCandidatesEnd)return!this.checkListDone;return false}stopConsentLifecycle(){this.consentSessionId++;this.consentFresh=false;if(this.consentExpiryTimer!==void 0){clearTimeout(this.consentExpiryTimer);this.consentExpiryTimer=void 0}this.consentRequestAbort?.abort();this.consentRequestAbort=void 0;const e=this.queryConsentHandle;this.queryConsentHandle=void 0;e?.resolve?.()}shouldNominateConsentRequest(e){return this.iceControlling&&this.remoteIsLite&&this.nominated?.id===e.id}canSendApplicationData(){if(!this.nominated)return false;if(this.state===`closed`||this.state===`failed`)return false;if(this.iceLite)return true;return this.consentFresh}abortableDelay(e,t){return new Promise((n,r)=>{if(t.aborted){r(new DOMException(`The operation was aborted`,`AbortError`));return}const i=setTimeout(()=>{t.removeEventListener(`abort`,onAbort);n()},e);const onAbort=()=>{clearTimeout(i);r(new DOMException(`The operation was aborted`,`AbortError`))};t.addEventListener(`abort`,onAbort,{once:true})})}queryConsent=()=>{if(this.iceLite)return;this.stopConsentLifecycle();const e=this.consentSessionId;this.consentFresh=true;const t=cancelable(async(n,r,i)=>{let a=false;const o=new AbortController;const clearConsentExpiry=()=>{if(this.consentExpiryTimer===void 0)return;clearTimeout(this.consentExpiryTimer);this.consentExpiryTimer=void 0};const refreshConsentExpiry=()=>{if(a||e!==this.consentSessionId)return;clearConsentExpiry();this.consentExpiryTimer=setTimeout(()=>{this.consentExpiryTimer=void 0;if(a||e!==this.consentSessionId)return;if(this.state===`closed`||this.state===`failed`)return;log23(`Consent to send expired`);this.consentFresh=false;this.consentSessionId++;this.consentRequestAbort?.abort();this.consentRequestAbort=void 0;if(this.queryConsentHandle===t)this.queryConsentHandle=void 0;a=true;o.abort();this.setState(`failed`)},30*1e3)};i.once(()=>{a=true;if(e===this.consentSessionId){clearConsentExpiry();this.consentRequestAbort?.abort();this.consentRequestAbort=void 0}o.abort();if(this.queryConsentHandle===t)this.queryConsentHandle=void 0});refreshConsentExpiry();const randomizedConsentInterval=()=>5*(.8+.4*Math.random())*1e3;let s=Date.now()+randomizedConsentInterval();const isTerminalState=()=>this.state===`closed`||this.state===`failed`;try{while(!isTerminalState()&&!a&&e===this.consentSessionId){await this.abortableDelay(Math.max(0,s-Date.now()),o.signal);if(a||isTerminalState()||e!==this.consentSessionId)break;s=Date.now()+randomizedConsentInterval();const t=this.nominated;if(!t)break;const n=t.id;const r=this.generation;const i=this.remotePassword;const{localUsername:c,remoteUsername:u,iceControlling:d}=this;const f=this.buildRequest({nominate:this.shouldNominateConsentRequest(t),localUsername:c,remoteUsername:u,iceControlling:d,localCandidate:t.localCandidate});this.consentRequestAbort?.abort();const p=new AbortController;this.consentRequestAbort=p;t.consentRequestsSent++;t.requestsSent++;const m=consentResponseTimeoutMs(t.rtt);const g=performance.now();t.protocol.request(f,t.remoteAddr,Buffer.from(i,`utf8`),{retransmissions:0,responseTimeout:m,signal:p.signal,onRequestSent:e=>{if(e>0)t.retransmissionsSent++}}).then(()=>{if(e!==this.consentSessionId||a)return;const o=this.state;if(o===`closed`||o===`failed`)return;if(this.nominated?.id!==n)return;if(this.generation!==r)return;if(this.remotePassword!==i)return;const s=(performance.now()-g)/1e3;t.rtt=s;t.totalRoundTripTime+=s;t.roundTripTimeMeasurements++;t.responsesReceived++;this.consentFresh=true;refreshConsentExpiry();if(o===`disconnected`)this.setState(`connected`)}).catch(t=>{if(e===this.consentSessionId&&this.nominated?.id===n)log23(`no stun response`,t)})}}catch(e){}finally{if(e===this.consentSessionId)clearConsentExpiry()}});this.queryConsentHandle=t};async close(){this.setState(`closed`);this.stopConsentLifecycle();if(this.checkList&&!this.checkListDone)this.checkListState.put(new Promise(e=>{e(2)}));this.nominated=void 0;for(const e of this.protocols)if(e.close)await e.close();this.protocols=[];this.localCandidates=[];this.lookup?.close?.();this.lookup=void 0}setState(e){this.state=e;this.stateChanged.execute(e)}async addRemoteCandidate(e){if(!e){this.remoteCandidatesEnd=true;return}if(e.host.includes(`.local`))try{if(!this.lookup)this.lookup=new MdnsLookup;e.host=await this.lookup.lookup(e.host)}catch(e){return}try{validateRemoteCandidate(e)}catch(e){return}log23(`addRemoteCandidate`,e);this._remoteCandidates.push(e);this.pairRemoteCandidate(e);this.sortCheckList()}send=async e=>{if(!this.canSendApplicationData())return;const t=this.nominated;await t.protocol.sendData(e,t.remoteAddr);t.packetsSent++;t.bytesSent+=e.length};getDefaultCandidate(){const[e]=this.localCandidates.sort((e,t)=>e.priority-t.priority);return e}set remoteCandidates(e){if(this.remoteCandidatesEnd)throw new Error(`Cannot set remote candidates after end-of-candidates.`);this._remoteCandidates=[];for(const t of e){try{validateRemoteCandidate(t)}catch(e){continue}this._remoteCandidates.push(t)}this.remoteCandidatesEnd=true}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){sortCandidatePairs(this.checkList,this.iceControlling)}findPair(e,t){return this.checkList.find(n=>n.protocol===e&&n.remoteCandidate===t)}applyIceControlling(e){this._iceControlling=e;for(const t of this.checkList)t.iceControlling=e}switchRole(e){log23(`switch role`,e);if(this.iceLite)e=false;this.applyIceControlling(e);this.sortCheckList()}checkComplete(e){e.handle=void 0;if(e.state===3){if(e.nominated&&(e.remoteCandidate.generation!=void 0?e.remoteCandidate.generation===this.generation:true)&&this.nominated==void 0){log23(`nominated`,e.toJSON());this.nominated=e;this.nominating=false;this.pruneTcpConnections(e);if(!this.iceLite&&(this.state===`connected`||this.state===`completed`))this.queryConsent();for(const t of this.checkList)if(t.component===e.component&&[1,0].includes(t.state))t.updateState(4)}if(this.nominated){if(!this.checkListDone){log23(`ICE completed`);this.checkListState.put(new Promise(e=>e(1)));this.checkListDone=true}return}log23(`not completed`,e.toJSON());for(const t of this.checkList)if(t.localCandidate.foundation===e.localCandidate.foundation&&t.state===0)t.updateState(1)}this.nominateTcpPairIfReady();if(this.nominating)return;{const e=[3,4];if(this.checkList.find(({state:t})=>!e.includes(t)))return}if(!this.iceControlling){const e=3;if(this.checkList.find(({state:t})=>t===e))return}if(!this.checkListDone){log23(`ICE failed`);this.checkListState.put(new Promise(e=>{e(2)}))}}checkStart=e=>cancelable(async t=>{log23(`check start`,e.toJSON());e.updateState(2);const n={};const{remotePassword:r,remoteUsername:i,generation:a}=this;const o=e.localCandidate.ufrag??this.localUsername;const s=this.iceControlling&&!this.remoteIsLite&&!this.isTcpPair(e);const c=this.buildRequest({nominate:s,localUsername:o,remoteUsername:i,iceControlling:this.iceControlling,localCandidate:e.localCandidate});const u=performance.now();try{e.requestsSent++;const[t,s]=await e.protocol.request(c,e.remoteAddr,Buffer.from(r,`utf8`),this.checkRequestOptions(e));e.responsesReceived++;const d=(performance.now()-u)/1e3;e.rtt=d;e.totalRoundTripTime+=d;e.roundTripTimeMeasurements++;log23(`response received`,c.toJSON(),t.toJSON(),s,{localUsername:o,remoteUsername:i,remotePassword:r,generation:a,rtt:d});n.response=t;n.addr=s}catch(n){const s=n;log23(`failure case`,c.toJSON(),s.response?JSON.stringify(s.response.toJSON(),null,2):n,{localUsername:o,remoteUsername:i,remotePassword:r,generation:a},e.remoteAddr);if(s.response?.getAttributeValue(`ERROR-CODE`)[0]===487){if(c.attributesKeys.includes(`ICE-CONTROLLED`))this.switchRole(true);else if(c.attributesKeys.includes(`ICE-CONTROLLING`))this.switchRole(false);await this.checkStart(e).awaitable;t();return}if(s.response?.getAttributeValue(`ERROR-CODE`)[0]===401){log23(`retry 401`,e.toJSON());await this.checkStart(e).awaitable;t();return}else{log23(`checkStart CandidatePairState.FAILED`,e.toJSON());e.updateState(4);this.checkComplete(e);t();return}}if(n.addr[0]!==e.remoteAddr[0]||n.addr[1]!==e.remoteAddr[1]){e.updateState(4);this.checkComplete(e);t();return}if(s||e.remoteNominated)e.nominated=true;else if(this.usesTcpRegularNomination(e)){}else if(this.iceControlling&&!this.nominating){this.nominating=true;const t=this.buildRequest({nominate:true,localUsername:o,remoteUsername:i,iceControlling:this.iceControlling,localCandidate:e.localCandidate});try{e.requestsSent++;await e.protocol.request(t,e.remoteAddr,Buffer.from(this.remotePassword,`utf8`),this.checkRequestOptions(e));e.responsesReceived++}catch(t){this.nominating=false;e.updateState(4);this.checkComplete(e);return}e.nominated=true}e.updateState(3);this.checkComplete(e);t()});isTcpPair(e){return e.localCandidate.transport.toLowerCase()===`tcp`}usesTcpRegularNomination(e){return this.iceControlling&&!this.remoteIsLite&&this.isTcpPair(e)}checkRequestOptions(e){const onRequestSent=t=>{if(t>0)e.retransmissionsSent++};if(this.isTcpPair(e))return{retransmissions:0,responseTimeout:TCP_CHECK_RESPONSE_TIMEOUT_MS,onRequestSent};return{retransmissions:4,onRequestSent}}nominateTcpPairIfReady(){if(!this.iceControlling||this.remoteIsLite||this.nominated||this.nominating)return;for(const e of this.checkList){if(!this.isTcpPair(e))continue;if(e.state===3){this.nominateTcpPair(e);return}if(e.state!==4)return}}nominateTcpPair(e){this.nominating=true;const{generation:t}=this;const n=this.buildRequest({nominate:true,localUsername:e.localCandidate.ufrag??this.localUsername,remoteUsername:this.remoteUsername,iceControlling:this.iceControlling,localCandidate:e.localCandidate});e.requestsSent++;e.protocol.request(n,e.remoteAddr,Buffer.from(this.remotePassword,`utf8`),this.checkRequestOptions(e)).then(()=>{if(this.isStaleNomination(e,t))return;e.responsesReceived++;e.nominated=true;this.nominating=false;this.checkComplete(e)},n=>{if(this.isStaleNomination(e,t))return;log23(`tcp nomination failed`,e.toJSON(),n);this.nominating=false;e.updateState(4);this.checkComplete(e)})}isStaleNomination(e,t){return this.state===`closed`||this.generation!==t||!this.checkList.includes(e)}addPair(e){this.checkList.push(e);this.sortCheckList()}checkIncoming(e,t,n){const{remoteUsername:r}=decodeTxUsername(e.getAttributeValue(`USERNAME`));let i;const[a,o]=t;for(const e of this.remoteCandidates)if(e.host===a&&e.port===o){i=e;break}if(!i){i=new Candidate(randomString(10),1,n.localCandidate?.transport??`udp`,e.getAttributeValue(`PRIORITY`),a,o,`prflx`,void 0,void 0,n.localCandidate?.transport===`tcp`?remoteTcpTypeForIncoming(n.localCandidate.tcptype):void 0,void 0,void 0);this._remoteCandidates.push(i)}let s=this.findPair(n,i);if(!s){s=new CandidatePair(n,i,this.iceControlling);s.updateState(1);this.addPair(s)}s.noteIncomingRequest(e.transactionIdHex);s.requestsReceived++;s.responsesSent++;s.localCandidate.ufrag=r;log23(`Triggered Checks`,e.toJSON(),s.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation});if(this.iceLite){if(e.attributesKeys.includes(`USE-CANDIDATE`)&&!this.iceControlling){s.remoteNominated=true;s.nominated=true;s.updateState(3);this.checkComplete(s)}return}if([1,4].includes(s.state))s.handle=this.checkStart(s);if(e.attributesKeys.includes(`USE-CANDIDATE`)&&!this.iceControlling){s.remoteNominated=true;if(s.state===3){s.nominated=true;this.checkComplete(s)}}}tryPair(e,t){if(e.localCandidate?.canPairWith(t)&&!(e.localCandidate.transport.toLowerCase()===`tcp`&&e.localCandidate.tcptype===`passive`&&t.type!==`prflx`)&&!this.findPair(e,t)){const n=new CandidatePair(e,t,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(n))return;n.updateState(1);this.addPair(n)}}pairLocalProtocol(e){for(const t of this.remoteCandidates)this.tryPair(e,t)}pairRemoteCandidate=e=>{for(const t of this.protocols)this.tryPair(t,e)};buildRequest({nominate:e,remoteUsername:t,localUsername:n,iceControlling:r,localCandidate:i}){const a=encodeTxUsername({remoteUsername:t,localUsername:n});const o=new Message(1,0);o.setAttribute(`USERNAME`,a).setAttribute(`PRIORITY`,candidatePriority(`prflx`,{transport:i?.transport,tcptype:i?.tcptype}));if(r){o.setAttribute(`ICE-CONTROLLING`,this.tieBreaker);if(e)o.setAttribute(`USE-CANDIDATE`,null)}else o.setAttribute(`ICE-CONTROLLED`,this.tieBreaker);return o}pruneTcpConnections(e){for(const t of this.protocols){if(t.localCandidate?.transport.toLowerCase()!==`tcp`)continue;if(`pruneForSelection`in t&&typeof t.pruneForSelection===`function`)t.pruneForSelection(t===e.protocol?e.remoteAddr:void 0)}}respondError(e,t,n,r){const i=new Message(e.messageMethod,272,e.transactionId);i.setAttribute(`ERROR-CODE`,r).addMessageIntegrity(Buffer.from(this.localPassword,`utf8`)).addFingerprint();n.sendStun(i,t).catch(e=>{log23(`sendStun error`,e)})}};var encodeTxUsername=({remoteUsername:e,localUsername:t})=>{return`${e}:${t}`};var decodeTxUsername=e=>{const[t,n]=e.split(`:`);return{remoteUsername:t,localUsername:n}};function enumerate2(e){return e.map((e,t)=>[t,e])}function divide(e,t){const n=e.split(t);return[n[0],n.slice(1).join(t)]}var EventTarget=class extends EventEmitter{emit(e,...t){if(typeof e!==`string`)return super.emit(e,...t);if(t.length===0)return super.emit(e,new Event(e));const[n,...r]=t;if(n&&typeof n===`object`&&!(`type`in n))try{Object.defineProperty(n,"type",{configurable:true,enumerable:true,value:e})}catch{return super.emit(e,{type:e,...n},...r)}return super.emit(e,n,...r)}addEventListener=(e,t,n)=>{if(typeof n===`object`&&n?.once){this.once(e,t);return}this.addListener(e,t)};removeEventListener=(e,t)=>{this.removeListener(e,t)};dispatchEvent=e=>this.emit(e.type,e)};var log24=debug(`werift:packages/webrtc/src/dataChannel.ts`);function getDataChannelMessageSize(e){return Buffer.isBuffer(e)?e.length:Buffer.byteLength(e)}var RTCDataChannel=class extends EventTarget{constructor(e,t,n=true){super();this.sctp=e;this.parameters=t;this.sendOpen=n;this.id=this.parameters.id;if(t.negotiated){if(this.id==void 0||this.id<0||this.id>65534)throw new Error(`ID must be in range 0-65534 if data channel is negotiated out-of-band`);this.sctp.dataChannelAddNegotiated(this)}else if(n){this.sendOpen=false;this.sctp.dataChannelOpen(this)}}statsId=randomUUID$1().toString();stateChange=new Event2;stateChanged=new Event2;onMessage=new Event2;error=new Event2;bufferedAmountLow=new Event2;onopen;onclose;onclosing;onmessage;onerror;isCreatedByRemote=false;id;readyState=`connecting`;bufferedAmount=0;_bufferedAmountLowThreshold=0;messagesSent=0;bytesSent=0;messagesReceived=0;bytesReceived=0;get ordered(){return this.parameters.ordered}get maxRetransmits(){return this.parameters.maxRetransmits??null}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime??null}get label(){return this.parameters.label}get protocol(){return this.parameters.protocol}get negotiated(){return this.parameters.negotiated}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){if(e<0||e>4294967295)throw new Error(`bufferedAmountLowThreshold must be in range 0 - 4294967295`);this._bufferedAmountLowThreshold=e}setId(e){this.id=e}setReadyState(e){if(e!==this.readyState){this.readyState=e;this.stateChange.execute(e);this.stateChanged.execute(e);switch(e){case`open`:if(this.onopen)this.onopen();this.emit(`open`);break;case`closed`:if(this.onclose)this.onclose();this.emit(`close`);break;case`closing`:if(this.onclosing)this.onclosing()}log24(`change state`,e)}}addBufferedAmount(e){const t=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+e<=this.bufferedAmountLowThreshold;this.bufferedAmount+=e;if(t){this.bufferedAmountLow.execute();this.emit(`bufferedamountlow`)}}send(e){const t=this.sctp.datachannelSend(this,e);this.messagesSent++;this.bytesSent+=t}close(){this.sctp.dataChannelClose(this)}};var RTCDataChannelParameters=class{label=``;maxPacketLifeTime;maxRetransmits;ordered=true;protocol=``;negotiated=false;id;constructor(e={}){Object.assign(this,e)}};var useFIR=()=>({type:`ccm`,parameter:`fir`});var useNACK=()=>({type:`nack`});var usePLI=()=>({type:`nack`,parameter:`pli`});var useREMB=()=>({type:`goog-remb`});var useTWCC=()=>({type:`transport-cc`});var RTCRtpCodecParameters=class{payloadType;mimeType;clockRate;channels;rtcpFeedback=[];parameters;direction=`all`;constructor(e){Object.assign(this,e)}get name(){return this.mimeType.split(`/`)[1]}get contentType(){return this.mimeType.split(`/`)[0]}get str(){let e=`${this.name}/${this.clockRate}`;if(this.channels===2)e+=`/2`;return e}};var RTCRtpHeaderExtensionParameters=class{id;uri;constructor(e){Object.assign(this,e)}};var RTCRtcpParameters=class{cname;mux=false;ssrc;constructor(e={}){Object.assign(this,e)}};var RTCRtcpFeedback=class{type;parameter;constructor(e={}){Object.assign(this,e)}};var RTCRtpRtxParameters=class{ssrc;constructor(e={}){Object.assign(this,e)}};var RTCRtpCodingParameters=class{ssrc;payloadType;rtx;constructor(e){Object.assign(this,e)}};var RTCRtpSimulcastParameters=class{rid;direction;constructor(e){Object.assign(this,e)}};var useH264=(e={})=>new RTCRtpCodecParameters({mimeType:`video/H264`,clockRate:9e4,rtcpFeedback:[useNACK(),usePLI(),useREMB()],parameters:`profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1`,...e});var useVP8=(e={})=>new RTCRtpCodecParameters({mimeType:`video/VP8`,clockRate:9e4,rtcpFeedback:[useNACK(),usePLI(),useREMB()],...e});var useVP9=(e={})=>new RTCRtpCodecParameters({mimeType:`video/VP9`,clockRate:9e4,rtcpFeedback:[useNACK(),usePLI(),useREMB()],...e});var useAV1=(e={})=>new RTCRtpCodecParameters({mimeType:`video/AV1`,clockRate:9e4,rtcpFeedback:[useNACK(),usePLI(),useREMB()],...e});var useAV1X=(e={})=>new RTCRtpCodecParameters({mimeType:`video/AV1X`,clockRate:9e4,rtcpFeedback:[useNACK(),usePLI(),useREMB()],...e});var useOPUS=(e={})=>new RTCRtpCodecParameters({mimeType:`audio/OPUS`,clockRate:48e3,channels:2,...e});var usePCMU=(e={})=>new RTCRtpCodecParameters({mimeType:`audio/PCMU`,clockRate:8e3,channels:1,payloadType:0,...e});var usePCMA=(e={})=>new RTCRtpCodecParameters({mimeType:`audio/PCMA`,clockRate:8e3,channels:1,payloadType:8,...e});var useG722=(e={})=>new RTCRtpCodecParameters({mimeType:`audio/G722`,clockRate:8e3,channels:1,payloadType:9,...e});function defaultCodecs(){return{audio:[useOPUS(),usePCMU()],video:[useVP8()]}}function cloneCodecParameters(e){return new RTCRtpCodecParameters({mimeType:e.mimeType,clockRate:e.clockRate,...e.channels!=void 0?{channels:e.channels}:{},...e.payloadType!=void 0?{payloadType:e.payloadType}:{},rtcpFeedback:e.rtcpFeedback.map(e=>({...e})),...e.parameters!=void 0?{parameters:e.parameters}:{},direction:e.direction})}var supportedCodecs=[useAV1(),useAV1X(),useVP9(),useVP8(),useH264(),useOPUS(),usePCMU()].map(e=>e.mimeType);var supportedVideoCodecs=supportedCodecs.filter(e=>e.toLowerCase().startsWith(`video/`));var supportedAudioCodecs=supportedCodecs.filter(e=>e.toLowerCase().startsWith(`audio/`));function createWebRtcDomException(e,t=e){return new DOMException(t,e)}function createWebRtcTypeError(e){return new TypeError(e)}var DATA_CHANNEL_ACK=2;var DATA_CHANNEL_OPEN=3;var DATA_CHANNEL_RELIABLE=0;var WEBRTC_DCEP=50;var WEBRTC_STRING=51;var WEBRTC_BINARY=53;var WEBRTC_STRING_EMPTY=56;var WEBRTC_BINARY_EMPTY=57;var DISCARD_HOST=`0.0.0.0`;var DISCARD_PORT=9;var DTLS_ROLE_SETUP={auto:`actpass`,client:`active`,server:`passive`};var DTLS_SETUP_ROLE=Object.keys(DTLS_ROLE_SETUP).reduce((e,t)=>{const n=DTLS_ROLE_SETUP[t];e[n]=t;return e},{});var FMTP_INT_PARAMETERS=[`apt`,`max-fr`,`max-fs`,`maxplaybackrate`,`minptime`,`packetization-mode`,`level-asymmetry-allowed`,`stereo`,`useinbandfec`];var SSRC_INFO_ATTRS=[`cname`,`msid`,`mslabel`,`label`];var SRTP_PROFILE={SRTP_AES128_CM_HMAC_SHA1_80:1,SRTP_AEAD_AES_128_GCM:7};var SenderDirections=[`sendonly`,`sendrecv`];var ReceiverDirection=[`sendrecv`,`recvonly`];var RTCStatsReport=class extends Map{constructor(e){super();if(e)for(const t of e)this.set(t.id,t)}};function generateStatsId(e,...t){return`${e}_${t.filter(e=>e!==void 0).join(`_`)}`}function generateCodecStatsId(e,t,n){return generateStatsId(`codec`,e,t,n)}function getStatsTimestamp(){return performance.timeOrigin+performance.now()}function getReferencedStatsIds(e){const t=[];for(const[n,r]of Object.entries(e)){if(n===`id`)continue;if(n.endsWith(`Id`)){if(typeof r===`string`)t.push(r);continue}if(n.endsWith(`Ids`)&&Array.isArray(r)){for(const e of r)if(typeof e===`string`)t.push(e)}}return t}function buildStatsReport(e,t){const n=/* @__PURE__ */ new Map;for(const t of e)n.set(t.id,t);if(!t)return new RTCStatsReport([...n.values()]);const r=/* @__PURE__ */ new Set;const i=[...new Set(Array.from(t))];while(i.length>0){const e=i.shift();if(!e||r.has(e))continue;const t=n.get(e);if(!t)continue;r.add(e);i.push(...getReferencedStatsIds(t))}return new RTCStatsReport([...r].map(e=>n.get(e)).filter(e=>!!e))}var RTCRtpTransceiver=class{constructor(e,t,n,r,i){this.kind=e;this.receiver=n;this.sender=r;this._direction=i;if(t)this.setDtlsTransport(t)}id=randomUUID$1().toString();onTrack=new Event2;mid=null;mLineIndex;usedForSender=false;_currentDirection;offerDirection;_codecs=[];set codecs(e){this._codecs=e}get codecs(){return this._codecs}headerExtensions=[];_codecPreferences;onCodecPreferencesChanged=new Event2;pendingLocalOfferCodecs;codecPreferencesNeedResolution=false;get codecPreferences(){return this._codecPreferences}setCodecPreferences(e){if(!Array.isArray(e))throw createWebRtcTypeError(`codecs must be an array`);const t=e.length===0?void 0:e.map(cloneCodecParameters);if(sameCodecPreferences(this._codecPreferences,t))return;this._codecPreferences=t;this.codecPreferencesNeedResolution=true;this._codecs=[];this.onCodecPreferencesChanged.execute()}options={};stopping=false;stopped=false;rejected=false;pendingRejection=false;firedReceiving=false;onStopRequested=new Event2;onRelease=new Event2;get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}set direction(e){this.setDirection(e)}setDirection(e){this._direction=e;if(this._currentDirection&&this._currentDirection!==`stopped`&&SenderDirections.includes(this._currentDirection))this.usedForSender=true}get currentDirection(){return this._currentDirection??null}setCurrentDirection(e){this._currentDirection=e;if(e&&e!==`stopped`&&SenderDirections.includes(e)&&this.sender.track)this.usedForSender=true}setDtlsTransport(e){this.receiver.setDtlsTransport(e);this.sender.setDtlsTransport(e)}get msid(){return this.msids[0]}get msids(){return this.sender.streamIds.map(e=>`${e} ${this.sender.trackId}`)}addTrack(e){if(this.receiver.addTrack(e))this.onTrack.execute(e,this)}get associated(){return this.mid!=null&&this.mLineIndex!=void 0}stop(){if(this.stopping)return;this.stopping=true;this.releaseMedia();if(!this.associated)this.markStopped();this.onStopRequested.execute()}commitStopped({rejected:e}){if(e&&!this.stopping)this.rejected=true;this.pendingRejection=false;this.stopping=true;this.releaseMedia();this.markStopped()}markStopped(){this.stopped=true;this.setCurrentDirection(`stopped`)}releaseMedia(){this.sender.stop({keepTrack:true});this.receiver.stop();this.receiver.endTracks();this.onRelease.execute()}forceStop(){if(this.stopped&&this.sender.stopped&&this.receiver.stopped)return;this.stopping=true;this.stopped=true;this.setCurrentDirection(`stopped`);this.receiver.stop();this.sender.stop();this.onRelease.execute()}getPayloadType(e){return this.codecs.find(t=>t.mimeType.toLowerCase().includes(e.toLowerCase()))?.payloadType}getCodecStats(){const e=getStatsTimestamp();return this.collectCodecStats(e)}collectCodecStats(e){const t=[];if(!this.dtlsTransport)return t;const n=generateStatsId(`transport`,this.dtlsTransport.id);for(const r of this.codecs){const i={type:`codec`,id:generateCodecStatsId(n,r.payloadType,this.id),timestamp:e,payloadType:r.payloadType,transportId:n,mimeType:r.mimeType,clockRate:r.clockRate,channels:r.channels,sdpFmtpLine:r.parameters};t.push(i)}return t}};function sameCodecPreferences(e,t){if(e===t)return true;if(e==void 0||t==void 0||e.length!==t.length)return false;return stableCodecValue(e)===stableCodecValue(t)}function stableCodecValue(e){if(Array.isArray(e))return`[${e.map(stableCodecValue).join(`,`)}]`;if(e!=void 0&&typeof e===`object`)return`{${Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${stableCodecValue(t)}`).join(`,`)}}`;return JSON.stringify(e)??`undefined`}var Inactive=`inactive`;var Sendonly=`sendonly`;var Recvonly=`recvonly`;var Sendrecv=`sendrecv`;var Directions=[Inactive,Sendonly,Recvonly,Sendrecv];var sourceCodecsByTrack=/* @__PURE__ */ new WeakMap;var sourceCodecsCapturedByTrack=/* @__PURE__ */ new WeakSet;function setTrackSourceCodecs(e,t){sourceCodecsCapturedByTrack.add(e);if(t==void 0)sourceCodecsByTrack.delete(e);else sourceCodecsByTrack.set(e,t)}function getTrackSourceCodecs(e){return e==void 0?void 0:sourceCodecsByTrack.get(e)}function captureTrackSourceCodecs(e){if(sourceCodecsCapturedByTrack.has(e))return;sourceCodecsCapturedByTrack.add(e);if(e.codec!=void 0)sourceCodecsByTrack.set(e,[e.codec])}var TrackBroadcastSource=class{tracks=/* @__PURE__ */ new Set;upstreamStops=/* @__PURE__ */ new Set;attach(e){this.tracks.add(e)}detach(e){this.tracks.delete(e);if(this.tracks.size>0)return;for(const e of[...this.upstreamStops])e();this.upstreamStops.clear()}addUpstreamStop(e){const once=()=>{this.upstreamStops.delete(once);e()};this.upstreamStops.add(once)}deliverRtp(e,t){const n=[...this.tracks].filter(e=>!e.stopped);for(const r of n)r.applyIncomingRtp(e.clone(),t)}deliverRtcp(e){for(const t of this.tracks)if(!t.stopped)t.onReceiveRtcp.execute(e)}deliverSourceChanged(e){for(const t of this.tracks)if(!t.stopped)t.onSourceChanged.execute(e)}stopAllTracks(){for(const e of[...this.tracks])e.stop()}};var MediaStreamTrack=class _MediaStreamTrack extends EventTarget{uuid=randomUUID$1().toString();streamId;remote=false;label;kind;id;ssrc;rid;header;codec;enabled=true;onReceiveRtp=new Event2;onReceiveRtcp=new Event2;onSourceChanged=new Event2;stopped=false;muted=true;broadcastSource;constructor(e){super();const t=e.broadcastSource;Object.assign(this,e);this.id??=this.uuid;this.broadcastSource=t??new TrackBroadcastSource;if(!this.stopped)this.broadcastSource.attach(this);this.onReceiveRtp.subscribe(e=>{this.muted=false;this.header=e.header});this.label=`${this.remote?`remote`:`local`} ${this.kind}`}get readyState(){return this.stopped?`ended`:`live`}stop=()=>{if(this.stopped)return;this.stopped=true;this.muted=true;this.onReceiveRtp.complete();this.emit(`ended`);this.broadcastSource.detach(this)};writeRtp=e=>{if(this.remote)throw new Error(`this is remoteTrack`);const t=Buffer.isBuffer(e)?RtpPacket.deSerialize(e):e.clone();t.header.payloadType=this.codec?.payloadType??t.header.payloadType;this.broadcastSource.deliverRtp(t)};writeRtcp=e=>{this.broadcastSource.deliverRtcp(e)};notifySourceChanged(e){this.broadcastSource.deliverSourceChanged(e)}applyIncomingRtp(e,t){if(this.stopped)return;this.onReceiveRtp.execute(e,t)}bindUpstreamStop(e){this.broadcastSource.addUpstreamStop(e)}stopMediaSource(){this.broadcastSource.stopAllTracks()}clone(){const e=new _MediaStreamTrack({kind:this.kind,remote:this.remote,enabled:this.enabled,muted:this.muted,stopped:this.stopped,codec:this.codec,ssrc:this.ssrc,rid:this.rid,header:this.header,broadcastSource:this.broadcastSource});if(sourceCodecsCapturedByTrack.has(this))setTrackSourceCodecs(e,getTrackSourceCodecs(this));else captureTrackSourceCodecs(e);return e}};var MediaStream=class _MediaStream{id;tracks=[];constructor(e={}){if(Array.isArray(e))this.tracks=e;else Object.assign(this,e);this.id??=randomUUID$1().toString()}addTrack(e){e.streamId=this.id;this.tracks.push(e)}removeTrack(e){this.tracks=this.tracks.filter(t=>t!==e);if(e.streamId===this.id)e.streamId=void 0}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(e=>e.kind===`audio`)}getVideoTracks(){return this.tracks.filter(e=>e.kind===`video`)}getTrackById(e){return this.tracks.find(t=>t.id===e)}get active(){return this.tracks.some(e=>!e.stopped)}clone(){const e=new _MediaStream;for(const t of this.tracks)e.addTrack(t.clone());return e}};var log25=debug(`werift:packages/webrtc/src/utils.ts`);function fingerprint(e,t){const upper=e=>e.toUpperCase();const colon=e=>e.match(/(.{2})/g).join(`:`);return colon(upper(createHash$1(t).update(e).digest(`hex`)))}var fingerprintHashAlgorithms={sha1:`sha1`,"sha-1":`sha1`,sha224:`sha224`,"sha-224":`sha224`,sha256:`sha256`,"sha-256":`sha256`,sha384:`sha384`,"sha-384":`sha384`,sha512:`sha512`,"sha-512":`sha512`};function normalizeFingerprintAlgorithm(e){return fingerprintHashAlgorithms[e.trim().toLowerCase()]}function normalizeFingerprintValue(e){return e.replace(/[^0-9a-f]/gi,``).toLowerCase()}function isDtls(e){const t=e[0];return t>19&&t<64}function reverseSimulcastDirection(e){if(e===`recv`)return`send`;return`recv`}var andDirection=(e,t)=>Directions[Directions.indexOf(e)&Directions.indexOf(t)];function reverseDirection(e){if(e===`sendonly`)return`recvonly`;if(e===`recvonly`)return`sendonly`;return e}var milliTime=Date.now;var startupTimestampInMicroseconds=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n;var microTime=()=>{return startupTimestampInMicroseconds+process.hrtime.bigint()/1000n};var timestampSeconds=()=>Date.now()/1e3;var ntpTime=()=>{const[e,t]=((performance$1.timeOrigin+performance$1.now()-Date.UTC(1900,0,1))/1e3).toString().split(`.`).map(Number);return bufferWriter([4,4],[e,t]).readBigUInt64BE()};var ntpTimeToEpochMs=e=>{const[t,n]=bufferReader(bufferWriter([8],[e]),[4,4]);return t*1e3+n+Date.UTC(1900,0,1)};var compactNtp=e=>{const[,t,n]=bufferReader(bufferWriter([8],[e]),[2,2,2,2]);return bufferWriter([2,2],[t,n]).readUInt32BE()};function parseIceServers(e){const t={};for(const n of e){const e=Array.isArray(n.urls)?n.urls:[n.urls];for(const r of e){const e=parseIceServerUrl(r);if(!e)continue;if(!t.stunServer&&e.kind===`stun`)t.stunServer=e.address;if(!t.turnServer&&e.kind===`turn`){t.turnServer=e.address;t.turnTransport=e.transport;t.turnUsername=n.username;t.turnPassword=n.credential}}}log25(`iceOptions`,t);return t}function resolveTurnTransport({configuredTurnTransport:e,forceTurnTCP:t,parsedTurnTransport:n}){if(n)return n;if(e)return e;if(t)return`tcp`}function parseIceServerUrl(e){const t=/^(stun|stuns|turn|turns):(.+)$/i.exec(e.trim());if(!t)return;const[,n,r]=t;const i=n.toLowerCase();const[a]=r.split(`?`,1);const[,o=``]=r.split(`?`);const s=parseAddress(a,defaultPort(i));if(!s)return;if(i===`stun`||i===`stuns`)return{kind:`stun`,address:s};const c=resolveParsedTurnTransport({scheme:i,transportParam:new URLSearchParams(o).get(`transport`)});if(c===`invalid`)return;return{kind:`turn`,address:s,transport:c}}function resolveParsedTurnTransport({scheme:e,transportParam:t}){if(t==null)return e===`turns`?`tls`:void 0;if(t===`udp`)return e===`turns`?`invalid`:`udp`;if(t===`tcp`)return e===`turns`?`tls`:`tcp`;return`invalid`}function defaultPort(e){if(e===`stuns`||e===`turns`)return 5349;return 3478}function parseAddress(e,t){const n=e.startsWith(`//`)?e.slice(2):e;if(!n)return;if(n.startsWith(`[`)){const e=n.indexOf(`]`);if(e===-1)return;return[n.slice(1,e),parsePort(n.slice(e+1),t)]}const r=n.indexOf(`:`);const i=n.lastIndexOf(`:`);if(r!==-1&&r===i)return[n.slice(0,r),parsePort(n.slice(r+1),t)];return[n,t]}function parsePort(e,t){const n=e.startsWith(`:`)?e.slice(1):e;const r=Number.parseInt(n,10);return Number.isFinite(r)?r:t}var createSelfSignedCertificate=CipherContext.createSelfSignedCertificateWithKey;var MediaStreamTrackFactory=class{static async rtpSource({port:e,kind:t,cb:n}){e??=await randomPort();const r=new MediaStreamTrack({kind:t});const i=createSocket(`udp4`);i.bind(e);const onMessage=e=>{if(n)e=n(e);r.writeRtp(e)};i.addListener(`message`,onMessage);const dispose=()=>{i.removeListener(`message`,onMessage);try{i.close()}catch(e){}};return[r,e,dispose]}};var deepMerge=(e,t)=>{if(!e||typeof e!==`object`){if(t!==null&&typeof t===`object`)return t;else return e}if(!t||typeof t!==`object`){if(t==void 0)return e;return t}for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const r=t[n];if(r!=void 0)e[n]=r}return e};var log26=debug(`werift:packages/webrtc/src/transport/dtls.ts`);function formatDtlsVersion(e){if(!e)return;if(e.major===254&&e.minor===253)return`DTLS 1.2`;if(e.major===254&&e.minor===255)return`DTLS 1.0`}function formatSrtpCipher(e){switch(e){case 1:return`AES_CM_128_HMAC_SHA1_80`;case 7:return`AEAD_AES_128_GCM`;default:return}}var RTCDtlsTransport=class _RTCDtlsTransport{constructor(e,t,n,r=[]){this.config=e;this.iceTransport=t;this.localCertificate=n;this.srtpProfiles=r;this.localCertificate??=_RTCDtlsTransport.localCertificate}id=randomUUID$1().toString();state=`new`;role=`auto`;srtpStarted=false;transportSequenceNumber=0;bytesSent=0;bytesReceived=0;packetsSent=0;packetsReceived=0;dataReceiver=()=>{};dtls;srtp;srtcp;onStateChange=new Event2;onRtcp=new Event2;onRtp=new Event2;events=new EventTarget;onstatechange;static localCertificate;static localCertificatePromise;remoteParameters;addEventListener=(e,t,n)=>{this.events.addEventListener(e,t,n)};removeEventListener=(e,t)=>{this.events.removeEventListener(e,t)};dispatchEvent=e=>this.events.dispatchEvent(e);get localParameters(){return new RTCDtlsParameters(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){if(this.localCertificate)return this.localCertificate;if(this.localCertificatePromise)return this.localCertificatePromise;this.localCertificatePromise=(async()=>{const{certPem:e,keyPem:t,signatureHash:n}=await CipherContext.createSelfSignedCertificateWithKey({signature:SignatureAlgorithm.ecdsa_3,hash:HashAlgorithm.sha256_4},NamedCurveAlgorithm.secp256r1_23);this.localCertificate=new RTCCertificate(t,e,n);return this.localCertificate})();return this.localCertificatePromise}setRemoteParams(e){const t=deduplicateFingerprints([...this.remoteParameters?.fingerprints??[],...e.fingerprints]);const n=e.role===`auto`&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new RTCDtlsParameters(t,n)}async start(){if(this.state!==`new`)throw new Error(`state must be new`);if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error(`remote fingerprint not exist`);if(this.role===`auto`){if(this.iceTransport.role===`controlling`)this.role=`server`;else this.role=`client`}this.setState(`connecting`);await new Promise(async(e,t)=>{if(this.role===`server`)this.dtls=new DtlsServer({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:createIceTransport(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:true,certificateRequest:true});else this.dtls=new DtlsClient({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:createIceTransport(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:true});this.dtls.onData.subscribe(e=>{if(this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random())return;this.dataReceiver(e)});this.dtls.onClose.subscribe(()=>{if(this.state!==`failed`)this.setState(`closed`)});this.dtls.onConnect.once(e);this.dtls.onError.once(e=>{this.setState(`failed`);log26(`dtls failed`,e);t(e)});if(this.dtls instanceof DtlsClient){await setTimeout$2(100);this.dtls.connect().catch(e=>{this.setState(`failed`);log26(`dtls connect failed`,e);t(e)})}});try{this.verifyRemoteCertificateFingerprint()}catch(e){this.setState(`failed`);this.dtls?.close();throw e}if(this.srtpProfiles.length>0)this.startSrtp();this.setState(`connected`);log26(`dtls connected`)}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error(`remote fingerprint not exist`);const e=this.dtls?.remoteCertificate;if(!e)throw new Error(`remote certificate not available`);const t=this.remoteParameters.fingerprints.flatMap(({algorithm:e,value:t})=>{const n=normalizeFingerprintAlgorithm(e);if(!n)return[];const r=normalizeFingerprintValue(t);if(!r)throw new Error(`remote fingerprint value is empty`);return[{normalizedAlgorithm:n,normalizedValue:r}]});if(t.length===0)throw new Error(`no supported remote fingerprint algorithms`);const n=selectPreferredFingerprintAlgorithm(t);const r=t.filter(({normalizedAlgorithm:e})=>e===n);const i=r.reduce((t,{normalizedAlgorithm:n})=>{if(!t.has(n))t.set(n,normalizeFingerprintValue(fingerprint(e,n)));return t},/* @__PURE__ */ new Map);if(!r.some(({normalizedAlgorithm:e,normalizedValue:t})=>i.get(e)===t))throw new Error(`remote certificate fingerprint mismatch`)}updateSrtpSession(){if(!this.dtls)throw new Error;const e=this.dtls.srtp.srtpProfile;if(!e)throw new Error(`need srtpProfile`);log26(`selected SRTP Profile`,e);const{localKey:t,localSalt:n,remoteKey:r,remoteSalt:i}=this.dtls.extractSessionKeys(keyLength(e),saltLength(e));const a={keys:{localMasterKey:t,localMasterSalt:n,remoteMasterKey:r,remoteMasterSalt:i},profile:e};this.srtp=new SrtpSession(a);this.srtcp=new SrtcpSession(a)}startSrtp(){if(this.srtpStarted)return;this.srtpStarted=true;this.updateSrtpSession();this.iceTransport.connection.onData.subscribe(e=>{if(this.config.debug?.inboundPacketLoss&&this.config.debug?.inboundPacketLoss/100<Math.random())return;if(!isMedia(e))return;this.bytesReceived+=e.length;this.packetsReceived++;if(isRtcp(e)){let t;try{t=this.srtcp.decrypt(e)}catch(e){if(e instanceof SrtpAuthenticationError){log26(`dropping invalid SRTCP packet`,e);return}throw e}let n;try{n=RtcpPacketConverter.deSerialize(t)}catch(e){log26(`dropping malformed SRTCP packet`,e);return}for(const e of n)try{this.onRtcp.execute(e)}catch(e){log26(`RTCP error`,e)}}else{let t;try{t=this.srtp.decrypt(e)}catch(e){if(e instanceof SrtpAuthenticationError){log26(`dropping invalid SRTP packet`,e);return}throw e}let n;try{n=RtpPacket.deSerialize(t)}catch(e){log26(`dropping malformed SRTP packet`,e);return}try{this.onRtp.execute(n)}catch(e){log26(`RTP error`,e)}}})}sendData=async e=>{if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random())return;if(!this.dtls)throw new Error(`dtls not established`);await this.dtls.send(e)};async sendRtp(e,t){try{const n=this.srtp.encrypt(e,t);if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random())return n.length;this.bytesSent+=n.length;this.packetsSent++;await this.iceTransport.connection.send(n).catch(()=>{});return n.length}catch(e){log26(`failed to send`,e);return 0}}async sendRtcp(e){const t=Buffer.concat(e.map(e=>e.serialize()));const n=this.srtcp.encrypt(t);if(this.config.debug?.outboundPacketLoss&&this.config.debug?.outboundPacketLoss/100<Math.random())return n.length;this.bytesSent+=n.length;this.packetsSent++;await this.iceTransport.connection.send(n).catch(()=>{})}setState(e,t=true){if(e!=this.state){this.state=e;this.onStateChange.execute(e);if(t){this.onstatechange?.();this.events.emit(`statechange`)}}}async stop(){this.setState(`closed`,false);await this.iceTransport.stop()}async getStats(e=getStatsTimestamp()){const t=[];const n=generateStatsId(`transport`,this.id);const r={type:`transport`,id:n,timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,iceRole:this.iceTransport.role===`unknown`?void 0:this.iceTransport.role,iceLocalUsernameFragment:this.iceTransport.localParameters.usernameFragment,selectedCandidatePairId:this.iceTransport.connection.nominated?generateStatsId(`candidate-pair`,this.iceTransport.connection.nominated.id):void 0,localCertificateId:this.localCertificate?generateStatsId(`certificate`,this.id,`local`):void 0,remoteCertificateId:this.dtls?.remoteCertificate?generateStatsId(`certificate`,this.id,`remote`):void 0,dtlsRole:this.role===`auto`?void 0:this.role,tlsVersion:formatDtlsVersion(this.dtls?.dtls.version),dtlsCipher:this.dtls?.cipher.cipher?.name,srtpCipher:formatSrtpCipher(this.dtls?.srtp.srtpProfile),iceRestarts:this.iceTransport.iceRestarts};t.push(r);if(this.localCertificate){const n=this.localCertificate.getFingerprints();if(n.length>0){const r={type:`certificate`,id:generateStatsId(`certificate`,this.id,`local`),timestamp:e,fingerprint:n[0].value,fingerprintAlgorithm:n[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString(`base64`)};t.push(r)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0&&this.dtls?.remoteCertificate){const n={type:`certificate`,id:generateStatsId(`certificate`,this.id,`remote`),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:Buffer.from(this.dtls.remoteCertificate).toString(`base64`)};t.push(n)}const i=await this.iceTransport.getStats(e,n);t.push(...i);return t}};var DtlsStates=[`new`,`connecting`,`connected`,`closed`,`failed`];var RTCCertificate=class{constructor(e,t,n){this.certPem=t;this.signatureHash=n;const r=import_build.Certificate.fromPEM(Buffer.from(t));this.publicKey=r.publicKey.toPEM();this.privateKey=import_build.PrivateKey.fromPEM(Buffer.from(e)).toPEM()}publicKey;privateKey;getFingerprints(){return[new RTCDtlsFingerprint(`sha-256`,fingerprint(import_build.Certificate.fromPEM(Buffer.from(this.certPem)).raw,`sha256`))]}};var RTCDtlsFingerprint=class{constructor(e,t){this.algorithm=e;this.value=t}};var RTCDtlsParameters=class{constructor(e=[],t){this.fingerprints=e;this.role=t}};var deduplicateFingerprints=e=>{const t=/* @__PURE__ */ new Set;return e.filter(({algorithm:e,value:n})=>{const r=`${normalizeFingerprintAlgorithm(e)??e.trim().toLowerCase()}:${normalizeFingerprintValue(n)}`;if(t.has(r))return false;t.add(r);return true})};var preferredFingerprintAlgorithms=[`sha512`,`sha384`,`sha256`,`sha224`,`sha1`];var selectPreferredFingerprintAlgorithm=e=>{return preferredFingerprintAlgorithms.find(t=>e.some(({normalizedAlgorithm:e})=>e===t))??e[0].normalizedAlgorithm};var IceTransport=class{constructor(e){this.ice=e;e.onData.subscribe(e=>{if(isDtls(e)){if(this.onData)this.onData(e)}})}closed=false;onData=()=>{};get address(){return{}}type=`ice`;send=e=>{return this.ice.send(e)};async close(){this.closed=true;this.ice.close()}};var createIceTransport=e=>new IceTransport(e);var log27=debug(`werift:packages/webrtc/src/transport/ice.ts`);function mapCandidatePairState(e){switch(e){case 0:return`frozen`;case 1:return`waiting`;case 2:return`in-progress`;case 3:return`succeeded`;case 4:return`failed`;default:return`failed`}}var RTCIceTransport=class{constructor(e){this.iceGather=e;this.connection=this.iceGather.connection;this.connection.stateChanged.subscribe(e=>{this.setState(e)});this.iceGather.onIceCandidate=e=>{this.onIceCandidate.execute(e)};this.iceGather.onGatheringStateChange.subscribe(()=>{this.ongatheringstatechange?.();this.events.emit(`gatheringstatechange`)})}id=randomUUID$1().toString();connection;state=`new`;component=`rtp`;iceRestarts=0;waitStart;renominating=false;events=new EventTarget;onstatechange;ongatheringstatechange;onStateChange=new Event2;onIceCandidate=new Event2;onNegotiationNeeded=new Event2;addEventListener=(e,t,n)=>{this.events.addEventListener(e,t,n)};removeEventListener=(e,t)=>{this.events.removeEventListener(e,t)};dispatchEvent=e=>this.events.dispatchEvent(e);get role(){if(!this.connection.remoteUsername||!this.connection.remotePassword)return`unknown`;if(this.connection.iceControlling)return`controlling`;else return`controlled`}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}getRemoteCandidates(){return this.connection.remoteCandidates.filter(e=>e.type!==`prflx`).map(e=>candidateFromIce(e).toJSON())}getLocalCandidates(){return this.connection.localCandidates.map(e=>candidateFromIce(e).toJSON())}getSelectedCandidatePair(){const e=this.connection.candidatePairs.find(e=>e.nominated)??this.connection.candidatePairs.find(e=>e.state===3);if(!e)return null;return{local:candidateFromIce(e.localCandidate).toJSON(),remote:candidateFromIce(e.remoteCandidate).toJSON()}}getLocalParameters(){return this.localParameters??null}getRemoteParameters(){if(!this.connection.remoteUsername||!this.connection.remotePassword)return null;return new RTCIceParameters({iceLite:this.connection.remoteIsLite,password:this.connection.remotePassword,usernameFragment:this.connection.remoteUsername})}setState(e,t=true){if(e!==this.state){this.state=e;this.onStateChange.execute(e);if(t){this.onstatechange?.();this.events.emit(`statechange`)}}}gather(){return this.iceGather.gather()}setIceServers(e){this.iceGather.setIceServers(e)}addRemoteCandidate=e=>{if(!this.connection.remoteCandidatesEnd)return!e?this.connection.addRemoteCandidate(void 0):this.connection.addRemoteCandidate(candidateToIce(e))};setRemoteParams(e,t=false){if(t)this.renominating=true;if(this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==e.usernameFragment||this.connection.remotePassword!==e.password)){if(this.renominating){log27(`renomination`,e);this.connection.resetNominatedPair();this.renominating=false}else{log27(`restart`,e);this.restart()}}this.connection.setRemoteParams(e)}restart(){this.iceRestarts++;this.connection.restart();this.setState(`new`);this.iceGather.setGatheringState(`new`);this.waitStart=void 0;this.onNegotiationNeeded.execute()}async start(){if(this.state===`closed`)throw new Error(`RTCIceTransport is closed`);if(!this.connection.remotePassword||!this.connection.remoteUsername)throw new Error(`remoteParams missing`);if(this.waitStart)await this.waitStart.asPromise();this.waitStart=new Event2;this.setState(`checking`);try{await this.connection.connect()}catch(e){this.setState(`failed`);throw e}this.waitStart.execute();this.waitStart.complete();this.waitStart=void 0}async stop(){if(this.state!==`closed`){this.setState(`closed`,false);await this.connection.close()}this.onStateChange.complete();this.onIceCandidate.complete();this.onNegotiationNeeded.complete()}async getStats(e=getStatsTimestamp(),t=generateStatsId(`transport`,this.id)){const n=[];for(const r of this.connection.localCandidates){const i={type:`local-candidate`,id:generateStatsId(`local-candidate`,r.id),timestamp:e,transportId:t,address:r.host,port:r.port,protocol:r.transport,candidateType:r.type,priority:r.priority,foundation:r.foundation,relatedAddress:r.relatedAddress,relatedPort:r.relatedPort,usernameFragment:r.ufrag,tcpType:r.tcptype};n.push(i)}for(const r of this.connection.remoteCandidates){const i={type:`remote-candidate`,id:generateStatsId(`remote-candidate`,r.id),timestamp:e,transportId:t,address:r.host,port:r.port,protocol:r.transport,candidateType:r.type,priority:r.priority,foundation:r.foundation,relatedAddress:r.relatedAddress,relatedPort:r.relatedPort,usernameFragment:r.ufrag,tcpType:r.tcptype};n.push(i)}const r=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(e=>e.nominated),...this.connection.candidatePairs.filter(e=>!e.nominated)]:[];for(const i of r){const r={type:`candidate-pair`,id:generateStatsId(`candidate-pair`,i.id),timestamp:e,transportId:t,localCandidateId:generateStatsId(`local-candidate`,i.localCandidate.id),remoteCandidateId:generateStatsId(`remote-candidate`,i.remoteCandidate.id),state:mapCandidatePairState(i.state),nominated:i.nominated,packetsSent:i.packetsSent,packetsReceived:i.packetsReceived,bytesSent:i.bytesSent,bytesReceived:i.bytesReceived,currentRoundTripTime:i.rtt,totalRoundTripTime:i.totalRoundTripTime,roundTripTimeMeasurements:i.roundTripTimeMeasurements,requestsReceived:i.requestsReceived,requestsSent:i.requestsSent,responsesReceived:i.responsesReceived,responsesSent:i.responsesSent,retransmissionsReceived:i.retransmissionsReceived,retransmissionsSent:i.retransmissionsSent,consentRequestsSent:i.consentRequestsSent};n.push(r)}return n}};var IceTransportStates=[`new`,`checking`,`connected`,`completed`,`disconnected`,`failed`,`closed`];var IceGathererStates=[`new`,`gathering`,`complete`];var RTCIceGatherer=class{constructor(e={}){this.options=e;this.connection=new Connection(false,this.options);this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(candidateFromIce(e))})}onIceCandidate=()=>{};gatheringState=`new`;connection;onGatheringStateChange=new Event2;async gather(){if(this.gatheringState===`new`){this.setState(`gathering`);await this.connection.gatherCandidates();this.onIceCandidate(void 0);this.setState(`complete`)}}setIceServers(e){this.connection.setIceServers(e)}setGatheringState(e){this.setState(e)}get localCandidates(){return this.connection.localCandidates.map(candidateFromIce)}get localParameters(){return new RTCIceParameters({iceLite:this.connection.iceLite,usernameFragment:this.connection.localUsername,password:this.connection.localPassword})}setState(e){if(e!==this.gatheringState){this.gatheringState=e;this.onGatheringStateChange.execute(e)}}};function candidateFromIce(e){const t=new IceCandidate(e.component,e.foundation,e.host,e.port,e.priority,e.transport,e.type,e.generation,e.ufrag);t.relatedAddress=e.relatedAddress;t.relatedPort=e.relatedPort;t.tcpType=e.tcptype;return t}function candidateToIce(e){return new Candidate(e.foundation,e.component,e.protocol,e.priority,e.ip,e.port,e.type,e.relatedAddress,e.relatedPort,e.tcpType,e.generation,e.ufrag)}var RTCIceCandidate=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(e){Object.assign(this,e)}static fromSdp(e){return candidateFromIce(Candidate.fromSdp(e)).toJSON()}static isThis(e){if(typeof e?.candidate===`string`)return true}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}};var IceCandidate=class{constructor(e,t,n,r,i,a,o,s,c){this.component=e;this.foundation=t;this.ip=n;this.port=r;this.priority=i;this.protocol=a;this.type=o;this.generation=s;this.ufrag=c}relatedAddress;relatedPort;sdpMid;sdpMLineIndex;tcpType;toJSON(){return new RTCIceCandidate({candidate:candidateToSdp(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(e){try{if(!e.candidate)throw new Error(`candidate is required`);const t=candidateFromSdp(e.candidate.startsWith(`candidate:`)?e.candidate.slice(10):e.candidate);t.sdpMLineIndex=e.sdpMLineIndex??void 0;t.sdpMid=e.sdpMid??void 0;return t}catch(e){}}};var RTCIceParameters=class{iceLite=false;usernameFragment;password;constructor(e={}){Object.assign(this,e)}};var SCTP_PADDING_MULTIPLE=4;var SCTP_COMMON_HEADER_SIZE=12;var SCTP_CHUNK_HEADER_SIZE=4;var SCTP_DATA_CHUNK_HEADER_SIZE=SCTP_CHUNK_HEADER_SIZE+12;var Chunk=class _Chunk{constructor(e=0,t=Buffer.from(``)){this.flags=e;this._body=t}get body(){return this._body}set body(e){this._body=e}static type=-1;get type(){return _Chunk.type}get bytes(){if(!this.body)throw new Error;const e=Buffer.alloc(SCTP_CHUNK_HEADER_SIZE);e.writeUInt8(this.type,0);e.writeUInt8(this.flags,1);e.writeUInt16BE(this.body.length+SCTP_CHUNK_HEADER_SIZE,2);return Buffer.concat([e,this.body,...[...Array(padL(this.body.length))].map(()=>Buffer.from(`\0`))])}};var BaseInitChunk=class extends Chunk{constructor(e=0,t){super(e,t);this.flags=e;if(t){this.initiateTag=t.readUInt32BE(0);this.advertisedRwnd=t.readUInt32BE(4);this.outboundStreams=t.readUInt16BE(8);this.inboundStreams=t.readUInt16BE(10);this.initialTsn=t.readUInt32BE(12);this.params=decodeParams(t.slice(16))}else{this.initiateTag=0;this.advertisedRwnd=0;this.outboundStreams=0;this.inboundStreams=0;this.initialTsn=0;this.params=[]}}initiateTag;advertisedRwnd;outboundStreams;inboundStreams;initialTsn;params;get body(){const e=Buffer.alloc(16);e.writeUInt32BE(this.initiateTag,0);e.writeUInt32BE(this.advertisedRwnd,4);e.writeUInt16BE(this.outboundStreams,8);e.writeUInt16BE(this.inboundStreams,10);e.writeUInt32BE(this.initialTsn,12);return Buffer.concat([e,encodeParams(this.params)])}};var InitChunk=class _InitChunk extends BaseInitChunk{static type=1;get type(){return _InitChunk.type}};var InitAckChunk=class _InitAckChunk extends BaseInitChunk{static type=2;get type(){return _InitAckChunk.type}};var ReConfigChunk=class _ReConfigChunk extends BaseInitChunk{static type=130;get type(){return _ReConfigChunk.type}};var ForwardTsnChunk=class _ForwardTsnChunk extends Chunk{constructor(e=0,t){super(e,t);this.flags=e;if(t){this.cumulativeTsn=t.readUInt32BE(0);let e=4;while(e<t.length){this.streams.push([t.readUInt16BE(e),t.readUInt16BE(e+2)]);e+=4}}else this.cumulativeTsn=0}static type=192;streams=[];cumulativeTsn;get type(){return _ForwardTsnChunk.type}set body(e){}get body(){const e=Buffer.alloc(4);e.writeUInt32BE(this.cumulativeTsn,0);return Buffer.concat([e,...this.streams.map(([e,t])=>{const n=Buffer.alloc(4);n.writeUInt16BE(e,0);n.writeUInt16BE(t,2);return n})])}};var DataChunk=class _DataChunk extends Chunk{constructor(e=0,t){super(e,t);this.flags=e;if(t){this.tsn=t.readUInt32BE(0);this.streamId=t.readUInt16BE(4);this.streamSeqNum=t.readUInt16BE(6);this.protocol=t.readUInt32BE(8);this.userData=t.slice(12)}}static type=0;get type(){return _DataChunk.type}tsn=0;streamId=0;streamSeqNum=0;protocol=0;userData=Buffer.from(``);abandoned=false;acked=false;misses=0;retransmit=false;sentCount=0;bookSize=0;expiry;maxRetransmits;sentTime;get bytes(){const e=SCTP_DATA_CHUNK_HEADER_SIZE+this.userData.length;const t=Buffer.alloc(SCTP_DATA_CHUNK_HEADER_SIZE);t.writeUInt8(this.type,0);t.writeUInt8(this.flags,1);t.writeUInt16BE(e,2);t.writeUInt32BE(this.tsn,4);t.writeUInt16BE(this.streamId,8);t.writeUInt16BE(this.streamSeqNum,10);t.writeUInt32BE(this.protocol,12);let n=Buffer.concat([t,this.userData]);if(e%4)n=Buffer.concat([n,...[...Array(padL(e))].map(()=>Buffer.from(`\0`))]);return n}};var CookieEchoChunk=class _CookieEchoChunk extends Chunk{static type=10;get type(){return _CookieEchoChunk.type}};var CookieAckChunk=class _CookieAckChunk extends Chunk{static type=11;get type(){return _CookieAckChunk.type}};var BaseParamsChunk=class extends Chunk{constructor(e=0,t=void 0){super(e,t);this.flags=e;if(t)this.params=decodeParams(t)}params=[];get body(){return encodeParams(this.params)}};var AbortChunk=class _AbortChunk extends BaseParamsChunk{static type=6;get type(){return _AbortChunk.type}};var ErrorChunk=class _ErrorChunk extends BaseParamsChunk{static type=9;static CODE={InvalidStreamIdentifier:1,MissingMandatoryParameter:2,StaleCookieError:3,OutofResource:4,UnresolvableAddress:5,UnrecognizedChunkType:6,InvalidMandatoryParameter:7,UnrecognizedParameters:8,NoUserData:9,CookieReceivedWhileShuttingDown:10,RestartofanAssociationwithNewAddresses:11,UserInitiatedAbort:12,ProtocolViolation:13};get type(){return _ErrorChunk.type}get descriptions(){return this.params.map(([e,t])=>{return{name:(Object.entries(_ErrorChunk.CODE).find(([,t])=>t===e)||[])[0],body:t}})}};var HeartbeatChunk=class _HeartbeatChunk extends BaseParamsChunk{static type=4;get type(){return _HeartbeatChunk.type}};var HeartbeatAckChunk=class _HeartbeatAckChunk extends BaseParamsChunk{static type=5;get type(){return _HeartbeatAckChunk.type}};var ReconfigChunk=class _ReconfigChunk extends BaseParamsChunk{static type=130;get type(){return _ReconfigChunk.type}};var SackChunk=class _SackChunk extends Chunk{constructor(e=0,t){super(e,t);this.flags=e;if(t){this.cumulativeTsn=t.readUInt32BE(0);this.advertisedRwnd=t.readUInt32BE(4);const e=t.readUInt16BE(8);const n=t.readUInt16BE(10);let r=12;[...Array(e)].forEach(()=>{this.gaps.push([t.readUInt16BE(r),t.readUInt16BE(r+2)]);r+=4});[...Array(n)].forEach(()=>{this.duplicates.push(t.readUInt32BE(r));r+=4})}}static type=3;get type(){return _SackChunk.type}gaps=[];duplicates=[];cumulativeTsn=0;advertisedRwnd=0;get bytes(){const e=16+4*(this.gaps.length+this.duplicates.length);const t=Buffer.alloc(16);t.writeUInt8(this.type,0);t.writeUInt8(this.flags,1);t.writeUInt16BE(e,2);t.writeUInt32BE(this.cumulativeTsn,4);t.writeUInt32BE(this.advertisedRwnd,8);t.writeUInt16BE(this.gaps.length,12);t.writeUInt16BE(this.duplicates.length,14);let n=Buffer.concat([t,...this.gaps.map(e=>{const t=Buffer.alloc(4);t.writeUInt16BE(e[0],0);t.writeUInt16BE(e[1],2);return t})]);n=Buffer.concat([n,...this.duplicates.map(e=>{const t=Buffer.alloc(4);t.writeUInt32BE(e,0);return t})]);return n}};var ShutdownChunk=class _ShutdownChunk extends Chunk{constructor(e=0,t){super(e,t);this.flags=e;if(t)this.cumulativeTsn=t.readUInt32BE(0)}static type=7;get type(){return _ShutdownChunk.type}cumulativeTsn=0;get body(){const e=Buffer.alloc(4);e.writeUInt32BE(this.cumulativeTsn,0);return e}};var ShutdownAckChunk=class _ShutdownAckChunk extends Chunk{static type=8;get type(){return _ShutdownAckChunk.type}};var ShutdownCompleteChunk=class _ShutdownCompleteChunk extends Chunk{static type=14;get type(){return _ShutdownCompleteChunk.type}};var CHUNK_BY_TYPE=[DataChunk,InitChunk,InitAckChunk,SackChunk,HeartbeatChunk,HeartbeatAckChunk,AbortChunk,ShutdownChunk,ShutdownAckChunk,ErrorChunk,CookieEchoChunk,CookieAckChunk,ShutdownCompleteChunk,ReconfigChunk,ForwardTsnChunk].reduce((e,t)=>{e[t.type]=t;return e},{});function padL(e){const t=e%SCTP_PADDING_MULTIPLE;return t?SCTP_PADDING_MULTIPLE-t:0}function encodeParams(e){let t=Buffer.from(``);let n=Buffer.from(``);e.forEach(([e,r])=>{const i=r.length+4;const a=Buffer.alloc(4);a.writeUInt16BE(e,0);a.writeUInt16BE(i,2);t=Buffer.concat([t,n,a,r]);n=Buffer.concat([...Array(padL(i))].map(()=>Buffer.from(`\0`)))});return t}function decodeParams(e){const t=[];let n=0;while(n<=e.length-4){const r=e.readUInt16BE(n);const i=e.readUInt16BE(n+2);t.push([r,e.slice(n+4,n+i)]);n+=i+padL(i)}return t}function parsePacket2(e){if(e.length<SCTP_COMMON_HEADER_SIZE)throw new Error(`SCTP packet length is less than 12 bytes`);const t=e.readUInt16BE(0);const n=e.readUInt16BE(2);const r=e.readUInt32BE(4);if(e.readUInt32LE(8)!==crc32c(Buffer.concat([e.slice(0,8),Buffer.from(`\0\0\0\0`),e.slice(SCTP_COMMON_HEADER_SIZE)])))throw new Error(`SCTP packet has invalid checksum`);const i=[];let a=SCTP_COMMON_HEADER_SIZE;while(a+4<=e.length){const t=e.readUInt8(a);const n=e.readUInt8(a+1);const r=e.readUInt16BE(a+2);const o=e.slice(a+4,a+r);const s=CHUNK_BY_TYPE[t.toString()];if(s)i.push(new s(n,o));else throw new Error(`unknown`);a+=r+padL(r)}return[t,n,r,i]}function serializePacket(e,t,n,r){const i=Buffer.alloc(SCTP_COMMON_HEADER_SIZE-4);i.writeUInt16BE(e,0);i.writeUInt16BE(t,2);i.writeUInt32BE(n,4);const a=r.bytes;const o=crc32c(Buffer.concat([i,Buffer.from(`\0\0\0\0`),a]));const s=Buffer.alloc(4);s.writeUInt32LE(o,0);return Buffer.concat([i,s,a])}function enumerate3(e){return e.map((e,t)=>[t,e])}function createEventsFromList(e){return e.reduce((e,t)=>{e[t]=new Event2;return e},{})}var OutgoingSSNResetRequestParam=class _OutgoingSSNResetRequestParam{constructor(e,t,n,r){this.requestSequence=e;this.responseSequence=t;this.lastTsn=n;this.streams=r}static type=13;get type(){return _OutgoingSSNResetRequestParam.type}get bytes(){const e=Buffer.allocUnsafe(12);e.writeUInt32BE(this.requestSequence,0);e.writeUInt32BE(this.responseSequence,4);e.writeUInt32BE(this.lastTsn,8);return Buffer.concat([e,...this.streams.map(e=>{const t=Buffer.allocUnsafe(2);t.writeUInt16BE(e,0);return t})])}static parse(e){const t=e.readUInt32BE(0);const n=e.readUInt32BE(4);const r=e.readUInt32BE(8);const i=[];for(let t=12;t<e.length;t+=2)i.push(e.readUInt16BE(t));return new _OutgoingSSNResetRequestParam(t,n,r,i)}};var StreamAddOutgoingParam=class _StreamAddOutgoingParam{constructor(e,t){this.requestSequence=e;this.newStreams=t}static type=17;get type(){return _StreamAddOutgoingParam.type}get bytes(){const e=Buffer.allocUnsafe(8);e.writeUInt32BE(this.requestSequence,0);e.writeUInt16BE(this.newStreams,4);e.writeUInt16BE(0,6);return e}static parse(e){const t=e.readUInt32BE(0);const n=e.readUInt16BE(4);return new _StreamAddOutgoingParam(t,n)}};var reconfigResult={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5};var ReconfigResponseParam=class _ReconfigResponseParam{constructor(e,t){this.responseSequence=e;this.result=t}static type=16;get type(){return _ReconfigResponseParam.type}get bytes(){const e=Buffer.allocUnsafe(8);e.writeUInt32BE(this.responseSequence,0);e.writeUInt32BE(this.result,4);return e}static parse(e){const t=e.readUInt32BE(0);const n=e.readUInt32BE(4);return new _ReconfigResponseParam(t,n)}};var RECONFIG_PARAM_BY_TYPES={13:OutgoingSSNResetRequestParam,16:ReconfigResponseParam,17:StreamAddOutgoingParam};var log28=debug(`werift/sctp/sctp`);var COOKIE_LENGTH=24;var COOKIE_LIFETIME=60;var MAX_STREAMS=65535;var DEFAULT_SCTP_MTU=1191;function maxPayloadSizeForMtu(e,t=SCTP_DATA_CHUNK_HEADER_SIZE){const n=SCTP_COMMON_HEADER_SIZE+t;if(e<=n)return 0;const r=e-n;return r-r%SCTP_PADDING_MULTIPLE}function validateSctpMtu(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`SCTP MTU must be a positive integer`);if(maxPayloadSizeForMtu(e)===0)throw new Error(`SCTP MTU is too small for a DATA chunk`)}var SCTP_DATA_LAST_FRAG=1;var SCTP_DATA_FIRST_FRAG=2;var SCTP_DATA_UNORDERED=4;var SCTP_MAX_ASSOCIATION_RETRANS=10;var SCTP_MAX_INIT_RETRANS=8;var SCTP_RTO_ALPHA=1/8;var SCTP_RTO_BETA=1/4;var SCTP_RTO_INITIAL=3;var SCTP_RTO_MIN=1;var SCTP_RTO_MAX=60;var SCTP_TSN_MODULO=2**32;var SCTP_SACK_DELAY_MS=200;var SCTP_HEARTBEAT_INTERVAL=30;var RECONFIG_MAX_STREAMS=135;var SCTP_STATE_COOKIE=7;var SCTP_SUPPORTED_CHUNK_EXT=32776;var SCTP_PRSCTP_SUPPORTED=49152;var SCTPConnectionStates=[`new`,`closed`,`connected`,`connecting`];var SCTP=class _SCTP{constructor(e,t=5e3,n={}){this.transport=e;this.port=t;this.mtu=n.mtu??DEFAULT_SCTP_MTU;validateSctpMtu(this.mtu);this.maxPayloadSize=maxPayloadSizeForMtu(this.mtu);this.cwnd=3*this.maxPayloadSize;this.localPort=this.port;this.transport.onData=e=>{this.handleData(e)}}flush=new Event2;stateChanged=createEventsFromList(SCTPConnectionStates);onReconfigStreams=new Event2;onReceive=new Event2;onSackReceived=async()=>{};associationState=1;started=false;state=`new`;isServer=true;isStopping=false;isClosed=false;hmacKey=randomBytes$1(16);localPartialReliability=true;localPort;localVerificationTag=random32();remoteExtensions=[];remotePartialReliability=true;remotePort;remoteVerificationTag=0;advertisedRwnd=1048576;peerAdvertisedRwnd=this.advertisedRwnd;get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}inboundStreams={};_inboundStreamsCount=0;_inboundStreamsMax=MAX_STREAMS;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=/* @__PURE__ */ new Set;sackNeeded=false;sackPacketCount=0;sackHasNewDataInPacket=false;sackImmediate=false;sackTimeout;cwnd;mtu;maxPayloadSize;fastRecoveryExit;fastRecoveryTransmit=false;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=MAX_STREAMS;localTsn=Number(random32());lastSackedTsn=tsnMinusOne(this.localTsn);advancedPeerAckTsn=tsnMinusOne(this.localTsn);partialBytesAcked=0;sentQueue=[];transmitting=false;transmitRequested=false;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=SCTP_RTO_INITIAL;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=SCTP_HEARTBEAT_INTERVAL;ssthresh;get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0)return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}static client(e,t=5e3,n={}){const r=new _SCTP(e,t,n);r.isServer=false;return r}static server(e,t=5e3,n={}){const r=new _SCTP(e,t,n);r.isServer=true;return r}async handleData(e){if(this.isStopped)return;let t;const[,,n,r]=parsePacket2(e);if(r.filter(e=>e.type===InitChunk.type).length>0){if(r.length!=1)throw new Error;t=0}else t=this.localVerificationTag;if(n!==t)return;this.sackHasNewDataInPacket=false;for(const e of r)await this.receiveChunk(e);if(this.sackNeeded){if(this.sackHasNewDataInPacket)this.sackPacketCount++;if(this.sackPacketCount>=2)this.sackImmediate=true;await this.scheduleSack()}}async scheduleSack(){if(this.isStopped)return;if(!this.sackNeeded)return;if(this.sackImmediate){if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}await this.sendSack();return}if(this.sackTimeout)return;this.sackTimeout=setTimeout(()=>{this.sackTimeout=void 0;this.sendSack().catch(e=>{log28(`send delayed sack failed`,e.message)})},SCTP_SACK_DELAY_MS)}async sendSack(){if(this.isStopped)return;if(!this.sackNeeded)return;const e=[];let t;[...this.sackMisOrdered].sort().forEach(n=>{const r=(n-this.lastReceivedTsn)%SCTP_TSN_MODULO;if(n===t)e[e.length-1][1]=r;else e.push([r,r]);t=tsnPlusOne(n)});const n=new SackChunk(0,void 0);n.cumulativeTsn=this.lastReceivedTsn;n.advertisedRwnd=Math.max(0,this.advertisedRwnd);n.duplicates=[...this.sackDuplicates];n.gaps=e;await this.sendChunk(n).catch(e=>{log28(`send sack failed`,e.message)});this.sackDuplicates=[];this.sackNeeded=false;this.sackPacketCount=0;this.sackImmediate=false}async receiveChunk(e){switch(e.type){case DataChunk.type:this.receiveDataChunk(e);break;case InitChunk.type:{if(!this.isServer)return;const t=e;log28(`receive init`,t);this.lastReceivedTsn=tsnMinusOne(t.initialTsn);this.reconfigResponseSeq=tsnMinusOne(t.initialTsn);this.remoteVerificationTag=t.initiateTag;this.ssthresh=t.advertisedRwnd;this.peerAdvertisedRwnd=t.advertisedRwnd;this.getExtensions(t.params);this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax);this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);const n=new InitAckChunk;n.initiateTag=this.localVerificationTag;n.advertisedRwnd=this.advertisedRwnd;n.outboundStreams=this._outboundStreamsCount;n.inboundStreams=this._inboundStreamsCount;n.initialTsn=this.localTsn;this.setExtensions(n.params);const r=Math.floor(Date.now()/1e3);const i=Buffer.allocUnsafe(4);i.writeUInt32BE(r,0);let a=i;a=Buffer.concat([a,createHmac$1(`sha1`,this.hmacKey).update(a).digest()]);n.params.push([SCTP_STATE_COOKIE,a]);log28(`send initAck`,n);await this.sendChunk(n).catch(e=>{log28(`send initAck failed`,e.message)})}break;case InitAckChunk.type:{if(this.associationState!=2)return;const t=e;this.timer1Cancel();this.lastReceivedTsn=tsnMinusOne(t.initialTsn);this.reconfigResponseSeq=tsnMinusOne(t.initialTsn);this.remoteVerificationTag=t.initiateTag;this.ssthresh=t.advertisedRwnd;this.peerAdvertisedRwnd=t.advertisedRwnd;this.getExtensions(t.params);this._inboundStreamsCount=Math.min(t.outboundStreams,this._inboundStreamsMax);this._outboundStreamsCount=Math.min(this._outboundStreamsCount,t.inboundStreams);const n=new CookieEchoChunk;for(const[e,r]of t.params)if(e===SCTP_STATE_COOKIE){n.body=r;break}await this.sendChunk(n).catch(e=>{log28(`send echo failed`,e.message)});this.timer1Start(n);this.setState(3)}break;case SackChunk.type:await this.receiveSackChunk(e);break;case HeartbeatChunk.type:{const t=new HeartbeatAckChunk;t.params=e.params;await this.sendChunk(t).catch(e=>{log28(`send heartbeat ack failed`,e.message)})}break;case AbortChunk.type:this.setState(1);break;case ShutdownChunk.type:{this.timer2Cancel();this.setState(7);const e=new ShutdownAckChunk;await this.sendChunk(e).catch(e=>{log28(`send shutdown ack failed`,e.message)});this.t2Start(e);this.setState(6)}break;case ErrorChunk.type:log28(`ErrorChunk`,e.descriptions);break;case CookieEchoChunk.type:{if(!this.isServer)return;const t=e.body;const n=createHmac$1(`sha1`,this.hmacKey).update(t.slice(0,4)).digest();if(t?.length!=COOKIE_LENGTH||!t.slice(4).equals(n)){log28(`x State cookie is invalid`);return}const r=Math.floor(Date.now()/1e3);const i=t.readUInt32BE(0);if(i<r-COOKIE_LIFETIME||i>r){const e=new ErrorChunk(0,void 0);e.params.push([ErrorChunk.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from(`\0`)))]);await this.sendChunk(e).catch(e=>{log28(`send errorChunk failed`,e.message)});return}const a=new CookieAckChunk;await this.sendChunk(a).catch(e=>{log28(`send cookieAck failed`,e.message)});this.setState(4)}break;case CookieAckChunk.type:if(this.associationState!=3)return;this.timer1Cancel();this.setState(4);break;case ShutdownCompleteChunk.type:if(this.associationState!=8)return;this.timer2Cancel();this.setState(1);break;case ReconfigChunk.type:{if(this.associationState!=4)return;const t=e;for(const[e,n]of t.params){const t=RECONFIG_PARAM_BY_TYPES[e];if(t)await this.receiveReconfigParam(t.parse(n))}}break;case ForwardTsnChunk.type:this.receiveForwardTsnChunk(e)}}getExtensions(e){for(const[t,n]of e)if(t===SCTP_PRSCTP_SUPPORTED)this.remotePartialReliability=true;else if(t===SCTP_SUPPORTED_CHUNK_EXT)this.remoteExtensions=[...n]}async receiveReconfigParam(e){log28(`receiveReconfigParam`,RECONFIG_PARAM_BY_TYPES[e.type]);switch(e.type){case OutgoingSSNResetRequestParam.type:{const t=e;const n=new ReconfigResponseParam(t.requestSequence,reconfigResult.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=t.requestSequence;await this.sendReconfigParam(n);await Promise.all(t.streams.map(async e=>{delete this.inboundStreams[e];if(this.outboundStreamSeq[e]){if(!this.reconfigQueue.includes(e))this.reconfigQueue.push(e)}}));await this.transmitReconfigRequest();this.onReconfigStreams.execute(t.streams)}break;case ReconfigResponseParam.type:{const t=e;if(t.result!==reconfigResult.ReconfigResultSuccessPerformed)log28(`OutgoingSSNResetRequestParam failed`,Object.keys(reconfigResult).find(e=>reconfigResult[e]===t.result));else if(t.responseSequence===this.reconfigRequest?.requestSequence){const e=this.reconfigRequest.streams.map(e=>{delete this.outboundStreamSeq[e];return e});this.onReconfigStreams.execute(e);this.reconfigRequest=void 0;this.timerReconfigCancel();this.rto=SCTP_RTO_INITIAL;this.timerReconfigFailures=0;if(this.reconfigQueue.length>0)await this.transmitReconfigRequest()}}break;case StreamAddOutgoingParam.type:{const t=e;this._inboundStreamsCount+=t.newStreams;const n=new ReconfigResponseParam(t.requestSequence,1);this.reconfigResponseSeq=t.requestSequence;await this.sendReconfigParam(n)}}}receiveDataChunk(e){this.sackNeeded=true;if(this.markReceived(e.tsn)){this.sackImmediate=true;return}this.sackHasNewDataInPacket=true;this.sackImmediate=true;if((e.flags&SCTP_DATA_LAST_FRAG)===0)this.sackImmediate=true;if(this.sackMisOrdered.size>0)this.sackImmediate=true;const t=this.getInboundStream(e.streamId);t.addChunk(e);this.advertisedRwnd-=e.userData.length;for(const e of t.popMessages()){this.advertisedRwnd+=e[2].length;this.receive(...e)}}async receiveSackChunk(e){if(uint32Gt(this.lastSackedTsn,e.cumulativeTsn))return;const t=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;const n=this.flightSize>=this.cwnd;let r=0,i=0;while(this.sentQueue.length>0&&uint32Gte(this.lastSackedTsn,this.sentQueue[0].tsn)){const e=this.sentQueue.shift();r++;if(!e?.acked){i+=e.bookSize;this.flightSizeDecrease(e)}if(r===1&&e.sentCount===1)this.updateRto(t-e.sentTime)}if(!this.sentQueue.length)this.sentQueue=[];let a=false;if(e.gaps.length>0){const t=/* @__PURE__ */ new Set;let n;e.gaps.forEach(r=>{for(let i=r[0];i<r[1]+1;i++){n=(e.cumulativeTsn+i)%SCTP_TSN_MODULO;t.add(n)}});let r=e.cumulativeTsn;for(const e of this.sentQueue){if(uint32Gt(e.tsn,n))break;if(t.has(e.tsn)&&!e.acked){i+=e.bookSize;e.acked=true;this.flightSizeDecrease(e);r=e.tsn}}for(const e of this.sentQueue){if(uint32Gt(e.tsn,r))break;if(!t.has(e.tsn)){e.misses++;if(e.misses===3){e.misses=0;if(!this.maybeAbandon(e))e.retransmit=true;e.acked=false;this.flightSizeDecrease(e);a=true}}}}if(this.fastRecoveryExit===void 0){if(r&&n){if(this.cwnd<=this.ssthresh)this.cwnd+=Math.min(i,this.maxPayloadSize);else{this.partialBytesAcked+=i;if(this.partialBytesAcked>=this.cwnd){this.partialBytesAcked-=this.cwnd;this.cwnd+=this.maxPayloadSize}}}if(a){this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*this.maxPayloadSize);this.cwnd=this.ssthresh;this.partialBytesAcked=0;this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn;this.fastRecoveryTransmit=true}}else if(uint32Gte(e.cumulativeTsn,this.fastRecoveryExit))this.fastRecoveryExit=void 0;if(this.sentQueue.length===0)this.timer3Cancel();else if(r>0)this.timer3Restart();this.peerAdvertisedRwnd=e.advertisedRwnd;this.updateAdvancedPeerAckPoint();await this.onSackReceived();await this.transmit()}receiveForwardTsnChunk(e){this.sackNeeded=true;this.sackImmediate=true;if(uint32Gte(this.lastReceivedTsn,e.cumulativeTsn))return;const isObsolete=e=>uint32Gt(e,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn;this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(isObsolete));for(const e of[...this.sackMisOrdered].sort())if(e===tsnPlusOne(this.lastReceivedTsn))this.lastReceivedTsn=e;else break;this.sackDuplicates=this.sackDuplicates.filter(isObsolete);this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(isObsolete));for(const[t,n]of e.streams){const e=this.getInboundStream(t);e.streamSequenceNumber=uint16Add(n,1);for(const t of e.popMessages()){this.advertisedRwnd+=t[2].length;this.receive(...t)}}Object.values(this.inboundStreams).forEach(e=>{this.advertisedRwnd+=e.pruneChunks(this.lastReceivedTsn)})}updateRto(e){if(!this.srtt){this.rttvar=e/2;this.srtt=e}else{this.rttvar=(1-SCTP_RTO_BETA)*this.rttvar+SCTP_RTO_BETA*Math.abs(this.srtt-e);this.srtt=(1-SCTP_RTO_ALPHA)*this.srtt+SCTP_RTO_ALPHA*e}this.rto=Math.max(SCTP_RTO_MIN,Math.min(this.srtt+4*this.rttvar,SCTP_RTO_MAX))}receive(e,t,n){this.onReceive.execute(e,t,n)}getInboundStream(e){if(!this.inboundStreams[e])this.inboundStreams[e]=new InboundStream;return this.inboundStreams[e]}markReceived(e){if(uint32Gte(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e)){this.sackDuplicates.push(e);return true}this.sackMisOrdered.add(e);for(const e of[...this.sackMisOrdered].sort())if(e===tsnPlusOne(this.lastReceivedTsn))this.lastReceivedTsn=e;else break;const isObsolete=e=>uint32Gt(e,this.lastReceivedTsn);this.sackDuplicates=this.sackDuplicates.filter(isObsolete);this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(isObsolete));return false}send=async(e,t,n,{expiry:r,maxRetransmits:i,ordered:a}={expiry:void 0,maxRetransmits:void 0,ordered:true})=>{const o=a?this.outboundStreamSeq[e]||0:0;const s=Math.ceil(n.length/this.maxPayloadSize);let c=0;const u=[];for(let d=0;d<s;d++){const f=new DataChunk(0,void 0);f.flags=0;if(!a)f.flags=SCTP_DATA_UNORDERED;if(d===0)f.flags|=SCTP_DATA_FIRST_FRAG;if(d===s-1)f.flags|=SCTP_DATA_LAST_FRAG;f.tsn=this.localTsn;f.streamId=e;f.streamSeqNum=o;f.protocol=t;f.userData=n.slice(c,c+this.maxPayloadSize);f.bookSize=f.userData.length;f.expiry=r;f.maxRetransmits=i;c+=this.maxPayloadSize;this.localTsn=tsnPlusOne(this.localTsn);u.push(f)}u.forEach(e=>{this.outboundQueue.push(e)});if(a)this.outboundStreamSeq[e]=uint16Add(o,1);await this.transmit();while(this.outboundQueue.length)await this.flush.asPromise()};async transmit(){if(this.isStopped)return;if(this.transmitting){this.transmitRequested=true;return}this.transmitting=true;try{do{this.transmitRequested=false;await this.transmitOnce()}while(this.transmitRequested)}finally{this.transmitting=false}}async transmitOnce(){if(this.isStopped)return;if(this.forwardTsnChunk){await this.sendChunk(this.forwardTsnChunk).catch(e=>{log28(`send forwardTsn failed`,e.message)});this.forwardTsnChunk=void 0;if(!this.timer3Handle)this.timer3Start()}const e=this.fastRecoveryExit!=void 0?2*this.maxPayloadSize:4*this.maxPayloadSize;const t=Math.min(this.flightSize+e,this.cwnd);let n=true;for(const e of this.sentQueue){if(e.retransmit){if(this.fastRecoveryTransmit)this.fastRecoveryTransmit=false;else if(this.flightSize>=t)break;this.flightSizeIncrease(e);e.misses=0;e.retransmit=false;e.sentCount++;await this.sendChunk(e).catch(e=>{log28(`send data failed`,e.message)});if(n)this.timer3Restart()}n=false}while(this.outboundQueue.length>0&&this.flightSize<t&&this.peerRwnd>0){const e=this.outboundQueue.shift();if(!e)break;if(e.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(e);break}this.sentQueue.push(e);this.flightSizeIncrease(e);e.sentCount++;e.sentTime=Date.now()/1e3;await this.sendChunk(e).catch(e=>{log28(`send data outboundQueue failed`,e.message)});if(!this.timer3Handle)this.timer3Start()}if(!this.outboundQueue.length)this.outboundQueue=[];this.flush.execute()}async transmitReconfigRequest(){if(this.reconfigQueue.length>0&&this.associationState===4&&!this.reconfigRequest){const e=[...new Set(this.reconfigQueue)];const t=e.slice(0,RECONFIG_MAX_STREAMS);this.reconfigQueue=e.slice(RECONFIG_MAX_STREAMS);const n=new OutgoingSSNResetRequestParam(this.reconfigRequestSeq,this.reconfigResponseSeq,tsnMinusOne(this.localTsn),t);this.reconfigRequestSeq=tsnPlusOne(this.reconfigRequestSeq);this.reconfigRequest=n;await this.sendReconfigParam(n);this.timerReconfigHandleStart()}}async sendReconfigParam(e){log28(`sendReconfigParam`,e);const t=new ReconfigChunk;t.params.push([e.type,e.bytes]);await this.sendChunk(t).catch(e=>{log28(`send reconfig failed`,e.message)})}async sendResetRequest(e){log28(`sendResetRequest`,e);const t=new DataChunk(0,void 0);t.streamId=e;this.outboundQueue.push(t);if(!this.timer3Handle)await this.transmit()}flightSizeIncrease(e){this.flightSize+=e.bookSize}flightSizeDecrease(e){this.flightSize=Math.max(0,this.flightSize-e.bookSize)}timer1Start(e){if(this.timer1Handle)throw new Error;this.timer1Chunk=e;this.timer1Failures=0;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}timer1Expired=()=>{if(this.isStopped)return;this.timer1Failures++;this.timer1Handle=void 0;if(this.timer1Failures>SCTP_MAX_INIT_RETRANS)this.setState(1);else{setImmediate(()=>{if(this.isStopped)return;this.sendChunk(this.timer1Chunk).catch(e=>{log28(`send timer1 chunk failed`,e.message)})});if(this.isStopped)return;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}};timer1Cancel(){if(this.timer1Handle){clearTimeout(this.timer1Handle);this.timer1Handle=void 0;this.timer1Chunk=void 0}}t2Start(e){if(this.timer2Handle)throw new Error;this.timer2Chunk=e;this.timer2Failures=0;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}timer2Expired=()=>{if(this.isStopped)return;this.timer2Failures++;this.timer2Handle=void 0;if(this.timer2Failures>SCTP_MAX_ASSOCIATION_RETRANS)this.setState(1);else{setImmediate(()=>{if(this.isStopped)return;this.sendChunk(this.timer2Chunk).catch(e=>{log28(`send timer2Chunk failed`,e.message)})});if(this.isStopped)return;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}};timer2Cancel(){if(this.timer2Handle){clearTimeout(this.timer2Handle);this.timer2Handle=void 0;this.timer2Chunk=void 0}}timer3Start(){if(this.isStopped)return;if(this.timer3Handle)throw new Error;this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}timer3Restart(){if(this.isStopped)return;this.timer3Cancel();this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}timer3Expired=()=>{if(this.isStopped)return;this.timer3Handle=void 0;this.sentQueue.forEach(e=>{if(!this.maybeAbandon(e))e.retransmit=true});this.updateAdvancedPeerAckPoint();this.fastRecoveryExit=void 0;this.flightSize=0;this.partialBytesAcked=0;this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*this.maxPayloadSize);this.cwnd=this.maxPayloadSize;this.transmit()};timer3Cancel(){if(this.timer3Handle){clearTimeout(this.timer3Handle);this.timer3Handle=void 0}}timerReconfigHandleStart(){if(this.isStopped)return;if(this.timerReconfigHandle)return;log28(`timerReconfigHandleStart`,{rto:this.rto});this.timerReconfigFailures=0;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}timerReconfigHandleExpired=async()=>{if(this.isStopped)return;this.timerReconfigFailures++;this.rto=Math.ceil(this.rto*1.5);if(this.timerReconfigFailures>SCTP_MAX_ASSOCIATION_RETRANS){log28(`timerReconfigFailures`,this.timerReconfigFailures);this.setState(1);this.timerReconfigHandle=void 0}else if(this.reconfigRequest){log28(`timerReconfigHandleExpired`,this.timerReconfigFailures,this.rto);await this.sendReconfigParam(this.reconfigRequest);if(this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}};timerReconfigCancel(){if(this.timerReconfigHandle){log28(`timerReconfigCancel`);clearTimeout(this.timerReconfigHandle);this.timerReconfigHandle=void 0;this.timerReconfigFailures=0}}heartbeatStart(){if(this.timerHeartbeatHandle||this.associationState!==4)return;this.timerHeartbeatHandle=setTimeout(this.timerHeartbeatExpired,(this.rto+this.heartbeatInterval)*1e3)}heartbeatRestart(){this.heartbeatCancel();this.heartbeatStart()}heartbeatCancel(){if(this.timerHeartbeatHandle){clearTimeout(this.timerHeartbeatHandle);this.timerHeartbeatHandle=void 0}}timerHeartbeatExpired=async()=>{this.timerHeartbeatHandle=void 0;if(this.associationState!==4)return;if(this.flightSize===0&&this.outboundQueue.length===0){const e=new HeartbeatChunk;const t=Buffer.allocUnsafe(4);t.writeUInt32BE(Math.floor(Date.now()/1e3),0);e.params.push([1,t]);await this.sendChunk(e).catch(e=>{log28(`send heartbeat failed`,e.message)})}this.heartbeatStart()};setHeartbeatInterval(e){if(e<=0)throw new Error(`heartbeat interval must be > 0`);this.heartbeatInterval=e;this.heartbeatRestart()}updateAdvancedPeerAckPoint(){if(uint32Gt(this.lastSackedTsn,this.advancedPeerAckTsn))this.advancedPeerAckTsn=this.lastSackedTsn;let e=0;const t={};while(this.sentQueue.length>0&&this.sentQueue[0].abandoned){const n=this.sentQueue.shift();this.advancedPeerAckTsn=n.tsn;e++;if(!(n.flags&SCTP_DATA_UNORDERED))t[n.streamId]=n.streamSeqNum}if(!this.sentQueue.length)this.sentQueue=[];if(e){this.forwardTsnChunk=new ForwardTsnChunk(0,void 0);this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn;this.forwardTsnChunk.streams=Object.entries(t).map(([e,t])=>[Number(e),t])}}maybeAbandon(e){if(e.abandoned)return true;if(!(!!e.maxRetransmits&&e.maxRetransmits<e.sentCount||!!e.expiry&&e.expiry<Date.now()/1e3))return false;const t=this.sentQueue.findIndex(t=>t.type===e.type);for(let e=t;e>=0;e--){const t=this.sentQueue[e];t.abandoned=true;t.retransmit=false;if(t.flags&SCTP_DATA_LAST_FRAG)break}for(let e=t;e<this.sentQueue.length;e++){const t=this.sentQueue[e];t.abandoned=true;t.retransmit=false;if(t.flags&SCTP_DATA_LAST_FRAG)break}return true}static getCapabilities(){return new RTCSctpCapabilities(65536)}setRemotePort(e){this.remotePort=e}async start(e){if(!this.started){this.started=true;this.setConnectionState(`connecting`);if(e)this.setRemotePort(e);if(!this.isServer)await this.init()}}async init(){const e=new InitChunk;e.initiateTag=this.localVerificationTag;e.advertisedRwnd=this.advertisedRwnd;e.outboundStreams=this._outboundStreamsCount;e.inboundStreams=this._inboundStreamsMax;e.initialTsn=this.localTsn;this.setExtensions(e.params);log28(`send init`,e);try{await this.sendChunk(e);this.timer1Start(e);this.setState(2)}catch(e){log28(`send init failed`,e.message)}}setExtensions(e){const t=[];if(this.localPartialReliability){e.push([SCTP_PRSCTP_SUPPORTED,Buffer.from(``)]);t.push(ForwardTsnChunk.type)}t.push(ReConfigChunk.type);e.push([SCTP_SUPPORTED_CHUNK_EXT,Buffer.from(t)])}async sendChunk(e){if(this.state===`closed`)return;if(this.remotePort===void 0)throw new Error(`invalid remote port`);const t=serializePacket(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(t)}setState(e){if(e!=this.associationState)this.associationState=e;if(e===4){this.isStopping=false;this.isClosed=false;this.setConnectionState(`connected`);this.heartbeatStart()}else if(e===1){this.isClosed=true;this.timer1Cancel();this.timer2Cancel();this.timer3Cancel();this.timerReconfigCancel();this.heartbeatCancel();if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}this.setConnectionState(`closed`);this.removeAllListeners()}}setConnectionState(e){this.state=e;log28(`setConnectionState`,e);this.stateChanged[e].execute()}async stop(){if(this.isStopped){this.setState(1);return}this.isStopping=true;this.transport.onData=void 0;if(this.sackTimeout){clearTimeout(this.sackTimeout);this.sackTimeout=void 0}if(this.associationState!==1)await this.abort();this.setState(1);clearTimeout(this.timer1Handle);clearTimeout(this.timer2Handle);clearTimeout(this.timer3Handle);clearTimeout(this.timerReconfigHandle);clearTimeout(this.timerHeartbeatHandle);clearTimeout(this.sackTimeout)}async abort(){const e=new AbortChunk;await this.sendChunk(e).catch(e=>{log28(`send abort failed`,e.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}};var InboundStream=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(e){if(this.reassembly.length===0||uint32Gt(e.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(e);return}for(const[t,n]of enumerate3(this.reassembly)){if(n.tsn===e.tsn)throw new Error(`duplicate chunk in reassembly`);if(uint32Gt(n.tsn,e.tsn)){this.reassembly.splice(t,0,e);break}}}*popMessages(){let e=0;let t;let n;let r;while(e<this.reassembly.length){const i=this.reassembly[e];if(t===void 0){r=!(i.flags&SCTP_DATA_UNORDERED);if(!(i.flags&SCTP_DATA_FIRST_FRAG)){if(r)break;else{e++;continue}}if(r&&uint16Gt(i.streamSeqNum,this.streamSequenceNumber))break;n=i.tsn;t=e}else if(i.tsn!==n){if(r)break;else{t=void 0;e++;continue}}if(i.flags&SCTP_DATA_LAST_FRAG){const n=this.reassembly.slice(t,e+1).map(e=>e.userData).reduce((e,t)=>{e.push(t);e.push(Buffer.from(``));return e},[]);n.pop();const a=Buffer.concat(n);this.reassembly=[...this.reassembly.slice(0,t),...this.reassembly.slice(e+1)];if(r&&i.streamSeqNum===this.streamSequenceNumber)this.streamSequenceNumber=uint16Add(this.streamSequenceNumber,1);e=t;yield[i.streamId,i.protocol,a]}else e++;n=tsnPlusOne(n)}}pruneChunks(e){let t=-1,n=0;for(const[r,i]of this.reassembly.entries())if(uint32Gte(e,i.tsn)){t=r;n+=i.userData.length}else break;this.reassembly=this.reassembly.slice(t+1);return n}};var RTCSctpCapabilities=class{constructor(e){this.maxMessageSize=e}};function tsnMinusOne(e){return(e-1)%SCTP_TSN_MODULO}function tsnPlusOne(e){return(e+1)%SCTP_TSN_MODULO}var log29=debug(`werift:packages/webrtc/src/transport/sctp.ts`);var DEFAULT_MAX_MESSAGE_SIZE=65536;var RTCSctpTransport=class _RTCSctpTransport{constructor(e=5e3,t=DEFAULT_MAX_MESSAGE_SIZE,n={}){this.port=e;this.maxMessageSize=t;this.sctpOptions=n}dtlsTransport;sctp;onDataChannel=new Event2;id=randomUUID$1().toString();mid;mLineIndex;bundled=false;dataChannels={};remoteMaxMessageSize=DEFAULT_MAX_MESSAGE_SIZE;dataChannelQueue=[];dataChannelId;eventDisposer=[];get transport(){return this.dtlsTransport}setDtlsTransport(e){if(this.dtlsTransport&&this.dtlsTransport.id===e.id)return;this.eventDisposer.forEach(e=>e());this.dtlsTransport=e;this.sctp=new SCTP(new BridgeDtls(this.dtlsTransport),this.port,this.sctpOptions);this.eventDisposer=[...[this.sctp.onReceive.subscribe(this.datachannelReceive),this.sctp.onReconfigStreams.subscribe(e=>{e.forEach(e=>{const t=this.dataChannels[e];if(!t)return;t.setReadyState(`closing`);t.setReadyState(`closed`);delete this.dataChannels[e]})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(e=>{if(e.negotiated&&e.readyState!==`open`)e.setReadyState(`open`)});this.dataChannelFlush()}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(e=>{e.setReadyState(`closed`)});this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(e=>{if(e===`closed`)this.sctp.setState(1)})].map(e=>e.unSubscribe),()=>this.sctp.onSackReceived=async()=>{}];this.sctp.onSackReceived=async()=>{await this.dataChannelFlush()}}get isServer(){return this.dtlsTransport.iceTransport.role!==`controlling`}channelByLabel(e){return Object.values(this.dataChannels).find(t=>t.label===e)}datachannelReceive=async(e,t,n)=>{if(t===WEBRTC_DCEP&&n.length>0){log29(`DCEP`,e,t,n);switch(n[0]){case DATA_CHANNEL_OPEN:{if(n.length<12){log29(`DATA_CHANNEL_OPEN data.length not enough`);return}if(!Object.keys(this.dataChannels).includes(e.toString())){const t=n.readUInt8(1);const r=n.readUInt32BE(4);const i=n.readUInt16BE(8);const a=n.readUInt16BE(10);let o=12;const s=n.slice(o,o+i).toString(`utf8`);o+=i;const c=n.slice(o,o+a).toString(`utf8`);log29(`DATA_CHANNEL_OPEN`,{channelType:t,reliability:r,streamId:e,label:s,protocol:c});const u=(t&3)===1?r:void 0;const d=(t&3)===2?r:void 0;const f=new RTCDataChannelParameters({label:s,ordered:(t&128)===0,maxPacketLifeTime:d,maxRetransmits:u,protocol:c,id:e});const p=new RTCDataChannel(this,f,false);p.isCreatedByRemote=true;this.dataChannels[e]=p;this.onDataChannel.execute(p);p.setReadyState(`open`)}else log29(`datachannel already opened`,`retransmit ack`);const t=this.dataChannels[e];const r=Buffer.allocUnsafe(1);r.writeUInt8(DATA_CHANNEL_ACK,0);this.dataChannelQueue.push([t,WEBRTC_DCEP,r]);await this.dataChannelFlush()}break;case DATA_CHANNEL_ACK:{log29(`DATA_CHANNEL_ACK`,e,t);const n=this.dataChannels[e];if(!n)throw new Error(`channel not found`);n.setReadyState(`open`)}}}else{const r=this.dataChannels[e];if(r){const e=(()=>{switch(t){case WEBRTC_STRING:return n.toString(`utf8`);case WEBRTC_STRING_EMPTY:return``;case WEBRTC_BINARY:return n;case WEBRTC_BINARY_EMPTY:return Buffer.from([]);default:throw new Error}})();r.messagesReceived++;r.bytesReceived+=n.length;r.onMessage.execute(e);r.emit(`message`,{data:e});if(r.onmessage)r.onmessage({data:e})}}};dataChannelAddNegotiated(e){if(e.id==void 0)throw new Error;if(this.dataChannels[e.id])throw new Error;this.dataChannels[e.id]=e;if(this.sctp.associationState===4)e.setReadyState(`open`)}dataChannelOpen(e){if(e.id!==void 0){if(this.dataChannels[e.id])throw new Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let t=DATA_CHANNEL_RELIABLE;const n=0;let r=0;if(!e.ordered)t=128;if(e.maxRetransmits!==null){t=1;r=e.maxRetransmits}else if(e.maxPacketLifeTime!==null){t=2;r=e.maxPacketLifeTime}const i=Buffer.allocUnsafe(12);i.writeUInt8(DATA_CHANNEL_OPEN,0);i.writeUInt8(t,1);i.writeUInt16BE(n,2);i.writeUInt32BE(r,4);i.writeUInt16BE(e.label.length,8);i.writeUInt16BE(e.protocol.length,10);const a=Buffer.concat([i,Buffer.from(e.label,`utf8`),Buffer.from(e.protocol,`utf8`)]);this.dataChannelQueue.push([e,WEBRTC_DCEP,a]);this.dataChannelFlush()}async dataChannelFlush(){if(this.sctp.associationState!=4)return;while(this.dataChannelQueue.length>0){const[e,t,n]=this.dataChannelQueue.shift();let r=e.id;if(r===void 0){r=this.dataChannelId;while(Object.keys(this.dataChannels).includes(r.toString()))r+=2;this.dataChannels[r]=e;e.setId(r)}if(t===WEBRTC_DCEP)await this.sctp.send(r,t,n,{ordered:true});else{const i=e.maxPacketLifeTime!==null?Date.now()+e.maxPacketLifeTime/1e3:void 0;await this.sctp.send(r,t,n,{expiry:i,maxRetransmits:e.maxRetransmits??void 0,ordered:e.ordered});e.addBufferedAmount(-n.length)}}this.dataChannelQueue=[]}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize)throw new Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}datachannelSend=(e,t)=>{const n=Buffer.isBuffer(t)?t:Buffer.from(t);const r=getDataChannelMessageSize(t);this.assertSendableMessageSize(r);e.addBufferedAmount(r);this.dataChannelQueue.push(typeof t===`string`?[e,WEBRTC_STRING,n]:[e,WEBRTC_BINARY,n]);if(this.sctp.associationState!==4)log29(`sctp not established`,this.sctp.associationState);this.dataChannelFlush();return r};getCapabilities(){return _RTCSctpTransport.getCapabilities(this.maxMessageSize)}static getCapabilities(e=DEFAULT_MAX_MESSAGE_SIZE){return new RTCSctpCapabilities2(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??65536}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){if(this.isServer)this.dataChannelId=0;else this.dataChannelId=1;this.sctp.isServer=this.isServer;await this.sctp.start(e)}async stop(){this.dtlsTransport.dataReceiver=()=>{};await this.sctp.stop()}dataChannelClose(e){if(![`closing`,`closed`].includes(e.readyState)){e.setReadyState(`closing`);if(this.sctp.associationState===4){if(!this.sctp.reconfigQueue.includes(e.id))this.sctp.reconfigQueue.push(e.id);if(this.sctp.reconfigQueue.length===1)this.sctp.transmitReconfigRequest()}else{this.dataChannelQueue=this.dataChannelQueue.filter(t=>t[0].id!==e.id);this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(t=>t!==e.id);if(e.id!==void 0)delete this.dataChannels[e.id];e.setReadyState(`closed`)}}}};var RTCSctpCapabilities2=class{constructor(e){this.maxMessageSize=e}};var BridgeDtls=class{constructor(e){this.dtls=e}set onData(e){this.dtls.dataReceiver=e}send=e=>{return this.dtls.sendData(e)};close(){}};var SessionDescription=class _SessionDescription{version=0;origin;name=`-`;time=`0 0`;host;group=[];extMapAllowMixed=true;msidSemantic=[];media=[];type;dtlsRole;iceOptions;iceLite;icePassword;iceUsernameFragment;dtlsFingerprints=[];cachedJson;static parse(e){const[t,n]=groupLines(e);const r=new _SessionDescription;t.forEach(e=>{if(e.startsWith(`v=`))r.version=Number.parseInt(e.slice(2),10);else if(e.startsWith(`o=`))r.origin=e.slice(2);else if(e.startsWith(`s=`))r.name=e.slice(2);else if(e.startsWith(`c=`))r.host=ipAddressFromSdp(e.slice(2));else if(e.startsWith(`t=`))r.time=e.slice(2);else if(e.startsWith(`a=`)){const[t,n]=parseAttr(e);switch(t){case`fingerprint`:{const[e,t]=n?.split(` `)||[];r.dtlsFingerprints.push(new RTCDtlsFingerprint(e,t))}break;case`ice-lite`:r.iceLite=true;break;case`ice-options`:r.iceOptions=n;break;case`ice-pwd`:r.icePassword=n;break;case`ice-ufrag`:r.iceUsernameFragment=n;break;case`group`:parseGroup(r.group,n);break;case`msid-semantic`:parseGroup(r.msidSemantic,n);break;case`setup`:r.dtlsRole=DTLS_SETUP_ROLE[n];break;case`extmap-allow-mixed`:r.extMapAllowMixed=true}}});const i=r.group.find(e=>e.semantic===`BUNDLE`);n.forEach(e=>{const t=e[0].match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!t)throw new Error(`m line not found`);const n=t[1];const a=t[4].split(` `);const o=[`audio`,`video`].includes(n)?a.map(e=>Number(e)):void 0;const s=new MediaDescription(n,Number.parseInt(t[2]),t[3],o||a);s.dtlsParams=new RTCDtlsParameters([...r.dtlsFingerprints],r.dtlsRole);s.iceParams=new RTCIceParameters({iceLite:r.iceLite,usernameFragment:r.iceUsernameFragment,password:r.icePassword});s.iceOptions=r.iceOptions;r.media.push(s);e.slice(1).forEach(e=>{if(e.startsWith(`c=`))s.host=ipAddressFromSdp(e.slice(2));else if(e.startsWith(`a=`)){const[t,n]=parseAttr(e);switch(t){case`candidate`:if(!n)throw new Error;s.iceCandidates.push(candidateFromSdp(n));break;case`end-of-candidates`:s.iceCandidatesComplete=true;break;case`extmap`:{let[e,t]=n.split(` `);if(e.includes(`/`))[e]=e.split(`/`);s.rtp.headerExtensions.push(new RTCRtpHeaderExtensionParameters({id:Number.parseInt(e),uri:t}))}break;case`fingerprint`:{if(!n)throw new Error;const[e,t]=n.split(` `);s.dtlsParams?.fingerprints.push(new RTCDtlsFingerprint(e,t))}break;case`ice-options`:s.iceOptions=n;break;case`ice-pwd`:s.iceParams.password=n;break;case`ice-ufrag`:s.iceParams.usernameFragment=n;break;case`ice-lite`:s.iceParams.iceLite=true;break;case`max-message-size`:s.sctpCapabilities=new RTCSctpCapabilities2(Number.parseInt(n,10));break;case`mid`:s.rtp.muxId=n;break;case`msid`:s.msids.push(n);break;case`rtcp`:{const[e,t]=divide(n,` `);s.rtcpPort=Number.parseInt(e);s.rtcpHost=ipAddressFromSdp(t)}break;case`rtcp-mux`:s.rtcpMux=true;break;case`setup`:s.dtlsParams.role=DTLS_SETUP_ROLE[n];break;case`recvonly`:case`sendonly`:case`sendrecv`:case`inactive`:s.direction=t;break;case`rtpmap`:{const[e,t]=divide(n,` `);const[r,i,a]=t.split(`/`);let o;if(s.kind===`audio`)o=a?Number.parseInt(a):1;const c=new RTCRtpCodecParameters({mimeType:s.kind+`/`+r,channels:o,clockRate:Number.parseInt(i),payloadType:Number.parseInt(e)});s.rtp.codecs.push(c)}break;case`sctpmap`:{if(!n)throw new Error;const[e,t]=divide(n,` `);s.sctpMap[Number.parseInt(e)]=t;s.sctpPort=Number.parseInt(e)}break;case`sctp-port`:if(!n)throw new Error;s.sctpPort=Number.parseInt(n);break;case`ssrc`:{const[e,t]=divide(n,` `);const r=Number.parseInt(e);const[i,a]=divide(t,`:`);let o=s.ssrc.find(e=>e.ssrc===r);if(!o){o=new SsrcDescription({ssrc:r});s.ssrc.push(o)}if(SSRC_INFO_ATTRS.includes(i))o[i]=a}break;case`ssrc-group`:parseGroup(s.ssrcGroup,n);break;case`rid`:{const[e,t]=divide(n,` `);s.simulcastParameters.push(new RTCRtpSimulcastParameters({rid:e,direction:t}))}}}});if(!s.iceParams.usernameFragment||!s.iceParams.password){if(s.rtp.muxId&&i&&i.items.includes(s.rtp.muxId))for(let e=0;e<i.items.length;e++){if(!i.items.includes(e.toString()))continue;const t=r.media[e];if(t.iceParams?.usernameFragment&&t.iceParams.password){s.iceParams={...t.iceParams};break}}}if(!s.dtlsParams.role)s.dtlsParams=void 0;const findCodec=e=>s.rtp.codecs.find(t=>t.payloadType===e);e.slice(1).forEach(e=>{if(e.startsWith(`a=`)){const[t,n]=parseAttr(e);if(t===`fmtp`){const[e,t]=divide(n,` `);const r=findCodec(Number(e));r.parameters=t}else if(t===`rtcp-fb`){const[e,t,r]=n.split(` `);s.rtp.codecs.forEach(n=>{if([`*`,n.payloadType.toString()].includes(e))n.rtcpFeedback.push(new RTCRtcpFeedback({type:t,parameter:r}))})}}})});return r}webrtcTrackId(e){if(e.msid?.includes(` `)){const t=e.msid.split(` `);for(const e of this.msidSemantic)if(e.semantic===`WMS`&&(e.items.includes(t[0])||e.items.includes(`*`)))return t[1]}}get string(){const e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];if(this.host)e.push(`c=${ipAddressToSdp(this.host)}`);e.push(`t=${this.time}`);this.group.forEach(t=>e.push(`a=group:${t.str}`));if(this.extMapAllowMixed)e.push(`a=extmap-allow-mixed`);this.msidSemantic.forEach(t=>e.push(`a=msid-semantic:${t.str}`));const t=this.media.map(e=>e.toString()).join(``);return e.join(`\r
`)+`\r
`+t}toJSON(){const e=this.string;if(!this.cachedJson||this.cachedJson.sdp!==e||this.cachedJson.type!==this.type)this.cachedJson=new RTCSessionDescription(e,this.type);return this.cachedJson}toSdp(){return{type:this.type,sdp:this.string}}};var MediaDescription=class{constructor(e,t,n,r){this.kind=e;this.port=t;this.profile=n;this.fmt=r}host;direction;msids=[];rtcpPort;rtcpHost;rtcpMux=false;ssrc=[];ssrcGroup=[];rtp={codecs:[],headerExtensions:[]};sctpCapabilities;sctpMap={};sctpPort;dtlsParams;iceParams;iceCandidates=[];iceCandidatesComplete=false;iceOptions;simulcastParameters=[];get msid(){return this.msids[0]}set msid(e){this.msids=e?[e]:[]}toString(){const e=[];e.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map(e=>e.toString()).join(` `)}`);if(this.host)e.push(`c=${ipAddressToSdp(this.host)}`);this.iceCandidates.forEach(t=>{e.push(`a=candidate:${candidateToSdp(t)}`)});if(this.iceCandidatesComplete)e.push(`a=end-of-candidates`);if(this.iceParams?.usernameFragment)e.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`);if(this.iceParams?.password)e.push(`a=ice-pwd:${this.iceParams.password}`);if(this.iceParams?.iceLite)e.push(`a=ice-lite`);if(this.iceOptions)e.push(`a=ice-options:${this.iceOptions}`);if(this.dtlsParams){this.dtlsParams.fingerprints.forEach(t=>{e.push(`a=fingerprint:${t.algorithm} ${t.value}`)});e.push(`a=setup:${DTLS_ROLE_SETUP[this.dtlsParams.role]}`)}if(this.direction)e.push(`a=${this.direction}`);if(this.rtp.muxId)e.push(`a=mid:${this.rtp.muxId}`);this.msids.forEach(t=>e.push(`a=msid:${t}`));if(this.rtcpPort&&this.rtcpHost){e.push(`a=rtcp:${this.rtcpPort} ${ipAddressToSdp(this.rtcpHost)}`);if(this.rtcpMux)e.push(`a=rtcp-mux`)}this.ssrcGroup.forEach(t=>{e.push(`a=ssrc-group:${t.str}`)});this.ssrc.forEach(t=>{SSRC_INFO_ATTRS.forEach(n=>{const r=t[n];if(r!==void 0)e.push(`a=ssrc:${t.ssrc} ${n}:${r}`)})});this.rtp.codecs.forEach(t=>{e.push(`a=rtpmap:${t.payloadType} ${t.str}`);t.rtcpFeedback.forEach(n=>{let r=n.type;if(n.parameter)r+=` ${n.parameter}`;e.push(`a=rtcp-fb:${t.payloadType} ${r}`)});if(t.parameters)e.push(`a=fmtp:${t.payloadType} ${t.parameters}`)});Object.keys(this.sctpMap).forEach(t=>{const n=this.sctpMap[Number(t)];e.push(`a=sctpmap:${t} ${n}`)});if(this.sctpPort)e.push(`a=sctp-port:${this.sctpPort}`);if(this.sctpCapabilities)e.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`);this.rtp.headerExtensions.forEach(t=>e.push(`a=extmap:${t.id} ${t.uri}`));if(this.simulcastParameters.length){this.simulcastParameters.forEach(t=>{e.push(`a=rid:${t.rid} ${t.direction}`)});let t=`a=simulcast:`;const n=this.simulcastParameters.filter(e=>e.direction===`recv`);if(n.length)t+=`recv ${n.map(e=>e.rid).join(`;`)} `;const r=this.simulcastParameters.filter(e=>e.direction===`send`);if(r.length)t+=`send ${r.map(e=>e.rid).join(`;`)}`;e.push(t)}return e.join(`\r
`)+`\r
`}};var GroupDescription=class{constructor(e,t){this.semantic=e;this.items=t}get str(){return`${this.semantic} ${this.items.join(` `)}`}};function ipAddressFromSdp(e){const t=e.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!t)throw new Error(`exception`);return t[2]}function ipAddressToSdp(e){return`IN IP${isIPv4$1(e)?4:6} ${e}`}function candidateToSdp(e){let t=`${e.foundation} ${e.component} ${e.protocol} ${e.priority} ${e.ip} ${e.port} typ ${e.type}`;if(e.relatedAddress!=void 0)t+=` raddr ${e.relatedAddress}`;if(e.relatedPort!=void 0)t+=` rport ${e.relatedPort}`;if(e.tcpType!=void 0)t+=` tcptype ${e.tcpType}`;if(e.generation!=void 0)t+=` generation ${e.generation}`;if(e.ufrag!=void 0)t+=` ufrag ${e.ufrag}`;return t}function groupLines(e){const t=[];const n=[];let r=e.split(`\r
`);if(r.length===1)r=e.split(`
`);r.forEach(e=>{if(e.startsWith(`m=`))n.push([e]);else if(n.length>0)n[n.length-1].push(e);else t.push(e)});return[t,n]}function parseAttr(e){if(e.includes(`:`)){const t=divide(e.slice(2),`:`);return[t[0],t[1]]}else return[e.slice(2),void 0]}function parseGroup(e,t,n=e=>e.toString()){const r=t.split(` `);if(r.length>0)e.push(new GroupDescription(r[0],r.slice(1).map(n)))}function candidateFromSdp(e){return candidateFromIce(Candidate.fromSdp(e))}var RTCSessionDescription=class{sdp;type;constructor(e,t){Object.defineProperties(this,{sdp:{configurable:true,enumerable:true,value:e,writable:false},type:{configurable:true,enumerable:true,value:t,writable:false}})}static isThis(e){if(typeof e?.sdp===`string`)return true}toSdp(){return{sdp:this.sdp,type:this.type}}};function addSDPHeader(e,t){t.origin=`- ${randomBytes$1(8).readBigUInt64BE(0).toString().slice(0,8)} 0 IN IP4 0.0.0.0`;t.msidSemantic.push(new GroupDescription(`WMS`,[`*`]));t.type=e}function codecParametersFromString(e){const t={};e.split(`;`).forEach(e=>{if(e.length===0)return;if(e.includes(`=`)){const[n,r]=divide(e,`=`);if(FMTP_INT_PARAMETERS.includes(n))t[n]=Number(r);else t[n]=r}else if(e.includes(`:`)){const[n,r]=e.split(`:`);t[n]=Number.isNaN(Number(r))?r:Number(r)}else t[e]=void 0});return t}function codecParametersToString(e,t=`=`){const n=Object.entries(e).filter(([e,t])=>e.length>0&&t!==void 0).map(([e,n])=>`${e}${t}${n}`);if(n.length>0)return n.join(`;`)}var SsrcDescription=class{ssrc;cname;msid;msLabel;label;constructor(e){Object.assign(this,e)}};function normalizeCodecMimeType(e){const t=e.toLowerCase();return t===`video/av1x`?`video/av1`:t}function codecName(e){return e.name.toLowerCase()}function optionalEqual(e,t){return e==void 0||t==void 0||e===t}function h264Parameters(e){const t=codecParametersFromString(e.parameters??``);return{packetizationMode:t[`packetization-mode`],profileLevelId:t[`profile-level-id`]?.toString().toLowerCase()}}function isCodecCompatible(e,t){if(normalizeCodecMimeType(e.mimeType)!==normalizeCodecMimeType(t.mimeType))return false;if(e.clockRate!==t.clockRate)return false;if(!optionalEqual(e.channels,t.channels))return false;if(codecName(e)!==`h264`)return true;const n=h264Parameters(e);const r=h264Parameters(t);if(!optionalEqual(n.packetizationMode,r.packetizationMode))return false;return optionalEqual(n.profileLevelId,r.profileLevelId)}function isAuxiliary(e){return[`rtx`,`red`].includes(codecName(e))}function deliveredTrackCodec(e,t,n){if(e!==`audio`||t==void 0||codecName(t)!==`red`)return t;const[r]=referencedPayloadTypes(t);return n.find(e=>!isAuxiliary(e)&&e.payloadType===r)??n.find(e=>!isAuxiliary(e))??t}function hasCommonPrimaryMimeType(e,t){return e.some(e=>!isAuxiliary(e)&&t.some(t=>normalizeCodecMimeType(t.mimeType)===normalizeCodecMimeType(e.mimeType)))}function referencedPayloadTypes(e){const t=e.parameters??``;if(codecName(e)===`rtx`){const e=Number(codecParametersFromString(t).apt);return Number.isNaN(e)?[]:[e]}if(codecName(e)===`red`)return t.split(`/`).map(Number).filter(e=>!Number.isNaN(e));return[]}function withAuxiliaryCodecs(e,t){const n=new Set(t.map(e=>e.payloadType));const r=e.filter(e=>{if(!isAuxiliary(e))return false;const t=referencedPayloadTypes(e);return t.length>0&&t.every(e=>n.has(e))});return e.filter(e=>t.includes(e)||r.includes(e))}function intersectCodecs(e,t){return withAuxiliaryCodecs(e,e.filter(e=>!isAuxiliary(e)&&t.some(t=>isCodecCompatible(t,e))))}function matchesPreference(e,t){return normalizeCodecMimeType(e.mimeType)===normalizeCodecMimeType(t.mimeType)&&optionalEqual(e.clockRate,t.clockRate)}function applyCodecPreferences(e,t){if(t==void 0)return e;const n=t.flatMap(t=>{const n=e.find(e=>matchesPreference(e,t));return n?[n]:[]});const r=[...new Set(n)];const i=new Set(r.filter(isAuxiliary).flatMap(referencedPayloadTypes));const a=withAuxiliaryCodecs(e,e.filter(e=>!isAuxiliary(e)&&(r.includes(e)||i.has(e.payloadType))));return[...r.filter(e=>a.includes(e)),...a.filter(e=>!r.includes(e))]}function resolveCodecs(e,t,n){return applyCodecPreferences(t==void 0?e:intersectCodecs(e,t),n)}function list(e){return e?.map(e=>e.mimeType).join(`, `)||`(none)`}function assertCodecsSupported(e){const{kind:t,configured:n,source:r,preferences:i}=e;const a=r==void 0?n:intersectCodecs(n,r);if(r!=void 0&&a.length===0)throw createWebRtcDomException(`NotSupportedError`,`Track codec ${list(r)} is not supported by this RTCPeerConnection. Configured ${t} codecs: ${list(n)}`);const o=applyCodecPreferences(a,i);if(o.length===0)throw createWebRtcDomException(`NotSupportedError`,`No codec remains after applying codec preferences. Source codecs: ${list(r)} Configured codecs: ${list(n)} Preferred codecs: ${list(i)}`);return o}function useSdesMid(){return new RTCRtpHeaderExtensionParameters({uri:RTP_EXTENSION_URI.sdesMid})}function useSdesRTPStreamId(){return new RTCRtpHeaderExtensionParameters({uri:RTP_EXTENSION_URI.sdesRTPStreamID})}function useRepairedRtpStreamId(){return new RTCRtpHeaderExtensionParameters({uri:RTP_EXTENSION_URI.repairedRtpStreamId})}function useTransportWideCC(){return new RTCRtpHeaderExtensionParameters({uri:RTP_EXTENSION_URI.transportWideCC})}function useAbsSendTime(){return new RTCRtpHeaderExtensionParameters({uri:RTP_EXTENSION_URI.absSendTime})}function useDependencyDescriptor(){return new RTCRtpHeaderExtensionParameters({uri:RTP_EXTENSION_URI.dependencyDescriptor})}function useAudioLevelIndication(){return new RTCRtpHeaderExtensionParameters({uri:RTP_EXTENSION_URI.audioLevelIndication})}function useVideoOrientation(){return new RTCRtpHeaderExtensionParameters({uri:RTP_EXTENSION_URI.videoOrientation})}var log30=debug(`werift:packages/webrtc/src/media/receiver/nack.ts`);var LOST_SIZE=150;var NackHandler=class{constructor(e){this.receiver=e}newEstSeqNum=0;_lost={};nackLoop;onPacketLost=new Event2;mediaSourceSsrc;retryCount=10;closed=false;get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(e){return this._lost[e]}setLost(e,t){this._lost[e]=t;if(this.nackLoop||this.closed)return;this.nackLoop=setInterval(async()=>{try{await this.sendNack();if(!Object.keys(this._lost).length){clearInterval(this.nackLoop);this.nackLoop=void 0}}catch(e){log30(`failed to send nack`,e)}},5)}removeLost(e){delete this._lost[e]}addPacket(e){const{sequenceNumber:t,ssrc:n}=e.header;this.mediaSourceSsrc=n;if(this.newEstSeqNum===0){this.newEstSeqNum=t;return}if(this.getLost(t)){this.removeLost(t);return}if(t===uint16Add(this.newEstSeqNum,1))this.newEstSeqNum=t;else if(t>uint16Add(this.newEstSeqNum,1)){for(let e=uint16Add(this.newEstSeqNum,1);e<t;e=uint16Add(e,1))this.setLost(e,1);this.newEstSeqNum=t;this.pruneLost()}}pruneLost(){if(this.lostSeqNumbers.length>LOST_SIZE)this._lost=Object.entries(this._lost).slice(-LOST_SIZE).reduce((e,[t,n])=>{e[t]=n;return e},{})}close(){this.closed=true;clearInterval(this.nackLoop);this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(e=>{if(this._lost[e]++>this.retryCount){this.removeLost(e);return e}})}sendNack=()=>new Promise((e,t)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){const n=new GenericNack({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers});const r=new RtcpTransportLayerFeedback({feedback:n});this.receiver.dtlsTransport.sendRtcp([r]).then(e).catch(t);this.updateRetryCount();this.onPacketLost.execute(n)}})};var log31=debug(`werift:packages/webrtc/media/receiver/receiverTwcc`);var ReceiverTWCC=class{constructor(e,t,n){this.dtlsTransport=e;this.rtcpSsrc=t;this.mediaSourceSsrc=n;this.runTWCC()}extensionInfo={};twccRunning=false;fbPktCount=0;lastTimestamp;handleTWCC(e){this.extensionInfo[e]={tsn:e,timestamp:microTime()};if(Object.keys(this.extensionInfo).length>10)this.sendTWCC()}async runTWCC(){while(this.twccRunning){this.sendTWCC();await setTimeout$2(100)}}sendTWCC(){if(Object.keys(this.extensionInfo).length===0)return;const e=Object.values(this.extensionInfo).sort((e,t)=>e.tsn-t.tsn);const t=e[0].tsn;const n=e.slice(-1)[0].tsn;const r=[];const i=e[0].tsn;const a=uint16Add(n-t,1);let o;let s;const c=[];for(let e=t;e<=n;e++){const t=this.extensionInfo[e]?.timestamp;if(t){if(!this.lastTimestamp)this.lastTimestamp=t;if(!o)o=this.lastTimestamp;const i=t-this.lastTimestamp;this.lastTimestamp=t;const a=new RecvDelta({delta:Number(i)});a.parseDelta();c.push(a);if(s!=void 0&&s.status!==a.type){r.push(new RunLengthChunk({packetStatus:s.status,runLength:e-s.minTSN}));s={minTSN:e,status:a.type}}if(e===n){if(s!=void 0)r.push(new RunLengthChunk({packetStatus:s.status,runLength:e-s.minTSN+1}));else r.push(new RunLengthChunk({packetStatus:a.type,runLength:1}))}if(s==void 0)s={minTSN:e,status:a.type}}}if(!o)return;const u=new RtcpTransportLayerFeedback({feedback:new TransportWideCC({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:i,packetStatusCount:a,referenceTime:uint24(Math.floor(Number(o/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:r})});this.dtlsTransport.sendRtcp([u]).catch(e=>{log31(e)});this.extensionInfo={};this.fbPktCount=uint8Add(this.fbPktCount,1)}};var StreamStatistics=class{base_seq;max_seq;cycles=0;packets_received=0;bytesReceived=0;headerBytesReceived=0;lastPacketReceivedTimestamp;clockRate;jitter_q4=0;last_arrival;last_timestamp;expected_prior=0;received_prior=0;constructor(e){this.clockRate=e}add(e,t=Date.now()/1e3){const n=this.max_seq==void 0||uint16Gt(e.header.sequenceNumber,this.max_seq);this.packets_received++;this.bytesReceived+=e.payload.length;this.headerBytesReceived+=e.header.serializeSize;this.lastPacketReceivedTimestamp=getStatsTimestamp();if(this.base_seq==void 0)this.base_seq=e.header.sequenceNumber;if(n){const n=int(t*this.clockRate);if(this.max_seq!=void 0&&e.header.sequenceNumber<this.max_seq)this.cycles+=65536;this.max_seq=e.header.sequenceNumber;if(e.header.timestamp!==this.last_timestamp&&this.packets_received>1){const t=Math.abs(n-(this.last_arrival??0)-(e.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=t-(this.jitter_q4+8>>4)}this.last_arrival=n;this.last_timestamp=e.header.timestamp}}get fraction_lost(){const e=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;const t=this.packets_received-this.received_prior;this.received_prior=this.packets_received;const n=e-t;if(e==0||n<=0)return 0;else return Math.floor((n<<8)/e)}get jitter(){return this.jitter_q4>>4}get packets_expected(){return this.cycles+(this.max_seq??0)-(this.base_seq??0)+1}get packets_lost(){const e=this.packets_expected-this.packets_received;return e<0?0:e}};var log32=debug(`werift:packages/webrtc/src/media/rtpReceiver.ts`);var RTCRtpReceiver=class{constructor(e,t,n){this.config=e;this.kind=t;this.rtcpSsrc=n;this.defaultTrack=new MediaStreamTrack({kind:t,remote:true});this.onPacketLost.subscribe(e=>{this.nackCountBySsrc[e.mediaSourceSsrc]=(this.nackCountBySsrc[e.mediaSourceSsrc]??0)+1})}codecs={};defaultTrack;get codecArray(){return Object.values(this.codecs).sort((e,t)=>e.payloadType-t.payloadType)}ssrcByRtx={};nack=new NackHandler(this);audioRedHandler=new RedHandler;type=`receiver`;uuid=randomUUID$1().toString();tracks=[];trackBySSRC={};trackByRID={};lastSRtimestamp={};receiveLastSRTimestamp={};onPacketLost=this.nack.onPacketLost;onRtcp=new Event2;dtlsTransport;sdesMid;latestRid;latestRepairedRid;receiverTWCC;stopped=false;remoteStreamId;remoteStreamIds=[];remoteTrackId;rtcpRunning=false;rtcpCancel=new AbortController;remoteStreams={};senderReportsReceivedBySsrc={};remoteTimestampsBySsrc={};remotePacketCountBySsrc={};remoteOctetCountBySsrc={};nackCountBySsrc={};pliCountBySsrc={};get transport(){return this.dtlsTransport??null}setDtlsTransport(e){this.dtlsTransport=e}get track(){return this.tracks[0]??this.defaultTrack}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===`nack`)}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===useTWCC().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(e=>e.type===usePLI().type)}prepareReceive(e){e.codecs.forEach(e=>{this.codecs[e.payloadType]=e});e.encodings.forEach(e=>{if(e.rtx)this.ssrcByRtx[e.rtx.ssrc]=e.ssrc})}resyncCodecs(e,t){for(const e of Object.keys(this.codecs))delete this.codecs[Number(e)];for(const e of Object.keys(this.ssrcByRtx))delete this.ssrcByRtx[Number(e)];this.prepareReceive(e);const n=deliveredTrackCodec(this.kind,e.codecs[0],e.codecs);if(n)for(const e of this.tracks)e.codec=n;this.receiverTWCC=void 0;if(t!=void 0)this.setupTWCC(t)}setupTWCC(e){if(this.twccEnabled&&!this.receiverTWCC)this.receiverTWCC=new ReceiverTWCC(this.dtlsTransport,this.rtcpSsrc,e)}addTrack(e){if(this.tracks.find(t=>{if(t.rid)return t.rid===e.rid;if(t.ssrc)return t.ssrc===e.ssrc}))return false;this.tracks.push(e);if(e.ssrc)this.trackBySSRC[e.ssrc]=e;if(e.rid)this.trackByRID[e.rid]=e;return true}stop(){this.stopped=true;this.rtcpRunning=false;this.rtcpCancel.abort();if(this.receiverTWCC)this.receiverTWCC.twccRunning=false;this.nack.close()}endTracks(){for(const e of[...this.tracks,this.defaultTrack])e.stop()}async runRtcp(){if(this.rtcpRunning||this.stopped)return;this.rtcpRunning=true;try{while(this.rtcpRunning){await setTimeout$2(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});const e=Object.entries(this.remoteStreams).map(([e,t])=>{let n=0,r=0;if(this.lastSRtimestamp[e]){n=this.lastSRtimestamp[e];const t=timestampSeconds()-this.receiveLastSRTimestamp[e];if(t>0&&t<65536)r=int(t*65536)}return new RtcpReceiverInfo({ssrc:Number(e),fractionLost:t.fraction_lost,packetsLost:t.packets_lost,highestSequence:t.max_seq,jitter:t.jitter,lsr:n,dlsr:r})});const t=new RtcpRrPacket({ssrc:this.rtcpSsrc,reports:e});try{if(this.config.debug.receiverReportDelay)await setTimeout$2(this.config.debug.receiverReportDelay);await this.dtlsTransport.sendRtcp([t])}catch(e){log32(`sendRtcp failed`,e);await setTimeout$2(500+Math.random()*1e3)}}}catch(e){}}getInboundRtpStatsId(e){return generateStatsId(`inbound-rtp`,e.id??e.uuid)}getRemoteOutboundRtpStatsId(e){return generateStatsId(`remote-outbound-rtp`,e.id??e.uuid)}getStatsRootIds(e){return this.tracks.filter(t=>!e?true:t===e).filter(e=>e.ssrc).map(e=>this.getInboundRtpStatsId(e))}collectStats(e){const t=[];const n=this.dtlsTransport?generateStatsId(`transport`,this.dtlsTransport.id):void 0;const r=this.codecArray[0];const i=/* @__PURE__ */ new Set;for(const a of this.tracks){if(!a.ssrc)continue;const o=this.remoteStreams[a.ssrc];const s=this.remoteTimestampsBySsrc[a.ssrc]!==void 0;const c=this.lastSRtimestamp[a.ssrc]!==void 0||s?this.getRemoteOutboundRtpStatsId(a):void 0;const u=r&&n?generateCodecStatsId(n,r.payloadType,a.id??a.uuid):void 0;if(r&&n&&u&&!i.has(u)){i.add(u);const a={type:`codec`,id:u,timestamp:e,payloadType:r.payloadType,transportId:n,mimeType:r.mimeType,clockRate:r.clockRate,channels:r.channels,sdpFmtpLine:r.parameters};t.push(a)}const d={type:`inbound-rtp`,id:this.getInboundRtpStatsId(a),timestamp:e,ssrc:a.ssrc,kind:this.kind,transportId:n,codecId:u,mid:this.sdesMid,trackIdentifier:a.id??a.uuid,packetsReceived:o?.packets_received??0,bytesReceived:o?.bytesReceived??0,headerBytesReceived:o?.headerBytesReceived??0,packetsLost:o?.packets_lost??0,jitter:o?.clockRate?o.jitter/o.clockRate:void 0,lastPacketReceivedTimestamp:o?.lastPacketReceivedTimestamp,remoteId:c,nackCount:this.nackCountBySsrc[a.ssrc]||void 0,pliCount:this.pliCountBySsrc[a.ssrc]||void 0};t.push(d);if(c){const r={type:`remote-outbound-rtp`,id:this.getRemoteOutboundRtpStatsId(a),timestamp:e,ssrc:a.ssrc,kind:this.kind,transportId:n,codecId:d.codecId,localId:d.id,remoteTimestamp:this.remoteTimestampsBySsrc[a.ssrc],reportsSent:this.senderReportsReceivedBySsrc[a.ssrc]??0,packetsSent:this.remotePacketCountBySsrc[a.ssrc],bytesSent:this.remoteOctetCountBySsrc[a.ssrc]};t.push(r)}}return t}async getStats(){const e=getStatsTimestamp();const t=this.collectStats(e);if(this.dtlsTransport)t.push(...await this.dtlsTransport.getStats(e));return buildStatsReport(t,this.getStatsRootIds())}async sendRtcpPLI(e){if(!this.pliEnabled){log32(`pli not supported`,{mediaSsrc:e});return}if(this.stopped)return;log32(`sendRtcpPLI`,{mediaSsrc:e});const t=new RtcpPayloadSpecificFeedback({feedback:new PictureLossIndication({senderSsrc:this.rtcpSsrc,mediaSsrc:e})});try{this.pliCountBySsrc[e]=(this.pliCountBySsrc[e]??0)+1;await this.dtlsTransport.sendRtcp([t])}catch(e){log32(e)}}handleRtcpPacket(e){switch(e.type){case RtcpSrPacket.type:{const t=e;this.lastSRtimestamp[t.ssrc]=compactNtp(t.senderInfo.ntpTimestamp);this.receiveLastSRTimestamp[t.ssrc]=timestampSeconds();this.senderReportsReceivedBySsrc[t.ssrc]=(this.senderReportsReceivedBySsrc[t.ssrc]??0)+1;this.remoteTimestampsBySsrc[t.ssrc]=ntpTimeToEpochMs(t.senderInfo.ntpTimestamp);this.remotePacketCountBySsrc[t.ssrc]=t.senderInfo.packetCount;this.remoteOctetCountBySsrc[t.ssrc]=t.senderInfo.octetCount;const n=this.trackBySSRC[e.ssrc];if(n)n.onReceiveRtcp.execute(e)}}this.onRtcp.execute(e)}handleRtpBySsrc=(e,t)=>{const n=this.trackBySSRC[e.header.ssrc];this.handleRTP(e,t,n)};handleRtpByRid=(e,t,n)=>{const r=this.trackByRID[t];if(!this.trackBySSRC[e.header.ssrc])this.trackBySSRC[e.header.ssrc]=r;this.handleRTP(e,n,r)};handleRTP(e,t,n){if(this.stopped)return;const r=this.codecs[e.header.payloadType];if(!r)return;this.remoteStreams[e.header.ssrc]=this.remoteStreams[e.header.ssrc]??new StreamStatistics(r.clockRate);this.remoteStreams[e.header.ssrc].add(e);if(this.receiverTWCC){const e=t[RTP_EXTENSION_URI.transportWideCC];if(!e==void 0)throw new Error(`undefined`);this.receiverTWCC.handleTWCC(e)}else if(this.twccEnabled)this.setupTWCC(e.header.ssrc);if(r.name.toLowerCase()===`rtx`){const t=this.ssrcByRtx[e.header.ssrc];const i=codecParametersFromString(r.parameters??``);const a=this.codecs[i[`apt`]];if(e.payload.length<2)return;e=unwrapRtx(e,a.payloadType,t);n=this.trackBySSRC[t]}let i;if(r.name.toLowerCase()===`red`){i=Red.deSerialize(e.payload);if(!Object.keys(this.codecs).includes(i.header.fields[0].blockPT.toString()))return}if(n?.kind===`video`&&this.nackEnabled)this.nack.addPacket(e);if(n){if(i){if(n.kind===`audio`){const r=this.audioRedHandler.push(i,e);for(const e of r)n.onReceiveRtp.execute(e.clone(),t)}}else n.onReceiveRtp.execute(e.clone(),t)}this.runRtcp()}};var log33=debug(`werift:packages/webrtc/src/media/router.ts`);var RtpRouter=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(e){this.ssrcTable[e.ssrc]=e}registerRtpReceiver(e,t){log33(`registerRtpReceiver`,t);this.ssrcTable[t]=e}registerRtpReceiverBySsrc(e,t){log33(`registerRtpReceiverBySsrc`,t);t.encodings.filter(e=>e.ssrc!=void 0).forEach((n,r)=>{this.registerRtpReceiver(e.receiver,n.ssrc);e.addTrack(new MediaStreamTrack({ssrc:n.ssrc,kind:e.kind,id:e.sender.trackId,remote:true,codec:deliveredTrackCodec(e.kind,t.codecs[r],t.codecs)}));if(n.rtx)this.registerRtpReceiver(e.receiver,n.rtx.ssrc)});t.headerExtensions.forEach(e=>{this.extIdUriMap[e.id]=e.uri})}registerRtpReceiverByRid(e,t,n){const[r]=n.codecs;log33(`registerRtpReceiverByRid`,t);e.addTrack(new MediaStreamTrack({rid:t.rid,kind:e.kind,id:e.sender.trackId,remote:true,codec:r}));this.ridTable[t.rid]=e.receiver}unregisterTransceiver(e){const t=[e.sender,e.receiver];for(const[e,n]of Object.entries(this.ssrcTable))if(t.includes(n))delete this.ssrcTable[Number(e)];for(const[e,n]of Object.entries(this.ridTable))if(t.includes(n))delete this.ridTable[e]}routeRtp=e=>{const t=rtpHeaderExtensionsParser(e.header.extensions,this.extIdUriMap);let n=this.ssrcTable[e.header.ssrc];const r=t[RTP_EXTENSION_URI.sdesRTPStreamID];if(typeof r===`string`){n=this.ridTable[r];if(n){n.latestRid=r;n.handleRtpByRid(e,r,t)}}else if(n)n.handleRtpBySsrc(e,t);else{n=Object.values(this.ridTable).filter(e=>e instanceof RTCRtpReceiver).find(t=>t.trackBySSRC[e.header.ssrc]);if(n){log33(`simulcast register receiver by ssrc`,e.header.ssrc);this.registerRtpReceiver(n,e.header.ssrc);n.handleRtpBySsrc(e,t)}}if(!n){log33(`ssrcReceiver not found`);return}const i=t[RTP_EXTENSION_URI.sdesMid];if(typeof i===`string`)n.sdesMid=i;const a=t[RTP_EXTENSION_URI.repairedRtpStreamId];if(typeof a===`string`)n.latestRepairedRid=a};routeRtcp=e=>{const t=[];switch(e.type){case RtcpSrPacket.type:e=e;t.push(this.ssrcTable[e.ssrc]);break;case RtcpRrPacket.type:e=e;e.reports.forEach(e=>{t.push(this.ssrcTable[e.ssrc])});break;case RtcpSourceDescriptionPacket.type:break;case RtcpTransportLayerFeedback.type:{const n=e;if(n.feedback)t.push(this.ssrcTable[n.feedback.mediaSourceSsrc])}break;case RtcpPayloadSpecificFeedback.type:{const n=e;switch(n.feedback.count){case ReceiverEstimatedMaxBitrate.count:{const e=n.feedback;t.push(this.ssrcTable[e.ssrcFeedbacks[0]])}break;default:t.push(this.ssrcTable[n.feedback.senderSsrc]||this.ssrcTable[n.feedback.mediaSsrc])}}}t.filter(e=>e).forEach(t=>t.handleRtcpPacket(e))}};var CumulativeResult=class{numPackets=0;totalSize=0;firstPacketSentAtMs=0;lastPacketSentAtMs=0;firstPacketReceivedAtMs=0;lastPacketReceivedAtMs=0;addPacket(e,t,n){if(this.numPackets===0){this.firstPacketSentAtMs=t;this.firstPacketReceivedAtMs=n;this.lastPacketSentAtMs=t;this.lastPacketReceivedAtMs=n}else{if(t<this.firstPacketSentAtMs)this.firstPacketSentAtMs=t;if(n<this.firstPacketReceivedAtMs)this.firstPacketReceivedAtMs=n;if(t>this.lastPacketSentAtMs)this.lastPacketSentAtMs=t;if(n>this.lastPacketReceivedAtMs)this.lastPacketReceivedAtMs=n}this.numPackets++;this.totalSize+=e}reset(){this.numPackets=0;this.totalSize=0;this.firstPacketSentAtMs=0;this.lastPacketSentAtMs=0;this.firstPacketReceivedAtMs=0;this.lastPacketReceivedAtMs=0}get receiveBitrate(){const e=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs;return Int(this.totalSize/e*8*1e3)}get sendBitrate(){const e=this.lastPacketSentAtMs-this.firstPacketSentAtMs;return Int(this.totalSize/e*8*1e3)}};var COUNTER_MAX=20;var SCORE_MAX=10;var SenderBandwidthEstimator=class{congestion=false;onAvailableBitrate=new Event2;onCongestion=new Event2;onCongestionScore=new Event2;congestionCounter=0;cumulativeResult=new CumulativeResult;sentInfos={};_congestionScore=1;get congestionScore(){return this._congestionScore}set congestionScore(e){this._congestionScore=e;this.onCongestionScore.execute(e)}_availableBitrate=0;get availableBitrate(){return this._availableBitrate}set availableBitrate(e){this._availableBitrate=e;this.onAvailableBitrate.execute(e)}constructor(){}receiveTWCC(e){const t=milliTime()-this.cumulativeResult.firstPacketSentAtMs;if(t>1e3){this.cumulativeResult.reset();if(this.congestionCounter<COUNTER_MAX)this.congestionCounter++;else if(this.congestionScore<SCORE_MAX)this.congestionScore++;if(this.congestionCounter>=COUNTER_MAX&&!this.congestion){this.congestion=true;this.onCongestion.execute(this.congestion)}}for(const t of e.packetResults){if(!t.received)continue;const e=t.sequenceNumber;const n=this.sentInfos[e];if(!n)continue;if(!t.receivedAtMs)continue;this.cumulativeResult.addPacket(n.size,n.sendingAtMs,t.receivedAtMs)}if(t>=100&&this.cumulativeResult.numPackets>=20){this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate);this.cumulativeResult.reset();if(this.congestionCounter>-COUNTER_MAX){const e=Int(COUNTER_MAX/2)+1;const t=e-(e-(Int(COUNTER_MAX/4)+1))/10*this.congestionScore;this.congestionCounter=this.congestionCounter-t}if(this.congestionCounter<=-COUNTER_MAX){if(this.congestionScore>1){this.congestionScore--;this.onCongestion.execute(false)}this.congestionCounter=0}if(this.congestionCounter<=0&&this.congestion){this.congestion=false;this.onCongestion.execute(this.congestion)}}}rtpPacketSent(e){Object.keys(e).map(e=>Number(e)).sort().filter(t=>t<e.wideSeq).forEach(e=>{delete this.sentInfos[e]});this.sentInfos[e.wideSeq]=e}};var log34=debug(`werift:packages/webrtc/src/media/rtpSender.ts`);var RTP_HISTORY_SIZE=128;var DEFAULT_PENDING_RTP_MAX_LENGTH=256;var RTT_ALPHA=.85;function resolvePendingRtpOptions(e){if(e===true)return{enabled:true,maxLength:DEFAULT_PENDING_RTP_MAX_LENGTH};if(e==void 0||e===false)return{enabled:false,maxLength:DEFAULT_PENDING_RTP_MAX_LENGTH};const t=typeof e.maxLength===`number`&&Number.isFinite(e.maxLength)&&e.maxLength>=1?Math.floor(e.maxLength):DEFAULT_PENDING_RTP_MAX_LENGTH;return{enabled:e.enabled??true,maxLength:t}}function freezeRtpContinuityOffsets(e,t,n,r,i){return{seqOffset:uint16Add(uint16Add(e,1),-n),timestampOffset:uint32Add(uint32Add(t,i),-r)}}var RTCRtpSender=class{constructor(e,t={}){this.trackOrKind=e;const n=resolvePendingRtpOptions(t.pendingRtp);this.pendingRtpEnabled=n.enabled;this.pendingRtpMaxLength=n.maxLength;this.kind=typeof this.trackOrKind===`string`?this.trackOrKind:this.trackOrKind.kind;if(typeof e!==`string`)this.registerTrack(e)}type=`sender`;kind;ssrc=randomBytes$1(4).readUInt32BE(0);rtxSsrc=randomBytes$1(4).readUInt32BE(0);trackId=randomUUID$1().toString();onReady=new Event2;onRtcp=new Event2;onPictureLossIndication=new Event2;onGenericNack=new Event2;senderBWE=new SenderBandwidthEstimator;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=random16();redRedundantPayloadType;_redDistance=2;redEncoder=new RedEncoder(this._redDistance);headerExtensions=[];disposeTrack;sendEncodings=[{}];lastSRtimestamp;lastSentSRTimestamp;ntpTimestamp=0n;rtpTimestamp=0;octetCount=0;packetCount=0;headerBytesSent=0;rtt;totalRoundTripTime=0;roundTripTimeMeasurements=0;retransmittedPacketsSent=0;retransmittedBytesSent=0;nackCount=0;pliCount=0;firCount=0;remotePacketsLost;remoteFractionLost;receiverEstimatedMaxBitrate=0n;sequenceNumber;timestamp;timestampOffset=0;seqOffset=0;rtpContinuityPending=false;pendingTimestampStep=1;rtpCache=[];pendingRtp=[];drainingPendingRtp=false;pendingRtpEnabled;pendingRtpMaxLength;codec;negotiatedCodecs=[];sendPrimaryCodec;dtlsTransport;dtlsDisposer=[];track=null;streamIds=[];stopped=false;rtcpRunning=false;rtcpCancel=new AbortController;get transport(){return this.dtlsTransport??null}get streamId(){return this.streamIds[0]}set streamId(e){this.streamIds=e?[e]:[]}setDtlsTransport(e){if(this.dtlsTransport)this.dtlsDisposer.forEach(e=>e());this.dtlsTransport=e;this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(e=>{if(e===`connected`){this.onReady.execute();this.drainPendingRtp()}}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(e){this._redDistance=e;this.redEncoder.distance=e}prepareSend(e){this.cname=e.rtcp?.cname;this.mid=e.muxId;this.headerExtensions=e.headerExtensions;this.rtpStreamId=e.rtpStreamId??this.rtpStreamId;this.repairedRtpStreamId=e.repairedRtpStreamId;this.negotiatedCodecs=[...e.codecs];this.codec=e.codecs.find(e=>e.name.toLowerCase()!==`rtx`)??e.codecs[0];const t=this.codec?.name.toLowerCase()===`red`?Number((this.codec.parameters??``).split(`/`)[0]):void 0;this.sendPrimaryCodec=this.codec?.name.toLowerCase()===`red`?e.codecs.find(e=>![`red`,`rtx`].includes(e.name.toLowerCase())&&e.payloadType===t):this.codec;if(this.track)this.track.codec=this.codec;this.rtxPayloadType=void 0;this.redRedundantPayloadType=void 0;e.codecs.forEach(e=>{const t=codecParametersFromString(e.parameters??``);if(e.name.toLowerCase()===`rtx`&&this.sendPrimaryCodec?.payloadType===t[`apt`])this.rtxPayloadType=e.payloadType});if(this.codec?.name.toLowerCase()===`red`&&this.sendPrimaryCodec!=void 0)this.redRedundantPayloadType=this.sendPrimaryCodec.payloadType;this.drainPendingRtp()}canSendRtp(){return!this.stopped&&this.dtlsTransport?.state===`connected`&&!!this.codec}settlePendingRtp(e,t){if(t==void 0){e.resolve();return}e.reject(t)}discardPendingRtp(){const e=this.pendingRtp.splice(0);for(const t of e)this.settlePendingRtp(t)}enqueuePendingRtp(e,t,n){const r=Buffer.isBuffer(e)?RtpPacket.deSerialize(e):e.clone();this.pendingRtp.push({packet:r,resolve:t,reject:n});while(this.pendingRtp.length>this.pendingRtpMaxLength){const e=this.pendingRtp.shift();if(e)this.settlePendingRtp(e)}}async drainPendingRtp(){if(this.drainingPendingRtp)return;this.drainingPendingRtp=true;try{while(this.pendingRtp.length>0&&this.canSendRtp()){const e=this.pendingRtp.shift();if(!this.canSendRtp()){this.settlePendingRtp(e);continue}try{await this.dispatchRtp(e.packet);this.settlePendingRtp(e)}catch(t){this.settlePendingRtp(e,t)}}}finally{this.drainingPendingRtp=false}if(this.pendingRtp.length>0&&this.canSendRtp())await this.drainPendingRtp()}registerTrack(e){if(e.stopped)throw new Error(`track is ended`);captureTrackSourceCodecs(e);if(this.disposeTrack)this.disposeTrack();e.id=this.trackId;const{unSubscribe:t}=e.onReceiveRtp.subscribe(async e=>{await this.sendRtp(e)});const{unSubscribe:n}=e.onSourceChanged.subscribe(e=>{this.replaceRTP(e)});this.track=e;this.disposeTrack=()=>{t();n()};if(this.codec)e.codec=this.codec}setStreams(e=[]){this.streamIds=[...new Set(e.map(e=>e.id))]}setSendEncodings(e=[]){this.sendEncodings=e.length>0?e.map(e=>({...e})):[{}];const t=this.sendEncodings.find(e=>typeof e.rid===`string`)?.rid;if(typeof t===`string`)this.rtpStreamId=t}async replaceTrack(e){if(e===null){this.detachTrack();return}if(e.stopped)throw new Error(`track is ended`);captureTrackSourceCodecs(e);const t=getTrackSourceCodecs(e);if(this.sendPrimaryCodec!=void 0&&t!=void 0&&!t.some(e=>isCodecCompatible(e,this.sendPrimaryCodec)))throw createWebRtcDomException(`InvalidModificationError`,`Track codec ${t.map(e=>e.mimeType).join(`, `)} is incompatible with negotiated codecs ${this.negotiatedCodecs.map(e=>e.mimeType).join(`, `)}`);if(this.sequenceNumber!=void 0)this.scheduleRtpContinuity();this.registerTrack(e);log34(`replaceTrack`,`ssrc`,e.ssrc,`rid`,e.rid)}detachTrack(){this.rtpContinuityPending=false;this.discardPendingRtp();if(this.disposeTrack){this.disposeTrack();this.disposeTrack=void 0}this.track=null}stop({keepTrack:e=false}={}){this.stopped=true;this.rtpContinuityPending=false;this.discardPendingRtp();this.rtcpRunning=false;this.rtcpCancel.abort();if(this.disposeTrack){this.disposeTrack();this.disposeTrack=void 0}if(!e)this.track=null}async runRtcp(){if(this.rtcpRunning||this.stopped)return;this.rtcpRunning=true;try{while(this.rtcpRunning){await setTimeout$2(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});const e=[new RtcpSrPacket({ssrc:this.ssrc,senderInfo:new RtcpSenderInfo({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=compactNtp(this.ntpTimestamp);this.lastSentSRTimestamp=timestampSeconds();if(this.cname)e.push(new RtcpSourceDescriptionPacket({chunks:[new SourceDescriptionChunk({source:this.ssrc,items:[new SourceDescriptionItem({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(e)}catch(e){log34(`sendRtcp failed`,e);await setTimeout$2(500+Math.random()*1e3)}}}catch(e){}}async sendRtp(e){if(this.stopped)return;if(!this.pendingRtpEnabled){if(!this.canSendRtp())return;await this.dispatchRtp(e);return}await new Promise((t,n)=>{this.enqueuePendingRtp(e,t,n);this.drainPendingRtp()})}replaceRTP(e,t=false,n=1){this.scheduleRtpContinuity(n);log34(`replaceRTP`,this.sequenceNumber,e.sequenceNumber,t,n)}scheduleRtpContinuity(e=1){this.rtpContinuityPending=true;this.pendingTimestampStep=e;this.rtpCache=[]}async dispatchRtp(e){if(!this.canSendRtp())return;const t=this.codec;if(!t)return;e=Buffer.isBuffer(e)?RtpPacket.deSerialize(e):e.clone();const{header:n,payload:r}=e;const i=n.sequenceNumber;const a=n.timestamp;if(this.rtpContinuityPending){if(this.sequenceNumber!=void 0&&this.timestamp!=void 0){const e=freezeRtpContinuityOffsets(this.sequenceNumber,this.timestamp,i,a,this.pendingTimestampStep);this.seqOffset=e.seqOffset;this.timestampOffset=e.timestampOffset}this.rtpContinuityPending=false;this.pendingTimestampStep=1}n.ssrc=this.ssrc;n.payloadType=t.payloadType;n.timestamp=uint32Add(n.timestamp,this.timestampOffset);n.sequenceNumber=uint16Add(n.sequenceNumber,this.seqOffset);this.timestamp=n.timestamp;this.sequenceNumber=n.sequenceNumber;const o=ntpTime();const s=[...n.extensions];n.extensions=this.headerExtensions.map(e=>{const t=(()=>{switch(e.uri){case RTP_EXTENSION_URI.sdesMid:if(this.mid)return serializeSdesMid(this.mid);return;case RTP_EXTENSION_URI.sdesRTPStreamID:if(this.rtpStreamId)return serializeSdesRTPStreamID(this.rtpStreamId);return;case RTP_EXTENSION_URI.repairedRtpStreamId:if(this.repairedRtpStreamId)return serializeRepairedRtpStreamId(this.repairedRtpStreamId);return;case RTP_EXTENSION_URI.transportWideCC:this.dtlsTransport.transportSequenceNumber=uint16Add(this.dtlsTransport.transportSequenceNumber,1);return serializeTransportWideCC(this.dtlsTransport.transportSequenceNumber);case RTP_EXTENSION_URI.absSendTime:return serializeAbsSendTime(o)}})();if(t)return{id:e.id,payload:t}}).filter(e=>e);for(const e of s){const t=n.extensions.find(t=>t.id===e.id);if(t)t.payload=e.payload;else n.extensions.push(e)}n.extensions=n.extensions.sort((e,t)=>e.id-t.id);this.ntpTimestamp=o;this.rtpTimestamp=n.timestamp;this.octetCount+=r.length;this.headerBytesSent+=n.serializeSize;this.packetCount=uint32Add(this.packetCount,1);this.rtpCache[n.sequenceNumber%RTP_HISTORY_SIZE]=e;let c=r;if(this.redRedundantPayloadType){this.redEncoder.push({block:c,timestamp:n.timestamp,blockPT:this.redRedundantPayloadType});c=this.redEncoder.build().serialize()}const u=await this.dtlsTransport.sendRtp(c,n);this.runRtcp();const d=milliTime();const f={wideSeq:this.dtlsTransport.transportSequenceNumber,size:u,sendingAtMs:d,sentAtMs:d};this.senderBWE.rtpPacketSent(f)}handleRtcpPacket(e){switch(e.type){case RtcpSrPacket.type:case RtcpRrPacket.type:e.reports.filter(e=>e.ssrc===this.ssrc).forEach(e=>{this.remotePacketsLost=e.packetsLost;this.remoteFractionLost=e.fractionLost/256;if(this.lastSRtimestamp===e.lsr&&e.dlsr){if(this.lastSentSRTimestamp){const t=timestampSeconds()-this.lastSentSRTimestamp-e.dlsr/65536;this.totalRoundTripTime+=t;this.roundTripTimeMeasurements++;if(this.rtt===void 0)this.rtt=t;else this.rtt=RTT_ALPHA*this.rtt+(1-RTT_ALPHA)*t}}});break;case RtcpTransportLayerFeedback.type:{const t=e;switch(t.feedback.count){case TransportWideCC.count:{const e=t.feedback;this.senderBWE.receiveTWCC(e)}break;case GenericNack.count:{const e=t.feedback;this.nackCount++;e.lost.forEach(async e=>{let t=this.rtpCache[e%RTP_HISTORY_SIZE];if(t&&t.header.sequenceNumber!==e)t=void 0;if(t){if(this.rtxPayloadType!=void 0){t=wrapRtx(t,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc);this.rtxSequenceNumber=uint16Add(this.rtxSequenceNumber,1)}this.retransmittedPacketsSent++;this.retransmittedBytesSent+=t.payload.length;this.headerBytesSent+=t.header.serializeSize;await this.dtlsTransport.sendRtp(t.payload,t.header)}});this.onGenericNack.execute(e)}}}break;case RtcpPayloadSpecificFeedback.type:{const t=e;switch(t.feedback.count){case ReceiverEstimatedMaxBitrate.count:{const e=t.feedback;this.receiverEstimatedMaxBitrate=e.bitrate}break;case PictureLossIndication.count:this.pliCount++;this.onPictureLossIndication.execute()}}}this.onRtcp.execute(e)}getParameters(){return{encodings:this.sendEncodings.map(e=>({...e}))}}setParameters(e){if(e.encodings)this.setSendEncodings(e.encodings)}get outboundRtpStatsId(){return generateStatsId(`outbound-rtp`,this.trackId)}get mediaSourceStatsId(){return generateStatsId(`media-source`,this.trackId)}get remoteInboundRtpStatsId(){return generateStatsId(`remote-inbound-rtp`,this.trackId)}getStatsRootIds(){return[this.outboundRtpStatsId]}collectStats(e){const t=[];const n=this.dtlsTransport?generateStatsId(`transport`,this.dtlsTransport.id):void 0;const r=this.codec&&n?generateCodecStatsId(n,this.codec.payloadType,this.trackId):void 0;const i={type:`outbound-rtp`,id:this.outboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:n,codecId:r,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,headerBytesSent:this.headerBytesSent,retransmittedPacketsSent:this.retransmittedPacketsSent||void 0,retransmittedBytesSent:this.retransmittedBytesSent||void 0,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0,mediaSourceId:this.track?this.mediaSourceStatsId:void 0,remoteId:this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0?this.remoteInboundRtpStatsId:void 0,nackCount:this.nackCount||void 0,pliCount:this.pliCount||void 0,firCount:this.firCount||void 0};t.push(i);if(this.track){const n={type:`media-source`,id:this.mediaSourceStatsId,timestamp:e,trackIdentifier:this.track.id??this.trackId,kind:this.kind};t.push(n)}if(this.codec&&n){const i={type:`codec`,id:r,timestamp:e,payloadType:this.codec.payloadType,transportId:n,mimeType:this.codec.mimeType,clockRate:this.codec.clockRate,channels:this.codec.channels,sdpFmtpLine:this.codec.parameters};t.push(i)}if(this.rtt!==void 0||this.remotePacketsLost!==void 0||this.remoteFractionLost!==void 0){const r={type:`remote-inbound-rtp`,id:this.remoteInboundRtpStatsId,timestamp:e,ssrc:this.ssrc,kind:this.kind,transportId:n,codecId:i.codecId,localId:i.id,roundTripTime:this.rtt,totalRoundTripTime:this.totalRoundTripTime,roundTripTimeMeasurements:this.roundTripTimeMeasurements,packetsLost:this.remotePacketsLost,fractionLost:this.remoteFractionLost};t.push(r)}return t}async getStats(){const e=getStatsTimestamp();const t=this.collectStats(e);if(this.dtlsTransport)t.push(...await this.dtlsTransport.getStats(e));return buildStatsReport(t,this.getStatsRootIds())}};var log35=debug(`werift:packages/webrtc/src/media/rtpTransceiverManager.ts`);function simulcastFromSendEncodings(e){if(!e||e.length<2)return;const t=e.map(e=>e.rid).filter(e=>typeof e===`string`&&e.length>0);if(t.length<2)return;return t.map(e=>({rid:e,direction:`send`}))}var TransceiverManager=class{constructor(e,t,n){this.cname=e;this.config=t;this.router=n}transceivers=[];watched=/* @__PURE__ */ new WeakSet;remoteOfferSnapshot;onTransceiverAdded=new Event2;onRemoteTransceiverAdded=new Event2;onTrack=new Event2;onNegotiationNeeded=new Event2;getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(e=>e.sender)}getReceivers(){return this.getTransceivers().map(e=>e.receiver)}getTransceiverByMLineIndex(e){return this.transceivers.find(t=>t.mLineIndex===e)}pushTransceiver(e){this.watchTransceiver(e);this.transceivers.push(e)}replaceTransceiver(e,t){this.watchTransceiver(e);this.transceivers[t]=e}unwatchTransceiver(e){this.watched.delete(e);e.onRelease.allUnsubscribe();e.onStopRequested.allUnsubscribe()}watchTransceiver(e){if(this.watched.has(e))return;this.watched.add(e);e.onRelease.subscribe(()=>{this.router.unregisterTransceiver(e)});e.onStopRequested.subscribe(()=>{if(!e.stopped)this.onNegotiationNeeded.execute()})}findReusableTransceiver(e){return this.transceivers.find(t=>t.stopped&&t.kind===e&&t.mLineIndex!=void 0&&!this.transceivers.some(e=>e!==t&&e.mLineIndex===t.mLineIndex))}takeOverMLine(e,t){const n=this.transceivers.indexOf(e);t.mLineIndex=e.mLineIndex;e.mid=null;e.mLineIndex=void 0;this.unwatchTransceiver(e);this.replaceTransceiver(t,n)}associateMLine(e,t){const n=this.transceivers.find(n=>n!==e&&n.stopped&&n.mLineIndex===t);if(!n)return;this.transceivers.splice(this.transceivers.indexOf(e),1);this.takeOverMLine(n,e)}releaseUnassociatedReservations(e,t){for(const n of this.transceivers)if(!e.has(n)&&n.mid==null&&n.mLineIndex!=void 0&&n.mLineIndex<t)n.mLineIndex=void 0}addTransceiver(e,t,n={},{remoteMLineIndex:r}={}){const i=typeof e===`string`?e:e.kind;const a=n.direction||`sendrecv`;if(typeof e!==`string`){captureTrackSourceCodecs(e);assertCodecsSupported({kind:i,configured:this.filterCodecsByDirection(i,a),source:getTrackSourceCodecs(e),preferences:void 0})}const o=new RTCRtpSender(e,{pendingRtp:this.config.pendingRtp});const s=new RTCRtpTransceiver(i,t,new RTCRtpReceiver(this.config,i,o.ssrc),o,a);s.onCodecPreferencesChanged.subscribe(()=>{this.onNegotiationNeeded.execute()});s.options={...n,simulcast:n.simulcast??simulcastFromSendEncodings(n.sendEncodings)};s.sender.setStreams(n.streams??[]);s.sender.setSendEncodings((n.sendEncodings??[]).map(e=>({...e})));this.router.registerRtpSender(s.sender);const c=r==void 0?this.findReusableTransceiver(i):this.transceivers.find(e=>e.stopped&&e.mLineIndex===r);if(c)this.takeOverMLine(c,s);else this.pushTransceiver(s);if(r!=void 0)this.remoteOfferSnapshot?.remoteCreated.add(s);this.onTransceiverAdded.execute(s);return s}addTrack(e,t=[]){if(this.getSenders().find(t=>t.track?.uuid===e.uuid))throw createWebRtcDomException(`InvalidAccessError`,`Track already added`);const reusableForTrack=t=>t.sender.track==void 0&&t.kind===e.kind&&!t.usedForSender&&!t.stopping&&!t.stopped&&!t.rejected&&!t.pendingRejection;const n=this.transceivers.find(e=>reusableForTrack(e)&&SenderDirections.includes(e.direction));if(n){this.validateTrackForTransceiver(e,n);const r=n.sender;r.setStreams(t);r.registerTrack(e);n.options={...n.options,streams:t};n.codecs=[];return n}const r=this.transceivers.find(e=>reusableForTrack(e)&&!SenderDirections.includes(e.direction));if(r){const n=r.direction===`recvonly`?`sendrecv`:r.direction===`inactive`?`sendonly`:r.direction;this.validateTrackForTransceiver(e,r,n);const i=r.sender;i.setStreams(t);i.registerTrack(e);r.options={...r.options,streams:t};switch(r.direction){case`recvonly`:r.setDirection(`sendrecv`);break;case`inactive`:r.setDirection(`sendonly`)}r.codecs=[];return r}else return this.addTransceiver(e,void 0,{direction:`sendrecv`,streams:t})}removeTrack(e){if(!this.getSenders().find(({ssrc:t})=>e.ssrc===t))throw createWebRtcDomException(`InvalidAccessError`,`Sender does not exist`);const t=this.transceivers.find(({sender:{ssrc:t}})=>e.ssrc===t);if(!t)throw new Error(`No matching transceiver found`);if(t.stopping||t.stopped)return false;if(e.track==void 0)return false;e.detachTrack();if(t.direction===`sendrecv`)t.setDirection(`recvonly`);else if(t.direction===`sendonly`)t.setDirection(`inactive`);return true}assignTransceiverCodecs(e){const t=this.filterCodecsByDirection(e.kind,e.direction);e.codecs=assertCodecsSupported({kind:e.kind,configured:t,source:getTrackSourceCodecs(e.sender.track),preferences:e.codecPreferences});e.codecPreferencesNeedResolution=false}filterCodecsByDirection(e,t){return this.config.codecs[e].filter(e=>{switch(e.direction){case`recvonly`:if(ReceiverDirection.includes(t))return true;return false;case`sendonly`:if(SenderDirections.includes(t))return true;return false;case`sendrecv`:if([`sendrecv`,`recvonly`,`sendonly`].includes(t))return true;return false;case`all`:return true;default:return false}})}validateTrackForTransceiver(e,t,n=t.direction){captureTrackSourceCodecs(e);assertCodecsSupported({kind:e.kind,configured:this.filterCodecsByDirection(e.kind,n),source:getTrackSourceCodecs(e),preferences:t.codecPreferences})}getLocalRtpParams(e){if(e.mid==void 0)throw new Error(`mid not assigned`);return{codecs:e.codecs,muxId:e.mid,headerExtensions:e.headerExtensions,rtcp:{cname:this.cname,ssrc:e.sender.ssrc,mux:true}}}getRemoteRtpParams(e,t){return{muxId:e.rtp.muxId,rtcp:e.rtp.rtcp,codecs:t.codecs,headerExtensions:t.headerExtensions,encodings:Object.values(t.codecs.reduce((t,n)=>{if(n.name.toLowerCase()===`rtx`){const r=t[codecParametersFromString(n.parameters??``)[`apt`]];if(r&&e.ssrc.length===2)r.rtx=new RTCRtpRtxParameters({ssrc:e.ssrc[1].ssrc});return t}t[n.payloadType]=new RTCRtpCodingParameters({ssrc:e.ssrc[0]?.ssrc,payloadType:n.payloadType});return t},{}))}}resyncAnswerCodecs(e,t){this.refreshAnswerCodecs(e,t);const n=this.getLocalRtpParams(e);e.sender.prepareSend(n);if([`recvonly`,`sendrecv`].includes(e.direction)){const n=this.getRemoteRtpParams(t,e);for(const r of t.simulcastParameters)this.router.registerRtpReceiverByRid(e,r,n);e.receiver.resyncCodecs(n,t.ssrc[0]?.ssrc);this.router.registerRtpReceiverBySsrc(e,n)}}resolveRemoteCodecSet(e,t,n,r){const codecName2=e=>e.name.toLowerCase();const redPayloadTypes=e=>(e.parameters??``).split(`/`).map(Number).filter(e=>!Number.isNaN(e));const i=/* @__PURE__ */ new Map;const a=/* @__PURE__ */ new Set;for(const n of e){if([`red`,`rtx`].includes(codecName2(n)))continue;const e=t.rtp.codecs.find(e=>!a.has(e)&&normalizeCodecMimeType(e.mimeType)===normalizeCodecMimeType(n.mimeType)&&(r==void 0||r.some(t=>isCodecCompatible(t,e))));if(e){i.set(n,e);a.add(e)}}const o=e.flatMap(n=>{if(codecName2(n)===`red`){const r=redPayloadTypes(n).flatMap(t=>{const n=e.find(e=>e.payloadType===t);const r=n?i.get(n):void 0;return r?[r.payloadType]:[]});const o=t.rtp.codecs.find(e=>{if(codecName2(e)!==`red`||a.has(e))return false;const t=redPayloadTypes(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(!o)return[];a.add(o);return[o]}if(codecName2(n)!==`rtx`){const e=i.get(n);return e?[e]:[]}const r=codecParametersFromString(n.parameters??``).apt;const o=e.find(e=>e.payloadType===r);if(!o)return[];const s=i.get(o);if(!s)return[];const c=t.rtp.codecs.find(e=>{if(codecName2(e)!==`rtx`||a.has(e))return false;return codecParametersFromString(e.parameters??``).apt===s.payloadType});if(!c)return[];a.add(c);return[c]});if(n===`remote`){const e=new Map(t.rtp.codecs.map((e,t)=>[e,t]));o.sort((t,n)=>e.get(t)-e.get(n))}if(o.length===0)throw createWebRtcDomException(`NotSupportedError`,`No compatible codec remains after remote negotiation.`);return o}refreshAnswerCodecs(e,t){const n=this.config.codecs[t.kind]||[];const r=getTrackSourceCodecs(e.sender.track);assertCodecsSupported({kind:t.kind,configured:n,source:r,preferences:e.codecPreferences});const i=resolveCodecs(n,r,e.codecPreferences);e.codecs=this.resolveRemoteCodecSet(i,t,`local`,r);e.codecPreferencesNeedResolution=false;log35(`negotiated codecs`,e.codecs)}planRemoteRtpCodecs(e,t){const n=/* @__PURE__ */ new Map;const r=e.type===`offer`;for(const[i,a]of e.media.entries()){if(![`audio`,`video`].includes(a.kind))continue;const e=t(a,i);if(a.port===0||e?.stopped||e?.stopping){n.set(i,[]);continue}const o=getTrackSourceCodecs(e?.sender.track);const s=this.config.codecs[a.kind]||[];const c=r?s:e?.pendingLocalOfferCodecs||[];if(!hasCommonPrimaryMimeType(c,a.rtp.codecs)){n.set(i,[]);continue}if(r)assertCodecsSupported({kind:a.kind,configured:s,source:o,preferences:e?.codecPreferences});const u=this.resolveRemoteCodecSet(r?resolveCodecs(s,o,e?.codecPreferences):c,a,r?`local`:`remote`,o);if(o!=void 0)assertCodecsSupported({kind:a.kind,configured:u,source:o,preferences:void 0});n.set(i,u)}return n}setRemoteRTP(e,t,n,r,i){if(!e.mid)e.mid=t.rtp.muxId??null;e.mLineIndex=r;if(n===`answer`)e.pendingLocalOfferCodecs=void 0;if(e.stopped)return false;if(e.stopping){if(n===`answer`&&t.port===0)e.commitStopped({rejected:false});return false}log35(`negotiated codecs`,i);if(t.port===0||i.length===0){if(n===`answer`)e.commitStopped({rejected:true});else e.pendingRejection=true;return false}e.pendingRejection=false;e.codecs=i;e.headerExtensions=t.rtp.headerExtensions.filter(e=>(this.config.headerExtensions[t.kind]||[]).find(t=>t.uri===e.uri));const a=t.direction??`inactive`;const o=reverseDirection(a);if([`answer`,`pranswer`].includes(n))e.setCurrentDirection(o);else e.offerDirection=o;const s=this.getLocalRtpParams(e);e.sender.prepareSend(s);if([`recvonly`,`sendrecv`].includes(e.direction)){const n=this.getRemoteRtpParams(t,e);for(const r of t.simulcastParameters)this.router.registerRtpReceiverByRid(e,r,n);e.receiver.resyncCodecs(n,t.ssrc[0]?.ssrc);this.router.registerRtpReceiverBySsrc(e,n)}if([`sendonly`,`sendrecv`].includes(a)){const n=[...new Set(t.msids.map(e=>e.split(` `)[0]))];const r=t.msids[0]?.split(` `)[1];e.receiver.remoteStreamId=n[0];e.receiver.remoteStreamIds=n;e.receiver.remoteTrackId=r;if(!e.firedReceiving){e.firedReceiving=true;this.onTrack.execute({track:e.receiver.track,transceiver:e,streams:n.map(t=>new MediaStream({id:t,tracks:[e.receiver.track]}))})}}else e.firedReceiving=false;return true}beginRemoteOffer(){if(this.remoteOfferSnapshot)return;this.remoteOfferSnapshot={transceivers:[...this.transceivers],remoteCreated:/* @__PURE__ */ new Set,states:new Map(this.transceivers.map(e=>[e,{mid:e.mid,mLineIndex:e.mLineIndex,pendingRejection:e.pendingRejection,firedReceiving:e.firedReceiving}]))}}commitRemoteOffer(){this.remoteOfferSnapshot=void 0;for(const e of this.transceivers)if(e.pendingRejection)e.commitStopped({rejected:true})}rollbackRemoteOffer(){const e=this.remoteOfferSnapshot;this.remoteOfferSnapshot=void 0;if(!e)return;for(const t of this.transceivers){if(e.states.has(t))continue;if(!e.remoteCreated.has(t)||t.sender.track){t.mid=null;t.mLineIndex=void 0;e.transceivers.push(t);continue}t.forceStop();this.unwatchTransceiver(t)}this.transceivers.splice(0,this.transceivers.length,...e.transceivers);e.transceivers.forEach(e=>this.watchTransceiver(e));for(const[t,n]of e.states){t.mid=n.mid;t.mLineIndex=n.mLineIndex;t.pendingRejection=n.pendingRejection;t.firedReceiving=n.firedReceiving}}settleStoppingTransceivers(e){for(const t of this.transceivers){if(!t.stopping||t.stopped)continue;if(t.mid==void 0||!e.has(t.mid))t.commitStopped({rejected:false})}return this.transceivers.some(e=>e.stopping&&!e.stopped)}collectStats(e){const t=[];for(const n of this.transceivers){if(n.sender)t.push(...n.sender.collectStats(e));if(n.receiver)t.push(...n.receiver.collectStats(e));const r=n.collectCodecStats(e);if(r)t.push(...r)}return t}getStatsRootIds(e){if(!e)return[];const t=[];for(const n of this.transceivers){if(n.sender.track===e)t.push(...n.sender.getStatsRootIds());if(n.receiver.tracks.includes(e))t.push(...n.receiver.getStatsRootIds(e))}return t}close(){for(const e of this.transceivers){e.forceStop();this.unwatchTransceiver(e)}this.onTransceiverAdded.allUnsubscribe();this.onRemoteTransceiverAdded.allUnsubscribe();this.onTrack.allUnsubscribe();this.onNegotiationNeeded.allUnsubscribe()}};var log36=debug(`werift:packages/webrtc/src/transport/sctpManager.ts`);var SctpTransportManager=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new Event2;constructor(){}createSctpTransport(e,t){const n=new RTCSctpTransport(5e3,e,t);n.mid=void 0;n.onDataChannel.subscribe(e=>{this.dataChannelsOpened++;this.dataChannels.push(e);this.onDataChannel.execute(e)});this.sctpTransport=n;return n}createDataChannel(e,t={}){const n=coerceUnsignedShortOption(t.maxPacketLifeTime,`maxPacketLifeTime`);const r=coerceUnsignedShortOption(t.maxRetransmits,`maxRetransmits`);const i={protocol:``,ordered:true,negotiated:false,...t,maxPacketLifeTime:n,maxRetransmits:r};if(i.maxPacketLifeTime!=null&&i.maxRetransmits!=null)throw createWebRtcTypeError(`maxPacketLifeTime and maxRetransmits cannot both be set`);if(!this.sctpTransport)this.sctpTransport=this.createSctpTransport();const a=new RTCDataChannelParameters({id:i.id,label:e,maxPacketLifeTime:i.maxPacketLifeTime,maxRetransmits:i.maxRetransmits,negotiated:i.negotiated,ordered:i.ordered,protocol:i.protocol});const o=new RTCDataChannel(this.sctpTransport,a);this.dataChannelsOpened++;this.dataChannels.push(o);o.stateChange.subscribe(e=>{if(e===`closed`){this.dataChannelsClosed++;const e=this.dataChannels.indexOf(o);if(e!==-1)this.dataChannels.splice(e,1)}});return o}async connectSctp(){if(!this.sctpTransport||!this.sctpRemotePort)return;await this.sctpTransport.start(this.sctpRemotePort);await this.sctpTransport.sctp.stateChanged.connected.asPromise();log36(`sctp connected`)}setRemoteSCTP(e,t){if(!this.sctpTransport)return;this.sctpTransport.setRemoteMaxMessageSize(e.sctpCapabilities?.maxMessageSize);this.sctpRemotePort=e.sctpPort;if(!this.sctpRemotePort)throw new Error(`sctpRemotePort not exist`);this.sctpTransport.setRemotePort(this.sctpRemotePort);this.sctpTransport.mLineIndex=t;if(!this.sctpTransport.mid)this.sctpTransport.mid=e.rtp.muxId}async close(){if(this.sctpTransport){await this.sctpTransport.stop();await new Promise(e=>setImmediate(e))}this.onDataChannel.allUnsubscribe()}async getStats(e=getStatsTimestamp()){const t=[];for(const n of this.dataChannels){const r={type:`data-channel`,id:generateStatsId(`data-channel`,n.id??n.statsId),timestamp:e,label:n.label,protocol:n.protocol,dataChannelIdentifier:n.id??void 0,state:n.readyState,messagesSent:n.messagesSent||0,bytesSent:n.bytesSent||0,messagesReceived:n.messagesReceived||0,bytesReceived:n.bytesReceived||0};t.push(r)}return t}};function coerceUnsignedShortOption(e,t){if(e===void 0)return;const n=Number(e);if(!Number.isFinite(n)||!Number.isInteger(n)||n<0||n>65535)throw createWebRtcTypeError(`${t} must be an unsigned short`);return n}var SDPManager=class{currentLocalDescription;currentRemoteDescription;pendingLocalDescription;pendingRemoteDescription;cname;midSuffix;bundlePolicy;mLineReuse;seenMid=/* @__PURE__ */ new Set;constructor({cname:e,midSuffix:t,bundlePolicy:n,mLineReuse:r}){this.cname=e;this.midSuffix=t??false;this.bundlePolicy=n;this.mLineReuse=r??`compatible`}get localDescription(){if(!this._localDescription)return;return this._localDescription.toJSON()}get remoteDescription(){if(!this._remoteDescription)return;return this._remoteDescription.toJSON()}get _localDescription(){return this.pendingLocalDescription||this.currentLocalDescription}get _remoteDescription(){return this.pendingRemoteDescription||this.currentRemoteDescription}get inactiveRemoteMedia(){return this._remoteDescription?.media?.find?.(e=>e.direction===`inactive`)}createMediaDescriptionForTransceiver(e,t){const n=new MediaDescription(e.kind,9,`UDP/TLS/RTP/SAVPF`,e.codecs.map(e=>e.payloadType));n.direction=t;n.msids=e.msids;n.rtp={codecs:e.codecs,headerExtensions:e.headerExtensions,muxId:e.mid??void 0};n.rtcpHost=`0.0.0.0`;n.rtcpPort=9;n.rtcpMux=true;n.ssrc=[new SsrcDescription({ssrc:e.sender.ssrc,cname:this.cname})];if(e.options.simulcast)n.simulcastParameters=e.options.simulcast.map(e=>new RTCRtpSimulcastParameters(e));if(n.rtp.codecs.find(e=>e.name.toLowerCase()===`rtx`)){n.ssrc.push(new SsrcDescription({ssrc:e.sender.rtxSsrc,cname:this.cname}));n.ssrcGroup=[new GroupDescription(`FID`,[e.sender.ssrc.toString(),e.sender.rtxSsrc.toString()])]}this.addTransportDescription(n,e.dtlsTransport);return n}createRejectedMediaDescription(e,t){const n=e.fmt[0]??e.codecs[0]?.payloadType??0;const r=new MediaDescription(e.kind,0,e.profile,[n]);r.host=DISCARD_HOST;r.direction=`inactive`;r.rtp={codecs:e.codecs.filter(e=>e.payloadType?.toString()===n.toString()),headerExtensions:[],muxId:e.mid};r.rtcpMux=true;if(t){r.iceParams=t.iceTransport.localParameters;r.dtlsParams=t.localParameters}return r}createMediaDescriptionForSctp(e){const t=new MediaDescription(`application`,DISCARD_PORT,`UDP/DTLS/SCTP`,[`webrtc-datachannel`]);t.sctpPort=e.port;t.rtp.muxId=e.mid;t.sctpCapabilities=e.getCapabilities();this.addTransportDescription(t,e.dtlsTransport);return t}addTransportDescription(e,t){const n=t.iceTransport;e.iceCandidates=n.localCandidates;e.iceCandidatesComplete=n.gatheringState===`complete`;e.iceParams=n.localParameters;e.iceOptions=`trickle`;e.host=DISCARD_HOST;e.port=DISCARD_PORT;if(e.direction===`inactive`){if(this.mLineReuse===`aggressive`)e.port=0;e.msids=[]}if(!e.dtlsParams){e.dtlsParams=t.localParameters;if(!e.dtlsParams.fingerprints)e.dtlsParams.fingerprints=t.localParameters.fingerprints}}allocateMid(e=``){let t=``;for(let n=0;;){t=(n++).toString()+e;if(!this.seenMid.has(t))break}this.seenMid.add(t);return t}parseSdp({sdp:e,isLocal:t,signalingState:n,type:r}){const i=SessionDescription.parse(e);this.validateDescription({description:i,isLocal:t,signalingState:n,type:r});i.type=r;return i}validateDescription({description:e,isLocal:t,signalingState:n,type:r}){if(t){if(r===`offer`){if(![`stable`,`have-local-offer`].includes(n))throw createWebRtcDomException(`InvalidStateError`,`Cannot handle offer in signaling state`)}else if([`answer`,`pranswer`].includes(r)){if(![`have-remote-offer`,`have-local-pranswer`].includes(n))throw createWebRtcDomException(`InvalidStateError`,`Cannot handle answer in signaling state`)}}else if(r===`offer`){if(![`stable`,`have-remote-offer`,`have-local-offer`].includes(n))throw createWebRtcDomException(`InvalidStateError`,`Cannot handle offer in signaling state`)}else if([`answer`,`pranswer`].includes(r)){if(![`have-local-offer`,`have-remote-pranswer`].includes(n))throw createWebRtcDomException(`InvalidStateError`,`Cannot handle answer in signaling state`)}}buildOfferSdp(e,t){const n=new SessionDescription;addSDPHeader(`offer`,n);const r=this.findLiveDtlsTransport(e,t);const i=this.currentLocalDescription?.media??[];const a=/* @__PURE__ */ new Set;i.forEach((i,o)=>{const s=i.rtp.muxId;if(!s)return;if(i.kind===`application`){if(!t)throw new Error(`sctpTransport not found`);t.mLineIndex=o;n.media.push(this.createMediaDescriptionForSctp(t))}else{const t=e.find(e=>e.mid===s);if(!t){a.add(o);n.media.push(this.createRejectedMediaDescription({kind:i.kind,profile:i.profile,fmt:i.fmt,codecs:i.rtp.codecs,mid:s},r));return}t.mLineIndex=o;if(t.stopping||t.stopped){n.media.push(this.createRejectedMediaDescription({kind:i.kind,profile:i.profile,fmt:i.fmt,codecs:i.rtp.codecs,mid:s},this.liveTransportOr(t.dtlsTransport,r)));return}n.media.push(this.createMediaDescriptionForTransceiver(t,t.direction))}});for(const t of e.filter(e=>!e.stopping&&!e.stopped&&!n.media.find(t=>t.rtp.muxId===e.mid))){if(t.mid==void 0)t.mid=this.allocateMid(this.midSuffix?`av`:``);const e=this.createMediaDescriptionForTransceiver(t,t.direction);const r=t.mLineIndex;if(r!=void 0&&a.has(r)&&n.media[r]?.kind===t.kind){a.delete(r);n.media[r]=e}else{t.mLineIndex=n.media.length;n.media.push(e)}}if(t&&!n.media.find(e=>e.kind===`application`)){t.mLineIndex=n.media.length;if(t.mid==void 0)t.mid=this.allocateMid(this.midSuffix?`dc`:``);n.media.push(this.createMediaDescriptionForSctp(t))}if(this.bundlePolicy!==`disable`){const e=n.media.filter(e=>e.port!==0).map(e=>e.rtp.muxId).filter(e=>e);if(e.length){const t=new GroupDescription(`BUNDLE`,orderBundleMids(e,this.negotiatedBundleTag));n.group.push(t)}}return n}liveTransportOr(e,t){return e&&e.state!==`closed`?e:t}findLiveDtlsTransport(e,t){return[...e.filter(e=>!e.stopped&&!e.pendingRejection).map(e=>e.dtlsTransport),t?.dtlsTransport,...e.map(e=>e.dtlsTransport)].find(e=>!!e&&e.state!==`closed`)}get negotiatedBundleTag(){return[this.currentLocalDescription,this.currentRemoteDescription].find(e=>e?.type===`answer`)?.group.find(e=>e.semantic===`BUNDLE`)?.items[0]}buildAnswerSdp({transceivers:e,sctpTransport:t,signalingState:n}){if(![`have-remote-offer`,`have-local-pranswer`].includes(n))throw new Error(`createAnswer failed`);if(!this._remoteDescription)throw new Error(`wrong state`);const r=new SessionDescription;addSDPHeader(`answer`,r);const i=this._remoteDescription;const a=this.findLiveDtlsTransport(e,t);for(const n of i.media){let i;let o;let s=true;if([`audio`,`video`].includes(n.kind)){const t=e.find(e=>e.mid!=void 0&&e.mid===n.rtp.muxId);if(!t&&n.port!==0)throw new Error(`Transceiver with mid=${n.rtp.muxId} not found`);if(!t||n.port===0||t.stopped||t.pendingRejection){s=false;i=this.liveTransportOr(t?.dtlsTransport,a);o=this.createRejectedMediaDescription({kind:n.kind,profile:n.profile,fmt:n.fmt,codecs:n.rtp.codecs,mid:n.rtp.muxId},i)}else{o=this.createMediaDescriptionForTransceiver(t,t.stopping?`inactive`:andDirection(t.direction,t.offerDirection));i=t.dtlsTransport}}else if(n.kind===`application`){if(!t||!t.mid)throw new Error(`sctpTransport not found`);o=this.createMediaDescriptionForSctp(t);i=t.dtlsTransport}else throw new Error(`invalid kind`);if(o.dtlsParams&&i){if(i.role===`auto`)o.dtlsParams.role=`client`;else o.dtlsParams.role=i.role}if(s&&n.simulcastParameters&&n.simulcastParameters.length>0)o.simulcastParameters=n.simulcastParameters.map(e=>({...e,direction:e.direction===`send`?`recv`:`send`}));r.media.push(o)}if(this.bundlePolicy!==`disable`)r.group.push(...this.buildAnswerBundleGroups(i,r));return r}buildAnswerBundleGroups(e,t){const n=new Set(t.media.filter(e=>e.port!==0&&e.rtp.muxId).map(e=>e.rtp.muxId));const r=this.negotiatedBundleTag;return e.group.filter(e=>e.semantic===`BUNDLE`).map(e=>e.items.filter((e,t,r)=>{return n.has(e)&&r.indexOf(e)===t})).filter(e=>e.length>0).map(e=>new GroupDescription(`BUNDLE`,orderBundleMids(e,r)))}assertRemoteAnswerCodecs(e){if(![`answer`,`pranswer`].includes(e.type))return;const t=this.pendingLocalDescription;if(!t)return;e.media.forEach((n,r)=>{if(![`audio`,`video`].includes(n.kind)||n.port===0)return;const i=t.media[r];if(!i||i.port===0||i.kind!==n.kind)return;if(!n.rtp.codecs.some(e=>e.name.toLowerCase()!==`rtx`&&i.rtp.codecs.some(t=>normalizeCodecMimeType(t.mimeType)===normalizeCodecMimeType(e.mimeType))))throw createWebRtcDomException(`InvalidAccessError`,`No common codec for m-line ${r} (mid=${n.rtp.muxId}) in remote ${e.type}`)})}assertBundlePreserved(e){if(e.type!==`offer`||this.bundlePolicy===`disable`)return;const t=[this.currentLocalDescription,this.currentRemoteDescription].find(e=>e?.type===`answer`)?.group.filter(e=>e.semantic===`BUNDLE`)??[];const n=e.group.filter(e=>e.semantic===`BUNDLE`);for(const r of t){let t;for(const i of r.items){const r=e.media.find(e=>e.rtp.muxId===i);if(!r||r.port===0)continue;const a=n.find(e=>e.items.includes(i));if(!a)throw createWebRtcDomException(`InvalidAccessError`,`BUNDLE transport of mid=${i} cannot be preserved by the remote offer`);t??=a;if(a!==t)throw createWebRtcDomException(`InvalidAccessError`,`BUNDLE transport of mid=${i} cannot be split into another BUNDLE group by the remote offer`)}}}setLocalDescription(e){if(e.type===`offer`||e.type===`pranswer`){this.pendingLocalDescription=e;return}this.currentLocalDescription=e;if(this.pendingRemoteDescription)this.currentRemoteDescription=this.pendingRemoteDescription;this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0}setRemoteDescription(e,t){if(!e.type)throw new Error(`invalid sessionDescription`);if(e.type===`rollback`){if(![`have-remote-offer`,`have-local-pranswer`].includes(t))throw createWebRtcDomException(`InvalidStateError`,`Cannot rollback remote description in signaling state`);this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0;return}if(!e.sdp)throw new Error(`invalid sessionDescription`);const n=this.parseSdp({sdp:e.sdp,isLocal:false,signalingState:t,type:e.type});this.assertRemoteAnswerCodecs(n);this.assertBundlePreserved(n);if(n.type===`offer`||n.type===`pranswer`)this.pendingRemoteDescription=n;else{if(this.pendingLocalDescription)this.currentLocalDescription=this.pendingLocalDescription;this.currentRemoteDescription=n;this.pendingRemoteDescription=void 0;this.pendingLocalDescription=void 0}return n}rollbackLocalDescription(e){if(![`have-local-offer`,`have-local-pranswer`].includes(e))throw createWebRtcDomException(`InvalidStateError`,`Cannot rollback local description in signaling state`);this.pendingLocalDescription=void 0;this.pendingRemoteDescription=void 0}registerMid(e){this.seenMid.add(e)}get remoteIsBundled(){const e=this._remoteDescription;if(!e)return;return e.group.find(e=>e.semantic===`BUNDLE`&&this.bundlePolicy!==`disable`)}setLocal(e,t,n){const r=new Map(t.map(e=>[e?.mLineIndex,e]));const i=t.find(e=>e?.dtlsTransport)?.dtlsTransport??n?.dtlsTransport;e.media.forEach((e,n)=>{if(![`audio`,`video`].includes(e.kind))return;const a=t.find(t=>t?.mid!=void 0&&t.mid===e.rtp.muxId)??r.get(n);if(e.port===0){if(!(a&&!a.stopping&&!a.stopped&&!a.pendingRejection))return}const o=a?.dtlsTransport??i;if(!o)throw new Error(`dtls transport not found for media index ${n}`);const s=e.port;this.addTransportDescription(e,o);if(s===0)e.port=0});const a=e.media.find(e=>e.kind===`application`);if(n&&a)this.addTransportDescription(a,n.dtlsTransport);this.setLocalDescription(e)}};function orderBundleMids(e,t){if(!t||!e.includes(t))return e;return[t,...e.filter(e=>e!==t)]}var log37=debug(`werift:packages/webrtc/src/transport/secureTransportManager.ts`);var SecureTransportManager=class{connectionState=`new`;iceConnectionState=`new`;iceGatheringState=`new`;certificate;iceGatheringStateChange=new Event2;iceConnectionStateChange=new Event2;onIceCandidate=new Event2;connectionStateChange=new Event2;config;transceiverManager;sctpManager;constructor({config:e,transceiverManager:t,sctpManager:n}){this.config=e;this.transceiverManager=t;this.sctpManager=n;if(this.config.dtls){const{keys:e}=this.config.dtls;if(this.config.certificates[0])this.certificate=this.config.certificates[0];else if(e)this.setupCertificate(e)}}get dtlsTransports(){return uniqueTransports([...this.transceiverManager.getTransceivers().filter(e=>!e.stopped).map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport])}get allDtlsTransports(){return uniqueTransports([...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport])}get iceTransports(){return this.dtlsTransports.map(e=>e.iceTransport)}setupCertificate(e){this.certificate=new RTCCertificate(e.keyPem,e.certPem,e.signatureHash)}resolveIceServerOptions(){const e=parseIceServers(this.config.iceServers);const t=resolveTurnTransport({parsedTurnTransport:e.turnTransport,configuredTurnTransport:this.config.turnTransport,forceTurnTCP:this.config.forceTurnTCP});return{stunServer:e.stunServer,turnServer:e.turnServer,turnUsername:e.turnUsername,turnPassword:e.turnPassword,turnTransport:t}}updateIceServers(){const e={...this.resolveIceServerOptions(),forceTurn:this.config.iceTransportPolicy===`relay`,useTcp:this.config.iceUseTcp,turnUdpFamily:this.config.turnUdpFamily};for(const t of this.iceTransports)if(t.gatheringState===`new`)t.setIceServers(e)}createTransport({inheritCredentials:e=true}={}){const t=e?this.iceTransports.find(e=>e.state!==`closed`):void 0;const n=new RTCIceGatherer({...this.resolveIceServerOptions(),iceLite:this.config.iceLite,forceTurn:this.config.iceTransportPolicy===`relay`,portRange:this.config.icePortRange,interfaceAddresses:this.config.iceInterfaceAddresses,additionalHostAddresses:this.config.iceAdditionalHostAddresses,filterStunResponse:this.config.iceFilterStunResponse,filterCandidatePair:this.config.iceFilterCandidatePair,localPasswordPrefix:this.config.icePasswordPrefix,useIpv4:this.config.iceUseIpv4,useIpv6:this.config.iceUseIpv6,useTcp:this.config.iceUseTcp,tcpPassive:this.config.iceTcpPassive,stunGatherTimeout:this.config.iceStunGatherTimeout,turnConnectTimeout:this.config.iceTurnConnectTimeout,turnTlsOptions:this.config.turnTlsOptions,turnUdpFamily:this.config.turnUdpFamily,useLinkLocalAddress:this.config.iceUseLinkLocalAddress});if(t){n.connection.localUsername=t.connection.localUsername;n.connection.localPassword=t.connection.localPassword}n.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()});this.updateIceGatheringState();const r=new RTCIceTransport(n);r.onStateChange.subscribe(()=>{this.updateIceConnectionState()});return new RTCDtlsTransport(this.config,r,this.certificate,srtpProfiles)}handleNewIceCandidate({candidate:e,sdpMid:t,sdpMLineIndex:n}){e.sdpMid=t;e.sdpMLineIndex=n;if(e.foundation&&!e.foundation.startsWith(`candidate:`))e.foundation=`candidate:`+e.foundation;this.onIceCandidate.execute(e);return e}async addIceCandidate(e,t){const n=t?.candidate;const r=t?.sdpMid;const i=t?.sdpMLineIndex;const a=t?.usernameFragment;const o=t==null||n==null||n===``;const s=this.resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:o,sdpMid:r,sdpMLineIndex:i,usernameFragment:a});if(o){const t=s.map(t=>this.getTransportByMLineIndex(e,t)).filter(e=>!!e).reduce((e,t)=>{if(!e.find(({id:e})=>e===t.id))e.push(t);return e},[]);await Promise.all(t.map(e=>e.addRemoteCandidate(void 0)));return{kind:`end-of-candidates`,mediaIndices:s}}const c=IceCandidate.fromJSON(t);if(!c)throw createWebRtcDomException(`OperationError`,`Failed to parse ICE candidate`);const u=s[0];const d=e.media[u];if(!d)throw createWebRtcDomException(`OperationError`,`ICE media section not found`);c.sdpMid=d.rtp.muxId??void 0;c.sdpMLineIndex=u;const f=this.getTransportByMLineIndex(e,u);if(!f){if(this.isRejectedMedia(d))return{kind:`candidate`,candidate:c,mediaIndices:[u]};throw createWebRtcDomException(`OperationError`,`ICE transport not found for candidate`)}await f.addRemoteCandidate(c);return{kind:`candidate`,candidate:c,mediaIndices:[u]}}resolveCandidateMediaIndices({sdp:e,isEndOfCandidates:t,sdpMid:n,sdpMLineIndex:r,usernameFragment:i}){let a;if(typeof n===`string`){const t=e.media.findIndex(e=>e.rtp.muxId===n);if(t<0)throw createWebRtcDomException(`OperationError`,`Media section for sdpMid was not found`);a=[t]}else if(typeof r===`number`){if(r<0||r>=e.media.length)throw createWebRtcDomException(`OperationError`,`Media section for sdpMLineIndex was not found`);a=[r]}else if(t)a=e.media.map((e,t)=>t);else throw createWebRtcTypeError(`sdpMid or sdpMLineIndex must be provided with a candidate`);if(typeof i===`string`){const t=a.filter(t=>e.media[t]?.iceParams?.usernameFragment===i);if(t.length===0)throw createWebRtcDomException(`OperationError`,`No media section matched the ICE usernameFragment`);a=t}return a}isRejectedMedia(e){if(e.port===0)return true;if(![`audio`,`video`].includes(e.kind))return false;const t=this.transceiverManager.getTransceivers().find(t=>t.mid!=void 0&&t.mid===e.rtp.muxId);return!t||t.stopped||t.stopping||t.pendingRejection}getTransportByMid(e){if(!e)return;let t;const n=this.transceiverManager.getTransceivers().find(t=>t.mid===e);if(n)t=n.dtlsTransport?.iceTransport;else if(!t&&this.sctpManager.sctpTransport?.mid===e)t=this.sctpManager.sctpTransport.dtlsTransport.iceTransport;if(t?.state===`closed`)return;return t}getTransportByMLineIndex(e,t){const n=e.media[t];if(!n)return;return this.getTransportByMid(n.rtp.muxId)}restartIce(){for(const e of this.iceTransports)e.restart();this.updateIceGatheringState()}setLocalRole({type:e,role:t,roleOfTransport:n}){for(const r of this.dtlsTransports){const i=r.iceTransport;if(i.connection.iceLite)i.connection.iceControlling=false;else if(i.connection.remoteIsLite)i.connection.iceControlling=true;else if(e===`offer`)i.connection.iceControlling=true;else i.connection.iceControlling=false;if(e===`answer`){const e=n?.get(r)??t;if(e)r.role=e}}}updateIceGatheringState(){const e=this.iceTransports;function allMatch(...t){return e.filter(e=>t.includes(e.gatheringState)).length===e.length}let t;if(e.length&&allMatch(`complete`))t=`complete`;else if(!e.length||allMatch(`new`,`complete`))t=`new`;else if(e.map(e=>e.gatheringState).includes(`gathering`))t=`gathering`;else t=`new`;if(this.iceGatheringState===t)return;this.iceGatheringState=t;this.iceGatheringStateChange.execute(t)}updateIceConnectionState(){const e=this.iceTransports;let t;function allMatch(...t){return e.filter(e=>t.includes(e.state)).length===e.length}function anyMatch(...t){return e.some(e=>t.includes(e.state))}if(this.connectionState===`closed`)t=`closed`;else if(anyMatch(`failed`))t=`failed`;else if(anyMatch(`disconnected`))t=`disconnected`;else if(allMatch(`new`,`closed`))t=`new`;else if(anyMatch(`new`,`checking`))t=`checking`;else if(allMatch(`completed`,`closed`))t=`completed`;else if(allMatch(`connected`,`completed`,`closed`))t=`connected`;else t=`new`;if(this.iceConnectionState===t)return;log37(`iceConnectionStateChange`,t);this.iceConnectionState=t;this.iceConnectionStateChange.execute(t);if(t===`failed`&&this.connectionState!==`closed`)this.setConnectionState(`failed`);else if(t===`disconnected`&&this.connectionState===`connected`)this.setConnectionState(`disconnected`)}async gatherCandidates(){await Promise.allSettled(this.iceTransports.filter(e=>e.state!==`closed`).map(e=>e.gather())).catch(e=>{log37(`gatherCandidates failed`,e)})}setConnectionState(e){if(this.connectionState===e)return;log37(`connectionStateChange`,e);this.connectionState=e;this.connectionStateChange.execute(e)}async getStats(e){const t=[];for(const n of this.dtlsTransports){const r=await n.getStats(e);if(r)t.push(...r)}return t}async ensureCerts(){if(!this.certificate)this.certificate=await RTCDtlsTransport.SetupCertificate();for(const e of this.dtlsTransports)e.localCertificate=this.certificate}async close(){this.setConnectionState(`closed`);await Promise.allSettled([...this.allDtlsTransports.map(e=>e.stop())]);this.iceGatheringStateChange.allUnsubscribe();this.iceConnectionStateChange.allUnsubscribe();this.onIceCandidate.allUnsubscribe();this.connectionStateChange.allUnsubscribe()}};function uniqueTransports(e){return e.reduce((e,t)=>{if(t&&!e.map(e=>e.id).includes(t.id))e.push(t);return e},[])}var srtpProfiles=[SRTP_PROFILE.SRTP_AEAD_AES_128_GCM,SRTP_PROFILE.SRTP_AES128_CM_HMAC_SHA1_80];var log38=debug(`werift:packages/webrtc/src/peerConnection.ts`);var RTCPeerConnection=class extends EventTarget{id=randomUUID$1().toString();cname=randomUUID$1().toString();config=generateDefaultPeerConfig();signalingState=`stable`;negotiationneeded=false;negotiationneededScheduled=false;negotiationChangeSeq=0;negotiatedChangeSeq=0;pendingOfferChangeSeq;lastCreatedOfferChangeSeq=0;needRestart=false;router=new RtpRouter;sdpManager;transceiverManager;sctpManager;secureManager;isClosed=false;shouldNegotiationneeded=false;lastCreatedAnswer;lastCreatedOffer;pendingRemoteCandidates=[];iceGatheringStateChange=new Event2;iceConnectionStateChange=new Event2;signalingStateChange=new Event2;connectionStateChange=new Event2;onDataChannel=new Event2;onRemoteTransceiverAdded=new Event2;onTransceiverAdded=new Event2;onIceCandidate=new Event2;onNegotiationneeded=new Event2;onTrack=new Event2;eventHandlers={};get ondatachannel(){return this.eventHandlers.ondatachannel??null}set ondatachannel(e){this.eventHandlers.ondatachannel=e??void 0}get onicecandidate(){return this.eventHandlers.onicecandidate??null}set onicecandidate(e){this.eventHandlers.onicecandidate=e??void 0}get onicecandidateerror(){return this.eventHandlers.onicecandidateerror??null}set onicecandidateerror(e){this.eventHandlers.onicecandidateerror=e??void 0}get onicegatheringstatechange(){return this.eventHandlers.onicegatheringstatechange??null}set onicegatheringstatechange(e){this.eventHandlers.onicegatheringstatechange=e??void 0}get onnegotiationneeded(){return this.eventHandlers.onnegotiationneeded??null}set onnegotiationneeded(e){this.eventHandlers.onnegotiationneeded=e??void 0}get onsignalingstatechange(){return this.eventHandlers.onsignalingstatechange??null}set onsignalingstatechange(e){this.eventHandlers.onsignalingstatechange=e??void 0}get ontrack(){return this.eventHandlers.ontrack??null}set ontrack(e){this.eventHandlers.ontrack=e??void 0}get onconnectionstatechange(){return this.eventHandlers.onconnectionstatechange??null}set onconnectionstatechange(e){this.eventHandlers.onconnectionstatechange=e??void 0}get oniceconnectionstatechange(){return this.eventHandlers.oniceconnectionstatechange??null}set oniceconnectionstatechange(e){this.eventHandlers.oniceconnectionstatechange=e??void 0}constructor(e={}){super();this.setConfiguration(e);this.sdpManager=new SDPManager({cname:this.cname,bundlePolicy:this.config.bundlePolicy,mLineReuse:this.config.mLineReuse});this.transceiverManager=new TransceiverManager(this.cname,this.config,this.router);this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded);this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded);this.transceiverManager.onTrack.subscribe(({track:e,streams:t,transceiver:n})=>{const r=new RTCTrackEvent({track:e,streams:t,transceiver:n,receiver:n.receiver});this.onTrack.execute(e);this.emit(`track`,r);if(this.ontrack)this.ontrack(r)});this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation());this.sctpManager=new SctpTransportManager;this.sctpManager.onDataChannel.subscribe(e=>{this.onDataChannel.execute(e);const t={type:`datachannel`,channel:e};this.ondatachannel?.(t);this.emit(`datachannel`,t)});this.secureManager=new SecureTransportManager({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager});this.secureManager.iceGatheringStateChange.subscribe(e=>{this.iceGatheringStateChange.execute(e);this.onicegatheringstatechange?.(new globalThis.Event(`icegatheringstatechange`));this.emit(`icegatheringstatechange`)});this.secureManager.iceConnectionStateChange.subscribe(e=>{if(e===`closed`)this.close();this.iceConnectionStateChange.execute(e);this.oniceconnectionstatechange?.();this.emit(`iceconnectionstatechange`)});this.secureManager.connectionStateChange.subscribe(e=>{this.connectionStateChange.execute(e);this.onconnectionstatechange?.();this.emit(`connectionstatechange`)});this.secureManager.onIceCandidate.subscribe(e=>{const t=e?e.toJSON():void 0;this.onIceCandidate.execute(t);const n={type:`icecandidate`,candidate:t};this.onicecandidate?.(n);this.emit(`icecandidate`,n)})}get connectionState(){return this.secureManager.connectionState}get iceConnectionState(){return this.secureManager.iceConnectionState}get iceGathererState(){return this.secureManager.iceGatheringState}get iceGatheringState(){return this.secureManager.iceGatheringState}get dtlsTransports(){return this.secureManager.dtlsTransports}get sctpTransport(){return this.sctpManager.sctpTransport}get sctp(){return this.sctpTransport??null}get sctpRemotePort(){return this.sctpManager.sctpRemotePort}get iceTransports(){return this.secureManager.iceTransports}get extIdUriMap(){return this.router.extIdUriMap}get iceGeneration(){return this.iceTransports[0].connection.generation}get localDescription(){return this.sdpManager.localDescription??null}get currentLocalDescription(){return this.sdpManager.currentLocalDescription?.toJSON()??null}get pendingLocalDescription(){return this.sdpManager.pendingLocalDescription?.toJSON()??null}get remoteDescription(){return this.sdpManager.remoteDescription??null}get currentRemoteDescription(){return this.sdpManager.currentRemoteDescription?.toJSON()??null}get pendingRemoteDescription(){return this.sdpManager.pendingRemoteDescription?.toJSON()??null}get canTrickleIceCandidates(){const e=this.sdpManager._remoteDescription;if(!e)return null;return[e.iceOptions,...e.media.map(e=>e.iceOptions)].filter(e=>!!e).join(` `).split(/\s+/).includes(`trickle`)}get remoteIsBundled(){return this.sdpManager.remoteIsBundled}get _localDescription(){return this.sdpManager._localDescription}get _remoteDescription(){return this.sdpManager._remoteDescription}getTransceivers(){return this.transceiverManager.getTransceivers()}getSenders(){return this.transceiverManager.getSenders()}getReceivers(){return this.transceiverManager.getReceivers()}setConfiguration(e){const t=normalizePeerConfiguration(e);const n=!!this.sdpManager;if(t.rtcpMuxPolicy&&t.rtcpMuxPolicy!==`require`)throw new Error(`rtcpMuxPolicy must be require`);if(t.iceCandidatePoolSize!==void 0&&(!Number.isInteger(t.iceCandidatePoolSize)||t.iceCandidatePoolSize<0))throw new Error(`iceCandidatePoolSize must be a non-negative integer`);if(n&&t.bundlePolicy!==void 0&&t.bundlePolicy!==this.config.bundlePolicy)throw new Error(`bundlePolicy cannot be changed`);if(t.mLineReuse!==void 0&&!MLineReuseModes.includes(t.mLineReuse))throw createWebRtcTypeError(`mLineReuse must be one of ${MLineReuseModes.join(`, `)}`);if(n&&t.mLineReuse!==void 0&&t.mLineReuse!==this.config.mLineReuse)throw createWebRtcDomException(`InvalidModificationError`,`mLineReuse cannot be changed`);if(n&&t.rtcpMuxPolicy!==void 0&&t.rtcpMuxPolicy!==this.config.rtcpMuxPolicy)throw new Error(`rtcpMuxPolicy cannot be changed`);if(n&&t.certificates!==void 0&&!hasSameCertificates(t.certificates,this.config.certificates))throw new Error(`certificates cannot be changed`);if(n&&t.iceCandidatePoolSize!==void 0&&this.localDescription&&t.iceCandidatePoolSize!==this.config.iceCandidatePoolSize)throw new Error(`iceCandidatePoolSize cannot be changed after setLocalDescription`);if((t.iceCandidatePoolSize??0)>0)throw new Error(`iceCandidatePoolSize > 0 is not supported`);if(t.sctp!==void 0){const e=t.sctp.mtu??DEFAULT_SCTP_MTU;validateSctpMtu(e);if(this.sctpManager?.sctpTransport&&e!==this.config.sctp.mtu)throw new Error(`sctp.mtu cannot be changed after SCTP transport creation`)}deepMerge(this.config,t);this.config.sctp={mtu:this.config.sctp?.mtu??DEFAULT_SCTP_MTU};if(this.config.icePortRange){const[e,t]=this.config.icePortRange;if(e===t)throw new Error(`should not be same value`);if(e>=t)throw new Error(`The min must be less than max`)}if(!Number.isInteger(this.config.maxMessageSize)||this.config.maxMessageSize<0)throw new Error(`maxMessageSize must be a non-negative integer`);if(this.sctpManager?.sctpTransport)this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize;assignDynamicPayloadTypes(this.config);[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]].forEach((e,t)=>{e.id=1+t});if(n&&this.secureManager&&(t.iceServers!==void 0||t.turnUdpFamily!==void 0))this.secureManager.updateIceServers()}getConfiguration(){return clonePeerConfiguration(this.config)}async createOffer({iceRestart:e}={}){if(e||this.needRestart){this.needRestart=false;this.secureManager.restartIce()}await this.secureManager.ensureCerts();for(const e of this.transceiverManager.getTransceivers()){if(e.codecs.length===0||e.codecPreferencesNeedResolution)this.transceiverManager.assignTransceiverCodecs(e);if(e.headerExtensions.length===0)e.headerExtensions=this.config.headerExtensions[e.kind]??[]}const t=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport).toJSON();this.lastCreatedOffer=t;this.lastCreatedOfferChangeSeq=this.negotiationChangeSeq;return t}createSctpTransport(){const e=this.sctpManager.createSctpTransport(this.config.maxMessageSize,this.config.sctp);const t=this.findOrCreateTransport();e.setDtlsTransport(t);return e}createDataChannel(e,t={}){if(!this.sctpTransport){this.createSctpTransport();this.needNegotiation()}const n=this.sctpManager.createDataChannel(e,t);if(!n.sctp.dtlsTransport){const e=this.findOrCreateTransport();n.sctp.setDtlsTransport(e)}return n}removeTrack(e){if(this.isClosed)throw createWebRtcDomException(`InvalidStateError`,`peer closed`);if(this.transceiverManager.removeTrack(e))this.needNegotiation()}needNegotiation=()=>{this.negotiationChangeSeq++;this.scheduleNegotiationneeded()};scheduleNegotiationneeded(){this.invalidateLastCreatedDescriptions();this.shouldNegotiationneeded=true;if(this.negotiationneeded||this.negotiationneededScheduled||this.signalingState!==`stable`)return;this.shouldNegotiationneeded=false;this.negotiationneededScheduled=true;setImmediate(()=>{this.negotiationneededScheduled=false;if(this.negotiatedChangeSeq>=this.negotiationChangeSeq)return;if(this.signalingState!==`stable`){this.shouldNegotiationneeded=true;return}this.negotiationneeded=true;this.onNegotiationneeded.execute();if(this.onnegotiationneeded)this.onnegotiationneeded(new globalThis.Event(`negotiationneeded`));this.emit(`negotiationneeded`)})}invalidateLastCreatedDescriptions(){this.lastCreatedAnswer=void 0;this.lastCreatedOffer=void 0}async waitForPendingDescriptionTask(){this.assertNotClosed();await Promise.resolve();if(this.isClosed)await new Promise(()=>void 0)}findOrCreateTransport(){const e=this.dtlsTransports.find(e=>e.state!==`closed`);if(this.sdpManager.bundlePolicy===`max-bundle`||this.sdpManager.bundlePolicy!==`disable`&&this.remoteIsBundled){if(e)return e}return this.createDtlsTransport()}createDtlsTransport({inheritCredentials:e=true}={}){const t=this.secureManager.createTransport({inheritCredentials:e});t.onRtp.subscribe(e=>{this.router.routeRtp(e)});t.onRtcp.subscribe(e=>{this.router.routeRtcp(e)});const n=t.iceTransport;n.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()});n.onIceCandidate.subscribe(e=>{if(!this.localDescription){log38(`localDescription not found when ice candidate was gathered`);return}if(!e){this.sdpManager.setLocal(this._localDescription,this.transceiverManager.getTransceivers(),this.sctpTransport);this.onIceCandidate.execute(void 0);if(this.onicecandidate)this.onicecandidate({candidate:void 0});this.emit(`icecandidate`,{candidate:void 0});return}if(!this._localDescription){log38(`localDescription not found when ice candidate was gathered`);return}const t=this.resolveLocalCandidateOwner(n);if(!t){log38(`no accepted m-line owns the ice transport`,n.id);return}this.secureManager.handleNewIceCandidate({candidate:e,sdpMid:t.mid,sdpMLineIndex:t.index})});return t}resolveLocalCandidateOwner(e){const t=this._localDescription;if(!t)return;const n=t.media.map((e,t)=>({media:e,index:t})).filter(({media:t})=>{if(t.port===0)return false;const n=t.rtp.muxId;if(t.kind===`application`)return!!this.sctpTransport&&this.sctpTransport.mid===n&&this.sctpTransport.dtlsTransport?.iceTransport.id===e.id;const r=this.transceiverManager.getTransceivers().find(e=>e.mid!=void 0&&e.mid===n);return!!r&&!r.stopped&&r.dtlsTransport?.iceTransport.id===e.id});const r=t.group.filter(e=>e.semantic===`BUNDLE`).map(e=>e.items[0]);const i=n.find(({media:e})=>r.includes(e.rtp.muxId))??n[0];if(!i)return;return{mid:i.media.rtp.muxId,index:i.index}}settleStoppingTransceivers(){const e=new Set((this.sdpManager.currentLocalDescription?.media??[]).filter(e=>e.port!==0&&e.rtp.muxId).map(e=>e.rtp.muxId));const t=this.transceiverManager.settleStoppingTransceivers(e);this.closeIdleTransports();return t}closeIdleTransports(e=this.transceiverManager.getTransceivers().filter(e=>e.stopped).map(e=>e.dtlsTransport)){const t=new Set(this.dtlsTransports.map(e=>e.id));for(const n of new Set(e)){if(!n||n.state===`closed`||t.has(n.id))continue;n.stop().catch(e=>{log38(`failed to close idle transport`,e)})}}async setLocalDescription(e){const t=[`stable`,`have-local-offer`,`have-remote-pranswer`];await this.waitForPendingDescriptionTask();if(e?.type===`rollback`){this.sdpManager.rollbackLocalDescription(this.signalingState);for(const e of this.transceiverManager.getTransceivers())e.pendingLocalOfferCodecs=void 0;this.pendingOfferChangeSeq=void 0;this.setSignalingState(`stable`);if(this.shouldNegotiationneeded)this.scheduleNegotiationneeded();this.invalidateLastCreatedDescriptions();return}const n=!e?.type||!e.sdp||e.sdp.length===0?e?.type===`offer`?this.lastCreatedOffer??await this.createOffer():e?.type===`answer`||e?.type===`pranswer`?this.lastCreatedAnswer??await this.createAnswer():t.includes(this.signalingState)?this.lastCreatedOffer??await this.createOffer():this.lastCreatedAnswer??await this.createAnswer():void 0;e={type:e?.type??n.type,sdp:e?.sdp&&e.sdp.length>0?e.sdp:n.sdp};if(e.type===`offer`&&this.lastCreatedOffer&&e.sdp!==this.lastCreatedOffer.sdp)throw createWebRtcDomException(`InvalidModificationError`,`setLocalDescription must use the latest created offer`);const r=e.type;const i=e.sdp;const a=this.sdpManager.parseSdp({sdp:i,isLocal:true,signalingState:this.signalingState,type:r});if(a.type===`offer`){this.pendingOfferChangeSeq=this.lastCreatedOffer?.sdp===e.sdp?this.lastCreatedOfferChangeSeq:void 0;this.setSignalingState(`have-local-offer`)}else if(a.type===`answer`)this.setSignalingState(`stable`);else if(a.type===`pranswer`)this.setSignalingState(`have-local-pranswer`);if(a.type===`answer`){this.transceiverManager.commitRemoteOffer();for(const e of a.media){if(![`audio`,`video`].includes(e.kind)||e.port!==0)continue;this.transceiverManager.getTransceivers().find(t=>t.mid===e.rtp.muxId&&!t.stopped)?.commitStopped({rejected:true})}this.closeIdleTransports()}for(const[e,t]of enumerate2(a.media)){const n=t.rtp.muxId;this.sdpManager.registerMid(n);if([`audio`,`video`].includes(t.kind)&&t.port!==0){const r=this.transceiverManager.getTransceivers().find(r=>r.mLineIndex===e&&!r.stopped&&r.kind===t.kind&&(r.mid==null||r.mid===n));if(r){r.mid=n;if(a.type===`offer`)r.pendingLocalOfferCodecs=[...t.rtp.codecs]}}if(t.kind===`application`&&this.sctpTransport)this.sctpTransport.mid=n}const o=a.media.find(e=>e.dtlsParams)?.dtlsParams?.role;const s=/* @__PURE__ */ new Map;for(const e of a.media){const t=e.rtp.muxId;const n=e.dtlsParams?.role;if(e.port===0||t==void 0||!n)continue;const r=e.kind===`application`?this.sctpTransport?.mid===t?this.sctpTransport:void 0:this.transceiverManager.getTransceivers().find(e=>e.mid===t&&!e.stopped);if(r?.dtlsTransport&&!s.has(r.dtlsTransport))s.set(r.dtlsTransport,n)}this.secureManager.setLocalRole({type:a.type===`offer`?`offer`:`answer`,role:o,roleOfTransport:s});if([`answer`,`pranswer`].includes(a.type))for(const e of a.media){const t=this.transceiverManager.getTransceivers().find(t=>t.mid!=void 0&&t.mid===e.rtp.muxId);if(!t||t.stopped||t.pendingRejection)continue;const n=t.stopping?`inactive`:andDirection(t.direction,t.offerDirection);t.setCurrentDirection(n)}this.sdpManager.setLocal(a,this.transceiverManager.getTransceivers(),this.sctpTransport);await this.gatherCandidates().catch(e=>{log38(`gatherCandidates failed`,e)});if(a.type===`answer`)this.connect().catch(e=>{log38(`connect failed`,e);this.secureManager.setConnectionState(`failed`)});this.sdpManager.setLocal(a,this.transceiverManager.getTransceivers(),this.sctpTransport);const c=a.type===`answer`&&this.settleStoppingTransceivers();if(this.shouldNegotiationneeded||c)this.scheduleNegotiationneeded();this.invalidateLastCreatedDescriptions();return a}async gatherCandidates(){await this.secureManager.gatherCandidates()}async addIceCandidate(e={}){if(this.isClosed)throw createWebRtcDomException(`InvalidStateError`,`is closed`);if(!this.remoteDescription||!this.sdpManager._remoteDescription){this.pendingRemoteCandidates.push(e);return}await this.applyRemoteIceCandidate(e)}async applyRemoteIceCandidate(e){const t=this.sdpManager._remoteDescription;if(!t)return;const n=await this.secureManager.addIceCandidate(t,e);const r=this.sdpManager._remoteDescription;if(!r||!n)return;if(n.kind===`end-of-candidates`){for(const e of n.mediaIndices){const t=r.media[e];if(t)t.iceCandidatesComplete=true}return}for(const e of n.mediaIndices){const t=r.media[e];if(!t)continue;t.iceCandidates.push(n.candidate)}}async flushPendingRemoteCandidates(){while(this.pendingRemoteCandidates.length>0&&this.remoteDescription&&this.sdpManager._remoteDescription){const e=this.pendingRemoteCandidates.shift();await this.applyRemoteIceCandidate(e??null)}}async connect(){log38(`start connect`);if((await Promise.allSettled(this.dtlsTransports.map(async e=>{const{iceTransport:t}=e;if(t.state===`connected`)return;const checkDtlsConnected=()=>e.state===`connected`;if(checkDtlsConnected())return;this.secureManager.setConnectionState(`connecting`);await t.start().catch(e=>{log38(`iceTransport.start failed`,e);throw e});if(checkDtlsConnected())return;await e.start().catch(e=>{log38(`dtlsTransport.start failed`,e);throw e});if(this.sctpTransport&&this.sctpTransport.dtlsTransport.id===e.id)await this.sctpManager.connectSctp()}))).find(e=>e.status===`rejected`))this.secureManager.setConnectionState(`failed`);else this.secureManager.setConnectionState(`connected`)}restartIce(){this.needRestart=true;this.needNegotiation()}async setRemoteDescription(e){if(e instanceof SessionDescription)e=e.toSdp();await this.waitForPendingDescriptionTask();let t=/* @__PURE__ */ new Map;if(e.type&&e.type!==`rollback`&&e.sdp){const n=this.sdpManager.parseSdp({sdp:e.sdp,isLocal:false,signalingState:this.signalingState,type:e.type});const r=/* @__PURE__ */ new Set;t=this.transceiverManager.planRemoteRtpCodecs(n,(e,t)=>{const n=this.findTransceiverForRemoteMedia(e,t,r);if(n)r.add(n);return n})}if(e.type===`offer`&&[`have-local-offer`,`have-local-pranswer`].includes(this.signalingState)){this.sdpManager.rollbackLocalDescription(this.signalingState);for(const e of this.transceiverManager.getTransceivers())e.pendingLocalOfferCodecs=void 0;this.pendingOfferChangeSeq=void 0;this.shouldNegotiationneeded=true;this.setSignalingState(`stable`);await Promise.resolve()}this.assertAnswerKeepsSharedTransports(e);const n=this.sdpManager.setRemoteDescription(e,this.signalingState);if(!n){const e=this.transceiverManager.getTransceivers().map(e=>e.dtlsTransport);this.transceiverManager.rollbackRemoteOffer();this.closeIdleTransports(e);this.setSignalingState(`stable`);if(this.shouldNegotiationneeded)this.scheduleNegotiationneeded();this.invalidateLastCreatedDescriptions();return}if(n.type===`offer`)this.transceiverManager.beginRemoteOffer();const r=this.config.bundlePolicy===`disable`?[]:n.group.filter(e=>e.semantic===`BUNDLE`);const groupOfMid=e=>e==void 0?void 0:r.find(t=>t.items.includes(e));const i=/* @__PURE__ */ new Set;const a=n.media.map((e,t)=>{if([`audio`,`video`].includes(e.kind)){let n=this.findTransceiverForRemoteMedia(e,t,i);if(!n){if(e.port===0)return{remoteMedia:e,index:t};n=this.addRemoteTransceiver(e,t)}else if(n.mid==null)this.transceiverManager.associateMLine(n,t);i.add(n);return{remoteMedia:e,index:t,transceiver:n}}else if(e.kind===`application`){let n=this.sctpTransport;if(!n){n=this.createSctpTransport();n.mid=e.rtp.muxId}return{remoteMedia:e,index:t,sctpTransport:n}}else throw new Error(`invalid media kind`)});if(n.type===`offer`)this.transceiverManager.releaseUnassociatedReservations(i,n.media.length);const ownerOf=e=>e.transceiver??e.sctpTransport;const o=n.type===`offer`;const liveTransport=e=>!!e&&e.state!==`closed`;const s=/* @__PURE__ */ new Map;const c=/* @__PURE__ */ new Set;for(const e of r){const t=a.filter(t=>!!ownerOf(t)&&e.items.includes(t.remoteMedia.rtp.muxId));if(t.length===0)continue;let n=t.map(e=>ownerOf(e).dtlsTransport).find(e=>liveTransport(e)&&(!o||!c.has(e)));if(!n)n=this.createDtlsTransport({inheritCredentials:false});s.set(e,n);c.add(n);for(const e of t){const t=ownerOf(e);if(t.dtlsTransport!==n)t.setDtlsTransport(n)}}if(o)for(const e of a){const t=ownerOf(e);if(!t||e.remoteMedia.port===0||groupOfMid(e.remoteMedia.rtp.muxId))continue;if(!liveTransport(t.dtlsTransport)||c.has(t.dtlsTransport))t.setDtlsTransport(this.createDtlsTransport({inheritCredentials:false}));c.add(t.dtlsTransport)}const u=/* @__PURE__ */ new Set;for(const e of a){const{remoteMedia:r,index:i}=e;if(e.transceiver){if(this.transceiverManager.setRemoteRTP(e.transceiver,r,n.type,i,t.get(i)??[]))u.add(e)}else if(e.sctpTransport){this.sctpManager.setRemoteSCTP(r,i);u.add(e)}}const d=/* @__PURE__ */ new Map;for(const e of r)for(const t of e.items){const n=a.find(e=>e.remoteMedia.rtp.muxId===t&&e.remoteMedia.port!==0&&u.has(e));if(n){d.set(e,n);break}}for(const e of a){const{remoteMedia:t}=e;const r=ownerOf(e);if(!r)continue;const i=u.has(e);const a=r.dtlsTransport;const o=groupOfMid(t.rtp.muxId);if(t.port===0||!a||a.state===`closed`||!i&&!o)continue;const s=a.iceTransport;if(!o||d.get(o)===e){if(t.iceParams){const e=!!this.sdpManager.inactiveRemoteMedia;s.setRemoteParams(t.iceParams,e);if(t.iceParams.iceLite&&!s.connection.iceLite)s.connection.iceControlling=true}if(t.dtlsParams)a.setRemoteParams(t.dtlsParams)}t.iceCandidates.forEach(s.addRemoteCandidate);if(t.iceCandidatesComplete)s.addRemoteCandidate(void 0);if(n.type===`answer`&&t.dtlsParams?.role)a.role=t.dtlsParams.role===`client`?`server`:`client`}if(n.type===`answer`){for(const e of this.transceiverManager.getTransceivers())if(!i.has(e)&&e.mid!=void 0&&!e.stopped)e.commitStopped({rejected:true});this.closeIdleTransports()}if(n.type===`offer`)this.setSignalingState(`have-remote-offer`);else if(n.type===`answer`)this.setSignalingState(`stable`);else if(n.type===`pranswer`)this.setSignalingState(`have-remote-pranswer`);await this.flushPendingRemoteCandidates();if(n.type===`answer`){log38(`caller start connect`);this.connect().catch(e=>{log38(`connect failed`,e);this.secureManager.setConnectionState(`failed`)})}this.negotiationneeded=false;if(n.type===`answer`&&this.pendingOfferChangeSeq!=void 0){this.negotiatedChangeSeq=Math.max(this.negotiatedChangeSeq,this.pendingOfferChangeSeq);this.pendingOfferChangeSeq=void 0}const f=n.type===`answer`&&this.settleStoppingTransceivers();if(this.shouldNegotiationneeded||f)this.scheduleNegotiationneeded();this.invalidateLastCreatedDescriptions()}assertAnswerKeepsSharedTransports(e){if(![`answer`,`pranswer`].includes(e.type??``)||![`have-local-offer`,`have-local-pranswer`].includes(this.signalingState)||!e.sdp||this.config.bundlePolicy===`disable`)return;const t=SessionDescription.parse(e.sdp);const n=t.group.filter(e=>e.semantic===`BUNDLE`);const r=/* @__PURE__ */ new Map;for(const i of t.media){const t=i.rtp.muxId;if(i.port===0||t==void 0)continue;const a=(i.kind===`application`?this.sctpTransport?.mid===t?this.sctpTransport:void 0:this.transceiverManager.getTransceivers().find(e=>e.mid===t&&!e.stopped))?.dtlsTransport;if(!a)continue;const o={group:n.find(e=>e.items.includes(t)),credentials:`${i.iceParams?.usernameFragment}:${i.iceParams?.password}`};const s=r.get(a);if(!s){r.set(a,o);continue}if(!(!!o.group&&o.group===s.group)&&o.credentials!==s.credentials)throw createWebRtcDomException(`InvalidAccessError`,`mid=${t} shares a transport in the local offer but the remote ${e.type} moves it out of that BUNDLE group`)}}findTransceiverForRemoteMedia(e,t,n){const r=this.transceiverManager.getTransceivers().filter(t=>!n.has(t)&&t.kind===e.kind);const i=e.rtp.muxId;const a=i!=void 0?r.find(e=>e.mid===i):void 0;if(a)return a;if(e.port===0)return;const o=r.filter(e=>e.mid==null&&!e.stopping&&!e.stopped);return o.find(e=>e.mLineIndex===t)??o[0]}addRemoteTransceiver(e,t){const n=this.findOrCreateTransport();const r=this.transceiverManager.addTransceiver(e.kind,n,{direction:`recvonly`},{remoteMLineIndex:t});r.mid=e.rtp.muxId??null;this.secureManager.updateIceConnectionState();this.onRemoteTransceiverAdded.execute(r);return r}addTransceiver(e,t={}){const n=this.findOrCreateTransport();const r=this.transceiverManager.addTransceiver(e,n,t);this.secureManager.updateIceConnectionState();this.needNegotiation();return r}addTrack(e,...t){if(this.isClosed)throw createWebRtcDomException(`InvalidStateError`,`is closed`);const n=this.transceiverManager.addTrack(e,t);if(!n.dtlsTransport){const e=this.findOrCreateTransport();n.setDtlsTransport(e)}this.needNegotiation();return n.sender}async createAnswer(){this.assertNotClosed();await this.secureManager.ensureCerts();for(const e of this.transceiverManager.getTransceivers()){if(e.codecs.length!==0&&!e.codecPreferencesNeedResolution)continue;if(e.pendingRejection||e.stopping||e.stopped)continue;const t=this.sdpManager._remoteDescription;const n=t?.media.find(t=>t.rtp.muxId!=void 0&&t.rtp.muxId===e.mid&&t.kind===e.kind)??(e.mLineIndex!=void 0?t?.media[e.mLineIndex]:void 0);if(n&&[`audio`,`video`].includes(n.kind))this.transceiverManager.resyncAnswerCodecs(e,n);else this.transceiverManager.assignTransceiverCodecs(e);if(e.headerExtensions.length===0)e.headerExtensions=this.config.headerExtensions[e.kind]??[]}const e=this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState}).toJSON();this.lastCreatedAnswer=e;return e}assertNotClosed(){if(this.isClosed)throw createWebRtcDomException(`InvalidStateError`,`RTCPeerConnection is closed`)}setSignalingState(e){if(this.signalingState===e)return;log38(`signalingStateChange`,e);this.signalingState=e;this.signalingStateChange.execute(e);if(this.onsignalingstatechange)this.onsignalingstatechange(new globalThis.Event(`signalingstatechange`));this.emit(`signalingstatechange`)}createPeerConnectionStats(e){return{type:`peer-connection`,id:generateStatsId(`peer-connection`,this.id),timestamp:e,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(e){const t=getStatsTimestamp();const n=[];if(!e)n.push(this.createPeerConnectionStats(t));n.push(...this.transceiverManager.collectStats(t));const r=await this.secureManager.getStats(t);n.push(...r);if(!e&&this.sctpTransport){const e=await this.sctpManager.getStats(t);if(e)n.push(...e)}if(!e)return buildStatsReport(n);return buildStatsReport(n,this.transceiverManager.getStatsRootIds(e))}async close(){if(this.isClosed)return;this.isClosed=true;this.pendingRemoteCandidates.length=0;this.setSignalingState(`closed`);this.transceiverManager.close();await this.sctpManager.close();await this.secureManager.close();this.completePeerEvents();log38(`peerConnection closed`)}completePeerEvents(){const e=[this.onDataChannel,this.iceGatheringStateChange,this.iceConnectionStateChange,this.signalingStateChange,this.connectionStateChange,this.onTransceiverAdded,this.onRemoteTransceiverAdded,this.onIceCandidate,this.onNegotiationneeded];for(const t of e)if(!t.ended)t.complete()}};var MLineReuseModes=[`compatible`,`aggressive`];var findCodecByMimeType=(e,t)=>e.find(e=>normalizeCodecMimeType(e.mimeType)===normalizeCodecMimeType(t.mimeType))?t:void 0;function assignDynamicPayloadTypes(e){for(const[t,n]of enumerate2([...e.codecs.audio||[],...e.codecs.video||[]])){if(n.payloadType!=void 0)continue;n.payloadType=96+t;switch(n.name.toLowerCase()){case`rtx`:n.parameters=`apt=${n.payloadType-1}`;break;case`red`:if(n.contentType===`audio`){const e=n.payloadType+1;n.parameters=`${e}/${e}`;n.payloadType=63}}}}function generateDefaultPeerConfig(){return{codecs:defaultCodecs(),headerExtensions:{audio:[],video:[]},iceTransportPolicy:`all`,iceLite:false,iceServers:[{urls:`stun:stun.l.google.com:19302`}],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:true,iceUseIpv6:true,iceUseTcp:false,iceTcpPassive:true,iceStunGatherTimeout:void 0,iceTurnConnectTimeout:void 0,turnTransport:void 0,turnTlsOptions:void 0,turnUdpFamily:void 0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:`max-compat`,rtcpMuxPolicy:`require`,iceCandidatePoolSize:0,certificates:[],debug:{},midSuffix:false,forceTurnTCP:false,maxMessageSize:DEFAULT_MAX_MESSAGE_SIZE,sctp:{mtu:DEFAULT_SCTP_MTU},pendingRtp:false,mLineReuse:`compatible`}}var defaultPeerConfig=generateDefaultPeerConfig();function normalizePeerConfiguration(e){const t=Object(e??{});const n={...t};if(t.sctp!==void 0)n.sctp={...t.sctp};if(t.bundlePolicy===`balanced`)n.bundlePolicy=`max-compat`;if(`certificates`in t){if(t.certificates===void 0)n.certificates=void 0;else if(!Array.isArray(t.certificates)||t.certificates.some(e=>e==null))throw createWebRtcTypeError(`certificates must be an array of RTCCertificate`);else n.certificates=[...t.certificates]}if(`iceCandidatePoolSize`in t)n.iceCandidatePoolSize=coerceUnsignedShort(t.iceCandidatePoolSize,`iceCandidatePoolSize`);return n}function coerceUnsignedShort(e,t){const n=Number(e);if(!Number.isFinite(n)||!Number.isInteger(n)||n<0||n>65535)throw createWebRtcTypeError(`${t} must be an unsigned short`);return n}function hasSameCertificates(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function clonePeerConfiguration(e){return{...e,codecs:{audio:e.codecs.audio?[...e.codecs.audio]:void 0,video:e.codecs.video?[...e.codecs.video]:void 0},headerExtensions:{audio:e.headerExtensions.audio?[...e.headerExtensions.audio]:void 0,video:e.headerExtensions.video?[...e.headerExtensions.video]:void 0},iceServers:e.iceServers.map(e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls})),icePortRange:e.icePortRange?[...e.icePortRange]:void 0,iceAdditionalHostAddresses:e.iceAdditionalHostAddresses?[...e.iceAdditionalHostAddresses]:void 0,dtls:{...e.dtls},certificates:[...e.certificates],debug:{...e.debug},sctp:{...e.sctp},pendingRtp:typeof e.pendingRtp===`object`&&e.pendingRtp!=void 0?{...e.pendingRtp}:e.pendingRtp}}var RTCTrackEvent=class{type=`track`;track;streams;transceiver;receiver;constructor(e){this.track=e.track;this.streams=[...e.streams];this.transceiver=e.transceiver;this.receiver=e.receiver}};var SignalingStates=[`stable`,`have-local-offer`,`have-remote-offer`,`have-local-pranswer`,`have-remote-pranswer`,`closed`];var ConnectionStates=[`closed`,`failed`,`disconnected`,`new`,`connecting`,`connected`];export{AAC_HBR_AU_HEADER_BITS,AAC_HBR_INDEX_DELTA_LENGTH,AAC_HBR_INDEX_LENGTH,AAC_HBR_SIZE_LENGTH,AV1Obu,AV1RtpPayload,AacHbrPacketizer,AacHbrRtpPayload,AttributeKeys,Av1Packetizer,BitStream,BitWriter,BitWriter2,BufferChain,CONSENT_FAILURES,CONSENT_INTERVAL,CONSENT_RESPONSE_TIMEOUT,CONSENT_RESPONSE_TIMEOUT_MIN,CONSENT_TIMEOUT,COOKIE,Candidate,CandidatePair,CandidatePairState,CipherContext,CipherSuite,CipherSuiteList,Connection,ConnectionStates,CurveType,DEFAULT_MAX_MESSAGE_SIZE,DePacketizerBase,Directions,DtlsClient,DtlsServer,DtlsSocket,DtlsStates,Event2 as Event,EventDisposer,ExtensionProfiles,FINGERPRINT_LENGTH,FINGERPRINT_XOR,G711_CLOCK_RATE,G722Packetizer,G722RtpPayload,G722_CLOCK_RATE,G722_OCTET_RATE,G722_PAYLOAD_TYPE,GenericNack,GroupDescription,H264Packetizer,H264RtpPayload,H264_MIN_NAL_LENGTH,H265AnnexBParser,H265Packetizer,H265RtpPayload,H265_IRAP_NAL_TYPES,H265_NAL_TYPE,H265_PAYLOAD_TYPE_AP,H265_PAYLOAD_TYPE_FU,H265_PAYLOAD_TYPE_PACI,HEADER_LENGTH,HashAlgorithm,ICE_COMPLETED,ICE_FAILED,INTEGRITY_LENGTH,IPV4_PROTOCOL,IPV6_PROTOCOL,IceCandidate,IceGathererStates,IceTransportStates,Inactive,Int,MPEG4_GENERIC_ENCODING_NAME,MediaDescription,MediaStream,MediaStreamTrack,MediaStreamTrackFactory,Message,NalUnitType,NamedCurveAlgorithm,NamedCurveAlgorithmList,OPUS_CLOCK_RATE,OpusPacketizer,OpusRtpPayload,PCMA_PAYLOAD_TYPE,PCMU_PAYLOAD_TYPE,PacketChunk,PacketResult,PacketStatus,PacketizerBase,PcmaPacketizer,PcmaRtpPayload,PcmuPacketizer,PcmuRtpPayload,PictureLossIndication,Profiles,PromiseQueue,ProtectionProfileAeadAes128Gcm,ProtectionProfileAes128CmHmacSha1_80,RETRY_MAX,RETRY_RTO,RTCCertificate,RTCDataChannel,RTCDataChannelParameters,RTCDtlsFingerprint,RTCDtlsParameters,RTCDtlsTransport,RTCIceCandidate,RTCIceGatherer,RTCIceParameters,RTCIceTransport,RTCP_HEADER_SIZE,RTCPeerConnection,RTCRtcpFeedback,RTCRtcpParameters,RTCRtpCodecParameters,RTCRtpCodingParameters,RTCRtpHeaderExtensionParameters,RTCRtpReceiver,RTCRtpRtxParameters,RTCRtpSender,RTCRtpSimulcastParameters,RTCRtpTransceiver,RTCSctpCapabilities2 as RTCSctpCapabilities,RTCSctpTransport,RTCSessionDescription,RTCStatsReport,RTCTrackEvent,RTP_EXTENSION_URI,ReceiverEstimatedMaxBitrate,RecvDelta,Recvonly,Red,RedEncoder,RedHandler,RedHeader,RtcpHeader,RtcpPacketConverter,RtcpPayloadSpecificFeedback,RtcpReceiverInfo,RtcpRrPacket,RtcpSenderInfo,RtcpSourceDescriptionPacket,RtcpSrPacket,RtcpTransportLayerFeedback,RtpBuilder,RtpHeader,RtpMediaClock,RtpMediaPacer,RtpMediaTimeline,RtpPacket,RtpRouter,RunLengthChunk,SDPManager,Sendonly,Sendrecv,SessionDescription,SignalingStates,SignatureAlgorithm,SignatureScheme,SourceDescriptionChunk,SourceDescriptionItem,SrtcpSession,SrtpAuthenticationError,SrtpContext,SrtpSession,SsrcDescription,StatusVectorChunk,StunOverTurnProtocol,StunProtocol,TCP_CHECK_RESPONSE_TIMEOUT_MS,TELEPHONE_EVENT_DEFAULT_CLOCK_RATE,TELEPHONE_EVENT_DEFAULT_PAYLOAD_TYPE,TcpActiveProtocol,TcpPassiveProtocol,TcpTransport,TelephoneEventPacketizer,TelephoneEventRtpPayload,TlsTransport,TransceiverManager,TransportWideCC,TurnProtocol,UdpTransport,VP8_PAYLOAD_DESCRIPTOR_LENGTH,Vp8Packetizer,Vp8RtpPayload,Vp9Packetizer,Vp9RtpPayload,WeriftError,addSDPHeader,andDirection,applyCodecPreferences,assertCodecsSupported,binaryData_exports as binaryData,buffer2ArrayBuffer,bufferArrayXor,bufferReader,bufferWriter,bufferWriterLE,bufferXor,buildH264StapA,buildStatsReport,candidateFoundation,candidateFromIce,candidateFromSdp,candidateLocalPreference,candidatePairPriority,candidatePriority,candidateToIce,candidateToSdp,captureTrackSourceCodecs,certificateTypes,classes,cloneCodecParameters,codecParametersFromString,codecParametersToString,compactNtp,consentResponseTimeoutMs,crc32,crc32c,createAv1AggregationHeader,createBufferWriter,createSelfSignedCertificate,createStunOverTurnClient,createTurnClient,createVp8PayloadDescriptor,dePacketizeRtpPackets,debug,deepMerge,defaultCodecs,defaultOptions,defaultPeerConfig,deliveredTrackCodec,depacketizerCodecs,deserializeAbsSendTime,deserializeAudioLevelIndication,deserializeString,deserializeUint16BE,deserializeVideoOrientation,dumpBuffer,encodeTcpFrame,enumerate,findCodecByMimeType,findPort,fingerprint,generateCodecStatsId,generateStatsId,getBit,getDataChannelMessageSize,getGlobalIp,getHostAddresses,getReferencedStatsIds,getStatsTimestamp,getTrackSourceCodecs,growBufferSize,hasCommonPrimaryMimeType,int,interfaceAddress,intersectCodecs,isCodecCompatible,isComprehensionRequiredAttribute,isDtls,isLinkLocalAddress,isMedia,isRtcp,isStunMessage,keyLength,leb128decode,makeIntegrityKey,methods,microTime,milliTime,nodeIpAddress,normalizeCodecMimeType,normalizeFamilyNodeV18,normalizeFingerprintAlgorithm,normalizeFingerprintValue,ntpTime,ntpTime2Sec,ntpTimeToEpochMs,paddingBits,paddingByte,paddingLength,parseAvcDecoderConfigurationRecord,parseGroup,parseH265PayloadHeader,parseIceServers,parseMessage,random16,random32,randomPort,randomPorts,remoteTcpTypeForIncoming,resolveCodecs,resolveTurnTransport,reverseDirection,reverseSimulcastDirection,rtpHeaderExtensionsParser,saltLength,selectMissingH264ParameterSets,serializeAbsSendTime,serializeAudioLevelIndication,serializeRepairedRtpStreamId,serializeSdesMid,serializeSdesRTPStreamID,serializeTransportWideCC,serverReflexiveCandidate,setTrackSourceCodecs,signatures,sortCandidatePairs,splitAv1Obus,splitH264NalUnits,splitH265NalUnits,splitTcpFrames,supportedAudioCodecs,supportedCodecs,supportedVideoCodecs,timer,timestampSeconds,uint16Add,uint16Gt,uint16Gte,uint24,uint32Add,uint32Gt,uint32Gte,uint8Add,unwrapRtx,url2Address,useAV1,useAV1X,useAbsSendTime,useAudioLevelIndication,useDependencyDescriptor,useFIR,useG722,useH264,useNACK,useOPUS,usePCMA,usePCMU,usePLI,useREMB,useRepairedRtpStreamId,useSdesMid,useSdesRTPStreamId,useTWCC,useTransportWideCC,useVP8,useVP9,useVideoOrientation,validateAddress,validateRemoteCandidate,wrapRtx,writeH265PayloadHeader};