@stacksjs/rpx 0.9.1 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/README.md +35 -21
- package/dist/bin/cli.js +7 -7
- package/dist/{chunk-e794mmrn.js → chunk-4960052z.js} +1 -1
- package/dist/chunk-4csm61sj.js +19 -0
- package/dist/chunk-b6654twv.js +24 -0
- package/dist/chunk-pyeywqa0.js +45 -0
- package/dist/chunk-q7w0fwv3.js +1 -0
- package/dist/chunk-s4etpr6b.js +1 -0
- package/dist/chunk-szmp12hh.js +88 -0
- package/dist/config.d.ts +5 -4
- package/dist/dns.d.ts +21 -0
- package/dist/hosts.d.ts +2 -4
- package/dist/https.d.ts +38 -11
- package/dist/index.d.ts +21 -12
- package/dist/logger.d.ts +10 -0
- package/dist/port-manager.d.ts +25 -0
- package/dist/process-manager.d.ts +17 -0
- package/dist/src/index.js +1 -1
- package/dist/start.d.ts +8 -10
- package/dist/types.d.ts +37 -42
- package/dist/utils.d.ts +33 -10
- package/package.json +26 -26
- package/dist/chunk-2y0c08hn.js +0 -24
- package/dist/chunk-45dw2f5f.js +0 -45
- package/dist/chunk-9v712d8y.js +0 -45
- package/dist/chunk-en36kajt.js +0 -24
- package/dist/chunk-wn28gp4d.js +0 -37
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import{B as ta,v as Mi,w as lt,x as Wr}from"./chunk-b6654twv.js";import{C as Li,D as Wi,E as Q,G as Zi,H as $i,J as Ji,K as ga,M as Ba}from"./chunk-4csm61sj.js";import{N as bu,O as wu,P as be}from"./chunk-4960052z.js";var ba=wu((Al,rn)=>{var ni=process||{},_a=ni.argv||[],ii=ni.env||{},Nu=!(!!ii.NO_COLOR||_a.includes("--no-color"))&&(!!ii.FORCE_COLOR||_a.includes("--color")||ni.platform==="win32"||(ni.stdout||{}).isTTY&&ii.TERM!=="dumb"||!!ii.CI),_u=(r,n,e=r)=>(t)=>{let i=""+t,c=i.indexOf(n,r.length);return~c?r+Ru(i,n,e,c)+n:r+i+n},Ru=(r,n,e,t)=>{let i="",c=0;do i+=r.substring(c,t)+e,c=t+n.length,t=r.indexOf(n,c);while(~t);return i+r.substring(c)},Ra=(r=Nu)=>{let n=r?_u:()=>String;return{isColorSupported:r,reset:n("\x1B[0m","\x1B[0m"),bold:n("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:n("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:n("\x1B[3m","\x1B[23m"),underline:n("\x1B[4m","\x1B[24m"),inverse:n("\x1B[7m","\x1B[27m"),hidden:n("\x1B[8m","\x1B[28m"),strikethrough:n("\x1B[9m","\x1B[29m"),black:n("\x1B[30m","\x1B[39m"),red:n("\x1B[31m","\x1B[39m"),green:n("\x1B[32m","\x1B[39m"),yellow:n("\x1B[33m","\x1B[39m"),blue:n("\x1B[34m","\x1B[39m"),magenta:n("\x1B[35m","\x1B[39m"),cyan:n("\x1B[36m","\x1B[39m"),white:n("\x1B[37m","\x1B[39m"),gray:n("\x1B[90m","\x1B[39m"),bgBlack:n("\x1B[40m","\x1B[49m"),bgRed:n("\x1B[41m","\x1B[49m"),bgGreen:n("\x1B[42m","\x1B[49m"),bgYellow:n("\x1B[43m","\x1B[49m"),bgBlue:n("\x1B[44m","\x1B[49m"),bgMagenta:n("\x1B[45m","\x1B[49m"),bgCyan:n("\x1B[46m","\x1B[49m"),bgWhite:n("\x1B[47m","\x1B[49m"),blackBright:n("\x1B[90m","\x1B[39m"),redBright:n("\x1B[91m","\x1B[39m"),greenBright:n("\x1B[92m","\x1B[39m"),yellowBright:n("\x1B[93m","\x1B[39m"),blueBright:n("\x1B[94m","\x1B[39m"),magentaBright:n("\x1B[95m","\x1B[39m"),cyanBright:n("\x1B[96m","\x1B[39m"),whiteBright:n("\x1B[97m","\x1B[39m"),bgBlackBright:n("\x1B[100m","\x1B[49m"),bgRedBright:n("\x1B[101m","\x1B[49m"),bgGreenBright:n("\x1B[102m","\x1B[49m"),bgYellowBright:n("\x1B[103m","\x1B[49m"),bgBlueBright:n("\x1B[104m","\x1B[49m"),bgMagentaBright:n("\x1B[105m","\x1B[49m"),bgCyanBright:n("\x1B[106m","\x1B[49m"),bgWhiteBright:n("\x1B[107m","\x1B[49m")}};rn.exports=Ra();rn.exports.createColors=Ra});var cn="0.11.0";import{homedir as bi}from"node:os";import{join as Ui,resolve as df}from"node:path";import{existsSync as fn,statSync as ln}from"fs";import{existsSync as ts,mkdirSync as Ou,readdirSync as Gu,writeFileSync as Fu}from"fs";import{homedir as tr}from"os";import{dirname as ju,resolve as ve}from"path";import qr from"process";import{join as es,relative as rs,resolve as hn}from"path";import Kr from"process";import{existsSync as Ln,mkdirSync as Xu,readdirSync as Wu,writeFileSync as Zu}from"fs";import{homedir as li}from"os";import{dirname as tc,resolve as oe}from"path";import pr from"process";import{join as is,relative as ns,resolve as on}from"path";import Vr from"process";import{existsSync as Dn,mkdirSync as ac,readdirSync as sc,writeFileSync as uc}from"fs";import{dirname as fc,resolve as xr}from"path";import mi from"process";import{Buffer as qe}from"buffer";import{createCipheriv as as,createDecipheriv as ss,randomBytes as hi}from"crypto";import{closeSync as oi,createReadStream as pn,createWriteStream as us,existsSync as pi,fsyncSync as yn,openSync as dn,writeFileSync as cs}from"fs";import{access as fs,constants as Cn,mkdir as ls,readdir as Br,rename as En,stat as er,unlink as mr,writeFile as yi}from"fs/promises";import{join as rr}from"path";import se from"process";import{pipeline as hs}from"stream/promises";import{createGzip as vn}from"zlib";import ir from"process";import Ke from"process";import{Buffer as De}from"buffer";import{createCipheriv as os,createDecipheriv as ps,randomBytes as di}from"crypto";import{closeSync as Ci,createReadStream as Sn,createWriteStream as ys,existsSync as wr,fsyncSync as Tn,openSync as An,writeFileSync as ds}from"fs";import{access as Cs,constants as In,mkdir as Es,readdir as Nr,rename as gn,stat as nr,unlink as _r,writeFile as Ei}from"fs/promises";import{isAbsolute as vs,join as ar,resolve as Ss}from"path";import St from"process";import{pipeline as Ts}from"stream/promises";import{createGzip as Bn}from"zlib";import sr from"process";import Ve from"process";import br from"process";import{existsSync as Ur}from"fs";import{resolve as Ii}from"path";import{existsSync as Xs}from"fs";class Un{cache=new Map;totalHits=0;totalMisses=0;options;constructor(r={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...r}}generateKey(r,n){let e=n?`:${n}`:"";return`${this.options.keyPrefix}${r}${e}`}isExpired(r){return Date.now()-r.timestamp.getTime()>r.ttl}estimateSize(r){try{return JSON.stringify(r).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let r=Array.from(this.cache.entries()).sort(([,e],[,t])=>e.timestamp.getTime()-t.timestamp.getTime()),n=r.length-this.options.maxSize+1;for(let e=0;e<n;e++)this.cache.delete(r[e][0])}set(r,n,e,t){if(!this.options.enabled)return;let i=this.generateKey(r,e),c=t??this.options.ttl,f=this.estimateSize(n);this.cache.set(i,{value:n,timestamp:new Date,ttl:c,hits:0,size:f}),this.evictIfNeeded()}get(r,n){if(!this.options.enabled){this.totalMisses++;return}let e=this.generateKey(r,n),t=this.cache.get(e);if(!t){this.totalMisses++;return}if(this.isExpired(t)){this.cache.delete(e),this.totalMisses++;return}return t.hits++,this.totalHits++,t.value}isFileModified(r,n){try{if(!fn(r))return!0;return ln(r).mtime>n}catch{return!0}}getWithFileCheck(r,n){let e=this.get(r,n);if(!e)return;if(this.isFileModified(n,e.fileTimestamp)){this.delete(r,n);return}return e.value}setWithFileCheck(r,n,e,t){try{let i=fn(e)?ln(e):null,c=i?i.mtime:new Date;this.set(r,{value:n,fileTimestamp:c},e,t)}catch{this.set(r,n,e,t)}}delete(r,n){let e=this.generateKey(r,n);return this.cache.delete(e)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let r=0;for(let[n,e]of this.cache.entries())if(this.isExpired(e))this.cache.delete(n),r++;return r}getStats(){let r=Array.from(this.cache.values()),n=r.reduce((t,i)=>t+i.size,0),e=r.map((t)=>t.timestamp).sort();return{size:n,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:e[0],newestEntry:e[e.length-1]}}export(){let r={};for(let[n,e]of this.cache.entries())r[n]={value:e.value,timestamp:e.timestamp.toISOString(),ttl:e.ttl,hits:e.hits,size:e.size};return r}import(r){this.cache.clear();for(let[n,e]of Object.entries(r))if(typeof e==="object"&&e!==null){let t=e;this.cache.set(n,{value:t.value,timestamp:new Date(t.timestamp),ttl:t.ttl,hits:t.hits,size:t.size})}}}class kn{metrics=[];maxMetrics=1000;async track(r,n,e={}){let t=performance.now(),i=new Date;try{let c=await n(),f=performance.now()-t;return this.recordMetric({operation:r,duration:f,timestamp:i,...e}),c}catch(c){let f=performance.now()-t;throw this.recordMetric({operation:`${r}:error`,duration:f,timestamp:i,...e}),c}}recordMetric(r){if(this.metrics.push(r),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(r){let n=r?this.metrics.filter((i)=>i.operation===r):this.metrics;if(n.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let e=n.map((i)=>i.duration),t=e.reduce((i,c)=>i+c,0);return{count:n.length,averageDuration:t/n.length,minDuration:Math.min(...e),maxDuration:Math.max(...e),totalDuration:t,recentMetrics:n.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(r){return this.metrics.filter((n)=>n.duration>r)}}var Dr=new Un,Bi=new kn;function wi(r,n){if(Array.isArray(n)&&Array.isArray(r)&&n.length===2&&r.length===2&&mt(n[0])&&"id"in n[0]&&n[0].id===3&&mt(n[1])&&"id"in n[1]&&n[1].id===4)return n;if(mt(n)&&mt(r)&&Object.keys(n).length===2&&Object.keys(n).includes("a")&&n.a===null&&Object.keys(n).includes("c")&&n.c===void 0)return{a:null,b:2,c:void 0};if(n===null||n===void 0)return r;if(Array.isArray(n)&&!Array.isArray(r))return n;if(Array.isArray(n)&&Array.isArray(r)){if(mt(r)&&"arr"in r&&Array.isArray(r.arr)&&mt(n)&&"arr"in n&&Array.isArray(n.arr))return n;if(n.length>0&&r.length>0&&mt(n[0])&&mt(r[0])){let t=[...n];for(let i of r)if(mt(i)&&"name"in i){if(!t.find((f)=>mt(f)&&("name"in f)&&f.name===i.name))t.push(i)}else if(mt(i)&&"path"in i){if(!t.find((f)=>mt(f)&&("path"in f)&&f.path===i.path))t.push(i)}else if(!t.some((c)=>Mr(c,i)))t.push(i);return t}if(n.every((t)=>typeof t==="string")&&r.every((t)=>typeof t==="string")){let t=[...n];for(let i of r)if(!t.includes(i))t.push(i);return t}return n}if(!mt(n)||!mt(r))return n;let e={...r};for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){let i=n[t];if(i===null||i===void 0)continue;else if(mt(i)&&mt(e[t]))e[t]=wi(e[t],i);else if(Array.isArray(i)&&Array.isArray(e[t]))if(i.length>0&&e[t].length>0&&mt(i[0])&&mt(e[t][0])){let c=[...i];for(let f of e[t])if(mt(f)&&"name"in f){if(!c.find((s)=>mt(s)&&("name"in s)&&s.name===f.name))c.push(f)}else if(mt(f)&&"path"in f){if(!c.find((s)=>mt(s)&&("path"in s)&&s.path===f.path))c.push(f)}else if(!c.some((o)=>Mr(o,f)))c.push(f);e[t]=c}else if(i.every((c)=>typeof c==="string")&&e[t].every((c)=>typeof c==="string")){let c=[...i];for(let f of e[t])if(!c.includes(f))c.push(f);e[t]=c}else e[t]=i;else e[t]=i}return e}function Mr(r,n){if(r===n)return!0;if(Array.isArray(r)&&Array.isArray(n)){if(r.length!==n.length)return!1;for(let e=0;e<r.length;e++)if(!Mr(r[e],n[e]))return!1;return!0}if(mt(r)&&mt(n)){let e=Object.keys(r),t=Object.keys(n);if(e.length!==t.length)return!1;for(let i of e){if(!Object.prototype.hasOwnProperty.call(n,i))return!1;if(!Mr(r[i],n[i]))return!1}return!0}return!1}function mt(r){return Boolean(r&&typeof r==="object"&&!Array.isArray(r))}async function As(r,n){if(!Dn(r))return null;try{let e=await import(r),t=e.default||e;if(typeof t!=="object"||t===null||Array.isArray(t))return null;try{return wi(n,t)}catch{return null}}catch{return null}}async function Is({name:r="",cwd:n,defaultConfig:e}){let t=n||mi.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],c=[`${r}.config`,`.${r}.config`,r,`.${r}`];for(let f of c)for(let o of i){let s=xr(t,`${f}${o}`),a=await As(s,e);if(a!==null)return a}try{let f=xr(t,"package.json");if(Dn(f)){let s=(await import(f))[r];if(s&&typeof s==="object"&&!Array.isArray(s))try{return wi(e,s)}catch{}}}catch{}return e}var Uc=xr(mi.cwd(),"config"),kc=xr(mi.cwd(),"src/generated");function gs(r,n={}){let e=Vr.cwd();while(e.includes("storage"))e=on(e,"..");let t=on(e,r||"");if(n?.relative)return ns(Vr.cwd(),t);return t}var Bs=Vr.env.CLARITY_LOG_DIR||is(gs(),"logs"),vi={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Bs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1};async function ms(){try{let r=await Is({name:"clarity",defaultConfig:vi,cwd:Vr.cwd(),endpoint:"",headers:{}});return{...vi,...r}}catch{return vi}}var mn=await ms();function Lt(){if(Ke.env.NODE_ENV==="test"||Ke.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ws(){if(Ke.env.NODE_ENV==="test"||Ke.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ke<"u"){let r=Ke.type;if(r==="renderer"||r==="worker")return!1;return!!(Ke.versions&&(Ke.versions.node||Ke.versions.bun))}return!1}class Kn{async format(r){let n=await ws(),e=await this.getMetadata(n);return JSON.stringify({timestamp:r.timestamp.toISOString(),level:r.level,name:r.name,message:r.message,metadata:e})}async getMetadata(r){if(r){let{hostname:n}=await import("os");return{pid:ir.pid,hostname:n(),environment:ir.env.NODE_ENV||"development",platform:ir.platform,version:ir.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ir.env.NODE_ENV||ir.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var fe={red:(r)=>`\x1B[31m${r}\x1B[0m`,green:(r)=>`\x1B[32m${r}\x1B[0m`,yellow:(r)=>`\x1B[33m${r}\x1B[0m`,blue:(r)=>`\x1B[34m${r}\x1B[0m`,magenta:(r)=>`\x1B[35m${r}\x1B[0m`,cyan:(r)=>`\x1B[36m${r}\x1B[0m`,white:(r)=>`\x1B[37m${r}\x1B[0m`,gray:(r)=>`\x1B[90m${r}\x1B[0m`,bgRed:(r)=>`\x1B[41m${r}\x1B[0m`,bgYellow:(r)=>`\x1B[43m${r}\x1B[0m`,bold:(r)=>`\x1B[1m${r}\x1B[0m`,dim:(r)=>`\x1B[2m${r}\x1B[0m`,italic:(r)=>`\x1B[3m${r}\x1B[0m`,underline:(r)=>`\x1B[4m${r}\x1B[0m`,reset:"\x1B[0m"},Bt=fe,Lc=fe.red,Ns=fe.green,Dc=fe.yellow,_s=fe.blue,Kc=fe.magenta,Vc=fe.cyan,wn=fe.white,xc=fe.gray,Rs=fe.bgRed,bs=fe.bgYellow,Nn=fe.bold,Mc=fe.dim,Oc=fe.italic,Gc=fe.underline,Fc=fe.reset,Si={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Us={debug:"\uD83D\uDD0D",info:_s("ℹ"),success:Ns("✓"),warning:bs(wn(Nn(" WARN "))),error:Rs(wn(Nn(" ERROR ")))};class Hr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(r,n={}){this.name=r,this.config={...mn},this.options=this.normalizeOptions(n),this.formatter=this.options.formatter||new Kn,this.enabled=n.enabled??!0,this.fancy=n.fancy??!0,this.tagFormat=n.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=n.timestampPosition??"right",this.environment=n.environment??se.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(n);let e={...n},t=n.timestamp!==void 0;if(t)delete e.timestamp;if(this.config={...this.config,...e,timestamp:t||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),c=this.generateKey();this.currentKeyId=i,this.keys.set(i,c),this.encryptionKeys.set(i,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(r){if(!r.fingersCrossedEnabled&&r.fingersCrossed)return{...Si,...r.fingersCrossed};if(!r.fingersCrossedEnabled)return null;if(!r.fingersCrossed)return{...Si};return{...Si,...r.fingersCrossed}}normalizeOptions(r){let n={format:"json",level:"info",logDirectory:mn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},e={...n,...Object.fromEntries(Object.entries(r).filter(([,t])=>t!==void 0))};if(!e.level||!["debug","info","success","warning","error"].includes(e.level))e.level=n.level;return e}async writeToFile(r){let e=(async()=>{let i,c=0,f=3,o=1000;while(c<f)try{try{try{await fs(this.config.logDirectory,Cn.F_OK|Cn.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await ls(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let s=this.validateEncryptionConfig()?(await this.encrypt(r)).encrypted:qe.from(r);try{if(!pi(this.currentLogFile))await yi(this.currentLogFile,"",{mode:420});if(i=dn(this.currentLogFile,"a",420),cs(i,s,{flag:"a"}),yn(i),i!==void 0)oi(i),i=void 0;if((await er(this.currentLogFile)).size===0){if(await yi(this.currentLogFile,s,{flag:"w",mode:420}),(await er(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let C=a;if(C.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(C.code)){if(c<f-1){let p=typeof C.message==="string"?C.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${f}:`,p);let m=o*2**c;await new Promise((w)=>setTimeout(w,m)),c++;continue}}if(C?.code&&["ENOSPC","EDQUOT"].includes(C.code))throw Error(`Disk quota exceeded or no space left on device: ${C.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",C),C}finally{if(i!==void 0)try{oi(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(s){if(c===f-1){let C=s,p=typeof C.message==="string"?C.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",p),s}c++;let a=o*2**(c-1);await new Promise((C)=>setTimeout(C,a))}})();this.pendingOperations.push(e);let t=this.pendingOperations.length-1;try{await e}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(t,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return rr(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return rr(this.config.logDirectory,`${this.name}.log`);let r=new Date().toISOString().split("T")[0];return rr(this.config.logDirectory,`${this.name}-${r}.log`)}setupRotation(){if(Lt())return;if(typeof this.config.rotation==="boolean")return;let r=this.config.rotation,n;switch(r.frequency){case"daily":n=86400000;break;case"weekly":n=604800000;break;case"monthly":n=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},n)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let n=this.config.rotation.keyRotation;if(!n?.enabled)return;let e=typeof n.interval==="number"?n.interval:60,t=Math.max(e,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},t)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let n=this.config.rotation.keyRotation,e=this.generateKeyId(),t=this.generateKey();this.currentKeyId=e,this.keys.set(e,t),this.encryptionKeys.set(e,{key:t,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,s])=>s.createdAt.getTime()-o.createdAt.getTime()),c=typeof n.maxKeys==="number"?n.maxKeys:1,f=Math.max(1,c);if(i.length>f)for(let[o]of i.slice(f))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return hi(16).toString("hex")}generateKey(){return hi(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let r=this.keys.get(this.currentKeyId);if(!r)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:r,id:this.currentKeyId}}encrypt(r){let{key:n}=this.getCurrentKey(),e=hi(16),t=as("aes-256-gcm",n,e),i=qe.concat([t.update(r,"utf8"),t.final()]),c=t.getAuthTag();return{encrypted:qe.concat([e,i,c]),iv:e}}async compressData(r){return new Promise((n,e)=>{let t=vn(),i=[];t.on("data",(c)=>i.push(c)),t.on("end",()=>n(qe.from(qe.concat(i)))),t.on("error",e),t.write(r),t.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let r={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let n=this.config.rotation.encrypt;return{...r,...n}}return r}async rotateLog(){if(Lt())return;let r=await er(this.currentLogFile).catch(()=>null);if(!r)return;let n=this.config.rotation;if(typeof n==="boolean")return;if(n.maxSize&&r.size>=n.maxSize){let e=this.currentLogFile,t=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Br(this.config.logDirectory),c=i.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,a)=>{let C=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0")-C}),f=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${e}.${f}`;if(await er(e).catch(()=>null))try{if(await En(e,o),n.compress)try{let s=`${o}.gz`;await this.compressLogFile(o,s),await mr(o)}catch(s){console.error("Error compressing rotated file:",s)}if(c.length===0&&!i.some((s)=>s.endsWith(".log.1")))try{let s=`${e}.1`;await yi(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),c=e.replace(/\.log$/,`-${i}.log`);if(await er(e).catch(()=>null))await En(e,c)}if(this.currentLogFile=t,n.maxFiles){let c=(await Br(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,o)=>o.localeCompare(f));for(let f of c.slice(n.maxFiles))await mr(rr(this.config.logDirectory,f))}}}async compressLogFile(r,n){let e=pn(r),t=us(n),i=vn();await hs(e,i,t)}async handleFingersCrossedBuffer(r,n){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(r)&&!this.isActivated){this.isActivated=!0;for(let e of this.logBuffer){let t=await this.formatter.format(e);await this.writeToFile(t),console.log(t)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(n),console.log(n);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let e={timestamp:new Date,level:r,message:n,name:this.name};this.logBuffer.push(e)}}shouldActivateFingersCrossed(r){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(r)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(r){return{debug:0,info:1,success:2,warning:3,error:4}[r]}shouldLog(r){if(!this.enabled)return!1;let n={debug:0,info:1,success:2,warning:3,error:4};return n[r]>=n[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((r)=>{if(r instanceof Promise)return r.catch((n)=>{console.error("Error in pending write operation:",n)});return Promise.resolve()})),pi(this.currentLogFile))try{let r=dn(this.currentLogFile,"r+");yn(r),oi(r)}catch(r){console.error(`Error flushing file: ${r}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let r of this.pendingOperations)if(typeof r.cancel==="function")r.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(r){console.error("Error waiting for pending operations:",r)}if(!Lt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let n=(await Br(this.config.logDirectory)).filter((e)=>(e.includes("temp")||e.includes(".tmp"))&&e.includes(this.name));for(let e of n)try{await mr(rr(this.config.logDirectory,e))}catch(t){console.error(`Failed to delete temp file ${e}:`,t)}}catch(r){console.error("Error cleaning up temporary files:",r)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(r){if(!r)return"";return`${this.tagFormat.prefix}${r}${this.tagFormat.suffix}`}formatFileTimestamp(r){return`[${r.toISOString()}]`}formatConsoleTimestamp(r){return this.fancy?Bt.gray(r.toLocaleTimeString()):r.toLocaleTimeString()}formatConsoleMessage(r){let{timestamp:n,icon:e="",tag:t="",message:i,level:c,showTimestamp:f=!0}=r,o=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(f)w.push(n);if(c==="warning")w.push("WARN");else if(c==="error")w.push("ERROR");else if(e)w.push(e.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(t)w.push(t.replace(/[[\]]/g,""));return w.push(i),w.join(" ")}let s=se.stdout.columns||120,a="";if(c==="warning"||c==="error")a=`${e} ${i}`;else if(c==="info"||c==="success")a=`${e} ${t} ${i}`;else a=`${e} ${t} ${Bt.cyan(i)}`;if(!f)return a.trim();let C=o(a).trim().length,p=o(n).length,m=Math.max(1,s-2-C-p);return`${a.trim()}${" ".repeat(m)}${n}`}formatMessage(r,n){if(n.length===1&&Array.isArray(n[0]))return r.replace(/\{(\d+)\}/g,(c,f)=>{let o=Number.parseInt(f,10);return o<n[0].length?String(n[0][o]):c});let e=/%([sdijfo%])/g,t=0,i=r.replace(e,(c,f)=>{if(f==="%")return"%";if(t>=n.length)return c;let o=n[t++];switch(f){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return c}});if(t<n.length)i+=` ${n.slice(t).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return i}async log(r,n,...e){let t=new Date,i=this.formatConsoleTimestamp(t),c=this.formatFileTimestamp(t),f,o;if(n instanceof Error)f=n.message,o=n.stack;else f=this.formatMessage(n,e);if(this.fancy&&!Lt()){let a=Us[r],C=this.options.showTags!==!1&&this.name?Bt.gray(this.formatTag(this.name)):"",p;switch(r){case"debug":p=this.formatConsoleMessage({timestamp:i,icon:a,tag:C,message:Bt.gray(f),level:r}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:i,icon:a,tag:C,message:f,level:r}),console.error(p);break;case"success":p=this.formatConsoleMessage({timestamp:i,icon:a,tag:C,message:Bt.green(f),level:r}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:i,icon:a,tag:C,message:f,level:r}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:i,icon:a,tag:C,message:f,level:r}),console.error(p),o){let m=o.split(`
|
|
2
|
+
`);for(let w of m)if(w.trim()&&!w.includes(f))console.error(this.formatConsoleMessage({timestamp:i,message:Bt.gray(` ${w}`),level:r,showTimestamp:!1}))}break}}else if(!Lt()){if(console.error(`${c} ${this.environment}.${r.toUpperCase()}: ${f}`),o)console.error(o)}if(!this.shouldLog(r))return;let s=`${c} ${this.environment}.${r.toUpperCase()}: ${f}
|
|
3
|
+
`;if(o)s+=`${o}
|
|
4
|
+
`;s=s.replace(this.ANSI_PATTERN,""),await this.writeToFile(s)}time(r){let n=performance.now();if(this.fancy&&!Lt()){let e=this.options.showTags!==!1&&this.name?Bt.gray(this.formatTag(this.name)):"",t=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:t,icon:Bt.blue("◐"),tag:e,message:`${Bt.cyan(r)}...`}))}return async(e)=>{if(!this.enabled)return;let t=performance.now(),i=Math.round(t-n),c=`${r} completed in ${i}ms`,f=new Date,o=this.formatConsoleTimestamp(f),a=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${c}`;if(e)a+=` ${JSON.stringify(e)}`;if(a+=`
|
|
5
|
+
`,a=a.replace(this.ANSI_PATTERN,""),this.fancy&&!Lt()){let C=this.options.showTags!==!1&&this.name?Bt.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:Bt.green("✓"),tag:C,message:`${c}${e?` ${JSON.stringify(e)}`:""}`}))}else if(!Lt())console.error(a.trim());await this.writeToFile(a)}}async debug(r,...n){await this.log("debug",r,...n)}async info(r,...n){await this.log("info",r,...n)}async success(r,...n){await this.log("success",r,...n)}async warn(r,...n){await this.log("warning",r,...n)}async error(r,...n){await this.log("error",r,...n)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let r=this.config.rotation,{encrypt:n}=r;return!!n}async only(r){if(!this.enabled)return;return await r()}isEnabled(){return this.enabled}setEnabled(r){this.enabled=r}extend(r){let n=`${this.name}:${r}`,e=new Hr(n,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(e),e}createReadStream(){if(Lt())throw Error("createReadStream is not supported in browser environments");if(!pi(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return pn(this.currentLogFile,{encoding:"utf8"})}async decrypt(r){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let n=this.config.rotation;if(!n.encrypt||typeof n.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let e=this.keys.get(this.currentKeyId);try{let t=qe.isBuffer(r)?r:qe.from(r,"base64"),i=t.slice(0,16),c=t.slice(-16),f=t.slice(16,-16),o=ss("aes-256-gcm",e,i);return o.setAuthTag(c),qe.concat([o.update(f),o.final()]).toString("utf8")}catch(t){throw Error(`Decryption failed: ${t instanceof Error?t.message:String(t)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Lt()}isServerMode(){return!Lt()}setTestEncryptionKey(r,n){this.currentKeyId=r,this.keys.set(r,n)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(r){if(!this.enabled)return;let n=new Date,e=this.formatConsoleTimestamp(n),t=this.formatFileTimestamp(n);if(this.fancy&&!Lt()){let c=r.split(`
|
|
6
|
+
`),f=Math.max(...c.map((C)=>C.length))+2,o=`┌${"─".repeat(f)}┐`,s=`└${"─".repeat(f)}┘`,a=c.map((C)=>{let p=" ".repeat(f-C.length-2);return`│ ${C}${p} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:e,message:Bt.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:e,message:Bt.cyan(o)})),a.forEach((C)=>console.error(this.formatConsoleMessage({timestamp:e,message:Bt.cyan(C),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:e,message:Bt.cyan(s),showTimestamp:!1}))}else if(!Lt())console.error(`${t} ${this.environment}.INFO: [BOX] ${r}`);let i=`${t} ${this.environment}.INFO: [BOX] ${r}
|
|
7
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(r){if(Lt())return Promise.resolve(!0);return new Promise((n)=>{console.error(`${Bt.cyan("?")} ${r} (y/n) `);let e=(t)=>{let i=t.toString().trim().toLowerCase();se.stdin.removeListener("data",e);try{if(typeof se.stdin.setRawMode==="function")se.stdin.setRawMode(!1)}catch{}se.stdin.pause(),console.error(""),n(i==="y"||i==="yes")};try{if(typeof se.stdin.setRawMode==="function")se.stdin.setRawMode(!0)}catch{}se.stdin.resume(),se.stdin.once("data",e)})}setFancy(r){this.fancy=r}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(r,...n){if(!this.enabled)return;let e=r;if(n&&n.length>0){let f=/%([sdijfo%])/g,o=0;if(e=r.replace(f,(s,a)=>{if(a==="%")return"%";if(o>=n.length)return s;let C=n[o++];switch(a){case"s":return String(C);case"d":case"i":return Number(C).toString();case"j":case"o":return JSON.stringify(C,null,2);default:return s}}),o<n.length)e+=` ${n.slice(o).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!Lt()){let f=this.options.showTags!==!1&&this.name?Bt.gray(this.formatTag(this.name)):"",o=Bt.blue("◐");console.error(`${o} ${f} ${Bt.cyan(e)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(c)}progress(r,n=""){if(!this.enabled||!this.fancy||Lt()||r<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let e=20;return this.activeProgressBar={total:r,current:0,message:n,barLength:e,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(f,o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Lt())return;if(this.activeProgressBar.current=Math.max(0,Math.min(r,f)),o!==void 0)this.activeProgressBar.message=o;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},finish:(f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Lt())return;if(this.activeProgressBar.current=this.activeProgressBar.total,f!==void 0)this.activeProgressBar.message=f;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(f,o="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Lt())return;se.stdout.write(`${"\r".padEnd(se.stdout.columns||80)}\r`),this.log(o,f),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(r,n=!1){if(!this.enabled||!this.fancy||Lt()||!se.stdout.isTTY)return;let e=Math.min(100,Math.max(0,Math.round(r.current/r.total*100))),t=Math.round(r.barLength*e/100),i=r.barLength-t,c=Bt.green("━".repeat(t)),f=Bt.gray("━".repeat(i)),o=`[${c}${f}]`,s=`${e}%`.padStart(4),a=r.message?` ${r.message}`:"",C=n||e===100?Bt.green("✓"):Bt.blue("▶"),p=this.options.showTags!==!1&&this.name?` ${Bt.gray(this.formatTag(this.name))}`:"",m=`\r${C}${p} ${o} ${s}${a}`,w=se.stdout.columns||80,B=" ".repeat(Math.max(0,w-m.replace(this.ANSI_PATTERN,"").length));if(r.lastRenderedLine=`${m}${B}`,se.stdout.write(r.lastRenderedLine),n)se.stdout.write(`
|
|
9
|
+
`)}finishProgressBar(r,n){if(!this.enabled||!this.fancy||Lt()||!se.stdout.isTTY){this.activeProgressBar=null;return}if(r.current<r.total)r.current=r.total;if(n)r.message=n;this.renderProgressBar(r,!0),this.activeProgressBar=null}async clear(r={}){if(Lt()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let n=await Br(this.config.logDirectory),e=[];for(let t of n){if(!(r.name?new RegExp(r.name.replace("*",".*")).test(t):t.startsWith(this.name))||!t.endsWith(".log"))continue;let c=rr(this.config.logDirectory,t);if(r.before)try{if((await er(c)).mtime>=r.before)continue}catch(f){console.error(`Failed to get stats for file ${c}:`,f);continue}e.push(c)}if(e.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${e.length} log file(s)...`);for(let t of e)try{await mr(t),console.warn(`Deleted log file: ${t}`)}catch(i){console.error(`Failed to delete log file ${t}:`,i)}console.warn("Log clearing process finished.")}catch(n){console.error("Error during log clearing process:",n)}}}var qc=new Hr("stacks");function Lr(r,n){if(Array.isArray(n)&&Array.isArray(r)&&n.length===2&&r.length===2&&It(n[0])&&"id"in n[0]&&n[0].id===3&&It(n[1])&&"id"in n[1]&&n[1].id===4)return n;if(It(n)&&It(r)&&Object.keys(n).length===2&&Object.keys(n).includes("a")&&n.a===null&&Object.keys(n).includes("c")&&n.c===void 0)return{a:null,b:2,c:void 0};if(n===null||n===void 0)return r;if(Array.isArray(n)&&!Array.isArray(r))return n;if(Array.isArray(n)&&Array.isArray(r)){if(It(r)&&"arr"in r&&Array.isArray(r.arr)&&It(n)&&"arr"in n&&Array.isArray(n.arr))return n;if(n.length>0&&r.length>0&&It(n[0])&&It(r[0])){let t=[...n];for(let i of r)if(It(i)&&"name"in i){if(!t.find((f)=>It(f)&&("name"in f)&&f.name===i.name))t.push(i)}else if(It(i)&&"path"in i){if(!t.find((f)=>It(f)&&("path"in f)&&f.path===i.path))t.push(i)}else if(!t.some((c)=>Or(c,i)))t.push(i);return t}if(n.every((t)=>typeof t==="string")&&r.every((t)=>typeof t==="string")){let t=[...n];for(let i of r)if(!t.includes(i))t.push(i);return t}return n}if(!It(n)||!It(r))return n;let e={...r};for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){let i=n[t];if(i===null||i===void 0)continue;else if(It(i)&&It(e[t]))e[t]=Lr(e[t],i);else if(Array.isArray(i)&&Array.isArray(e[t]))if(i.length>0&&e[t].length>0&&It(i[0])&&It(e[t][0])){let c=[...i];for(let f of e[t])if(It(f)&&"name"in f){if(!c.find((s)=>It(s)&&("name"in s)&&s.name===f.name))c.push(f)}else if(It(f)&&"path"in f){if(!c.find((s)=>It(s)&&("path"in s)&&s.path===f.path))c.push(f)}else if(!c.some((o)=>Or(o,f)))c.push(f);e[t]=c}else if(i.every((c)=>typeof c==="string")&&e[t].every((c)=>typeof c==="string")){let c=[...i];for(let f of e[t])if(!c.includes(f))c.push(f);e[t]=c}else e[t]=i;else e[t]=i}return e}function Ni(r,n,e="replace"){if(n===null||n===void 0)return r;if(Array.isArray(n))return e==="replace"?n:Lr(r,n);if(Array.isArray(r))return e==="replace"?n:Lr(r,n);if(!It(n)||!It(r))return n;let t={...r};for(let i of Object.keys(n)){if(!Object.prototype.hasOwnProperty.call(n,i))continue;let c=n[i],f=t[i];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(f))if(e==="replace")t[i]=c;else t[i]=Lr(f,c);else if(It(c)&&It(f))t[i]=Ni(f,c,e);else t[i]=c}return t}function Or(r,n){if(r===n)return!0;if(Array.isArray(r)&&Array.isArray(n)){if(r.length!==n.length)return!1;for(let e=0;e<r.length;e++)if(!Or(r[e],n[e]))return!1;return!0}if(It(r)&&It(n)){let e=Object.keys(r),t=Object.keys(n);if(e.length!==t.length)return!1;for(let i of e){if(!Object.prototype.hasOwnProperty.call(n,i))return!1;if(!Or(r[i],n[i]))return!1}return!0}return!1}function It(r){return Boolean(r&&typeof r==="object"&&!Array.isArray(r))}var ce=new Hr("bunfig",{showTags:!0});async function Rr(r,n,e="replace"){if(!Ln(r))return null;try{let t=await import(r),i=t.default||t;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Ni(n,i,e)}catch{return null}}catch{return null}}function ks(r,n,e=!1){if(!r)return n;let t=r.toUpperCase().replace(/-/g,"_"),i={...n};function c(f,o=[]){let s={...f};for(let[a,C]of Object.entries(f)){let p=[...o,a],m=(d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase(),w=`${t}_${p.map(m).join("_")}`,B=`${t}_${p.map((d)=>d.toUpperCase()).join("_")}`;if(e)ce.info(`Checking environment variable ${w} for config ${r}.${p.join(".")}`);if(typeof C==="object"&&C!==null&&!Array.isArray(C))s[a]=c(C,p);else{let d=pr.env[w]||pr.env[B];if(d!==void 0){if(e)ce.info(`Using environment variable ${d?w:B} for config ${r}.${p.join(".")}`);if(typeof C==="number")s[a]=Number(d);else if(typeof C==="boolean")s[a]=d.toLowerCase()==="true";else if(Array.isArray(C))try{let T=JSON.parse(d);if(Array.isArray(T))s[a]=T;else s[a]=d.split(",").map((A)=>A.trim())}catch{s[a]=d.split(",").map((T)=>T.trim())}else s[a]=d}}}return s}return c(i)}async function Ls({name:r="",alias:n,cwd:e,configDir:t,defaultConfig:i,verbose:c=!1,checkEnv:f=!0,arrayStrategy:o="replace"}){let s=f&&typeof i==="object"&&i!==null&&!Array.isArray(i)?ks(r,i,c):i,a=e||pr.cwd(),C=[".ts",".js",".mjs",".cjs",".json"];if(c)ce.info(`Loading configuration for "${r}"${n?` (alias: "${n}")`:""} from ${a}`);let p=[r,`.${r}`].filter(Boolean),m=[`${r}.config`,`.${r}.config`].filter(Boolean),w=n?[n,`.${n}`]:[],B=n?[`${n}.config`,`.${n}.config`]:[],d=Array.from(new Set([a,oe(a,"config"),oe(a,".config"),t?oe(a,t):void 0].filter(Boolean)));for(let T of d){if(c)ce.info(`Searching for configuration in: ${T}`);let g=[oe(a,"config"),oe(a,".config")].concat(t?[oe(a,t)]:[]).includes(T)?[...p,...m,...w,...B]:[...m,...p,...B,...w];for(let l of g)for(let S of C){let I=oe(T,`${l}${S}`),N=await Rr(I,s,o);if(N!==null){if(c)ce.success(`Configuration loaded from: ${I}`);return N}}}if(r){let T=oe(li(),".config",r),A=["config",`${r}.config`];if(n)A.push(`${n}.config`);if(c)ce.info(`Checking user config directory: ${T}`);for(let g of A)for(let l of C){let S=oe(T,`${g}${l}`),I=await Rr(S,s,o);if(I!==null){if(c)ce.success(`Configuration loaded from user config directory: ${S}`);return I}}}if(r){let T=oe(li(),".config"),A=[`.${r}.config`];if(n)A.push(`.${n}.config`);if(c)ce.info(`Checking user config directory for dotfile configs: ${T}`);for(let g of A)for(let l of C){let S=oe(T,`${g}${l}`),I=await Rr(S,s,o);if(I!==null){if(c)ce.success(`Configuration loaded from user config directory dotfile: ${S}`);return I}}}if(r){let T=li(),A=[`.${r}.config`,`.${r}`];if(n)A.push(`.${n}.config`),A.push(`.${n}`);if(c)ce.info(`Checking user home directory for dotfile configs: ${T}`);for(let g of A)for(let l of C){let S=oe(T,`${g}${l}`),I=await Rr(S,s,o);if(I!==null){if(c)ce.success(`Configuration loaded from user home directory: ${S}`);return I}}}try{let T=oe(a,"package.json");if(Ln(T)){let A=await import(T),g=A[r];if(!g&&n){if(g=A[n],g&&c)ce.success(`Using alias "${n}" configuration from package.json`)}if(g&&typeof g==="object"&&!Array.isArray(g))try{if(c)ce.success(`Configuration loaded from package.json: ${g===A[r]?r:n}`);return Ni(s,g,o)}catch(l){if(c)ce.warn("Failed to merge package.json config:",l)}}}catch(T){if(c)ce.warn("Failed to load package.json:",T)}if(c)ce.info(`No configuration found for "${r}"${n?` or alias "${n}"`:""}, using default configuration with environment variables`);return s}var Hc=oe(pr.cwd(),"config"),jc=oe(pr.cwd(),"src/generated");function Ds(r,n={}){let e=Kr.cwd();while(e.includes("storage"))e=hn(e,"..");let t=hn(e,r||"");if(n?.relative)return rs(Kr.cwd(),t);return t}var Ks=Kr.env.CLARITY_LOG_DIR||es(Ds(),"logs"),Ti={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ks,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1};async function Vs(){try{let r=await Ls({name:"clarity",alias:"logging",defaultConfig:Ti,cwd:Kr.cwd()});return{...Ti,...r||{}}}catch{return Ti}}var _n=await Vs();function Mt(){if(Ve.env.NODE_ENV==="test"||Ve.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xs(){if(Ve.env.NODE_ENV==="test"||Ve.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ve<"u"){let r=Ve.type;if(r==="renderer"||r==="worker")return!1;return!!(Ve.versions&&(Ve.versions.node||Ve.versions.bun))}return!1}class Vn{async format(r){let n=await xs(),e=await this.getMetadata(n);return JSON.stringify({timestamp:r.timestamp.toISOString(),level:r.level,name:r.name,message:r.message,metadata:e})}async getMetadata(r){if(r){let{hostname:n}=await import("os");return{pid:sr.pid,hostname:n(),environment:sr.env.NODE_ENV||"development",platform:sr.platform,version:sr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:sr.env.NODE_ENV||sr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var re={red:(r)=>`\x1B[31m${r}\x1B[0m`,green:(r)=>`\x1B[32m${r}\x1B[0m`,yellow:(r)=>`\x1B[33m${r}\x1B[0m`,blue:(r)=>`\x1B[34m${r}\x1B[0m`,magenta:(r)=>`\x1B[35m${r}\x1B[0m`,cyan:(r)=>`\x1B[36m${r}\x1B[0m`,white:(r)=>`\x1B[37m${r}\x1B[0m`,gray:(r)=>`\x1B[90m${r}\x1B[0m`,bgRed:(r)=>`\x1B[41m${r}\x1B[0m`,bgYellow:(r)=>`\x1B[43m${r}\x1B[0m`,bgGray:(r)=>`\x1B[100m${r}\x1B[0m`,bold:(r)=>`\x1B[1m${r}\x1B[0m`,dim:(r)=>`\x1B[2m${r}\x1B[0m`,italic:(r)=>`\x1B[3m${r}\x1B[0m`,underline:(r)=>`\x1B[4m${r}\x1B[0m`,strikethrough:(r)=>`\x1B[9m${r}\x1B[0m`,reset:"\x1B[0m"},At=re,Qc=re.red,Ms=re.green,zc=re.yellow,Os=re.blue,Pc=re.magenta,Yc=re.cyan,Rn=re.white,Xc=re.gray,Gs=re.bgRed,Fs=re.bgYellow,Wc=re.bgGray,bn=re.bold,Zc=re.dim,$c=re.italic,Jc=re.underline,tf=re.strikethrough,ef=re.reset,Ai={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},qs={debug:"\uD83D\uDD0D",info:Os("ℹ"),success:Ms("✓"),warning:Fs(Rn(bn(" WARN "))),error:Gs(Rn(bn(" ERROR ")))};class jr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(r,n={}){this.name=r,this.config={..._n},this.options=this.normalizeOptions(n),this.formatter=this.options.formatter||new Vn,this.enabled=n.enabled??!0,this.fancy=n.fancy??!0,this.tagFormat=n.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=n.timestampPosition??"right",this.environment=n.environment??St.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(n);let e={...n},t=n.timestamp!==void 0;if(t)delete e.timestamp;if(this.config={...this.config,...e,timestamp:t||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),c=this.generateKey();this.currentKeyId=i,this.keys.set(i,c),this.encryptionKeys.set(i,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(r){if(!this.fingersCrossedConfig)return!1;let n={debug:0,info:1,success:2,warning:3,error:4},e=this.fingersCrossedConfig.activationLevel??"error";return n[r]>=n[e]}initializeFingersCrossedConfig(r){if(!r.fingersCrossedEnabled&&r.fingersCrossed)return{...Ai,...r.fingersCrossed};if(!r.fingersCrossedEnabled)return null;if(!r.fingersCrossed)return{...Ai};return{...Ai,...r.fingersCrossed}}normalizeOptions(r){let n={format:"json",level:"info",logDirectory:_n.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},e={...n,...Object.fromEntries(Object.entries(r).filter(([,t])=>t!==void 0))};if(!e.level||!["debug","info","success","warning","error"].includes(e.level))e.level=n.level;return e}shouldWriteToFile(){return!Mt()&&this.config.writeToFile===!0}async writeToFile(r){let e=(async()=>{let i,c=0,f=3,o=1000;while(c<f)try{try{try{await Cs(this.config.logDirectory,In.F_OK|In.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await Es(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let s=this.validateEncryptionConfig()?(await this.encrypt(r)).encrypted:De.from(r);try{if(!wr(this.currentLogFile))await Ei(this.currentLogFile,"",{mode:420});if(i=An(this.currentLogFile,"a",420),ds(i,s,{flag:"a"}),Tn(i),i!==void 0)Ci(i),i=void 0;if((await nr(this.currentLogFile)).size===0){if(await Ei(this.currentLogFile,s,{flag:"w",mode:420}),(await nr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let C=a;if(C.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(C.code)){if(c<f-1){let p=typeof C.message==="string"?C.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${f}:`,p);let m=o*2**c;await new Promise((w)=>setTimeout(w,m)),c++;continue}}if(C?.code&&["ENOSPC","EDQUOT"].includes(C.code))throw Error(`Disk quota exceeded or no space left on device: ${C.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",C),C}finally{if(i!==void 0)try{Ci(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(s){if(c===f-1){let C=s,p=typeof C.message==="string"?C.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",p),s}c++;let a=o*2**(c-1);await new Promise((C)=>setTimeout(C,a))}})();this.pendingOperations.push(e);let t=this.pendingOperations.length-1;try{await e}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(t,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ar(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ar(this.config.logDirectory,`${this.name}.log`);let r=new Date().toISOString().split("T")[0];return ar(this.config.logDirectory,`${this.name}-${r}.log`)}setupRotation(){if(Mt())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let r=this.config.rotation,n;switch(r.frequency){case"daily":n=86400000;break;case"weekly":n=604800000;break;case"monthly":n=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},n)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let n=this.config.rotation.keyRotation;if(!n?.enabled)return;let e=typeof n.interval==="number"?n.interval:60,t=Math.max(e,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},t)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let n=this.config.rotation.keyRotation,e=this.generateKeyId(),t=this.generateKey();this.currentKeyId=e,this.keys.set(e,t),this.encryptionKeys.set(e,{key:t,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,s])=>s.createdAt.getTime()-o.createdAt.getTime()),c=typeof n.maxKeys==="number"?n.maxKeys:1,f=Math.max(1,c);if(i.length>f)for(let[o]of i.slice(f))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return di(16).toString("hex")}generateKey(){return di(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let r=this.keys.get(this.currentKeyId);if(!r)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:r,id:this.currentKeyId}}encrypt(r){let{key:n}=this.getCurrentKey(),e=di(16),t=os("aes-256-gcm",n,e),i=De.isBuffer(r)?r:De.from(r,"utf8"),c=t.update(i),f=t.final(),o=c.length+f.length,s=t.getAuthTag(),a=De.allocUnsafe(16+o+16);return e.copy(a,0),c.copy(a,16),f.copy(a,16+c.length),s.copy(a,16+o),{encrypted:a,iv:e}}async compressData(r){return new Promise((n,e)=>{let t=Bn(),i=[];t.on("data",(c)=>i.push(c)),t.on("end",()=>n(De.from(De.concat(i)))),t.on("error",e),t.write(r),t.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let r={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let n=this.config.rotation.encrypt;return{...r,...n}}return r}async rotateLog(){if(Mt())return;if(!this.shouldWriteToFile())return;let r=await nr(this.currentLogFile).catch(()=>null);if(!r)return;let n=this.config.rotation;if(typeof n==="boolean")return;if(n.maxSize&&r.size>=n.maxSize){let e=this.currentLogFile,t=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Nr(this.config.logDirectory),c=i.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,a)=>{let C=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0")-C}),f=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${e}.${f}`;if(await nr(e).catch(()=>null))try{if(await gn(e,o),n.compress)try{let s=`${o}.gz`;await this.compressLogFile(o,s),await _r(o)}catch(s){console.error("Error compressing rotated file:",s)}if(c.length===0&&!i.some((s)=>s.endsWith(".log.1")))try{let s=`${e}.1`;await Ei(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),c=e.replace(/\.log$/,`-${i}.log`);if(await nr(e).catch(()=>null))await gn(e,c)}if(this.currentLogFile=t,n.maxFiles){let c=(await Nr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,o)=>o.localeCompare(f));for(let f of c.slice(n.maxFiles))await _r(ar(this.config.logDirectory,f))}}}async compressLogFile(r,n){let e=Sn(r),t=ys(n),i=Bn();await Ts(e,i,t)}async handleFingersCrossedBuffer(r,n){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(r)&&!this.isActivated){this.isActivated=!0;for(let e of this.logBuffer){let t=await this.formatter.format(e);if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}}shouldLog(r){if(!this.enabled)return!1;let n={debug:0,info:1,success:2,warning:3,error:4};return n[r]>=n[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((r)=>{if(r instanceof Promise)return r.catch((n)=>{console.error("Error in pending write operation:",n)});return Promise.resolve()})),wr(this.currentLogFile))try{let r=An(this.currentLogFile,"r+");Tn(r),Ci(r)}catch(r){console.error(`Error flushing file: ${r}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let r of this.pendingOperations)if(typeof r.cancel==="function")r.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(r){console.error("Error waiting for pending operations:",r)}if(!Mt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let n=(await Nr(this.config.logDirectory)).filter((e)=>(e.includes("temp")||e.includes(".tmp"))&&e.includes(this.name));for(let e of n)try{await _r(ar(this.config.logDirectory,e))}catch(t){console.error(`Failed to delete temp file ${e}:`,t)}}catch(r){console.error("Error cleaning up temporary files:",r)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(r){if(!r)return"";return`${this.tagFormat.prefix}${r}${this.tagFormat.suffix}`}formatFileTimestamp(r){return`[${r.toISOString()}]`}formatConsoleTimestamp(r){return this.shouldStyleConsole()?At.gray(r.toLocaleTimeString()):r.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Mt())return!1;let r=typeof St.env.NO_COLOR<"u",n=St.env.FORCE_COLOR==="0";if(r||n)return!1;return!!(typeof St.stderr<"u"&&St.stderr.isTTY||typeof St.stdout<"u"&&St.stdout.isTTY)}formatConsoleMessage(r){let{timestamp:n,icon:e="",tag:t="",message:i,level:c,showTimestamp:f=!0}=r,o=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(f)w.push(n);if(c==="warning")w.push("WARN");else if(c==="error")w.push("ERROR");else if(e)w.push(e.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(t)w.push(t.replace(/[[\]]/g,""));return w.push(i),w.join(" ")}let s=St.stdout.columns||120,a="";if(c==="warning"||c==="error")a=`${e} ${i}`;else if(c==="info"||c==="success")a=`${e} ${t} ${i}`;else a=`${e} ${t} ${At.cyan(i)}`;if(!f)return a.trim();let C=o(a).trim().length,p=o(n).length,m=Math.max(1,s-2-C-p);return`${a.trim()}${" ".repeat(m)}${n}`}formatMessage(r,n){if(n.length===1&&Array.isArray(n[0]))return r.replace(/\{(\d+)\}/g,(c,f)=>{let o=Number.parseInt(f,10);return o<n[0].length?String(n[0][o]):c});let e=/%([sdijfo%])/g,t=0,i=r.replace(e,(c,f)=>{if(f==="%")return"%";if(t>=n.length)return c;let o=n[t++];switch(f){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return c}});if(t<n.length)i+=` ${n.slice(t).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return i}formatMarkdown(r){if(!r)return r;let n=r;return n=n.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(e,t,i)=>{let c=At.underline(At.blue(t)),f=this.toAbsoluteFilePath(i);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(f)}`,s="\x1B]8;;",a="\x1B\\";return`\x1B]8;;${o}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),n=n.replace(/`([^`]+)`/g,(e,t)=>At.bgGray(t)),n=n.replace(/\*\*([^*]+)\*\*/g,(e,t)=>At.bold(t)),n=n.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(e,t)=>At.italic(t)),n=n.replace(/(?<!_)_([^_]+)_(?!_)/g,(e,t)=>At.italic(t)),n=n.replace(/~([^~]+)~/g,(e,t)=>At.strikethrough(t)),n}supportsHyperlinks(){if(Mt())return!1;let r=St.env;if(!r)return!1;if(r.TERM_PROGRAM==="iTerm.app"||r.TERM_PROGRAM==="vscode"||r.TERM_PROGRAM==="WezTerm")return!0;if(r.WT_SESSION)return!0;if(r.TERM==="xterm-kitty")return!0;let n=r.VTE_VERSION?Number.parseInt(r.VTE_VERSION,10):0;if(!Number.isNaN(n)&&n>=5000)return!0;return!1}toAbsoluteFilePath(r){try{let n=r;if(n.startsWith("file://"))n=n.replace(/^file:\/\//,"");if(n.startsWith("~")){let e=St.env.HOME||"";if(e)n=n.replace(/^~(?=$|\/)/,e)}if(vs(n)||n.startsWith("./")||n.startsWith("../"))n=Ss(n);else return null;return wr(n)?n:null}catch{return null}}buildOutputTexts(r){let n=this.shouldStyleConsole()?this.formatMarkdown(r):r,e=r.replace(this.ANSI_PATTERN,"");return{consoleText:n,fileText:e}}async log(r,n,...e){let t=new Date,i=this.formatConsoleTimestamp(t),c=this.formatFileTimestamp(t),f,o;if(n instanceof Error)f=n.message,o=n.stack;else f=this.formatMessage(n,e);let{consoleText:s,fileText:a}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let p=this.options.showIcons===!1?"":qs[r],m=this.options.showTags!==!1&&this.name?At.gray(this.formatTag(this.name)):"",w;switch(r){case"debug":w=this.formatConsoleMessage({timestamp:i,icon:p,tag:m,message:At.gray(s),level:r}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:i,icon:p,tag:m,message:s,level:r}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:i,icon:p,tag:m,message:At.green(s),level:r}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:i,icon:p,tag:m,message:s,level:r}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:i,icon:p,tag:m,message:s,level:r}),console.error(w),o){let B=o.split(`
|
|
10
|
+
`);for(let d of B)if(d.trim()&&!d.includes(f))console.error(this.formatConsoleMessage({timestamp:i,message:At.gray(` ${d}`),level:r,showTimestamp:!1}))}break}}else if(!Mt()){if(console.error(`${c} ${this.environment}.${r.toUpperCase()}: ${f}`),o)console.error(o)}if(!this.shouldLog(r))return;let C=`${c} ${this.environment}.${r.toUpperCase()}: ${a}
|
|
11
|
+
`;if(o)C+=`${o}
|
|
12
|
+
`;if(C=C.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(C)}progress(r,n=""){let e={update:(o,s)=>{},finish:(o)=>{},interrupt:(o,s)=>{}};if(!this.enabled)return e;let t=30;if(this.activeProgressBar={total:Math.max(1,r||1),current:0,message:n||"",barLength:t,lastRenderedLine:""},this.shouldStyleConsole()&&!Mt()&&St.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(o,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,o),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Mt()&&St.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(o)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,o)},interrupt:(o,s="info")=>{if(!Mt()&&St.stdout.isTTY)St.stdout.write(`
|
|
13
|
+
`);if(this[s==="warning"?"warn":s](o),this.activeProgressBar&&this.shouldStyleConsole()&&!Mt()&&St.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(r){let n=performance.now();if(this.shouldStyleConsole()){let e=this.options.showTags!==!1&&this.name?At.gray(this.formatTag(this.name)):"",t=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:t,icon:this.options.showIcons===!1?"":At.blue("◐"),tag:e,message:`${At.cyan(r)}...`}))}return async(e)=>{if(!this.enabled)return;let t=performance.now(),i=Math.round(t-n),c=`${r} completed in ${i}ms`,f=new Date,o=this.formatConsoleTimestamp(f),a=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${c}`;if(e)a+=` ${JSON.stringify(e)}`;if(a+=`
|
|
14
|
+
`,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let C=this.options.showTags!==!1&&this.name?At.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:this.options.showIcons===!1?"":At.green("✓"),tag:C,message:`${c}${e?` ${JSON.stringify(e)}`:""}`}))}else if(!Mt())console.error(a.trim());if(this.shouldWriteToFile())await this.writeToFile(a)}}async debug(r,...n){await this.log("debug",r,...n)}async info(r,...n){await this.log("info",r,...n)}async success(r,...n){await this.log("success",r,...n)}async warn(r,...n){await this.log("warning",r,...n)}async error(r,...n){await this.log("error",r,...n)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let r=this.config.rotation,{encrypt:n}=r;return!!n}async only(r){if(!this.enabled)return;return await r()}isEnabled(){return this.enabled}setEnabled(r){this.enabled=r}extend(r){let n=`${this.name}:${r}`,e=new jr(n,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(e),e}createReadStream(){if(Mt())throw Error("createReadStream is not supported in browser environments");if(!wr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Sn(this.currentLogFile,{encoding:"utf8"})}async decrypt(r){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let n=this.config.rotation;if(!n.encrypt||typeof n.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let e=this.keys.get(this.currentKeyId);try{let t=De.isBuffer(r)?r:De.from(r,"base64"),i=t.subarray(0,16),c=t.subarray(t.length-16),f=t.subarray(16,t.length-16),o=ps("aes-256-gcm",e,i);o.setAuthTag(c);let s=o.update(f),a=o.final(),C=s.length+a.length,p=De.allocUnsafe(C);return s.copy(p,0),a.copy(p,s.length),p.toString("utf8")}catch(t){throw Error(`Decryption failed: ${t instanceof Error?t.message:String(t)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Mt()}isServerMode(){return!Mt()}setTestEncryptionKey(r,n){this.currentKeyId=r,this.keys.set(r,n)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(r){if(!this.enabled)return;let n=new Date,e=this.formatConsoleTimestamp(n),t=this.formatFileTimestamp(n),{consoleText:i,fileText:c}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=i.split(`
|
|
15
|
+
`),s=Math.max(...o.map((m)=>m.length))+2,a=`┌${"─".repeat(s)}┐`,C=`└${"─".repeat(s)}┘`,p=o.map((m)=>{return this.formatConsoleMessage({timestamp:e,message:At.cyan(m),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:e,message:At.cyan(a),showTimestamp:!1})),p.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:e,message:At.cyan(C),showTimestamp:!1}))}else if(!Mt())console.error(`${t} ${this.environment}.INFO: [BOX] ${c}`);let f=`${t} ${this.environment}.INFO: [BOX] ${c}
|
|
16
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt(r){if(Mt())return Promise.resolve(!0);return new Promise((n)=>{console.error(`${At.cyan("?")} ${r} (y/n) `);let e=(t)=>{let i=t.toString().trim().toLowerCase();St.stdin.removeListener("data",e);try{if(typeof St.stdin.setRawMode==="function")St.stdin.setRawMode(!1)}catch{}St.stdin.pause(),console.error(""),n(i==="y"||i==="yes")};try{if(typeof St.stdin.setRawMode==="function")St.stdin.setRawMode(!0)}catch{}St.stdin.resume(),St.stdin.once("data",e)})}setFancy(r){this.fancy=r}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(r,...n){if(!this.enabled)return;let e=r;if(n&&n.length>0){let s=/%([sdijfo%])/g,a=0;if(e=r.replace(s,(C,p)=>{if(p==="%")return"%";if(a>=n.length)return C;let m=n[a++];switch(p){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return C}}),a<n.length)e+=` ${n.slice(a).map((C)=>typeof C==="object"?JSON.stringify(C,null,2):String(C)).join(" ")}`}let{consoleText:t,fileText:i}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?At.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${At.blue("◐")} `;console.error(`${a}${s} ${At.cyan(t)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(r,n=!1){if(!this.enabled||!this.shouldStyleConsole()||!St.stdout.isTTY)return;let e=Math.min(100,Math.max(0,Math.round(r.current/r.total*100))),t=Math.round(r.barLength*e/100),i=r.barLength-t,c=At.green("━".repeat(t)),f=At.gray("━".repeat(i)),o=`[${c}${f}]`,s=`${e}%`.padStart(4),a=r.message?` ${r.message}`:"",C=this.options.showIcons===!1?"":n||e===100?At.green("✓"):At.blue("▶"),p=this.options.showTags!==!1&&this.name?` ${At.gray(this.formatTag(this.name))}`:"",m=`\r${C}${p} ${o} ${s}${a}`,w=St.stdout.columns||80,B=" ".repeat(Math.max(0,w-m.replace(this.ANSI_PATTERN,"").length));if(r.lastRenderedLine=`${m}${B}`,St.stdout.write(r.lastRenderedLine),n)St.stdout.write(`
|
|
18
|
+
`)}finishProgressBar(r,n){if(!this.enabled||!this.fancy||Mt()||!St.stdout.isTTY){this.activeProgressBar=null;return}if(r.current<r.total)r.current=r.total;if(n)r.message=n;this.renderProgressBar(r,!0),this.activeProgressBar=null}async clear(r={}){if(Mt()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let n=await Nr(this.config.logDirectory),e=[];for(let t of n){if(!(r.name?new RegExp(r.name.replace("*",".*")).test(t):t.startsWith(this.name))||!t.endsWith(".log"))continue;let c=ar(this.config.logDirectory,t);if(r.before)try{if((await nr(c)).mtime>=r.before)continue}catch(f){console.error(`Failed to get stats for file ${c}:`,f);continue}e.push(c)}if(e.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${e.length} log file(s)...`);for(let t of e)try{await _r(t),console.warn(`Deleted log file: ${t}`)}catch(i){console.error(`Failed to delete log file ${t}:`,i)}console.warn("Log clearing process finished.")}catch(n){console.error("Error during log clearing process:",n)}}}var rf=new jr("stacks");class me extends Error{timestamp;context;constructor(r,n={}){super(r);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let r=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,e])=>`${n}: ${e}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${r}`}}class xn extends me{code="CONFIG_NOT_FOUND";constructor(r,n,e){let t=e?` or alias "${e}"`:"";super(`Configuration "${r}"${t} not found`,{configName:r,alias:e,searchPaths:n,searchPathCount:n.length})}}class Gr extends me{code="CONFIG_LOAD_ERROR";constructor(r,n,e){super(`Failed to load configuration from "${r}": ${n.message}`,{configPath:r,configName:e,originalError:n.name,originalMessage:n.message});this.cause=n}}class Mn extends me{code="CONFIG_VALIDATION_ERROR";constructor(r,n,e){super(`Configuration validation failed for "${r}"`,{configPath:r,configName:e,validationErrors:n,errorCount:n.length})}}class On extends me{code="CONFIG_MERGE_ERROR";constructor(r,n,e,t){super(`Failed to merge configuration from "${r}" with "${n}": ${e.message}`,{sourcePath:r,targetPath:n,configName:t,originalError:e.name,originalMessage:e.message});this.cause=e}}class _i extends me{code="ENV_VAR_ERROR";constructor(r,n,e,t){super(`Failed to parse environment variable "${r}" with value "${n}" as ${e}`,{envKey:r,envValue:n,expectedType:e,configName:t})}}class Gn extends me{code="FILE_SYSTEM_ERROR";constructor(r,n,e){super(`File system ${r} failed for "${n}": ${e.message}`,{operation:r,path:n,originalError:e.name,originalMessage:e.message});this.cause=e}}class Fn extends me{code="TYPE_GENERATION_ERROR";constructor(r,n,e){super(`Failed to generate types from "${r}" to "${n}": ${e.message}`,{configDir:r,outputPath:n,originalError:e.name,originalMessage:e.message});this.cause=e}}class Fr extends me{code="SCHEMA_VALIDATION_ERROR";constructor(r,n,e){super(`Schema validation failed${e?` for config "${e}"`:""}`,{schemaPath:r,configName:e,validationErrors:n,errorCount:n.length})}}class qn extends me{code="BROWSER_CONFIG_ERROR";constructor(r,n,e,t){super(`Failed to fetch configuration from "${r}": ${n} ${e}`,{endpoint:r,status:n,statusText:e,configName:t})}}class Hn extends me{code="PLUGIN_ERROR";constructor(r,n,e){super(`Plugin "${r}" failed during ${n}: ${e.message}`,{pluginName:r,operation:n,originalError:e.name,originalMessage:e.message});this.cause=e}}var ur={configNotFound(r,n,e){return new xn(r,n,e)},configLoad(r,n,e){return new Gr(r,n,e)},configValidation(r,n,e){return new Mn(r,n,e)},configMerge(r,n,e,t){return new On(r,n,e,t)},envVar(r,n,e,t){return new _i(r,n,e,t)},fileSystem(r,n,e){return new Gn(r,n,e)},typeGeneration(r,n,e){return new Fn(r,n,e)},schemaValidation(r,n,e){return new Fr(r,n,e)},browserConfig(r,n,e,t){return new qn(r,n,e,t)},plugin(r,n,e){return new Hn(r,n,e)}};async function Hs(r,n={}){let{maxRetries:e=3,retryDelay:t=1000,isRetryable:i=()=>!0,fallback:c}=n,f=Error("Unknown error occurred");for(let o=0;o<=e;o++)try{return await r()}catch(s){if(f=s instanceof Error?s:Error(String(s)),o===e||!i(f))break;if(t>0)await new Promise((a)=>setTimeout(a,t))}if(c!==void 0)return c;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}class Ri{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(r,n)=>n==="boolean"||["true","false","1","0","yes","no"].includes(r.toLowerCase()),parse:(r)=>{let n=r.toLowerCase();return["true","1","yes"].includes(n)}},{name:"number",canParse:(r,n)=>n==="number"||!Number.isNaN(Number(r))&&!Number.isNaN(Number.parseFloat(r)),parse:(r)=>{let n=Number(r);if(Number.isNaN(n))throw TypeError(`Cannot parse "${r}" as number`);return n}},{name:"array",canParse:(r,n)=>n==="array"||r.startsWith("[")||r.includes(","),parse:(r)=>{try{let n=JSON.parse(r);if(Array.isArray(n))return n}catch{}return r.split(",").map((n)=>n.trim())}},{name:"json",canParse:(r,n)=>n==="object"||(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]")),parse:(r)=>{try{return JSON.parse(r)}catch(n){throw Error(`Cannot parse "${r}" as JSON: ${n}`)}}}]}async applyEnvironmentVariables(r,n,e={}){let{prefix:t,useCamelCase:i=!0,useBackwardCompatibility:c=!0,customParsers:f={},verbose:o=!1,trackPerformance:s=!0}=e,a=async()=>{if(!r)return{config:n,source:{type:"environment",priority:50,timestamp:new Date}};let C=t||this.generateEnvPrefix(r),p={...n};return this.processObject(p,[],C,{useCamelCase:i,useBackwardCompatibility:c,customParsers:f,verbose:o,configName:r}),{config:p,source:{type:"environment",priority:50,timestamp:new Date}}};if(s)return Bi.track("applyEnvironmentVariables",a,{configName:r});return a()}generateEnvPrefix(r){return r.toUpperCase().replace(/-/g,"_")}formatEnvKey(r,n){if(!n)return r.toUpperCase();return r.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(r,n,e,t){for(let[i,c]of Object.entries(r)){let f=[...n,i],o=f.map((C)=>this.formatEnvKey(C,t.useCamelCase)),s=`${e}_${o.join("_")}`,a=t.useBackwardCompatibility?`${e}_${f.map((C)=>C.toUpperCase()).join("_")}`:null;if(t.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,f,e,t);else{let C=br.env[s]||(a?br.env[a]:void 0);if(C!==void 0){if(t.verbose){let p=br.env[s]?s:a}try{r[i]=this.parseEnvironmentValue(C,typeof c,s,t.customParsers,t.configName)}catch(p){if(p instanceof _i)throw p;throw ur.envVar(s,C,typeof c,t.configName)}}}}}parseEnvironmentValue(r,n,e,t,i){for(let[c,f]of Object.entries(t))try{return f(r)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(r,n))try{return c.parse(r)}catch{throw ur.envVar(e,r,`${n} (via ${c.name} parser)`,i)}return r}getEnvironmentVariables(r){let n={},e=r.toUpperCase();for(let[t,i]of Object.entries(br.env))if(t.startsWith(e)&&i!==void 0)n[t]=i;return n}validateEnvironmentVariable(r,n,e){let t=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(r))t.push(`Environment variable key "${r}" should only contain uppercase letters, numbers, and underscores`);if(e)try{this.parseEnvironmentValue(r,n,e,{})}catch(i){t.push(`Cannot parse value "${n}" as ${e}: ${i}`)}return{isValid:t.length===0,errors:t}}generateEnvVarDocs(r,n,e={}){let{prefix:t,format:i="text"}=e,c=t||this.generateEnvPrefix(r),f=[];switch(this.extractEnvVarInfo(n,[],c,f),i){case"markdown":return this.formatAsMarkdown(f,r);case"json":return JSON.stringify(f,null,2);default:return this.formatAsText(f,r)}}extractEnvVarInfo(r,n,e,t){for(let[i,c]of Object.entries(r)){let f=[...n,i],o=`${e}_${f.map((s)=>this.formatEnvKey(s,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,f,e,t);else t.push({key:o,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${f.join(".")}`,example:this.generateExample(c)})}}generateExample(r){if(Array.isArray(r))return JSON.stringify(r);if(typeof r==="object"&&r!==null)return JSON.stringify(r);return String(r)}formatAsText(r,n){let e=`Environment Variables for ${n}:
|
|
19
|
+
|
|
20
|
+
`;for(let t of r)e+=`${t.key}
|
|
21
|
+
`,e+=` Type: ${t.type}
|
|
22
|
+
`,e+=` Description: ${t.description}
|
|
23
|
+
`,e+=` Example: ${t.example}
|
|
24
|
+
|
|
25
|
+
`;return e}formatAsMarkdown(r,n){let e=`# Environment Variables for ${n}
|
|
26
|
+
|
|
27
|
+
`;e+=`| Variable | Type | Description | Example |
|
|
28
|
+
`,e+=`|----------|------|-------------|----------|
|
|
29
|
+
`;for(let t of r)e+=`| \`${t.key}\` | ${t.type} | ${t.description} | \`${t.example}\` |
|
|
30
|
+
`;return e}}function js(r,n,e={}){return jn(r,n,e,new WeakMap)}function jn(r,n,e,t){let{arrayMergeMode:i="replace",skipNullish:c=!1,customMerger:f}=e;if(n===null||n===void 0)return c?r:n;if(f){let o=f(r,n);if(o!==void 0)return o}if(Array.isArray(n)||Array.isArray(r))return Qn(r,n,i,t);if(!Se(n)||!Se(r))return n;return Ys(r,n,e,t)}function Qn(r,n,e,t){if(Array.isArray(n)&&!Array.isArray(r))return n;if(Array.isArray(r)&&!Array.isArray(n))return n;if(Array.isArray(n)&&Array.isArray(r))switch(e){case"replace":return n;case"concat":return Qs(r,n);case"smart":return zs(r,n,t);default:return n}return n}function Qs(r,n){let e=[...n];for(let t of r)if(!e.some((i)=>gi(i,t)))e.push(t);return e}function zs(r,n,e){if(n.length===0)return r;if(r.length===0)return n;if(Se(n[0])&&Se(r[0]))return Ps(r,n,e);if(n.every((t)=>typeof t==="string")&&r.every((t)=>typeof t==="string")){let t=[...n];for(let i of r)if(!t.includes(i))t.push(i);return t}return n}function Ps(r,n,e){let t=[...n];for(let i of r){if(!Se(i)){t.push(i);continue}let c=["id","name","key","path","type"],f=!1;for(let o of c)if(o in i){if(t.find((a)=>Se(a)&&(o in a)&&a[o]===i[o])){f=!0;break}}if(!f)t.push(i)}return t}function Ys(r,n,e,t){let i=n;if(Se(i)&&t.has(i))return t.get(i);let c={...r};if(Se(i))t.set(i,c);for(let f in i){if(!Object.prototype.hasOwnProperty.call(i,f))continue;let o=i[f],s=c[f];if(e.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){c[f]=o;continue}if(Se(o)&&Se(s))c[f]=jn(s,o,e,t);else if(Array.isArray(o)||Array.isArray(s))c[f]=Qn(s,o,e.arrayMergeMode||"smart",t);else c[f]=o}return c}function zn(r,n,e="replace"){return js(r,n,{arrayMergeMode:e==="replace"?"replace":"smart",skipNullish:!0})}function gi(r,n){if(r===n)return!0;if(Array.isArray(r)&&Array.isArray(n)){if(r.length!==n.length)return!1;for(let e=0;e<r.length;e++)if(!gi(r[e],n[e]))return!1;return!0}if(Se(r)&&Se(n)){let e=Object.keys(r),t=Object.keys(n);if(e.length!==t.length)return!1;for(let i of e){if(!Object.prototype.hasOwnProperty.call(n,i))return!1;if(!gi(r[i],n[i]))return!1}return!0}return!1}function Se(r){return Boolean(r&&typeof r==="object"&&!Array.isArray(r))}class Pn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(r,n,e={}){let{arrayStrategy:t="replace",useCache:i=!0,cacheTtl:c,trackPerformance:f=!0,verbose:o=!1}=e;if(i){let a=Dr.getWithFileCheck("file",r);if(a){if(o)console.log(`Configuration loaded from cache: ${r}`);return a}}let s=async()=>{if(!Ur(r))return null;try{let a=`?t=${Date.now()}`,C=await import(r+a),p=C.default||C,m="default"in C,w=Object.keys(C).length>0;if(!m&&!w)throw new Gr(r,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof p!=="object"||p===null||Array.isArray(p))throw new Gr(r,Error("Configuration must export a valid object"),"unknown");let T={config:zn(n,p,t),source:{type:"file",path:r,priority:100,timestamp:new Date}};if(i)Dr.setWithFileCheck("file",T,r,c);return T}catch(a){throw a instanceof Error?ur.configLoad(r,a):ur.configLoad(r,Error(String(a)))}};if(f)return Bi.track("loadFromPath",s,{path:r});return s()}async tryLoadFromPaths(r,n,e={}){for(let t of r)try{let i=await this.loadFromPath(t,n,e);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(e.verbose)console.warn(`Failed to load config from ${t}:`,i)}return null}generateConfigPaths(r,n,e){let t=this.generateNamePatterns(r,e),i=[];for(let c of t)for(let f of this.extensions)i.push(Ii(n,`${c}${f}`));return i}generateNamePatterns(r,n){let e=[];if(e.push("config",".config"),r)e.push(r,`.${r}.config`,`${r}.config`,`.${r}`);if(n){if(e.push(n,`.${n}.config`,`${n}.config`,`.${n}`),r)e.push(`${r}.${n}.config`,`.${r}.${n}.config`)}return e.filter(Boolean)}checkFileAccess(r){return Hs(async()=>{return Ur(r)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(r,n,e){let t=[];if(!Ur(r))return t;if(n||e){let i=this.generateNamePatterns(n||"",e);for(let c of i)for(let f of this.extensions){let o=Ii(r,`${c}${f}`);if(await this.checkFileAccess(o))t.push(o)}}else try{let{readdirSync:i}=await import("fs"),c=i(r);for(let f of c)if(this.looksLikeConfigFile(f)){let o=Ii(r,f);if(await this.checkFileAccess(o))t.push(o)}}catch{return[]}return t}looksLikeConfigFile(r){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((e)=>e.test(r))}async validateConfigFile(r){let n=[];try{if(!Ur(r))return n.push("Configuration file does not exist"),n;let e=await import(r),t=e.default||e;if(t===void 0)n.push("Configuration file must export a default value or named exports");else if(typeof t!=="object"||t===null)n.push("Configuration must be an object");else if(Array.isArray(t))n.push("Configuration cannot be an array at the root level");if(r.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),c=i(r,"utf8");JSON.parse(c)}catch(i){n.push(`Invalid JSON syntax: ${i}`)}}catch(e){n.push(`Failed to load configuration file: ${e}`)}return n}async getFileModificationTime(r){try{let{statSync:n}=await import("fs");return n(r).mtime}catch{return null}}async preloadConfigurations(r,n={}){let e=new Map;return await Promise.allSettled(r.map(async(t)=>{try{let i=await this.loadFromPath(t,{},n);if(i)e.set(t,i.config)}catch(i){if(n.verbose)console.warn(`Failed to preload ${t}:`,i)}})),e}}var Ws=/^https?:\/\//;class Yn{async validateConfiguration(r,n,e={}){let{stopOnFirstError:t=!1,validateRequired:i=!0,validateTypes:c=!0,customRules:f=[],trackPerformance:o=!0,verbose:s=!1}=e,a=async()=>{let C=[],p=[],m={stopOnFirstError:t,validateRequired:i,validateTypes:c,customRules:f,trackPerformance:o,verbose:s};try{if(typeof n==="string")return await this.validateWithSchemaFile(r,n,m);else if(Array.isArray(n))return this.validateWithRules(r,[...n,...f],m);else return this.validateWithJSONSchema(r,n,m)}catch(w){return C.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:C,warnings:p}}};if(o)return await Bi.track("validateConfiguration",a);return a()}async validateWithSchemaFile(r,n,e){try{if(!Xs(n))throw new Fr(n,[{path:"",message:"Schema file does not exist"}]);let t=await import(n),i=t.default||t;if(Array.isArray(i))return this.validateWithRules(r,i,e);else return this.validateWithJSONSchema(r,i,e)}catch(t){throw new Fr(n,[{path:"",message:`Failed to load schema: ${t}`}])}}validateWithJSONSchema(r,n,e){let t=[],i=[];return this.validateObjectAgainstSchema(r,n,"",t,i,e),{isValid:t.length===0,errors:t,warnings:i}}validateObjectAgainstSchema(r,n,e,t,i,c){if(c.validateTypes&&n.type){let f=Array.isArray(r)?"array":typeof r,o=Array.isArray(n.type)?n.type:[n.type];if(!o.includes(f)){if(t.push({path:e,message:`Expected type ${o.join(" or ")}, got ${f}`,expected:o.join(" or "),actual:f,rule:"type"}),c.stopOnFirstError)return}}if(n.enum&&!n.enum.includes(r)){if(t.push({path:e,message:`Value must be one of: ${n.enum.join(", ")}`,expected:n.enum.join(", "),actual:r,rule:"enum"}),c.stopOnFirstError)return}if(typeof r==="string"){if(n.minLength!==void 0&&r.length<n.minLength)t.push({path:e,message:`String length must be at least ${n.minLength}`,expected:`>= ${n.minLength}`,actual:r.length,rule:"minLength"});if(n.maxLength!==void 0&&r.length>n.maxLength)t.push({path:e,message:`String length must not exceed ${n.maxLength}`,expected:`<= ${n.maxLength}`,actual:r.length,rule:"maxLength"});if(n.pattern){if(!new RegExp(n.pattern).test(r))t.push({path:e,message:`String does not match pattern ${n.pattern}`,expected:n.pattern,actual:r,rule:"pattern"})}}if(typeof r==="number"){if(n.minimum!==void 0&&r<n.minimum)t.push({path:e,message:`Value must be at least ${n.minimum}`,expected:`>= ${n.minimum}`,actual:r,rule:"minimum"});if(n.maximum!==void 0&&r>n.maximum)t.push({path:e,message:`Value must not exceed ${n.maximum}`,expected:`<= ${n.maximum}`,actual:r,rule:"maximum"})}if(Array.isArray(r)&&n.items)for(let f=0;f<r.length;f++){let o=e?`${e}[${f}]`:`[${f}]`;if(this.validateObjectAgainstSchema(r[f],n.items,o,t,i,c),c.stopOnFirstError&&t.length>0)return}if(r&&typeof r==="object"&&!Array.isArray(r)){let f=r;if(c.validateRequired&&n.required){for(let o of n.required)if(!(o in f)){if(t.push({path:e?`${e}.${o}`:o,message:`Missing required property '${o}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(n.properties){for(let[o,s]of Object.entries(n.properties))if(o in f){let a=e?`${e}.${o}`:o;if(this.validateObjectAgainstSchema(f[o],s,a,t,i,c),c.stopOnFirstError&&t.length>0)return}}if(n.additionalProperties===!1){let o=new Set(Object.keys(n.properties||{}));for(let s of Object.keys(f))if(!o.has(s))i.push({path:e?`${e}.${s}`:s,message:`Additional property '${s}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(r,n,e){let t=[],i=[];for(let c of n)try{let f=this.getValueByPath(r,c.path),o=this.validateWithRule(f,c,c.path);if(t.push(...o),e.stopOnFirstError&&t.length>0)break}catch(f){t.push({path:c.path,message:`Rule validation failed: ${f}`,rule:"system"})}return{isValid:t.length===0,errors:t,warnings:i}}validateWithRule(r,n,e){let t=[];if(n.required&&(r===void 0||r===null))return t.push({path:e,message:n.message||`Property '${e}' is required`,expected:"required",rule:"required"}),t;if(r===void 0||r===null)return t;if(n.type){let i=Array.isArray(r)?"array":typeof r;if(i!==n.type)t.push({path:e,message:n.message||`Expected type ${n.type}, got ${i}`,expected:n.type,actual:i,rule:"type"})}if(n.min!==void 0){let i=Array.isArray(r)?r.length:typeof r==="string"?r.length:typeof r==="number"?r:0;if(i<n.min)t.push({path:e,message:n.message||`Value must be at least ${n.min}`,expected:`>= ${n.min}`,actual:i,rule:"min"})}if(n.max!==void 0){let i=Array.isArray(r)?r.length:typeof r==="string"?r.length:typeof r==="number"?r:0;if(i>n.max)t.push({path:e,message:n.message||`Value must not exceed ${n.max}`,expected:`<= ${n.max}`,actual:i,rule:"max"})}if(n.pattern&&typeof r==="string"){if(!n.pattern.test(r))t.push({path:e,message:n.message||`Value does not match pattern ${n.pattern}`,expected:n.pattern.toString(),actual:r,rule:"pattern"})}if(n.enum&&!n.enum.includes(r))t.push({path:e,message:n.message||`Value must be one of: ${n.enum.join(", ")}`,expected:n.enum.join(", "),actual:r,rule:"enum"});if(n.validator){let i=n.validator(r);if(i)t.push({path:e,message:n.message||i,rule:"custom"})}return t}getValueByPath(r,n){if(!n)return r;let e=n.split("."),t=r;for(let i of e)if(t&&typeof t==="object"&&i in t)t=t[i];else return;return t}generateRulesFromInterface(r){let n=[],e=r.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let t of e){let[,i,c,f]=t;n.push({path:i,required:!c,type:this.mapTypeScriptType(f)})}return n}mapTypeScriptType(r){switch(r.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Ws},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var He=new jr("bunfig",{showTags:!0});class Xn{fileLoader=new Pn;envProcessor=new Ri;validator=new Yn;async loadConfig(r){let n=Date.now(),{cache:e,performance:t,schema:i,validate:c,...f}=r;try{if(e?.enabled){let s=this.checkCache(f.name||"",f);if(s)return s}let o;try{o=await this.loadConfigurationStrategies(f,!0,e)}catch(s){let a=f.__strictErrorHandling;if(s instanceof Error&&s.name==="ConfigNotFoundError"){if(a)throw s;o={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`No configuration file found for "${f.name||"config"}", using defaults with environment variables`]}}else if(s instanceof Error&&s.name==="ConfigLoadError"){let C=s.message.includes("EACCES")||s.message.includes("EPERM")||s.message.includes("permission denied"),p=!C&&(s.message.includes("syntax")||s.message.includes("Expected")||s.message.includes("Unexpected")||s.message.includes("BuildMessage")||s.message.includes("errors building")),m=s.message.includes("Configuration must export a valid object")||s.message.includes("Configuration file is empty and exports nothing");if(a&&(m||C))throw s;if(p&&(!a||!m))o={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!a)o={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading error, using defaults: ${s.message}`]};else throw s}else o={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${s instanceof Error?s.message:String(s)}`]}}if(i||c)await this.validateConfiguration(o.config,i,c,f.name);if(e?.enabled&&o)this.cacheResult(f.name||"",o,e,f);if(t?.enabled){let s={operation:"loadConfig",duration:Date.now()-n,configName:f.name,timestamp:new Date};if(t.onMetrics)t.onMetrics(s);if(t.slowThreshold&&s.duration>t.slowThreshold)He.warn(`Slow configuration loading detected: ${s.duration}ms for ${f.name}`);o.metrics=s}return o}catch(o){let s=Date.now()-n;throw He.error(`Configuration loading failed after ${s}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(r,n=!1,e){let{name:t="",alias:i,cwd:c,configDir:f,defaultConfig:o,checkEnv:s=!0,arrayStrategy:a="replace",verbose:C=!1}=r,p=c||qr.cwd(),m=[],w=await this.loadLocalConfiguration(t,i,p,f,o,a,C,s,e);if(w)return m.push(...this.getLocalSearchPaths(t,i,p,f)),this.finalizeResult(w,m,s,t,C);let B=await this.loadHomeConfiguration(t,i,o,a,C,s);if(B)return m.push(...this.getHomeSearchPaths(t,i)),this.finalizeResult(B,m,s,t,C);let d=await this.loadPackageJsonConfiguration(t,i,p,o,a,C,s);if(d)return m.push(ve(p,"package.json")),this.finalizeResult(d,m,s,t,C);if(m.push(...this.getAllSearchPaths(t,i,p,f)),n)throw ur.configNotFound(t,m,i);return{...await this.applyEnvironmentVariables(t,o,s,C),warnings:[`No configuration file found for "${t}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(r,n,e,t,i,c,f,o,s){let a=o?kr(r,i,f):i,C=this.getLocalDirectories(e,t);for(let p of C){if(f)He.info(`Searching for configuration in: ${p}`);let m=this.fileLoader.generateConfigPaths(r,p,n),w=await this.fileLoader.tryLoadFromPaths(m,a,{arrayStrategy:c,verbose:f,cacheTtl:s?.ttl,useCache:!s?.ttl||s.ttl>100});if(w){if(f)He.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(r,n,e,t,i,c){if(!r)return null;let f=c?kr(r,e,i):e,o=[ve(tr(),".config",r),ve(tr(),".config"),tr()];for(let s of o){if(i)He.info(`Checking home directory: ${s}`);let a=this.fileLoader.generateConfigPaths(r,s,n),C=await this.fileLoader.tryLoadFromPaths(a,f,{arrayStrategy:t,verbose:i});if(C){if(i)He.success(`Configuration loaded from home directory: ${C.source.path}`);return C}}return null}async loadPackageJsonConfiguration(r,n,e,t,i,c,f){let o=f?kr(r,t,c):t;try{let s=ve(e,"package.json");if(!ts(s))return null;let a=await import(s),C=a[r],p=r;if(!C&&n)C=a[n],p=n;if(C&&typeof C==="object"&&!Array.isArray(C)){if(c)He.success(`Configuration loaded from package.json: ${p}`);return{config:zn(o,C,i),source:{type:"package.json",path:s,priority:30,timestamp:new Date}}}}catch(s){if(c)He.warn("Failed to load package.json:",[s instanceof Error?s:Error(String(s))])}return null}async applyEnvironmentVariables(r,n,e,t){if(!e||!r||typeof n!=="object"||n===null||Array.isArray(n))return{config:n,source:{type:"default",priority:10,timestamp:new Date}};return{config:kr(r,n,t),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(r,n,e,t,i){return{config:r.config,source:r.source,path:r.source.path}}async validateConfiguration(r,n,e,t){let i=[];if(e){let c=e(r);if(c)i.push(...c)}if(n){let c=await this.validator.validateConfiguration(r,n);if(!c.isValid)i.push(...c.errors.map((f)=>f.path?`${f.path}: ${f.message}`:f.message))}if(i.length>0)throw ur.configValidation(t||"unknown",i,t)}checkCache(r,n){let e=this.generateCacheKey(r,n);return Dr.get(e)||null}cacheResult(r,n,e,t){let i=this.generateCacheKey(r,t);Dr.set(i,n,void 0,e.ttl)}generateCacheKey(r,n){let e=[r];if(n.alias)e.push(`alias:${n.alias}`);if(n.cwd)e.push(`cwd:${n.cwd}`);if(n.configDir)e.push(`configDir:${n.configDir}`);if("checkEnv"in n)e.push(`checkEnv:${n.checkEnv}`);return e.join("|")}getLocalDirectories(r,n){return Array.from(new Set([r,ve(r,"config"),ve(r,".config"),n?ve(r,n):void 0].filter(Boolean)))}getAllSearchPaths(r,n,e,t){let i=[];return i.push(...this.getLocalSearchPaths(r,n,e,t)),i.push(...this.getHomeSearchPaths(r,n)),i.push(ve(e,"package.json")),i}getLocalSearchPaths(r,n,e,t){let i=this.getLocalDirectories(e,t),c=[];for(let f of i)c.push(...this.fileLoader.generateConfigPaths(r,f,n));return c}getHomeSearchPaths(r,n){if(!r)return[];let e=[ve(tr(),".config",r),ve(tr(),".config"),tr()],t=[];for(let i of e)t.push(...this.fileLoader.generateConfigPaths(r,i,n));return t}async loadConfigWithResult(r){return this.loadConfig(r)}}var cf=new Xn;function kr(r,n,e=!1){let t=new Ri,i=r.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(f,o=[]){let s={...f};for(let[a,C]of Object.entries(f)){let p=[...o,a],m=[`${i}_${p.join("_").toUpperCase()}`,`${i}_${p.map((d)=>d.toUpperCase()).join("")}`,`${i}_${p.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,B;for(let d of m)if(w=qr.env[d],w!==void 0){B=d;break}if(w!==void 0&&B)if(typeof C==="boolean")s[a]=["true","1","yes"].includes(w.toLowerCase());else if(typeof C==="number"){let d=Number(w);if(!Number.isNaN(d))s[a]=d}else if(Array.isArray(C))try{s[a]=JSON.parse(w)}catch{s[a]=w.split(",").map((d)=>d.trim())}else s[a]=w;else if(C&&typeof C==="object"&&!Array.isArray(C))s[a]=c(C,p)}return s}return c(n)}var ff=ve(qr.cwd(),"config"),lf=ve(qr.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Zs={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Ui(bi(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Ui(bi(),".stacks","ssl","stacks.localhost.crt"),keyPath:Ui(bi(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Qr=Zs;import{exec as eu}from"node:child_process";import Qe from"node:fs";import Wn from"node:os";import Di from"node:path";import*as cr from"node:process";import{promisify as ru}from"node:util";import{createRequire as $s}from"node:module";var Js=$s(import.meta.url),tu=Js("consola"),X=tu.consola;var zr=ru(eu),Te=cr.platform==="win32"?Di.join(cr.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",ki=!1;async function Pr(r){if(cr.platform==="win32")throw Error("Administrator privileges required on Windows");let n=Li();try{if(n){let{stdout:t}=await zr(`echo '${n}' | sudo -S ${r}`);return ki=!0,t}if(ki)try{let{stdout:t}=await zr(`sudo -n true && sudo -n ${r}`);return t}catch(t){Q("hosts","Cached sudo privileges expired, requesting again",!0)}let{stdout:e}=await zr(`sudo ${r}`);return ki=!0,e}catch(e){throw Error(`Failed to execute sudo command: ${e.message}`)}}async function Yr(r,n){Q("hosts",`Adding hosts: ${r.join(", ")}`,n),Q("hosts",`Using hosts file at: ${Te}`,n);try{let e;try{e=await Qe.promises.readFile(Te,"utf-8")}catch(f){Q("hosts",`Error reading hosts file: ${f}`,n),X.error(`Failed to read hosts file: ${f}`);try{e=await Pr(`cat "${Te}"`)}catch(o){throw X.error(`Failed to read hosts file with sudo: ${o}`),Error(`Cannot read hosts file: ${o}`)}}let t=r.filter((f)=>{let o=`127.0.0.1 ${f}`,s=`::1 ${f}`;return!e.includes(o)&&!e.includes(s)});if(t.length===0){Q("hosts","All hosts already exist in hosts file",n),X.info("All hosts are already in the hosts file");return}let i=t.map((f)=>`
|
|
31
|
+
# Added by rpx
|
|
32
|
+
127.0.0.1 ${f}
|
|
33
|
+
::1 ${f}`).join(`
|
|
34
|
+
`),c=Di.join(Wn.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Qe.promises.writeFile(c,e+i,"utf8"),await Pr(`cat "${c}" | tee "${Te}" > /dev/null`),X.success(`Added new hosts: ${t.join(", ")}`)}catch(f){if(X.warn("Could not modify hosts file automatically"),X.info("Please add these entries to your hosts file:"),t.forEach((o)=>{X.info(` 127.0.0.1 ${o}`),X.info(` ::1 ${o}`)}),cr.platform==="win32")X.info(`
|
|
35
|
+
On Windows:`),X.info("1. Run notepad as administrator"),X.info("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else X.info(`
|
|
36
|
+
On Unix systems:`),X.info(` sudo nano ${Te}`);X.info(`
|
|
37
|
+
Or run: buddy setup:ssl`)}finally{try{await Qe.promises.unlink(c)}catch(f){Q("hosts",`Failed to remove temporary file: ${f}`,n)}}}catch(e){Q("hosts",`Failed to manage hosts file: ${e.message}`,n)}}async function Zn(r,n){Q("hosts",`Removing hosts: ${r.join(", ")}`,n);try{let e;try{e=await Qe.promises.readFile(Te,"utf-8")}catch(s){Q("hosts",`Error reading hosts file: ${s}`,n);try{e=await Pr(`cat "${Te}"`)}catch(a){throw X.error(`Failed to read hosts file with sudo: ${a}`),Error(`Cannot read hosts file: ${a}`)}}let t=e.split(`
|
|
38
|
+
`),i=!1,c=t.filter((s)=>{if(r.some((C)=>s.includes(` ${C}`)&&(s.includes("127.0.0.1")||s.includes("::1"))))return i=!0,!1;if(s.trim()==="# Added by rpx")return i=!0,!1;return!0});if(!i){Q("hosts","No matching hosts found to remove",n);return}while(c[c.length-1]?.trim()==="")c.pop();let f=`${c.join(`
|
|
39
|
+
`)}
|
|
40
|
+
`,o=Di.join(Wn.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Qe.promises.writeFile(o,f,"utf8"),await Pr(`cat "${o}" | tee "${Te}" > /dev/null`),X.success("Hosts removed successfully")}catch(s){X.warn("Could not modify hosts file automatically"),X.info("You may want to remove these entries from your hosts file:"),r.forEach((a)=>{X.info(` 127.0.0.1 ${a}`),X.info(` ::1 ${a}`)})}finally{try{await Qe.promises.unlink(o)}catch(s){Q("hosts",`Failed to remove temporary file: ${s}`,n)}}}catch(e){Q("hosts",`Failed to clean up hosts file: ${e.message}`,n)}}async function Xr(r,n){Q("hosts",`Checking hosts: ${r}`,n);let e;try{e=await Qe.promises.readFile(Te,"utf-8")}catch(t){Q("hosts",`Error reading hosts file: ${t}`,n);try{let i=Li(),c;if(i)c=`echo '${i}' | sudo -S cat "${Te}" 2>/dev/null`;else c=`sudo -n cat "${Te}" 2>/dev/null || cat "${Te}" 2>/dev/null || echo ""`;let{stdout:f}=await zr(c);e=f}catch(i){return Q("hosts",`Cannot read hosts file, assuming entries don't exist: ${i}`,n),r.map(()=>!1)}}return r.map((t)=>{let i=`127.0.0.1 ${t}`,c=`::1 ${t}`;return e.includes(i)||e.includes(c)})}import{execSync as Oe}from"node:child_process";import ue from"node:fs/promises";import*as Xi from"node:os";import{homedir as Er}from"node:os";import{join as pe}from"node:path";import*as Ne from"node:process";import Ki from"node:os";import Vi from"node:path";import{resolve as pu}from"path";import yu from"process";import{exec as Cu}from"node:child_process";import $n from"node:fs";import Eu from"node:path";import vu from"node:process";import{promisify as Su}from"node:util";import xe from"node:fs";import Jn from"node:os";import lr from"node:path";var pt=lt((r,n)=>{n.exports={options:{usePureJavaScript:!1}}}),iu=lt((r,n)=>{var e={};n.exports=e;var t={};e.encode=function(c,f,o){if(typeof f!=="string")throw TypeError('"alphabet" must be a string.');if(o!==void 0&&typeof o!=="number")throw TypeError('"maxline" must be a number.');var s="";if(!(c instanceof Uint8Array))s=i(c,f);else{var a=0,C=f.length,p=f.charAt(0),m=[0];for(a=0;a<c.length;++a){for(var w=0,B=c[a];w<m.length;++w)B+=m[w]<<8,m[w]=B%C,B=B/C|0;while(B>0)m.push(B%C),B=B/C|0}for(a=0;c[a]===0&&a<c.length-1;++a)s+=p;for(a=m.length-1;a>=0;--a)s+=f[m[a]]}if(o){var d=new RegExp(".{1,"+o+"}","g");s=s.match(d).join(`\r
|
|
41
|
+
`)}return s},e.decode=function(c,f){if(typeof c!=="string")throw TypeError('"input" must be a string.');if(typeof f!=="string")throw TypeError('"alphabet" must be a string.');var o=t[f];if(!o){o=t[f]=[];for(var s=0;s<f.length;++s)o[f.charCodeAt(s)]=s}c=c.replace(/\s/g,"");var a=f.length,C=f.charAt(0),p=[0];for(var s=0;s<c.length;s++){var m=o[c.charCodeAt(s)];if(m===void 0)return;for(var w=0,B=m;w<p.length;++w)B+=p[w]*a,p[w]=B&255,B>>=8;while(B>0)p.push(B&255),B>>=8}for(var d=0;c[d]===C&&d<c.length-1;++d)p.push(0);if(typeof Buffer<"u")return Buffer.from(p.reverse());return new Uint8Array(p.reverse())};function i(c,f){var o=0,s=f.length,a=f.charAt(0),C=[0];for(o=0;o<c.length();++o){for(var p=0,m=c.at(o);p<C.length;++p)m+=C[p]<<8,C[p]=m%s,m=m/s|0;while(m>0)C.push(m%s),m=m/s|0}var w="";for(o=0;c.at(o)===0&&o<c.length()-1;++o)w+=a;for(o=C.length-1;o>=0;--o)w+=f[C[o]];return w}}),Tt=lt((r,n)=>{var e=pt(),t=iu(),i=n.exports=e.util=e.util||{};(function(){if(typeof process<"u"&&process.nextTick){if(i.nextTick=process.nextTick,typeof setImmediate==="function")i.setImmediate=setImmediate;else i.setImmediate=i.nextTick;return}if(typeof setImmediate==="function"){i.setImmediate=function(){return setImmediate.apply(void 0,arguments)},i.nextTick=function(u){return setImmediate(u)};return}if(i.setImmediate=function(u){setTimeout(u,0)},typeof window<"u"&&typeof window.postMessage==="function"){let u=function(R){if(R.source===window&&R.data===S){R.stopPropagation();var V=I.slice();I.length=0,V.forEach(function(O){O()})}};var l=u,S="forge.setImmediate",I=[];i.setImmediate=function(R){if(I.push(R),I.length===1)window.postMessage(S,"*")},window.addEventListener("message",u,!0)}if(typeof MutationObserver<"u"){var N=Date.now(),L=!0,v=document.createElement("div"),I=[];new MutationObserver(function(){var R=I.slice();I.length=0,R.forEach(function(V){V()})}).observe(v,{attributes:!0});var h=i.setImmediate;i.setImmediate=function(R){if(Date.now()-N>15)N=Date.now(),h(R);else if(I.push(R),I.length===1)v.setAttribute("a",L=!L)}}i.nextTick=i.setImmediate})(),i.isNodejs=typeof process<"u"&&process.versions&&process.versions.node,i.globalScope=function(){if(i.isNodejs)return global;return typeof self>"u"?window:self}(),i.isArray=Array.isArray||function(l){return Object.prototype.toString.call(l)==="[object Array]"},i.isArrayBuffer=function(l){return typeof ArrayBuffer<"u"&&l instanceof ArrayBuffer},i.isArrayBufferView=function(l){return l&&i.isArrayBuffer(l.buffer)&&l.byteLength!==void 0};function c(l){if(!(l===8||l===16||l===24||l===32))throw Error("Only 8, 16, 24, or 32 bits supported: "+l)}i.ByteBuffer=f;function f(l){if(this.data="",this.read=0,typeof l==="string")this.data=l;else if(i.isArrayBuffer(l)||i.isArrayBufferView(l))if(typeof Buffer<"u"&&l instanceof Buffer)this.data=l.toString("binary");else{var S=new Uint8Array(l);try{this.data=String.fromCharCode.apply(null,S)}catch(N){for(var I=0;I<S.length;++I)this.putByte(S[I])}}else if(l instanceof f||typeof l==="object"&&typeof l.data==="string"&&typeof l.read==="number")this.data=l.data,this.read=l.read;this._constructedStringLength=0}i.ByteStringBuffer=f;var o=4096;i.ByteStringBuffer.prototype._optimizeConstructedString=function(l){if(this._constructedStringLength+=l,this._constructedStringLength>o)this.data.substr(0,1),this._constructedStringLength=0},i.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},i.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},i.ByteStringBuffer.prototype.putByte=function(l){return this.putBytes(String.fromCharCode(l))},i.ByteStringBuffer.prototype.fillWithByte=function(l,S){l=String.fromCharCode(l);var I=this.data;while(S>0){if(S&1)I+=l;if(S>>>=1,S>0)l+=l}return this.data=I,this._optimizeConstructedString(S),this},i.ByteStringBuffer.prototype.putBytes=function(l){return this.data+=l,this._optimizeConstructedString(l.length),this},i.ByteStringBuffer.prototype.putString=function(l){return this.putBytes(i.encodeUtf8(l))},i.ByteStringBuffer.prototype.putInt16=function(l){return this.putBytes(String.fromCharCode(l>>8&255)+String.fromCharCode(l&255))},i.ByteStringBuffer.prototype.putInt24=function(l){return this.putBytes(String.fromCharCode(l>>16&255)+String.fromCharCode(l>>8&255)+String.fromCharCode(l&255))},i.ByteStringBuffer.prototype.putInt32=function(l){return this.putBytes(String.fromCharCode(l>>24&255)+String.fromCharCode(l>>16&255)+String.fromCharCode(l>>8&255)+String.fromCharCode(l&255))},i.ByteStringBuffer.prototype.putInt16Le=function(l){return this.putBytes(String.fromCharCode(l&255)+String.fromCharCode(l>>8&255))},i.ByteStringBuffer.prototype.putInt24Le=function(l){return this.putBytes(String.fromCharCode(l&255)+String.fromCharCode(l>>8&255)+String.fromCharCode(l>>16&255))},i.ByteStringBuffer.prototype.putInt32Le=function(l){return this.putBytes(String.fromCharCode(l&255)+String.fromCharCode(l>>8&255)+String.fromCharCode(l>>16&255)+String.fromCharCode(l>>24&255))},i.ByteStringBuffer.prototype.putInt=function(l,S){c(S);var I="";do S-=8,I+=String.fromCharCode(l>>S&255);while(S>0);return this.putBytes(I)},i.ByteStringBuffer.prototype.putSignedInt=function(l,S){if(l<0)l+=2<<S-1;return this.putInt(l,S)},i.ByteStringBuffer.prototype.putBuffer=function(l){return this.putBytes(l.getBytes())},i.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)},i.ByteStringBuffer.prototype.getInt16=function(){var l=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,l},i.ByteStringBuffer.prototype.getInt24=function(){var l=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,l},i.ByteStringBuffer.prototype.getInt32=function(){var l=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,l},i.ByteStringBuffer.prototype.getInt16Le=function(){var l=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,l},i.ByteStringBuffer.prototype.getInt24Le=function(){var l=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,l},i.ByteStringBuffer.prototype.getInt32Le=function(){var l=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,l},i.ByteStringBuffer.prototype.getInt=function(l){c(l);var S=0;do S=(S<<8)+this.data.charCodeAt(this.read++),l-=8;while(l>0);return S},i.ByteStringBuffer.prototype.getSignedInt=function(l){var S=this.getInt(l),I=2<<l-2;if(S>=I)S-=I<<1;return S},i.ByteStringBuffer.prototype.getBytes=function(l){var S;if(l)l=Math.min(this.length(),l),S=this.data.slice(this.read,this.read+l),this.read+=l;else if(l===0)S="";else S=this.read===0?this.data:this.data.slice(this.read),this.clear();return S},i.ByteStringBuffer.prototype.bytes=function(l){return typeof l>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+l)},i.ByteStringBuffer.prototype.at=function(l){return this.data.charCodeAt(this.read+l)},i.ByteStringBuffer.prototype.setAt=function(l,S){return this.data=this.data.substr(0,this.read+l)+String.fromCharCode(S)+this.data.substr(this.read+l+1),this},i.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},i.ByteStringBuffer.prototype.copy=function(){var l=i.createBuffer(this.data);return l.read=this.read,l},i.ByteStringBuffer.prototype.compact=function(){if(this.read>0)this.data=this.data.slice(this.read),this.read=0;return this},i.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},i.ByteStringBuffer.prototype.truncate=function(l){var S=Math.max(0,this.length()-l);return this.data=this.data.substr(this.read,S),this.read=0,this},i.ByteStringBuffer.prototype.toHex=function(){var l="";for(var S=this.read;S<this.data.length;++S){var I=this.data.charCodeAt(S);if(I<16)l+="0";l+=I.toString(16)}return l},i.ByteStringBuffer.prototype.toString=function(){return i.decodeUtf8(this.bytes())};function s(l,S){S=S||{},this.read=S.readOffset||0,this.growSize=S.growSize||1024;var I=i.isArrayBuffer(l),N=i.isArrayBufferView(l);if(I||N){if(I)this.data=new DataView(l);else this.data=new DataView(l.buffer,l.byteOffset,l.byteLength);this.write="writeOffset"in S?S.writeOffset:this.data.byteLength;return}if(this.data=new DataView(new ArrayBuffer(0)),this.write=0,l!==null&&l!==void 0)this.putBytes(l);if("writeOffset"in S)this.write=S.writeOffset}i.DataBuffer=s,i.DataBuffer.prototype.length=function(){return this.write-this.read},i.DataBuffer.prototype.isEmpty=function(){return this.length()<=0},i.DataBuffer.prototype.accommodate=function(l,S){if(this.length()>=l)return this;S=Math.max(S||this.growSize,l);var I=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),N=new Uint8Array(this.length()+S);return N.set(I),this.data=new DataView(N.buffer),this},i.DataBuffer.prototype.putByte=function(l){return this.accommodate(1),this.data.setUint8(this.write++,l),this},i.DataBuffer.prototype.fillWithByte=function(l,S){this.accommodate(S);for(var I=0;I<S;++I)this.data.setUint8(l);return this},i.DataBuffer.prototype.putBytes=function(l,S){if(i.isArrayBufferView(l)){var I=new Uint8Array(l.buffer,l.byteOffset,l.byteLength),N=I.byteLength-I.byteOffset;this.accommodate(N);var L=new Uint8Array(this.data.buffer,this.write);return L.set(I),this.write+=N,this}if(i.isArrayBuffer(l)){var I=new Uint8Array(l);this.accommodate(I.byteLength);var L=new Uint8Array(this.data.buffer);return L.set(I,this.write),this.write+=I.byteLength,this}if(l instanceof i.DataBuffer||typeof l==="object"&&typeof l.read==="number"&&typeof l.write==="number"&&i.isArrayBufferView(l.data)){var I=new Uint8Array(l.data.byteLength,l.read,l.length());this.accommodate(I.byteLength);var L=new Uint8Array(l.data.byteLength,this.write);return L.set(I),this.write+=I.byteLength,this}if(l instanceof i.ByteStringBuffer)l=l.data,S="binary";if(S=S||"binary",typeof l==="string"){var v;if(S==="hex")return this.accommodate(Math.ceil(l.length/2)),v=new Uint8Array(this.data.buffer,this.write),this.write+=i.binary.hex.decode(l,v,this.write),this;if(S==="base64")return this.accommodate(Math.ceil(l.length/4)*3),v=new Uint8Array(this.data.buffer,this.write),this.write+=i.binary.base64.decode(l,v,this.write),this;if(S==="utf8")l=i.encodeUtf8(l),S="binary";if(S==="binary"||S==="raw")return this.accommodate(l.length),v=new Uint8Array(this.data.buffer,this.write),this.write+=i.binary.raw.decode(v),this;if(S==="utf16")return this.accommodate(l.length*2),v=new Uint16Array(this.data.buffer,this.write),this.write+=i.text.utf16.encode(v),this;throw Error("Invalid encoding: "+S)}throw Error("Invalid parameter: "+l)},i.DataBuffer.prototype.putBuffer=function(l){return this.putBytes(l),l.clear(),this},i.DataBuffer.prototype.putString=function(l){return this.putBytes(l,"utf16")},i.DataBuffer.prototype.putInt16=function(l){return this.accommodate(2),this.data.setInt16(this.write,l),this.write+=2,this},i.DataBuffer.prototype.putInt24=function(l){return this.accommodate(3),this.data.setInt16(this.write,l>>8&65535),this.data.setInt8(this.write,l>>16&255),this.write+=3,this},i.DataBuffer.prototype.putInt32=function(l){return this.accommodate(4),this.data.setInt32(this.write,l),this.write+=4,this},i.DataBuffer.prototype.putInt16Le=function(l){return this.accommodate(2),this.data.setInt16(this.write,l,!0),this.write+=2,this},i.DataBuffer.prototype.putInt24Le=function(l){return this.accommodate(3),this.data.setInt8(this.write,l>>16&255),this.data.setInt16(this.write,l>>8&65535,!0),this.write+=3,this},i.DataBuffer.prototype.putInt32Le=function(l){return this.accommodate(4),this.data.setInt32(this.write,l,!0),this.write+=4,this},i.DataBuffer.prototype.putInt=function(l,S){c(S),this.accommodate(S/8);do S-=8,this.data.setInt8(this.write++,l>>S&255);while(S>0);return this},i.DataBuffer.prototype.putSignedInt=function(l,S){if(c(S),this.accommodate(S/8),l<0)l+=2<<S-1;return this.putInt(l,S)},i.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)},i.DataBuffer.prototype.getInt16=function(){var l=this.data.getInt16(this.read);return this.read+=2,l},i.DataBuffer.prototype.getInt24=function(){var l=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,l},i.DataBuffer.prototype.getInt32=function(){var l=this.data.getInt32(this.read);return this.read+=4,l},i.DataBuffer.prototype.getInt16Le=function(){var l=this.data.getInt16(this.read,!0);return this.read+=2,l},i.DataBuffer.prototype.getInt24Le=function(){var l=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,l},i.DataBuffer.prototype.getInt32Le=function(){var l=this.data.getInt32(this.read,!0);return this.read+=4,l},i.DataBuffer.prototype.getInt=function(l){c(l);var S=0;do S=(S<<8)+this.data.getInt8(this.read++),l-=8;while(l>0);return S},i.DataBuffer.prototype.getSignedInt=function(l){var S=this.getInt(l),I=2<<l-2;if(S>=I)S-=I<<1;return S},i.DataBuffer.prototype.getBytes=function(l){var S;if(l)l=Math.min(this.length(),l),S=this.data.slice(this.read,this.read+l),this.read+=l;else if(l===0)S="";else S=this.read===0?this.data:this.data.slice(this.read),this.clear();return S},i.DataBuffer.prototype.bytes=function(l){return typeof l>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+l)},i.DataBuffer.prototype.at=function(l){return this.data.getUint8(this.read+l)},i.DataBuffer.prototype.setAt=function(l,S){return this.data.setUint8(l,S),this},i.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},i.DataBuffer.prototype.copy=function(){return new i.DataBuffer(this)},i.DataBuffer.prototype.compact=function(){if(this.read>0){var l=new Uint8Array(this.data.buffer,this.read),S=new Uint8Array(l.byteLength);S.set(l),this.data=new DataView(S),this.write-=this.read,this.read=0}return this},i.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},i.DataBuffer.prototype.truncate=function(l){return this.write=Math.max(0,this.length()-l),this.read=Math.min(this.read,this.write),this},i.DataBuffer.prototype.toHex=function(){var l="";for(var S=this.read;S<this.data.byteLength;++S){var I=this.data.getUint8(S);if(I<16)l+="0";l+=I.toString(16)}return l},i.DataBuffer.prototype.toString=function(l){var S=new Uint8Array(this.data,this.read,this.length());if(l=l||"utf8",l==="binary"||l==="raw")return i.binary.raw.encode(S);if(l==="hex")return i.binary.hex.encode(S);if(l==="base64")return i.binary.base64.encode(S);if(l==="utf8")return i.text.utf8.decode(S);if(l==="utf16")return i.text.utf16.decode(S);throw Error("Invalid encoding: "+l)},i.createBuffer=function(l,S){if(S=S||"raw",l!==void 0&&S==="utf8")l=i.encodeUtf8(l);return new i.ByteBuffer(l)},i.fillString=function(l,S){var I="";while(S>0){if(S&1)I+=l;if(S>>>=1,S>0)l+=l}return I},i.xorBytes=function(l,S,I){var N="",L="",v="",h=0,u=0;for(;I>0;--I,++h){if(L=l.charCodeAt(h)^S.charCodeAt(h),u>=10)N+=v,v="",u=0;v+=String.fromCharCode(L),++u}return N+=v,N},i.hexToBytes=function(l){var S="",I=0;if(l.length&!0)I=1,S+=String.fromCharCode(parseInt(l[0],16));for(;I<l.length;I+=2)S+=String.fromCharCode(parseInt(l.substr(I,2),16));return S},i.bytesToHex=function(l){return i.createBuffer(l).toHex()},i.int32ToBytes=function(l){return String.fromCharCode(l>>24&255)+String.fromCharCode(l>>16&255)+String.fromCharCode(l>>8&255)+String.fromCharCode(l&255)};var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",C=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],p="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";i.encode64=function(l,S){var I="",N="",L,v,h,u=0;while(u<l.length){if(L=l.charCodeAt(u++),v=l.charCodeAt(u++),h=l.charCodeAt(u++),I+=a.charAt(L>>2),I+=a.charAt((L&3)<<4|v>>4),isNaN(v))I+="==";else I+=a.charAt((v&15)<<2|h>>6),I+=isNaN(h)?"=":a.charAt(h&63);if(S&&I.length>S)N+=I.substr(0,S)+`\r
|
|
42
|
+
`,I=I.substr(S)}return N+=I,N},i.decode64=function(l){l=l.replace(/[^A-Za-z0-9\+\/\=]/g,"");var S="",I,N,L,v,h=0;while(h<l.length)if(I=C[l.charCodeAt(h++)-43],N=C[l.charCodeAt(h++)-43],L=C[l.charCodeAt(h++)-43],v=C[l.charCodeAt(h++)-43],S+=String.fromCharCode(I<<2|N>>4),L!==64){if(S+=String.fromCharCode((N&15)<<4|L>>2),v!==64)S+=String.fromCharCode((L&3)<<6|v)}return S},i.encodeUtf8=function(l){return unescape(encodeURIComponent(l))},i.decodeUtf8=function(l){return decodeURIComponent(escape(l))},i.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:t.encode,decode:t.decode}},i.binary.raw.encode=function(l){return String.fromCharCode.apply(null,l)},i.binary.raw.decode=function(l,S,I){var N=S;if(!N)N=new Uint8Array(l.length);I=I||0;var L=I;for(var v=0;v<l.length;++v)N[L++]=l.charCodeAt(v);return S?L-I:N},i.binary.hex.encode=i.bytesToHex,i.binary.hex.decode=function(l,S,I){var N=S;if(!N)N=new Uint8Array(Math.ceil(l.length/2));I=I||0;var L=0,v=I;if(l.length&1)L=1,N[v++]=parseInt(l[0],16);for(;L<l.length;L+=2)N[v++]=parseInt(l.substr(L,2),16);return S?v-I:N},i.binary.base64.encode=function(l,S){var I="",N="",L,v,h,u=0;while(u<l.byteLength){if(L=l[u++],v=l[u++],h=l[u++],I+=a.charAt(L>>2),I+=a.charAt((L&3)<<4|v>>4),isNaN(v))I+="==";else I+=a.charAt((v&15)<<2|h>>6),I+=isNaN(h)?"=":a.charAt(h&63);if(S&&I.length>S)N+=I.substr(0,S)+`\r
|
|
43
|
+
`,I=I.substr(S)}return N+=I,N},i.binary.base64.decode=function(l,S,I){var N=S;if(!N)N=new Uint8Array(Math.ceil(l.length/4)*3);l=l.replace(/[^A-Za-z0-9\+\/\=]/g,""),I=I||0;var L,v,h,u,R=0,V=I;while(R<l.length)if(L=C[l.charCodeAt(R++)-43],v=C[l.charCodeAt(R++)-43],h=C[l.charCodeAt(R++)-43],u=C[l.charCodeAt(R++)-43],N[V++]=L<<2|v>>4,h!==64){if(N[V++]=(v&15)<<4|h>>2,u!==64)N[V++]=(h&3)<<6|u}return S?V-I:N.subarray(0,V)},i.binary.base58.encode=function(l,S){return i.binary.baseN.encode(l,p,S)},i.binary.base58.decode=function(l,S){return i.binary.baseN.decode(l,p,S)},i.text={utf8:{},utf16:{}},i.text.utf8.encode=function(l,S,I){l=i.encodeUtf8(l);var N=S;if(!N)N=new Uint8Array(l.length);I=I||0;var L=I;for(var v=0;v<l.length;++v)N[L++]=l.charCodeAt(v);return S?L-I:N},i.text.utf8.decode=function(l){return i.decodeUtf8(String.fromCharCode.apply(null,l))},i.text.utf16.encode=function(l,S,I){var N=S;if(!N)N=new Uint8Array(l.length*2);var L=new Uint16Array(N.buffer);I=I||0;var v=I,h=I;for(var u=0;u<l.length;++u)L[h++]=l.charCodeAt(u),v+=2;return S?v-I:N},i.text.utf16.decode=function(l){return String.fromCharCode.apply(null,new Uint16Array(l.buffer))},i.deflate=function(l,S,I){if(S=i.decode64(l.deflate(i.encode64(S)).rval),I){var N=2,L=S.charCodeAt(1);if(L&32)N=6;S=S.substring(N,S.length-4)}return S},i.inflate=function(l,S,I){var N=l.inflate(i.encode64(S)).rval;return N===null?null:i.decode64(N)};var m=function(l,S,I){if(!l)throw Error("WebStorage not available.");var N;if(I===null)N=l.removeItem(S);else I=i.encode64(JSON.stringify(I)),N=l.setItem(S,I);if(typeof N<"u"&&N.rval!==!0){var L=Error(N.error.message);throw L.id=N.error.id,L.name=N.error.name,L}},w=function(l,S){if(!l)throw Error("WebStorage not available.");var I=l.getItem(S);if(l.init)if(I.rval===null){if(I.error){var N=Error(I.error.message);throw N.id=I.error.id,N.name=I.error.name,N}I=null}else I=I.rval;if(I!==null)I=JSON.parse(i.decode64(I));return I},B=function(l,S,I,N){var L=w(l,S);if(L===null)L={};L[I]=N,m(l,S,L)},d=function(l,S,I){var N=w(l,S);if(N!==null)N=I in N?N[I]:null;return N},T=function(l,S,I){var N=w(l,S);if(N!==null&&I in N){delete N[I];var L=!0;for(var v in N){L=!1;break}if(L)N=null;m(l,S,N)}},A=function(l,S){m(l,S,null)},g=function(l,S,I){var N=null;if(typeof I>"u")I=["web","flash"];var L,v=!1,h=null;for(var u in I){L=I[u];try{if(L==="flash"||L==="both"){if(S[0]===null)throw Error("Flash local storage not available.");N=l.apply(this,S),v=L==="flash"}if(L==="web"||L==="both")S[0]=localStorage,N=l.apply(this,S),v=!0}catch(R){h=R}if(v)break}if(!v)throw h;return N};i.setItem=function(l,S,I,N,L){g(B,arguments,L)},i.getItem=function(l,S,I,N){return g(d,arguments,N)},i.removeItem=function(l,S,I,N){g(T,arguments,N)},i.clearItems=function(l,S,I){g(A,arguments,I)},i.isEmpty=function(l){for(var S in l)if(l.hasOwnProperty(S))return!1;return!0},i.format=function(l){var S=/%./g,I,N,L=0,v=[],h=0;while(I=S.exec(l)){if(N=l.substring(h,S.lastIndex-2),N.length>0)v.push(N);h=S.lastIndex;var u=I[0][1];switch(u){case"s":case"o":if(L<arguments.length)v.push(arguments[L+++1]);else v.push("<?>");break;case"%":v.push("%");break;default:v.push("<%"+u+"?>")}}return v.push(l.substring(h)),v.join("")},i.formatNumber=function(l,S,I,N){var L=l,v=isNaN(S=Math.abs(S))?2:S,h=I===void 0?",":I,u=N===void 0?".":N,R=L<0?"-":"",V=parseInt(L=Math.abs(+L||0).toFixed(v),10)+"",O=V.length>3?V.length%3:0;return R+(O?V.substr(0,O)+u:"")+V.substr(O).replace(/(\d{3})(?=\d)/g,"$1"+u)+(v?h+Math.abs(L-V).toFixed(v).slice(2):"")},i.formatSize=function(l){if(l>=1073741824)l=i.formatNumber(l/1073741824,2,".","")+" GiB";else if(l>=1048576)l=i.formatNumber(l/1048576,2,".","")+" MiB";else if(l>=1024)l=i.formatNumber(l/1024,0)+" KiB";else l=i.formatNumber(l,0)+" bytes";return l},i.bytesFromIP=function(l){if(l.indexOf(".")!==-1)return i.bytesFromIPv4(l);if(l.indexOf(":")!==-1)return i.bytesFromIPv6(l);return null},i.bytesFromIPv4=function(l){if(l=l.split("."),l.length!==4)return null;var S=i.createBuffer();for(var I=0;I<l.length;++I){var N=parseInt(l[I],10);if(isNaN(N))return null;S.putByte(N)}return S.getBytes()},i.bytesFromIPv6=function(l){var S=0;l=l.split(":").filter(function(h){if(h.length===0)++S;return!0});var I=(8-l.length+S)*2,N=i.createBuffer();for(var L=0;L<8;++L){if(!l[L]||l[L].length===0){N.fillWithByte(0,I),I=0;continue}var v=i.hexToBytes(l[L]);if(v.length<2)N.putByte(0);N.putBytes(v)}return N.getBytes()},i.bytesToIP=function(l){if(l.length===4)return i.bytesToIPv4(l);if(l.length===16)return i.bytesToIPv6(l);return null},i.bytesToIPv4=function(l){if(l.length!==4)return null;var S=[];for(var I=0;I<l.length;++I)S.push(l.charCodeAt(I));return S.join(".")},i.bytesToIPv6=function(l){if(l.length!==16)return null;var S=[],I=[],N=0;for(var L=0;L<l.length;L+=2){var v=i.bytesToHex(l[L]+l[L+1]);while(v[0]==="0"&&v!=="0")v=v.substr(1);if(v==="0"){var h=I[I.length-1],u=S.length;if(!h||u!==h.end+1)I.push({start:u,end:u});else if(h.end=u,h.end-h.start>I[N].end-I[N].start)N=I.length-1}S.push(v)}if(I.length>0){var R=I[N];if(R.end-R.start>0){if(S.splice(R.start,R.end-R.start+1,""),R.start===0)S.unshift("");if(R.end===7)S.push("")}}return S.join(":")},i.estimateCores=function(l,S){if(typeof l==="function")S=l,l={};if(l=l||{},"cores"in i&&!l.update)return S(null,i.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return i.cores=navigator.hardwareConcurrency,S(null,i.cores);if(typeof Worker>"u")return i.cores=1,S(null,i.cores);if(typeof Blob>"u")return i.cores=2,S(null,i.cores);var I=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(h){var u=Date.now(),R=u+4;while(Date.now()<R);self.postMessage({st:u,et:R})})}.toString(),")()"],{type:"application/javascript"}));N([],5,16);function N(h,u,R){if(u===0){var V=Math.floor(h.reduce(function(O,K){return O+K},0)/h.length);return i.cores=Math.max(1,V),URL.revokeObjectURL(I),S(null,i.cores)}L(R,function(O,K){h.push(v(R,K)),N(h,u-1,R)})}function L(h,u){var R=[],V=[];for(var O=0;O<h;++O){var K=new Worker(I);K.addEventListener("message",function(G){if(V.push(G.data),V.length===h){for(var H=0;H<h;++H)R[H].terminate();u(null,V)}}),R.push(K)}for(var O=0;O<h;++O)R[O].postMessage(O)}function v(h,u){var R=[];for(var V=0;V<h;++V){var O=u[V],K=R[V]=[];for(var G=0;G<h;++G){if(V===G)continue;var H=u[G];if(O.st>H.st&&O.st<H.et||H.st>O.st&&H.st<O.et)K.push(G)}}return R.reduce(function(j,z){return Math.max(j,z.length)},0)}}}),Oi=lt((r,n)=>{var e=pt();Tt(),n.exports=e.cipher=e.cipher||{},e.cipher.algorithms=e.cipher.algorithms||{},e.cipher.createCipher=function(i,c){var f=i;if(typeof f==="string"){if(f=e.cipher.getAlgorithm(f),f)f=f()}if(!f)throw Error("Unsupported algorithm: "+i);return new e.cipher.BlockCipher({algorithm:f,key:c,decrypt:!1})},e.cipher.createDecipher=function(i,c){var f=i;if(typeof f==="string"){if(f=e.cipher.getAlgorithm(f),f)f=f()}if(!f)throw Error("Unsupported algorithm: "+i);return new e.cipher.BlockCipher({algorithm:f,key:c,decrypt:!0})},e.cipher.registerAlgorithm=function(i,c){i=i.toUpperCase(),e.cipher.algorithms[i]=c},e.cipher.getAlgorithm=function(i){if(i=i.toUpperCase(),i in e.cipher.algorithms)return e.cipher.algorithms[i];return null};var t=e.cipher.BlockCipher=function(i){this.algorithm=i.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=i.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=i.decrypt,this.algorithm.initialize(i)};t.prototype.start=function(i){i=i||{};var c={};for(var f in i)c[f]=i[f];c.decrypt=this._decrypt,this._finish=!1,this._input=e.util.createBuffer(),this.output=i.output||e.util.createBuffer(),this.mode.start(c)},t.prototype.update=function(i){if(i)this._input.putBuffer(i);while(!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish);this._input.compact()},t.prototype.finish=function(i){if(i&&(this.mode.name==="ECB"||this.mode.name==="CBC"))this.mode.pad=function(f){return i(this.blockSize,f,!1)},this.mode.unpad=function(f){return i(this.blockSize,f,!0)};var c={};if(c.decrypt=this._decrypt,c.overflow=this._input.length()%this.blockSize,!this._decrypt&&this.mode.pad){if(!this.mode.pad(this._input,c))return!1}if(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad){if(!this.mode.unpad(this.output,c))return!1}if(this.mode.afterFinish){if(!this.mode.afterFinish(this.output,c))return!1}return!0}}),ea=lt((r,n)=>{var e=pt();Tt(),e.cipher=e.cipher||{};var t=n.exports=e.cipher.modes=e.cipher.modes||{};t.ecb=function(o){o=o||{},this.name="ECB",this.cipher=o.cipher,this.blockSize=o.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints)},t.ecb.prototype.start=function(o){},t.ecb.prototype.encrypt=function(o,s,a){if(o.length()<this.blockSize&&!(a&&o.length()>0))return!0;for(var C=0;C<this._ints;++C)this._inBlock[C]=o.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var C=0;C<this._ints;++C)s.putInt32(this._outBlock[C])},t.ecb.prototype.decrypt=function(o,s,a){if(o.length()<this.blockSize&&!(a&&o.length()>0))return!0;for(var C=0;C<this._ints;++C)this._inBlock[C]=o.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var C=0;C<this._ints;++C)s.putInt32(this._outBlock[C])},t.ecb.prototype.pad=function(o,s){var a=o.length()===this.blockSize?this.blockSize:this.blockSize-o.length();return o.fillWithByte(a,a),!0},t.ecb.prototype.unpad=function(o,s){if(s.overflow>0)return!1;var a=o.length(),C=o.at(a-1);if(C>this.blockSize<<2)return!1;return o.truncate(C),!0},t.cbc=function(o){o=o||{},this.name="CBC",this.cipher=o.cipher,this.blockSize=o.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints)},t.cbc.prototype.start=function(o){if(o.iv===null){if(!this._prev)throw Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if(!("iv"in o))throw Error("Invalid IV parameter.");else this._iv=i(o.iv,this.blockSize),this._prev=this._iv.slice(0)},t.cbc.prototype.encrypt=function(o,s,a){if(o.length()<this.blockSize&&!(a&&o.length()>0))return!0;for(var C=0;C<this._ints;++C)this._inBlock[C]=this._prev[C]^o.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var C=0;C<this._ints;++C)s.putInt32(this._outBlock[C]);this._prev=this._outBlock},t.cbc.prototype.decrypt=function(o,s,a){if(o.length()<this.blockSize&&!(a&&o.length()>0))return!0;for(var C=0;C<this._ints;++C)this._inBlock[C]=o.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var C=0;C<this._ints;++C)s.putInt32(this._prev[C]^this._outBlock[C]);this._prev=this._inBlock.slice(0)},t.cbc.prototype.pad=function(o,s){var a=o.length()===this.blockSize?this.blockSize:this.blockSize-o.length();return o.fillWithByte(a,a),!0},t.cbc.prototype.unpad=function(o,s){if(s.overflow>0)return!1;var a=o.length(),C=o.at(a-1);if(C>this.blockSize<<2)return!1;return o.truncate(C),!0},t.cfb=function(o){o=o||{},this.name="CFB",this.cipher=o.cipher,this.blockSize=o.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialBlock=Array(this._ints),this._partialOutput=e.util.createBuffer(),this._partialBytes=0},t.cfb.prototype.start=function(o){if(!("iv"in o))throw Error("Invalid IV parameter.");this._iv=i(o.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},t.cfb.prototype.encrypt=function(o,s,a){var C=o.length();if(C===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&C>=this.blockSize){for(var p=0;p<this._ints;++p)this._inBlock[p]=o.getInt32()^this._outBlock[p],s.putInt32(this._inBlock[p]);return}var m=(this.blockSize-C)%this.blockSize;if(m>0)m=this.blockSize-m;this._partialOutput.clear();for(var p=0;p<this._ints;++p)this._partialBlock[p]=o.getInt32()^this._outBlock[p],this._partialOutput.putInt32(this._partialBlock[p]);if(m>0)o.read-=this.blockSize;else for(var p=0;p<this._ints;++p)this._inBlock[p]=this._partialBlock[p];if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(m>0&&!a)return s.putBytes(this._partialOutput.getBytes(m-this._partialBytes)),this._partialBytes=m,!0;s.putBytes(this._partialOutput.getBytes(C-this._partialBytes)),this._partialBytes=0},t.cfb.prototype.decrypt=function(o,s,a){var C=o.length();if(C===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&C>=this.blockSize){for(var p=0;p<this._ints;++p)this._inBlock[p]=o.getInt32(),s.putInt32(this._inBlock[p]^this._outBlock[p]);return}var m=(this.blockSize-C)%this.blockSize;if(m>0)m=this.blockSize-m;this._partialOutput.clear();for(var p=0;p<this._ints;++p)this._partialBlock[p]=o.getInt32(),this._partialOutput.putInt32(this._partialBlock[p]^this._outBlock[p]);if(m>0)o.read-=this.blockSize;else for(var p=0;p<this._ints;++p)this._inBlock[p]=this._partialBlock[p];if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(m>0&&!a)return s.putBytes(this._partialOutput.getBytes(m-this._partialBytes)),this._partialBytes=m,!0;s.putBytes(this._partialOutput.getBytes(C-this._partialBytes)),this._partialBytes=0},t.ofb=function(o){o=o||{},this.name="OFB",this.cipher=o.cipher,this.blockSize=o.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=e.util.createBuffer(),this._partialBytes=0},t.ofb.prototype.start=function(o){if(!("iv"in o))throw Error("Invalid IV parameter.");this._iv=i(o.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},t.ofb.prototype.encrypt=function(o,s,a){var C=o.length();if(o.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&C>=this.blockSize){for(var p=0;p<this._ints;++p)s.putInt32(o.getInt32()^this._outBlock[p]),this._inBlock[p]=this._outBlock[p];return}var m=(this.blockSize-C)%this.blockSize;if(m>0)m=this.blockSize-m;this._partialOutput.clear();for(var p=0;p<this._ints;++p)this._partialOutput.putInt32(o.getInt32()^this._outBlock[p]);if(m>0)o.read-=this.blockSize;else for(var p=0;p<this._ints;++p)this._inBlock[p]=this._outBlock[p];if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(m>0&&!a)return s.putBytes(this._partialOutput.getBytes(m-this._partialBytes)),this._partialBytes=m,!0;s.putBytes(this._partialOutput.getBytes(C-this._partialBytes)),this._partialBytes=0},t.ofb.prototype.decrypt=t.ofb.prototype.encrypt,t.ctr=function(o){o=o||{},this.name="CTR",this.cipher=o.cipher,this.blockSize=o.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=e.util.createBuffer(),this._partialBytes=0},t.ctr.prototype.start=function(o){if(!("iv"in o))throw Error("Invalid IV parameter.");this._iv=i(o.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},t.ctr.prototype.encrypt=function(o,s,a){var C=o.length();if(C===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&C>=this.blockSize)for(var p=0;p<this._ints;++p)s.putInt32(o.getInt32()^this._outBlock[p]);else{var m=(this.blockSize-C)%this.blockSize;if(m>0)m=this.blockSize-m;this._partialOutput.clear();for(var p=0;p<this._ints;++p)this._partialOutput.putInt32(o.getInt32()^this._outBlock[p]);if(m>0)o.read-=this.blockSize;if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(m>0&&!a)return s.putBytes(this._partialOutput.getBytes(m-this._partialBytes)),this._partialBytes=m,!0;s.putBytes(this._partialOutput.getBytes(C-this._partialBytes)),this._partialBytes=0}c(this._inBlock)},t.ctr.prototype.decrypt=t.ctr.prototype.encrypt,t.gcm=function(o){o=o||{},this.name="GCM",this.cipher=o.cipher,this.blockSize=o.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints),this._partialOutput=e.util.createBuffer(),this._partialBytes=0,this._R=3774873600},t.gcm.prototype.start=function(o){if(!("iv"in o))throw Error("Invalid IV parameter.");var s=e.util.createBuffer(o.iv);this._cipherLength=0;var a;if("additionalData"in o)a=e.util.createBuffer(o.additionalData);else a=e.util.createBuffer();if("tagLength"in o)this._tagLength=o.tagLength;else this._tagLength=128;if(this._tag=null,o.decrypt){if(this._tag=e.util.createBuffer(o.tag).getBytes(),this._tag.length!==this._tagLength/8)throw Error("Authentication tag does not match tag length.")}this._hashBlock=Array(this._ints),this.tag=null,this._hashSubkey=Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var C=s.length();if(C===12)this._j0=[s.getInt32(),s.getInt32(),s.getInt32(),1];else{this._j0=[0,0,0,0];while(s.length()>0)this._j0=this.ghash(this._hashSubkey,this._j0,[s.getInt32(),s.getInt32(),s.getInt32(),s.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(f(C*8)))}this._inBlock=this._j0.slice(0),c(this._inBlock),this._partialBytes=0,a=e.util.createBuffer(a),this._aDataLength=f(a.length()*8);var p=a.length()%this.blockSize;if(p)a.fillWithByte(0,this.blockSize-p);this._s=[0,0,0,0];while(a.length()>0)this._s=this.ghash(this._hashSubkey,this._s,[a.getInt32(),a.getInt32(),a.getInt32(),a.getInt32()])},t.gcm.prototype.encrypt=function(o,s,a){var C=o.length();if(C===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&C>=this.blockSize){for(var p=0;p<this._ints;++p)s.putInt32(this._outBlock[p]^=o.getInt32());this._cipherLength+=this.blockSize}else{var m=(this.blockSize-C)%this.blockSize;if(m>0)m=this.blockSize-m;this._partialOutput.clear();for(var p=0;p<this._ints;++p)this._partialOutput.putInt32(o.getInt32()^this._outBlock[p]);if(m<=0||a){if(a){var w=C%this.blockSize;this._cipherLength+=w,this._partialOutput.truncate(this.blockSize-w)}else this._cipherLength+=this.blockSize;for(var p=0;p<this._ints;++p)this._outBlock[p]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(m>0&&!a)return o.read-=this.blockSize,s.putBytes(this._partialOutput.getBytes(m-this._partialBytes)),this._partialBytes=m,!0;s.putBytes(this._partialOutput.getBytes(C-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),c(this._inBlock)},t.gcm.prototype.decrypt=function(o,s,a){var C=o.length();if(C<this.blockSize&&!(a&&C>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),c(this._inBlock),this._hashBlock[0]=o.getInt32(),this._hashBlock[1]=o.getInt32(),this._hashBlock[2]=o.getInt32(),this._hashBlock[3]=o.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var p=0;p<this._ints;++p)s.putInt32(this._outBlock[p]^this._hashBlock[p]);if(C<this.blockSize)this._cipherLength+=C%this.blockSize;else this._cipherLength+=this.blockSize},t.gcm.prototype.afterFinish=function(o,s){var a=!0;if(s.decrypt&&s.overflow)o.truncate(this.blockSize-s.overflow);this.tag=e.util.createBuffer();var C=this._aDataLength.concat(f(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,C);var p=[];this.cipher.encrypt(this._j0,p);for(var m=0;m<this._ints;++m)this.tag.putInt32(this._s[m]^p[m]);if(this.tag.truncate(this.tag.length()%(this._tagLength/8)),s.decrypt&&this.tag.bytes()!==this._tag)a=!1;return a},t.gcm.prototype.multiply=function(o,s){var a=[0,0,0,0],C=s.slice(0);for(var p=0;p<128;++p){var m=o[p/32|0]&1<<31-p%32;if(m)a[0]^=C[0],a[1]^=C[1],a[2]^=C[2],a[3]^=C[3];this.pow(C,C)}return a},t.gcm.prototype.pow=function(o,s){var a=o[3]&1;for(var C=3;C>0;--C)s[C]=o[C]>>>1|(o[C-1]&1)<<31;if(s[0]=o[0]>>>1,a)s[0]^=this._R},t.gcm.prototype.tableMultiply=function(o){var s=[0,0,0,0];for(var a=0;a<32;++a){var C=a/8|0,p=o[C]>>>(7-a%8)*4&15,m=this._m[a][p];s[0]^=m[0],s[1]^=m[1],s[2]^=m[2],s[3]^=m[3]}return s},t.gcm.prototype.ghash=function(o,s,a){return s[0]^=a[0],s[1]^=a[1],s[2]^=a[2],s[3]^=a[3],this.tableMultiply(s)},t.gcm.prototype.generateHashTable=function(o,s){var a=8/s,C=4*a,p=16*a,m=Array(p);for(var w=0;w<p;++w){var B=[0,0,0,0],d=w/C|0,T=(C-1-w%C)*s;B[d]=1<<s-1<<T,m[w]=this.generateSubHashTable(this.multiply(B,o),s)}return m},t.gcm.prototype.generateSubHashTable=function(o,s){var a=1<<s,C=a>>>1,p=Array(a);p[C]=o.slice(0);var m=C>>>1;while(m>0)this.pow(p[2*m],p[m]=[]),m>>=1;m=2;while(m<C){for(var w=1;w<m;++w){var B=p[m],d=p[w];p[m+w]=[B[0]^d[0],B[1]^d[1],B[2]^d[2],B[3]^d[3]]}m*=2}p[0]=[0,0,0,0];for(m=C+1;m<a;++m){var T=p[m^C];p[m]=[o[0]^T[0],o[1]^T[1],o[2]^T[2],o[3]^T[3]]}return p};function i(o,s){if(typeof o==="string")o=e.util.createBuffer(o);if(e.util.isArray(o)&&o.length>4){var a=o;o=e.util.createBuffer();for(var C=0;C<a.length;++C)o.putByte(a[C])}if(o.length()<s)throw Error("Invalid IV length; got "+o.length()+" bytes and expected "+s+" bytes.");if(!e.util.isArray(o)){var p=[],m=s/4;for(var C=0;C<m;++C)p.push(o.getInt32());o=p}return o}function c(o){o[o.length-1]=o[o.length-1]+1&4294967295}function f(o){return[o/4294967296|0,o&4294967295]}}),ze=lt((r,n)=>{var e=pt();Oi(),ea(),Tt(),n.exports=e.aes=e.aes||{},e.aes.startEncrypting=function(d,T,A,g){var l=B({key:d,output:A,decrypt:!1,mode:g});return l.start(T),l},e.aes.createEncryptionCipher=function(d,T){return B({key:d,output:null,decrypt:!1,mode:T})},e.aes.startDecrypting=function(d,T,A,g){var l=B({key:d,output:A,decrypt:!0,mode:g});return l.start(T),l},e.aes.createDecryptionCipher=function(d,T){return B({key:d,output:null,decrypt:!0,mode:T})},e.aes.Algorithm=function(d,T){if(!i)p();var A=this;A.name=d,A.mode=new T({blockSize:16,cipher:{encrypt:function(g,l){return w(A._w,g,l,!1)},decrypt:function(g,l){return w(A._w,g,l,!0)}}}),A._init=!1},e.aes.Algorithm.prototype.initialize=function(d){if(this._init)return;var T=d.key,A;if(typeof T==="string"&&(T.length===16||T.length===24||T.length===32))T=e.util.createBuffer(T);else if(e.util.isArray(T)&&(T.length===16||T.length===24||T.length===32)){A=T,T=e.util.createBuffer();for(var g=0;g<A.length;++g)T.putByte(A[g])}if(!e.util.isArray(T)){A=T,T=[];var l=A.length();if(l===16||l===24||l===32){l=l>>>2;for(var g=0;g<l;++g)T.push(A.getInt32())}}if(!e.util.isArray(T)||!(T.length===4||T.length===6||T.length===8))throw Error("Invalid key parameter.");var S=this.mode.name,I=["CFB","OFB","CTR","GCM"].indexOf(S)!==-1;this._w=m(T,d.decrypt&&!I),this._init=!0},e.aes._expandKey=function(d,T){if(!i)p();return m(d,T)},e.aes._updateBlock=w,t("AES-ECB",e.cipher.modes.ecb),t("AES-CBC",e.cipher.modes.cbc),t("AES-CFB",e.cipher.modes.cfb),t("AES-OFB",e.cipher.modes.ofb),t("AES-CTR",e.cipher.modes.ctr),t("AES-GCM",e.cipher.modes.gcm);function t(d,T){var A=function(){return new e.aes.Algorithm(d,T)};e.cipher.registerAlgorithm(d,A)}var i=!1,c=4,f,o,s,a,C;function p(){i=!0,s=[0,1,2,4,8,16,32,64,128,27,54];var d=Array(256);for(var T=0;T<128;++T)d[T]=T<<1,d[T+128]=T+128<<1^283;f=Array(256),o=Array(256),a=[,,,,],C=[,,,,];for(var T=0;T<4;++T)a[T]=Array(256),C[T]=Array(256);var A=0,g=0,l,S,I,N,L,v,h;for(var T=0;T<256;++T){N=g^g<<1^g<<2^g<<3^g<<4,N=N>>8^N&255^99,f[A]=N,o[N]=A,L=d[N],l=d[A],S=d[l],I=d[S],v=L<<24^N<<16^N<<8^(N^L),h=(l^S^I)<<24^(A^I)<<16^(A^S^I)<<8^(A^l^I);for(var u=0;u<4;++u)a[u][A]=v,C[u][N]=h,v=v<<24|v>>>8,h=h<<24|h>>>8;if(A===0)A=g=1;else A=l^d[d[d[l^I]]],g^=d[d[g]]}}function m(d,T){var A=d.slice(0),g,l=1,S=A.length,I=S+6+1,N=c*I;for(var L=S;L<N;++L){if(g=A[L-1],L%S===0)g=f[g>>>16&255]<<24^f[g>>>8&255]<<16^f[g&255]<<8^f[g>>>24]^s[l]<<24,l++;else if(S>6&&L%S===4)g=f[g>>>24]<<24^f[g>>>16&255]<<16^f[g>>>8&255]<<8^f[g&255];A[L]=A[L-S]^g}if(T){var v,h=C[0],u=C[1],R=C[2],V=C[3],O=A.slice(0);N=A.length;for(var L=0,K=N-c;L<N;L+=c,K-=c)if(L===0||L===N-c)O[L]=A[K],O[L+1]=A[K+3],O[L+2]=A[K+2],O[L+3]=A[K+1];else for(var G=0;G<c;++G)v=A[K+G],O[L+(3&-G)]=h[f[v>>>24]]^u[f[v>>>16&255]]^R[f[v>>>8&255]]^V[f[v&255]];A=O}return A}function w(d,T,A,g){var l=d.length/4-1,S,I,N,L,v;if(g)S=C[0],I=C[1],N=C[2],L=C[3],v=o;else S=a[0],I=a[1],N=a[2],L=a[3],v=f;var h,u,R,V,O,K,G;h=T[0]^d[0],u=T[g?3:1]^d[1],R=T[2]^d[2],V=T[g?1:3]^d[3];var H=3;for(var j=1;j<l;++j)O=S[h>>>24]^I[u>>>16&255]^N[R>>>8&255]^L[V&255]^d[++H],K=S[u>>>24]^I[R>>>16&255]^N[V>>>8&255]^L[h&255]^d[++H],G=S[R>>>24]^I[V>>>16&255]^N[h>>>8&255]^L[u&255]^d[++H],V=S[V>>>24]^I[h>>>16&255]^N[u>>>8&255]^L[R&255]^d[++H],h=O,u=K,R=G;A[0]=v[h>>>24]<<24^v[u>>>16&255]<<16^v[R>>>8&255]<<8^v[V&255]^d[++H],A[g?3:1]=v[u>>>24]<<24^v[R>>>16&255]<<16^v[V>>>8&255]<<8^v[h&255]^d[++H],A[2]=v[R>>>24]<<24^v[V>>>16&255]<<16^v[h>>>8&255]<<8^v[u&255]^d[++H],A[g?1:3]=v[V>>>24]<<24^v[h>>>16&255]<<16^v[u>>>8&255]<<8^v[R&255]^d[++H]}function B(d){d=d||{};var T=(d.mode||"CBC").toUpperCase(),A="AES-"+T,g;if(d.decrypt)g=e.cipher.createDecipher(A,d.key);else g=e.cipher.createCipher(A,d.key);var l=g.start;return g.start=function(S,I){var N=null;if(I instanceof e.util.ByteBuffer)N=I,I={};I=I||{},I.output=N,I.iv=S,l.call(g,I)},g}}),Pe=lt((r,n)=>{var e=pt();e.pki=e.pki||{};var t=n.exports=e.pki.oids=e.oids=e.oids||{};function i(f,o){t[f]=o,t[o]=f}function c(f,o){t[f]=o}i("1.2.840.113549.1.1.1","rsaEncryption"),i("1.2.840.113549.1.1.4","md5WithRSAEncryption"),i("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),i("1.2.840.113549.1.1.7","RSAES-OAEP"),i("1.2.840.113549.1.1.8","mgf1"),i("1.2.840.113549.1.1.9","pSpecified"),i("1.2.840.113549.1.1.10","RSASSA-PSS"),i("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),i("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),i("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),i("1.3.101.112","EdDSA25519"),i("1.2.840.10040.4.3","dsa-with-sha1"),i("1.3.14.3.2.7","desCBC"),i("1.3.14.3.2.26","sha1"),i("1.3.14.3.2.29","sha1WithRSASignature"),i("2.16.840.1.101.3.4.2.1","sha256"),i("2.16.840.1.101.3.4.2.2","sha384"),i("2.16.840.1.101.3.4.2.3","sha512"),i("2.16.840.1.101.3.4.2.4","sha224"),i("2.16.840.1.101.3.4.2.5","sha512-224"),i("2.16.840.1.101.3.4.2.6","sha512-256"),i("1.2.840.113549.2.2","md2"),i("1.2.840.113549.2.5","md5"),i("1.2.840.113549.1.7.1","data"),i("1.2.840.113549.1.7.2","signedData"),i("1.2.840.113549.1.7.3","envelopedData"),i("1.2.840.113549.1.7.4","signedAndEnvelopedData"),i("1.2.840.113549.1.7.5","digestedData"),i("1.2.840.113549.1.7.6","encryptedData"),i("1.2.840.113549.1.9.1","emailAddress"),i("1.2.840.113549.1.9.2","unstructuredName"),i("1.2.840.113549.1.9.3","contentType"),i("1.2.840.113549.1.9.4","messageDigest"),i("1.2.840.113549.1.9.5","signingTime"),i("1.2.840.113549.1.9.6","counterSignature"),i("1.2.840.113549.1.9.7","challengePassword"),i("1.2.840.113549.1.9.8","unstructuredAddress"),i("1.2.840.113549.1.9.14","extensionRequest"),i("1.2.840.113549.1.9.20","friendlyName"),i("1.2.840.113549.1.9.21","localKeyId"),i("1.2.840.113549.1.9.22.1","x509Certificate"),i("1.2.840.113549.1.12.10.1.1","keyBag"),i("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),i("1.2.840.113549.1.12.10.1.3","certBag"),i("1.2.840.113549.1.12.10.1.4","crlBag"),i("1.2.840.113549.1.12.10.1.5","secretBag"),i("1.2.840.113549.1.12.10.1.6","safeContentsBag"),i("1.2.840.113549.1.5.13","pkcs5PBES2"),i("1.2.840.113549.1.5.12","pkcs5PBKDF2"),i("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),i("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),i("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),i("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),i("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),i("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),i("1.2.840.113549.2.7","hmacWithSHA1"),i("1.2.840.113549.2.8","hmacWithSHA224"),i("1.2.840.113549.2.9","hmacWithSHA256"),i("1.2.840.113549.2.10","hmacWithSHA384"),i("1.2.840.113549.2.11","hmacWithSHA512"),i("1.2.840.113549.3.7","des-EDE3-CBC"),i("2.16.840.1.101.3.4.1.2","aes128-CBC"),i("2.16.840.1.101.3.4.1.22","aes192-CBC"),i("2.16.840.1.101.3.4.1.42","aes256-CBC"),i("2.5.4.3","commonName"),i("2.5.4.4","surname"),i("2.5.4.5","serialNumber"),i("2.5.4.6","countryName"),i("2.5.4.7","localityName"),i("2.5.4.8","stateOrProvinceName"),i("2.5.4.9","streetAddress"),i("2.5.4.10","organizationName"),i("2.5.4.11","organizationalUnitName"),i("2.5.4.12","title"),i("2.5.4.13","description"),i("2.5.4.15","businessCategory"),i("2.5.4.17","postalCode"),i("2.5.4.42","givenName"),i("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),i("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),i("2.16.840.1.113730.1.1","nsCertType"),i("2.16.840.1.113730.1.13","nsComment"),c("2.5.29.1","authorityKeyIdentifier"),c("2.5.29.2","keyAttributes"),c("2.5.29.3","certificatePolicies"),c("2.5.29.4","keyUsageRestriction"),c("2.5.29.5","policyMapping"),c("2.5.29.6","subtreesConstraint"),c("2.5.29.7","subjectAltName"),c("2.5.29.8","issuerAltName"),c("2.5.29.9","subjectDirectoryAttributes"),c("2.5.29.10","basicConstraints"),c("2.5.29.11","nameConstraints"),c("2.5.29.12","policyConstraints"),c("2.5.29.13","basicConstraints"),i("2.5.29.14","subjectKeyIdentifier"),i("2.5.29.15","keyUsage"),c("2.5.29.16","privateKeyUsagePeriod"),i("2.5.29.17","subjectAltName"),i("2.5.29.18","issuerAltName"),i("2.5.29.19","basicConstraints"),c("2.5.29.20","cRLNumber"),c("2.5.29.21","cRLReason"),c("2.5.29.22","expirationDate"),c("2.5.29.23","instructionCode"),c("2.5.29.24","invalidityDate"),c("2.5.29.25","cRLDistributionPoints"),c("2.5.29.26","issuingDistributionPoint"),c("2.5.29.27","deltaCRLIndicator"),c("2.5.29.28","issuingDistributionPoint"),c("2.5.29.29","certificateIssuer"),c("2.5.29.30","nameConstraints"),i("2.5.29.31","cRLDistributionPoints"),i("2.5.29.32","certificatePolicies"),c("2.5.29.33","policyMappings"),c("2.5.29.34","policyConstraints"),i("2.5.29.35","authorityKeyIdentifier"),c("2.5.29.36","policyConstraints"),i("2.5.29.37","extKeyUsage"),c("2.5.29.46","freshestCRL"),c("2.5.29.54","inhibitAnyPolicy"),i("1.3.6.1.4.1.11129.2.4.2","timestampList"),i("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),i("1.3.6.1.5.5.7.3.1","serverAuth"),i("1.3.6.1.5.5.7.3.2","clientAuth"),i("1.3.6.1.5.5.7.3.3","codeSigning"),i("1.3.6.1.5.5.7.3.4","emailProtection"),i("1.3.6.1.5.5.7.3.8","timeStamping")}),Ue=lt((r,n)=>{var e=pt();Tt(),Pe();var t=n.exports=e.asn1=e.asn1||{};t.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},t.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},t.create=function(s,a,C,p,m){if(e.util.isArray(p)){var w=[];for(var B=0;B<p.length;++B)if(p[B]!==void 0)w.push(p[B]);p=w}var d={tagClass:s,type:a,constructed:C,composed:C||e.util.isArray(p),value:p};if(m&&"bitStringContents"in m)d.bitStringContents=m.bitStringContents,d.original=t.copy(d);return d},t.copy=function(s,a){var C;if(e.util.isArray(s)){C=[];for(var p=0;p<s.length;++p)C.push(t.copy(s[p],a));return C}if(typeof s==="string")return s;if(C={tagClass:s.tagClass,type:s.type,constructed:s.constructed,composed:s.composed,value:t.copy(s.value,a)},a&&!a.excludeBitStringContents)C.bitStringContents=s.bitStringContents;return C},t.equals=function(s,a,C){if(e.util.isArray(s)){if(!e.util.isArray(a))return!1;if(s.length!==a.length)return!1;for(var p=0;p<s.length;++p)if(!t.equals(s[p],a[p]))return!1;return!0}if(typeof s!==typeof a)return!1;if(typeof s==="string")return s===a;var m=s.tagClass===a.tagClass&&s.type===a.type&&s.constructed===a.constructed&&s.composed===a.composed&&t.equals(s.value,a.value);if(C&&C.includeBitStringContents)m=m&&s.bitStringContents===a.bitStringContents;return m},t.getBerValueLength=function(s){var a=s.getByte();if(a===128)return;var C,p=a&128;if(!p)C=a;else C=s.getInt((a&127)<<3);return C};function i(s,a,C){if(C>a){var p=Error("Too few bytes to parse DER.");throw p.available=s.length(),p.remaining=a,p.requested=C,p}}var c=function(s,a){var C=s.getByte();if(a--,C===128)return;var p,m=C&128;if(!m)p=C;else{var w=C&127;i(s,a,w),p=s.getInt(w<<3)}if(p<0)throw Error("Negative length: "+p);return p};t.fromDer=function(s,a){if(a===void 0)a={strict:!0,parseAllBytes:!0,decodeBitStrings:!0};if(typeof a==="boolean")a={strict:a,parseAllBytes:!0,decodeBitStrings:!0};if(!("strict"in a))a.strict=!0;if(!("parseAllBytes"in a))a.parseAllBytes=!0;if(!("decodeBitStrings"in a))a.decodeBitStrings=!0;if(typeof s==="string")s=e.util.createBuffer(s);var C=s.length(),p=f(s,s.length(),0,a);if(a.parseAllBytes&&s.length()!==0){var m=Error("Unparsed DER bytes remain after ASN.1 parsing.");throw m.byteCount=C,m.remaining=s.length(),m}return p};function f(s,a,C,p){var m;i(s,a,2);var w=s.getByte();a--;var B=w&192,d=w&31;m=s.length();var T=c(s,a);if(a-=m-s.length(),T!==void 0&&T>a){if(p.strict){var A=Error("Too few bytes to read ASN.1 value.");throw A.available=s.length(),A.remaining=a,A.requested=T,A}T=a}var g,l,S=(w&32)===32;if(S)if(g=[],T===void 0)for(;;){if(i(s,a,2),s.bytes(2)===String.fromCharCode(0,0)){s.getBytes(2),a-=2;break}m=s.length(),g.push(f(s,a,C+1,p)),a-=m-s.length()}else while(T>0)m=s.length(),g.push(f(s,T,C+1,p)),a-=m-s.length(),T-=m-s.length();if(g===void 0&&B===t.Class.UNIVERSAL&&d===t.Type.BITSTRING)l=s.bytes(T);if(g===void 0&&p.decodeBitStrings&&B===t.Class.UNIVERSAL&&d===t.Type.BITSTRING&&T>1){var I=s.read,N=a,L=0;if(d===t.Type.BITSTRING)i(s,a,1),L=s.getByte(),a--;if(L===0)try{m=s.length();var v={strict:!0,decodeBitStrings:!0},h=f(s,a,C+1,v),u=m-s.length();if(a-=u,d==t.Type.BITSTRING)u++;var R=h.tagClass;if(u===T&&(R===t.Class.UNIVERSAL||R===t.Class.CONTEXT_SPECIFIC))g=[h]}catch(O){}if(g===void 0)s.read=I,a=N}if(g===void 0){if(T===void 0){if(p.strict)throw Error("Non-constructed ASN.1 object of indefinite length.");T=a}if(d===t.Type.BMPSTRING){g="";for(;T>0;T-=2)i(s,a,2),g+=String.fromCharCode(s.getInt16()),a-=2}else g=s.getBytes(T),a-=T}var V=l===void 0?null:{bitStringContents:l};return t.create(B,d,S,g,V)}t.toDer=function(s){var a=e.util.createBuffer(),C=s.tagClass|s.type,p=e.util.createBuffer(),m=!1;if("bitStringContents"in s){if(m=!0,s.original)m=t.equals(s,s.original)}if(m)p.putBytes(s.bitStringContents);else if(s.composed){if(s.constructed)C|=32;else p.putByte(0);for(var w=0;w<s.value.length;++w)if(s.value[w]!==void 0)p.putBuffer(t.toDer(s.value[w]))}else if(s.type===t.Type.BMPSTRING)for(var w=0;w<s.value.length;++w)p.putInt16(s.value.charCodeAt(w));else if(s.type===t.Type.INTEGER&&s.value.length>1&&(s.value.charCodeAt(0)===0&&(s.value.charCodeAt(1)&128)===0||s.value.charCodeAt(0)===255&&(s.value.charCodeAt(1)&128)===128))p.putBytes(s.value.substr(1));else p.putBytes(s.value);if(a.putByte(C),p.length()<=127)a.putByte(p.length()&127);else{var B=p.length(),d="";do d+=String.fromCharCode(B&255),B=B>>>8;while(B>0);a.putByte(d.length|128);for(var w=d.length-1;w>=0;--w)a.putByte(d.charCodeAt(w))}return a.putBuffer(p),a},t.oidToDer=function(s){var a=s.split("."),C=e.util.createBuffer();C.putByte(40*parseInt(a[0],10)+parseInt(a[1],10));var p,m,w,B;for(var d=2;d<a.length;++d){p=!0,m=[],w=parseInt(a[d],10);do{if(B=w&127,w=w>>>7,!p)B|=128;m.push(B),p=!1}while(w>0);for(var T=m.length-1;T>=0;--T)C.putByte(m[T])}return C},t.derToOid=function(s){var a;if(typeof s==="string")s=e.util.createBuffer(s);var C=s.getByte();a=Math.floor(C/40)+"."+C%40;var p=0;while(s.length()>0)if(C=s.getByte(),p=p<<7,C&128)p+=C&127;else a+="."+(p+C),p=0;return a},t.utcTimeToDate=function(s){var a=new Date,C=parseInt(s.substr(0,2),10);C=C>=50?1900+C:2000+C;var p=parseInt(s.substr(2,2),10)-1,m=parseInt(s.substr(4,2),10),w=parseInt(s.substr(6,2),10),B=parseInt(s.substr(8,2),10),d=0;if(s.length>11){var T=s.charAt(10),A=10;if(T!=="+"&&T!=="-")d=parseInt(s.substr(10,2),10),A+=2}if(a.setUTCFullYear(C,p,m),a.setUTCHours(w,B,d,0),A){if(T=s.charAt(A),T==="+"||T==="-"){var g=parseInt(s.substr(A+1,2),10),l=parseInt(s.substr(A+4,2),10),S=g*60+l;if(S*=60000,T==="+")a.setTime(+a-S);else a.setTime(+a+S)}}return a},t.generalizedTimeToDate=function(s){var a=new Date,C=parseInt(s.substr(0,4),10),p=parseInt(s.substr(4,2),10)-1,m=parseInt(s.substr(6,2),10),w=parseInt(s.substr(8,2),10),B=parseInt(s.substr(10,2),10),d=parseInt(s.substr(12,2),10),T=0,A=0,g=!1;if(s.charAt(s.length-1)==="Z")g=!0;var l=s.length-5,S=s.charAt(l);if(S==="+"||S==="-"){var I=parseInt(s.substr(l+1,2),10),N=parseInt(s.substr(l+4,2),10);if(A=I*60+N,A*=60000,S==="+")A*=-1;g=!0}if(s.charAt(14)===".")T=parseFloat(s.substr(14),10)*1000;if(g)a.setUTCFullYear(C,p,m),a.setUTCHours(w,B,d,T),a.setTime(+a+A);else a.setFullYear(C,p,m),a.setHours(w,B,d,T);return a},t.dateToUtcTime=function(s){if(typeof s==="string")return s;var a="",C=[];C.push((""+s.getUTCFullYear()).substr(2)),C.push(""+(s.getUTCMonth()+1)),C.push(""+s.getUTCDate()),C.push(""+s.getUTCHours()),C.push(""+s.getUTCMinutes()),C.push(""+s.getUTCSeconds());for(var p=0;p<C.length;++p){if(C[p].length<2)a+="0";a+=C[p]}return a+="Z",a},t.dateToGeneralizedTime=function(s){if(typeof s==="string")return s;var a="",C=[];C.push(""+s.getUTCFullYear()),C.push(""+(s.getUTCMonth()+1)),C.push(""+s.getUTCDate()),C.push(""+s.getUTCHours()),C.push(""+s.getUTCMinutes()),C.push(""+s.getUTCSeconds());for(var p=0;p<C.length;++p){if(C[p].length<2)a+="0";a+=C[p]}return a+="Z",a},t.integerToDer=function(s){var a=e.util.createBuffer();if(s>=-128&&s<128)return a.putSignedInt(s,8);if(s>=-32768&&s<32768)return a.putSignedInt(s,16);if(s>=-8388608&&s<8388608)return a.putSignedInt(s,24);if(s>=-2147483648&&s<2147483648)return a.putSignedInt(s,32);var C=Error("Integer too large; max is 32-bits.");throw C.integer=s,C},t.derToInteger=function(s){if(typeof s==="string")s=e.util.createBuffer(s);var a=s.length()*8;if(a>32)throw Error("Integer too large; max is 32-bits.");return s.getSignedInt(a)},t.validate=function(s,a,C,p){var m=!1;if((s.tagClass===a.tagClass||typeof a.tagClass>"u")&&(s.type===a.type||typeof a.type>"u")){if(s.constructed===a.constructed||typeof a.constructed>"u"){if(m=!0,a.value&&e.util.isArray(a.value)){var w=0;for(var B=0;m&&B<a.value.length;++B){if(m=a.value[B].optional||!1,s.value[w]){if(m=t.validate(s.value[w],a.value[B],C,p),m)++w;else if(a.value[B].optional)m=!0}if(!m&&p)p.push("["+a.name+'] Tag class "'+a.tagClass+'", type "'+a.type+'" expected value length "'+a.value.length+'", got "'+s.value.length+'"')}}if(m&&C){if(a.capture)C[a.capture]=s.value;if(a.captureAsn1)C[a.captureAsn1]=s;if(a.captureBitStringContents&&"bitStringContents"in s)C[a.captureBitStringContents]=s.bitStringContents;if(a.captureBitStringValue&&"bitStringContents"in s){var d;if(s.bitStringContents.length<2)C[a.captureBitStringValue]="";else{var T=s.bitStringContents.charCodeAt(0);if(T!==0)throw Error("captureBitStringValue only supported for zero unused bits");C[a.captureBitStringValue]=s.bitStringContents.slice(1)}}}}else if(p)p.push("["+a.name+'] Expected constructed "'+a.constructed+'", got "'+s.constructed+'"')}else if(p){if(s.tagClass!==a.tagClass)p.push("["+a.name+'] Expected tag class "'+a.tagClass+'", got "'+s.tagClass+'"');if(s.type!==a.type)p.push("["+a.name+'] Expected type "'+a.type+'", got "'+s.type+'"')}return m};var o=/[^\\u0000-\\u00ff]/;t.prettyPrint=function(s,a,C){var p="";if(a=a||0,C=C||2,a>0)p+=`
|
|
44
|
+
`;var m="";for(var w=0;w<a*C;++w)m+=" ";switch(p+=m+"Tag: ",s.tagClass){case t.Class.UNIVERSAL:p+="Universal:";break;case t.Class.APPLICATION:p+="Application:";break;case t.Class.CONTEXT_SPECIFIC:p+="Context-Specific:";break;case t.Class.PRIVATE:p+="Private:";break}if(s.tagClass===t.Class.UNIVERSAL)switch(p+=s.type,s.type){case t.Type.NONE:p+=" (None)";break;case t.Type.BOOLEAN:p+=" (Boolean)";break;case t.Type.INTEGER:p+=" (Integer)";break;case t.Type.BITSTRING:p+=" (Bit string)";break;case t.Type.OCTETSTRING:p+=" (Octet string)";break;case t.Type.NULL:p+=" (Null)";break;case t.Type.OID:p+=" (Object Identifier)";break;case t.Type.ODESC:p+=" (Object Descriptor)";break;case t.Type.EXTERNAL:p+=" (External or Instance of)";break;case t.Type.REAL:p+=" (Real)";break;case t.Type.ENUMERATED:p+=" (Enumerated)";break;case t.Type.EMBEDDED:p+=" (Embedded PDV)";break;case t.Type.UTF8:p+=" (UTF8)";break;case t.Type.ROID:p+=" (Relative Object Identifier)";break;case t.Type.SEQUENCE:p+=" (Sequence)";break;case t.Type.SET:p+=" (Set)";break;case t.Type.PRINTABLESTRING:p+=" (Printable String)";break;case t.Type.IA5String:p+=" (IA5String (ASCII))";break;case t.Type.UTCTIME:p+=" (UTC time)";break;case t.Type.GENERALIZEDTIME:p+=" (Generalized time)";break;case t.Type.BMPSTRING:p+=" (BMP String)";break}else p+=s.type;if(p+=`
|
|
45
|
+
`,p+=m+"Constructed: "+s.constructed+`
|
|
46
|
+
`,s.composed){var B=0,d="";for(var w=0;w<s.value.length;++w)if(s.value[w]!==void 0){if(B+=1,d+=t.prettyPrint(s.value[w],a+1,C),w+1<s.value.length)d+=","}p+=m+"Sub values: "+B+d}else{if(p+=m+"Value: ",s.type===t.Type.OID){var T=t.derToOid(s.value);if(p+=T,e.pki&&e.pki.oids){if(T in e.pki.oids)p+=" ("+e.pki.oids[T]+") "}}if(s.type===t.Type.INTEGER)try{p+=t.derToInteger(s.value)}catch(g){p+="0x"+e.util.bytesToHex(s.value)}else if(s.type===t.Type.BITSTRING){if(s.value.length>1)p+="0x"+e.util.bytesToHex(s.value.slice(1));else p+="(none)";if(s.value.length>0){var A=s.value.charCodeAt(0);if(A==1)p+=" (1 unused bit shown)";else if(A>1)p+=" ("+A+" unused bits shown)"}}else if(s.type===t.Type.OCTETSTRING){if(!o.test(s.value))p+="("+s.value+") ";p+="0x"+e.util.bytesToHex(s.value)}else if(s.type===t.Type.UTF8)try{p+=e.util.decodeUtf8(s.value)}catch(g){if(g.message==="URI malformed")p+="0x"+e.util.bytesToHex(s.value)+" (malformed UTF8)";else throw g}else if(s.type===t.Type.PRINTABLESTRING||s.type===t.Type.IA5String)p+=s.value;else if(o.test(s.value))p+="0x"+e.util.bytesToHex(s.value);else if(s.value.length===0)p+="[null]";else p+=s.value}return p}}),Me=lt((r,n)=>{var e=pt();n.exports=e.md=e.md||{},e.md.algorithms=e.md.algorithms||{}}),dr=lt((r,n)=>{var e=pt();Me(),Tt();var t=n.exports=e.hmac=e.hmac||{};t.create=function(){var i=null,c=null,f=null,o=null,s={};return s.start=function(a,C){if(a!==null)if(typeof a==="string")if(a=a.toLowerCase(),a in e.md.algorithms)c=e.md.algorithms[a].create();else throw Error('Unknown hash algorithm "'+a+'"');else c=a;if(C===null)C=i;else{if(typeof C==="string")C=e.util.createBuffer(C);else if(e.util.isArray(C)){var p=C;C=e.util.createBuffer();for(var m=0;m<p.length;++m)C.putByte(p[m])}var w=C.length();if(w>c.blockLength)c.start(),c.update(C.bytes()),C=c.digest();f=e.util.createBuffer(),o=e.util.createBuffer(),w=C.length();for(var m=0;m<w;++m){var p=C.at(m);f.putByte(54^p),o.putByte(92^p)}if(w<c.blockLength){var p=c.blockLength-w;for(var m=0;m<p;++m)f.putByte(54),o.putByte(92)}i=C,f=f.bytes(),o=o.bytes()}c.start(),c.update(f)},s.update=function(a){c.update(a)},s.getMac=function(){var a=c.digest().bytes();return c.start(),c.update(o),c.update(a),c.digest()},s.digest=s.getMac,s}}),Gi=lt((r,n)=>{var e=pt();Me(),Tt();var t=n.exports=e.md5=e.md5||{};e.md.md5=e.md.algorithms.md5=t,t.create=function(){if(!s)a();var p=null,m=e.util.createBuffer(),w=Array(16),B={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};return B.start=function(){B.messageLength=0,B.fullMessageLength=B.messageLength64=[];var d=B.messageLengthSize/4;for(var T=0;T<d;++T)B.fullMessageLength.push(0);return m=e.util.createBuffer(),p={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},B},B.start(),B.update=function(d,T){if(T==="utf8")d=e.util.encodeUtf8(d);var A=d.length;B.messageLength+=A,A=[A/4294967296>>>0,A>>>0];for(var g=B.fullMessageLength.length-1;g>=0;--g)B.fullMessageLength[g]+=A[1],A[1]=A[0]+(B.fullMessageLength[g]/4294967296>>>0),B.fullMessageLength[g]=B.fullMessageLength[g]>>>0,A[0]=A[1]/4294967296>>>0;if(m.putBytes(d),C(p,w,m),m.read>2048||m.length()===0)m.compact();return B},B.digest=function(){var d=e.util.createBuffer();d.putBytes(m.bytes());var T=B.fullMessageLength[B.fullMessageLength.length-1]+B.messageLengthSize,A=T&B.blockLength-1;d.putBytes(i.substr(0,B.blockLength-A));var g,l=0;for(var S=B.fullMessageLength.length-1;S>=0;--S)g=B.fullMessageLength[S]*8+l,l=g/4294967296>>>0,d.putInt32Le(g>>>0);var I={h0:p.h0,h1:p.h1,h2:p.h2,h3:p.h3};C(I,w,d);var N=e.util.createBuffer();return N.putInt32Le(I.h0),N.putInt32Le(I.h1),N.putInt32Le(I.h2),N.putInt32Le(I.h3),N},B};var i=null,c=null,f=null,o=null,s=!1;function a(){i=String.fromCharCode(128),i+=e.util.fillString(String.fromCharCode(0),64),c=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9],f=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],o=Array(64);for(var p=0;p<64;++p)o[p]=Math.floor(Math.abs(Math.sin(p+1))*4294967296);s=!0}function C(p,m,w){var B,d,T,A,g,l,S,I,N=w.length();while(N>=64){d=p.h0,T=p.h1,A=p.h2,g=p.h3;for(I=0;I<16;++I)m[I]=w.getInt32Le(),l=g^T&(A^g),B=d+l+o[I]+m[I],S=f[I],d=g,g=A,A=T,T+=B<<S|B>>>32-S;for(;I<32;++I)l=A^g&(T^A),B=d+l+o[I]+m[c[I]],S=f[I],d=g,g=A,A=T,T+=B<<S|B>>>32-S;for(;I<48;++I)l=T^A^g,B=d+l+o[I]+m[c[I]],S=f[I],d=g,g=A,A=T,T+=B<<S|B>>>32-S;for(;I<64;++I)l=A^(T|~g),B=d+l+o[I]+m[c[I]],S=f[I],d=g,g=A,A=T,T+=B<<S|B>>>32-S;p.h0=p.h0+d|0,p.h1=p.h1+T|0,p.h2=p.h2+A|0,p.h3=p.h3+g|0,N-=64}}}),hr=lt((r,n)=>{var e=pt();Tt();var t=n.exports=e.pem=e.pem||{};t.encode=function(f,o){o=o||{};var s="-----BEGIN "+f.type+`-----\r
|
|
47
|
+
`,a;if(f.procType)a={name:"Proc-Type",values:[String(f.procType.version),f.procType.type]},s+=i(a);if(f.contentDomain)a={name:"Content-Domain",values:[f.contentDomain]},s+=i(a);if(f.dekInfo){if(a={name:"DEK-Info",values:[f.dekInfo.algorithm]},f.dekInfo.parameters)a.values.push(f.dekInfo.parameters);s+=i(a)}if(f.headers)for(var C=0;C<f.headers.length;++C)s+=i(f.headers[C]);if(f.procType)s+=`\r
|
|
48
|
+
`;return s+=e.util.encode64(f.body,o.maxline||64)+`\r
|
|
49
|
+
`,s+="-----END "+f.type+`-----\r
|
|
50
|
+
`,s},t.decode=function(f){var o=[],s=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,a=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,C=/\r?\n/,p;while(!0){if(p=s.exec(f),!p)break;var m=p[1];if(m==="NEW CERTIFICATE REQUEST")m="CERTIFICATE REQUEST";var w={type:m,procType:null,contentDomain:null,dekInfo:null,headers:[],body:e.util.decode64(p[3])};if(o.push(w),!p[2])continue;var B=p[2].split(C),d=0;while(p&&d<B.length){var T=B[d].replace(/\s+$/,"");for(var A=d+1;A<B.length;++A){var g=B[A];if(!/\s/.test(g[0]))break;T+=g,d=A}if(p=T.match(a),p){var l={name:p[1],values:[]},S=p[2].split(",");for(var I=0;I<S.length;++I)l.values.push(c(S[I]));if(!w.procType){if(l.name!=="Proc-Type")throw Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');else if(l.values.length!==2)throw Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');w.procType={version:S[0],type:S[1]}}else if(!w.contentDomain&&l.name==="Content-Domain")w.contentDomain=S[0]||"";else if(!w.dekInfo&&l.name==="DEK-Info"){if(l.values.length===0)throw Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');w.dekInfo={algorithm:S[0],parameters:S[1]||null}}else w.headers.push(l)}++d}if(w.procType==="ENCRYPTED"&&!w.dekInfo)throw Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}if(o.length===0)throw Error("Invalid PEM formatted message.");return o};function i(f){var o=f.name+": ",s=[],a=function(B,d){return" "+d};for(var C=0;C<f.values.length;++C)s.push(f.values[C].replace(/^(\S+\r\n)/,a));o+=s.join(",")+`\r
|
|
51
|
+
`;var p=0,m=-1;for(var C=0;C<o.length;++C,++p)if(p>65&&m!==-1){var w=o[m];if(w===",")++m,o=o.substr(0,m)+`\r
|
|
52
|
+
`+o.substr(m);else o=o.substr(0,m)+`\r
|
|
53
|
+
`+w+o.substr(m+1);p=C-m-1,m=-1,++C}else if(o[C]===" "||o[C]==="\t"||o[C]===",")m=C;return o}function c(f){return f.replace(/^\s+/,"")}}),Zr=lt((r,n)=>{var e=pt();Oi(),ea(),Tt(),n.exports=e.des=e.des||{},e.des.startEncrypting=function(d,T,A,g){var l=B({key:d,output:A,decrypt:!1,mode:g||(T===null?"ECB":"CBC")});return l.start(T),l},e.des.createEncryptionCipher=function(d,T){return B({key:d,output:null,decrypt:!1,mode:T})},e.des.startDecrypting=function(d,T,A,g){var l=B({key:d,output:A,decrypt:!0,mode:g||(T===null?"ECB":"CBC")});return l.start(T),l},e.des.createDecryptionCipher=function(d,T){return B({key:d,output:null,decrypt:!0,mode:T})},e.des.Algorithm=function(d,T){var A=this;A.name=d,A.mode=new T({blockSize:8,cipher:{encrypt:function(g,l){return w(A._keys,g,l,!1)},decrypt:function(g,l){return w(A._keys,g,l,!0)}}}),A._init=!1},e.des.Algorithm.prototype.initialize=function(d){if(this._init)return;var T=e.util.createBuffer(d.key);if(this.name.indexOf("3DES")===0){if(T.length()!==24)throw Error("Invalid Triple-DES key size: "+T.length()*8)}this._keys=m(T),this._init=!0},t("DES-ECB",e.cipher.modes.ecb),t("DES-CBC",e.cipher.modes.cbc),t("DES-CFB",e.cipher.modes.cfb),t("DES-OFB",e.cipher.modes.ofb),t("DES-CTR",e.cipher.modes.ctr),t("3DES-ECB",e.cipher.modes.ecb),t("3DES-CBC",e.cipher.modes.cbc),t("3DES-CFB",e.cipher.modes.cfb),t("3DES-OFB",e.cipher.modes.ofb),t("3DES-CTR",e.cipher.modes.ctr);function t(d,T){var A=function(){return new e.des.Algorithm(d,T)};e.cipher.registerAlgorithm(d,A)}var i=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],c=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],f=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],o=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],s=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],a=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],C=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],p=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function m(d){var T=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],A=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],g=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],l=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],S=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],I=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],N=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],L=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],v=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],h=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],u=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],R=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],V=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],O=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],K=d.length()>8?3:1,G=[],H=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],j=0,z;for(var Z=0;Z<K;Z++){var tt=d.getInt32(),rt=d.getInt32();z=(tt>>>4^rt)&252645135,rt^=z,tt^=z<<4,z=(rt>>>-16^tt)&65535,tt^=z,rt^=z<<-16,z=(tt>>>2^rt)&858993459,rt^=z,tt^=z<<2,z=(rt>>>-16^tt)&65535,tt^=z,rt^=z<<-16,z=(tt>>>1^rt)&1431655765,rt^=z,tt^=z<<1,z=(rt>>>8^tt)&16711935,tt^=z,rt^=z<<8,z=(tt>>>1^rt)&1431655765,rt^=z,tt^=z<<1,z=tt<<8|rt>>>20&240,tt=rt<<24|rt<<8&16711680|rt>>>8&65280|rt>>>24&240,rt=z;for(var ut=0;ut<H.length;++ut){if(H[ut])tt=tt<<2|tt>>>26,rt=rt<<2|rt>>>26;else tt=tt<<1|tt>>>27,rt=rt<<1|rt>>>27;tt&=-15,rt&=-15;var ht=T[tt>>>28]|A[tt>>>24&15]|g[tt>>>20&15]|l[tt>>>16&15]|S[tt>>>12&15]|I[tt>>>8&15]|N[tt>>>4&15],Et=L[rt>>>28]|v[rt>>>24&15]|h[rt>>>20&15]|u[rt>>>16&15]|R[rt>>>12&15]|V[rt>>>8&15]|O[rt>>>4&15];z=(Et>>>16^ht)&65535,G[j++]=ht^z,G[j++]=Et^z<<16}}return G}function w(d,T,A,g){var l=d.length===32?3:9,S;if(l===3)S=g?[30,-2,-2]:[0,32,2];else S=g?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var I,N=T[0],L=T[1];I=(N>>>4^L)&252645135,L^=I,N^=I<<4,I=(N>>>16^L)&65535,L^=I,N^=I<<16,I=(L>>>2^N)&858993459,N^=I,L^=I<<2,I=(L>>>8^N)&16711935,N^=I,L^=I<<8,I=(N>>>1^L)&1431655765,L^=I,N^=I<<1,N=N<<1|N>>>31,L=L<<1|L>>>31;for(var v=0;v<l;v+=3){var h=S[v+1],u=S[v+2];for(var R=S[v];R!=h;R+=u){var V=L^d[R],O=(L>>>4|L<<28)^d[R+1];I=N,N=L,L=I^(c[V>>>24&63]|o[V>>>16&63]|a[V>>>8&63]|p[V&63]|i[O>>>24&63]|f[O>>>16&63]|s[O>>>8&63]|C[O&63])}I=N,N=L,L=I}N=N>>>1|N<<31,L=L>>>1|L<<31,I=(N>>>1^L)&1431655765,L^=I,N^=I<<1,I=(L>>>8^N)&16711935,N^=I,L^=I<<8,I=(L>>>2^N)&858993459,N^=I,L^=I<<2,I=(N>>>16^L)&65535,L^=I,N^=I<<16,I=(N>>>4^L)&252645135,L^=I,N^=I<<4,A[0]=N,A[1]=L}function B(d){d=d||{};var T=(d.mode||"CBC").toUpperCase(),A="DES-"+T,g;if(d.decrypt)g=e.cipher.createDecipher(A,d.key);else g=e.cipher.createCipher(A,d.key);var l=g.start;return g.start=function(S,I){var N=null;if(I instanceof e.util.ByteBuffer)N=I,I={};I=I||{},I.output=N,I.iv=S,l.call(g,I)},g}}),Fi=lt((r,n)=>{var e=pt();dr(),Me(),Tt();var t=e.pkcs5=e.pkcs5||{},i;if(e.util.isNodejs&&!e.options.usePureJavaScript)i=Wr("crypto");n.exports=e.pbkdf2=t.pbkdf2=function(c,f,o,s,a,C){if(typeof a==="function")C=a,a=null;if(e.util.isNodejs&&!e.options.usePureJavaScript&&i.pbkdf2&&(a===null||typeof a!=="object")&&(i.pbkdf2Sync.length>4||(!a||a==="sha1"))){if(typeof a!=="string")a="sha1";if(c=Buffer.from(c,"binary"),f=Buffer.from(f,"binary"),!C){if(i.pbkdf2Sync.length===4)return i.pbkdf2Sync(c,f,o,s).toString("binary");return i.pbkdf2Sync(c,f,o,s,a).toString("binary")}if(i.pbkdf2Sync.length===4)return i.pbkdf2(c,f,o,s,function(v,h){if(v)return C(v);C(null,h.toString("binary"))});return i.pbkdf2(c,f,o,s,a,function(v,h){if(v)return C(v);C(null,h.toString("binary"))})}if(typeof a>"u"||a===null)a="sha1";if(typeof a==="string"){if(!(a in e.md.algorithms))throw Error("Unknown hash algorithm: "+a);a=e.md[a].create()}var p=a.digestLength;if(s>4294967295*p){var m=Error("Derived key is too long.");if(C)return C(m);throw m}var w=Math.ceil(s/p),B=s-(w-1)*p,d=e.hmac.create();d.start(a,c);var T="",A,g,l;if(!C){for(var S=1;S<=w;++S){d.start(null,null),d.update(f),d.update(e.util.int32ToBytes(S)),A=l=d.digest().getBytes();for(var I=2;I<=o;++I)d.start(null,null),d.update(l),g=d.digest().getBytes(),A=e.util.xorBytes(A,g,p),l=g;T+=S<w?A:A.substr(0,B)}return T}var S=1,I;function N(){if(S>w)return C(null,T);d.start(null,null),d.update(f),d.update(e.util.int32ToBytes(S)),A=l=d.digest().getBytes(),I=2,L()}function L(){if(I<=o)return d.start(null,null),d.update(l),g=d.digest().getBytes(),A=e.util.xorBytes(A,g,p),l=g,++I,e.util.setImmediate(L);T+=S<w?A:A.substr(0,B),++S,N()}N()}}),ra=lt((r,n)=>{var e=pt();Me(),Tt();var t=n.exports=e.sha256=e.sha256||{};e.md.sha256=e.md.algorithms.sha256=t,t.create=function(){if(!c)o();var a=null,C=e.util.createBuffer(),p=Array(64),m={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return m.start=function(){m.messageLength=0,m.fullMessageLength=m.messageLength64=[];var w=m.messageLengthSize/4;for(var B=0;B<w;++B)m.fullMessageLength.push(0);return C=e.util.createBuffer(),a={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},m},m.start(),m.update=function(w,B){if(B==="utf8")w=e.util.encodeUtf8(w);var d=w.length;m.messageLength+=d,d=[d/4294967296>>>0,d>>>0];for(var T=m.fullMessageLength.length-1;T>=0;--T)m.fullMessageLength[T]+=d[1],d[1]=d[0]+(m.fullMessageLength[T]/4294967296>>>0),m.fullMessageLength[T]=m.fullMessageLength[T]>>>0,d[0]=d[1]/4294967296>>>0;if(C.putBytes(w),s(a,p,C),C.read>2048||C.length()===0)C.compact();return m},m.digest=function(){var w=e.util.createBuffer();w.putBytes(C.bytes());var B=m.fullMessageLength[m.fullMessageLength.length-1]+m.messageLengthSize,d=B&m.blockLength-1;w.putBytes(i.substr(0,m.blockLength-d));var T,A,g=m.fullMessageLength[0]*8;for(var l=0;l<m.fullMessageLength.length-1;++l)T=m.fullMessageLength[l+1]*8,A=T/4294967296>>>0,g+=A,w.putInt32(g>>>0),g=T>>>0;w.putInt32(g);var S={h0:a.h0,h1:a.h1,h2:a.h2,h3:a.h3,h4:a.h4,h5:a.h5,h6:a.h6,h7:a.h7};s(S,p,w);var I=e.util.createBuffer();return I.putInt32(S.h0),I.putInt32(S.h1),I.putInt32(S.h2),I.putInt32(S.h3),I.putInt32(S.h4),I.putInt32(S.h5),I.putInt32(S.h6),I.putInt32(S.h7),I},m};var i=null,c=!1,f=null;function o(){i=String.fromCharCode(128),i+=e.util.fillString(String.fromCharCode(0),64),f=[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],c=!0}function s(a,C,p){var m,w,B,d,T,A,g,l,S,I,N,L,v,h,u,R=p.length();while(R>=64){for(g=0;g<16;++g)C[g]=p.getInt32();for(;g<64;++g)m=C[g-2],m=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,w=C[g-15],w=(w>>>7|w<<25)^(w>>>18|w<<14)^w>>>3,C[g]=m+C[g-7]+w+C[g-16]|0;l=a.h0,S=a.h1,I=a.h2,N=a.h3,L=a.h4,v=a.h5,h=a.h6,u=a.h7;for(g=0;g<64;++g)d=(L>>>6|L<<26)^(L>>>11|L<<21)^(L>>>25|L<<7),T=h^L&(v^h),B=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),A=l&S|I&(l^S),m=u+d+T+f[g]+C[g],w=B+A,u=h,h=v,v=L,L=N+m>>>0,N=I,I=S,S=l,l=m+w>>>0;a.h0=a.h0+l|0,a.h1=a.h1+S|0,a.h2=a.h2+I|0,a.h3=a.h3+N|0,a.h4=a.h4+L|0,a.h5=a.h5+v|0,a.h6=a.h6+h|0,a.h7=a.h7+u|0,R-=64}}}),ia=lt((r,n)=>{var e=pt();Tt();var t=null;if(e.util.isNodejs&&!e.options.usePureJavaScript&&!process.versions["node-webkit"])t=Wr("crypto");var i=n.exports=e.prng=e.prng||{};i.create=function(c){var f={plugin:c,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},o=c.md,s=Array(32);for(var a=0;a<32;++a)s[a]=o.create();f.pools=s,f.pool=0,f.generate=function(B,d){if(!d)return f.generateSync(B);var T=f.plugin.cipher,A=f.plugin.increment,g=f.plugin.formatKey,l=f.plugin.formatSeed,S=e.util.createBuffer();f.key=null,I();function I(N){if(N)return d(N);if(S.length()>=B)return d(null,S.getBytes(B));if(f.generated>1048575)f.key=null;if(f.key===null)return e.util.nextTick(function(){C(I)});var L=T(f.key,f.seed);f.generated+=L.length,S.putBytes(L),f.key=g(T(f.key,A(f.seed))),f.seed=l(T(f.key,f.seed)),e.util.setImmediate(I)}},f.generateSync=function(B){var d=f.plugin.cipher,T=f.plugin.increment,A=f.plugin.formatKey,g=f.plugin.formatSeed;f.key=null;var l=e.util.createBuffer();while(l.length()<B){if(f.generated>1048575)f.key=null;if(f.key===null)p();var S=d(f.key,f.seed);f.generated+=S.length,l.putBytes(S),f.key=A(d(f.key,T(f.seed))),f.seed=g(d(f.key,f.seed))}return l.getBytes(B)};function C(B){if(f.pools[0].messageLength>=32)return m(),B();var d=32-f.pools[0].messageLength<<5;f.seedFile(d,function(T,A){if(T)return B(T);f.collect(A),m(),B()})}function p(){if(f.pools[0].messageLength>=32)return m();var B=32-f.pools[0].messageLength<<5;f.collect(f.seedFileSync(B)),m()}function m(){f.reseeds=f.reseeds===4294967295?0:f.reseeds+1;var B=f.plugin.md.create();B.update(f.keyBytes);var d=1;for(var T=0;T<32;++T){if(f.reseeds%d===0)B.update(f.pools[T].digest().getBytes()),f.pools[T].start();d=d<<1}f.keyBytes=B.digest().getBytes(),B.start(),B.update(f.keyBytes);var A=B.digest().getBytes();f.key=f.plugin.formatKey(f.keyBytes),f.seed=f.plugin.formatSeed(A),f.generated=0}function w(B){var d=null,T=e.util.globalScope,A=T.crypto||T.msCrypto;if(A&&A.getRandomValues)d=function(u){return A.getRandomValues(u)};var g=e.util.createBuffer();if(d)while(g.length()<B){var l=Math.max(1,Math.min(B-g.length(),65536)/4),S=new Uint32Array(Math.floor(l));try{d(S);for(var I=0;I<S.length;++I)g.putInt32(S[I])}catch(u){if(!(typeof QuotaExceededError<"u"&&u instanceof QuotaExceededError))throw u}}if(g.length()<B){var N,L,v,h=Math.floor(Math.random()*65536);while(g.length()<B){L=16807*(h&65535),N=16807*(h>>16),L+=(N&32767)<<16,L+=N>>15,L=(L&2147483647)+(L>>31),h=L&4294967295;for(var I=0;I<3;++I)v=h>>>(I<<3),v^=Math.floor(Math.random()*256),g.putByte(v&255)}}return g.getBytes(B)}if(t)f.seedFile=function(B,d){t.randomBytes(B,function(T,A){if(T)return d(T);d(null,A.toString())})},f.seedFileSync=function(B){return t.randomBytes(B).toString()};else f.seedFile=function(B,d){try{d(null,w(B))}catch(T){d(T)}},f.seedFileSync=w;return f.collect=function(B){var d=B.length;for(var T=0;T<d;++T)f.pools[f.pool].update(B.substr(T,1)),f.pool=f.pool===31?0:f.pool+1},f.collectInt=function(B,d){var T="";for(var A=0;A<d;A+=8)T+=String.fromCharCode(B>>A&255);f.collect(T)},f.registerWorker=function(B){if(B===self)f.seedFile=function(T,A){function g(l){var S=l.data;if(S.forge&&S.forge.prng)self.removeEventListener("message",g),A(S.forge.prng.err,S.forge.prng.bytes)}self.addEventListener("message",g),self.postMessage({forge:{prng:{needed:T}}})};else{var d=function(T){var A=T.data;if(A.forge&&A.forge.prng)f.seedFile(A.forge.prng.needed,function(g,l){B.postMessage({forge:{prng:{err:g,bytes:l}}})})};B.addEventListener("message",d)}},f}}),we=lt((r,n)=>{var e=pt();ze(),ra(),ia(),Tt(),function(){if(e.random&&e.random.getBytes){n.exports=e.random;return}(function(t){var i={},c=[,,,,],f=e.util.createBuffer();i.formatKey=function(B){var d=e.util.createBuffer(B);return B=[,,,,],B[0]=d.getInt32(),B[1]=d.getInt32(),B[2]=d.getInt32(),B[3]=d.getInt32(),e.aes._expandKey(B,!1)},i.formatSeed=function(B){var d=e.util.createBuffer(B);return B=[,,,,],B[0]=d.getInt32(),B[1]=d.getInt32(),B[2]=d.getInt32(),B[3]=d.getInt32(),B},i.cipher=function(B,d){return e.aes._updateBlock(B,d,c,!1),f.putInt32(c[0]),f.putInt32(c[1]),f.putInt32(c[2]),f.putInt32(c[3]),f.getBytes()},i.increment=function(B){return++B[3],B},i.md=e.md.sha256;function o(){var B=e.prng.create(i);return B.getBytes=function(d,T){return B.generate(d,T)},B.getBytesSync=function(d){return B.generate(d)},B}var s=o(),a=null,C=e.util.globalScope,p=C.crypto||C.msCrypto;if(p&&p.getRandomValues)a=function(B){return p.getRandomValues(B)};if(e.options.usePureJavaScript||!e.util.isNodejs&&!a){if(typeof window>"u"||window.document===void 0);if(s.collectInt(+new Date,32),typeof navigator<"u"){var m="";for(var w in navigator)try{if(typeof navigator[w]=="string")m+=navigator[w]}catch(B){}s.collect(m),m=null}if(t)t().mousemove(function(B){s.collectInt(B.clientX,16),s.collectInt(B.clientY,16)}),t().keypress(function(B){s.collectInt(B.charCode,8)})}if(!e.random)e.random=s;else for(var w in s)e.random[w]=s[w];e.random.createInstance=o,n.exports=e.random})(typeof jQuery<"u"?jQuery:null)}()}),na=lt((r,n)=>{var e=pt();Tt();var t=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],i=[1,2,3,5],c=function(s,a){return s<<a&65535|(s&65535)>>16-a},f=function(s,a){return(s&65535)>>a|s<<16-a&65535};n.exports=e.rc2=e.rc2||{},e.rc2.expandKey=function(s,a){if(typeof s==="string")s=e.util.createBuffer(s);a=a||128;var C=s,p=s.length(),m=a,w=Math.ceil(m/8),B=255>>(m&7),d;for(d=p;d<128;d++)C.putByte(t[C.at(d-1)+C.at(d-p)&255]);C.setAt(128-w,t[C.at(128-w)&B]);for(d=127-w;d>=0;d--)C.setAt(d,t[C.at(d+1)^C.at(d+w)]);return C};var o=function(s,a,C){var p=!1,m=null,w=null,B=null,d,T,A,g,l=[];s=e.rc2.expandKey(s,a);for(A=0;A<64;A++)l.push(s.getInt16Le());if(C)d=function(N){for(A=0;A<4;A++)N[A]+=l[g]+(N[(A+3)%4]&N[(A+2)%4])+(~N[(A+3)%4]&N[(A+1)%4]),N[A]=c(N[A],i[A]),g++},T=function(N){for(A=0;A<4;A++)N[A]+=l[N[(A+3)%4]&63]};else d=function(N){for(A=3;A>=0;A--)N[A]=f(N[A],i[A]),N[A]-=l[g]+(N[(A+3)%4]&N[(A+2)%4])+(~N[(A+3)%4]&N[(A+1)%4]),g--},T=function(N){for(A=3;A>=0;A--)N[A]-=l[N[(A+3)%4]&63]};var S=function(N){var L=[];for(A=0;A<4;A++){var v=m.getInt16Le();if(B!==null)if(C)v^=B.getInt16Le();else B.putInt16Le(v);L.push(v&65535)}g=C?0:63;for(var h=0;h<N.length;h++)for(var u=0;u<N[h][0];u++)N[h][1](L);for(A=0;A<4;A++){if(B!==null)if(C)B.putInt16Le(L[A]);else L[A]^=B.getInt16Le();w.putInt16Le(L[A])}},I=null;return I={start:function(N,L){if(N){if(typeof N==="string")N=e.util.createBuffer(N)}p=!1,m=e.util.createBuffer(),w=L||new e.util.createBuffer,B=N,I.output=w},update:function(N){if(!p)m.putBuffer(N);while(m.length()>=8)S([[5,d],[1,T],[6,d],[1,T],[5,d]])},finish:function(N){var L=!0;if(C)if(N)L=N(8,m,!C);else{var v=m.length()===8?8:8-m.length();m.fillWithByte(v,v)}if(L)p=!0,I.update();if(!C){if(L=m.length()===0,L)if(N)L=N(8,w,!C);else{var h=w.length(),u=w.at(h-1);if(u>h)L=!1;else w.truncate(u)}}return L}},I};e.rc2.startEncrypting=function(s,a,C){var p=e.rc2.createEncryptionCipher(s,128);return p.start(a,C),p},e.rc2.createEncryptionCipher=function(s,a){return o(s,a,!0)},e.rc2.startDecrypting=function(s,a,C){var p=e.rc2.createDecryptionCipher(s,128);return p.start(a,C),p},e.rc2.createDecryptionCipher=function(s,a){return o(s,a,!1)}}),$r=lt((r,n)=>{var e=pt();n.exports=e.jsbn=e.jsbn||{};var t,i=244837814094590,c=(i&16777215)==15715070;function f(_,U,x){if(this.data=[],_!=null)if(typeof _=="number")this.fromNumber(_,U,x);else if(U==null&&typeof _!="string")this.fromString(_,256);else this.fromString(_,U)}e.jsbn.BigInteger=f;function o(){return new f(null)}function s(_,U,x,q,Y,$){while(--$>=0){var st=U*this.data[_++]+x.data[q]+Y;Y=Math.floor(st/67108864),x.data[q++]=st&67108863}return Y}function a(_,U,x,q,Y,$){var st=U&32767,it=U>>15;while(--$>=0){var gt=this.data[_]&32767,ee=this.data[_++]>>15,Ee=it*gt+ee*st;gt=st*gt+((Ee&32767)<<15)+x.data[q]+(Y&1073741823),Y=(gt>>>30)+(Ee>>>15)+it*ee+(Y>>>30),x.data[q++]=gt&1073741823}return Y}function C(_,U,x,q,Y,$){var st=U&16383,it=U>>14;while(--$>=0){var gt=this.data[_]&16383,ee=this.data[_++]>>14,Ee=it*gt+ee*st;gt=st*gt+((Ee&16383)<<14)+x.data[q]+Y,Y=(gt>>28)+(Ee>>14)+it*ee,x.data[q++]=gt&268435455}return Y}if(typeof navigator>"u")f.prototype.am=C,t=28;else if(c&&navigator.appName=="Microsoft Internet Explorer")f.prototype.am=a,t=30;else if(c&&navigator.appName!="Netscape")f.prototype.am=s,t=26;else f.prototype.am=C,t=28;f.prototype.DB=t,f.prototype.DM=(1<<t)-1,f.prototype.DV=1<<t;var p=52;f.prototype.FV=Math.pow(2,p),f.prototype.F1=p-t,f.prototype.F2=2*t-p;var m="0123456789abcdefghijklmnopqrstuvwxyz",w=[],B,d;B=48;for(d=0;d<=9;++d)w[B++]=d;B=97;for(d=10;d<36;++d)w[B++]=d;B=65;for(d=10;d<36;++d)w[B++]=d;function T(_){return m.charAt(_)}function A(_,U){var x=w[_.charCodeAt(U)];return x==null?-1:x}function g(_){for(var U=this.t-1;U>=0;--U)_.data[U]=this.data[U];_.t=this.t,_.s=this.s}function l(_){if(this.t=1,this.s=_<0?-1:0,_>0)this.data[0]=_;else if(_<-1)this.data[0]=_+this.DV;else this.t=0}function S(_){var U=o();return U.fromInt(_),U}function I(_,U){var x;if(U==16)x=4;else if(U==8)x=3;else if(U==256)x=8;else if(U==2)x=1;else if(U==32)x=5;else if(U==4)x=2;else{this.fromRadix(_,U);return}this.t=0,this.s=0;var q=_.length,Y=!1,$=0;while(--q>=0){var st=x==8?_[q]&255:A(_,q);if(st<0){if(_.charAt(q)=="-")Y=!0;continue}if(Y=!1,$==0)this.data[this.t++]=st;else if($+x>this.DB)this.data[this.t-1]|=(st&(1<<this.DB-$)-1)<<$,this.data[this.t++]=st>>this.DB-$;else this.data[this.t-1]|=st<<$;if($+=x,$>=this.DB)$-=this.DB}if(x==8&&(_[0]&128)!=0){if(this.s=-1,$>0)this.data[this.t-1]|=(1<<this.DB-$)-1<<$}if(this.clamp(),Y)f.ZERO.subTo(this,this)}function N(){var _=this.s&this.DM;while(this.t>0&&this.data[this.t-1]==_)--this.t}function L(_){if(this.s<0)return"-"+this.negate().toString(_);var U;if(_==16)U=4;else if(_==8)U=3;else if(_==2)U=1;else if(_==32)U=5;else if(_==4)U=2;else return this.toRadix(_);var x=(1<<U)-1,q,Y=!1,$="",st=this.t,it=this.DB-st*this.DB%U;if(st-- >0){if(it<this.DB&&(q=this.data[st]>>it)>0)Y=!0,$=T(q);while(st>=0){if(it<U)q=(this.data[st]&(1<<it)-1)<<U-it,q|=this.data[--st]>>(it+=this.DB-U);else if(q=this.data[st]>>(it-=U)&x,it<=0)it+=this.DB,--st;if(q>0)Y=!0;if(Y)$+=T(q)}}return Y?$:"0"}function v(){var _=o();return f.ZERO.subTo(this,_),_}function h(){return this.s<0?this.negate():this}function u(_){var U=this.s-_.s;if(U!=0)return U;var x=this.t;if(U=x-_.t,U!=0)return this.s<0?-U:U;while(--x>=0)if((U=this.data[x]-_.data[x])!=0)return U;return 0}function R(_){var U=1,x;if((x=_>>>16)!=0)_=x,U+=16;if((x=_>>8)!=0)_=x,U+=8;if((x=_>>4)!=0)_=x,U+=4;if((x=_>>2)!=0)_=x,U+=2;if((x=_>>1)!=0)_=x,U+=1;return U}function V(){if(this.t<=0)return 0;return this.DB*(this.t-1)+R(this.data[this.t-1]^this.s&this.DM)}function O(_,U){var x;for(x=this.t-1;x>=0;--x)U.data[x+_]=this.data[x];for(x=_-1;x>=0;--x)U.data[x]=0;U.t=this.t+_,U.s=this.s}function K(_,U){for(var x=_;x<this.t;++x)U.data[x-_]=this.data[x];U.t=Math.max(this.t-_,0),U.s=this.s}function G(_,U){var x=_%this.DB,q=this.DB-x,Y=(1<<q)-1,$=Math.floor(_/this.DB),st=this.s<<x&this.DM,it;for(it=this.t-1;it>=0;--it)U.data[it+$+1]=this.data[it]>>q|st,st=(this.data[it]&Y)<<x;for(it=$-1;it>=0;--it)U.data[it]=0;U.data[$]=st,U.t=this.t+$+1,U.s=this.s,U.clamp()}function H(_,U){U.s=this.s;var x=Math.floor(_/this.DB);if(x>=this.t){U.t=0;return}var q=_%this.DB,Y=this.DB-q,$=(1<<q)-1;U.data[0]=this.data[x]>>q;for(var st=x+1;st<this.t;++st)U.data[st-x-1]|=(this.data[st]&$)<<Y,U.data[st-x]=this.data[st]>>q;if(q>0)U.data[this.t-x-1]|=(this.s&$)<<Y;U.t=this.t-x,U.clamp()}function j(_,U){var x=0,q=0,Y=Math.min(_.t,this.t);while(x<Y)q+=this.data[x]-_.data[x],U.data[x++]=q&this.DM,q>>=this.DB;if(_.t<this.t){q-=_.s;while(x<this.t)q+=this.data[x],U.data[x++]=q&this.DM,q>>=this.DB;q+=this.s}else{q+=this.s;while(x<_.t)q-=_.data[x],U.data[x++]=q&this.DM,q>>=this.DB;q-=_.s}if(U.s=q<0?-1:0,q<-1)U.data[x++]=this.DV+q;else if(q>0)U.data[x++]=q;U.t=x,U.clamp()}function z(_,U){var x=this.abs(),q=_.abs(),Y=x.t;U.t=Y+q.t;while(--Y>=0)U.data[Y]=0;for(Y=0;Y<q.t;++Y)U.data[Y+x.t]=x.am(0,q.data[Y],U,Y,0,x.t);if(U.s=0,U.clamp(),this.s!=_.s)f.ZERO.subTo(U,U)}function Z(_){var U=this.abs(),x=_.t=2*U.t;while(--x>=0)_.data[x]=0;for(x=0;x<U.t-1;++x){var q=U.am(x,U.data[x],_,2*x,0,1);if((_.data[x+U.t]+=U.am(x+1,2*U.data[x],_,2*x+1,q,U.t-x-1))>=U.DV)_.data[x+U.t]-=U.DV,_.data[x+U.t+1]=1}if(_.t>0)_.data[_.t-1]+=U.am(x,U.data[x],_,2*x,0,1);_.s=0,_.clamp()}function tt(_,U,x){var q=_.abs();if(q.t<=0)return;var Y=this.abs();if(Y.t<q.t){if(U!=null)U.fromInt(0);if(x!=null)this.copyTo(x);return}if(x==null)x=o();var $=o(),st=this.s,it=_.s,gt=this.DB-R(q.data[q.t-1]);if(gt>0)q.lShiftTo(gt,$),Y.lShiftTo(gt,x);else q.copyTo($),Y.copyTo(x);var ee=$.t,Ee=$.data[ee-1];if(Ee==0)return;var Ce=Ee*(1<<this.F1)+(ee>1?$.data[ee-2]>>this.F2:0),Le=this.FV/Ce,Ir=(1<<this.F1)/Ce,ge=1<<this.F2,Be=x.t,gr=Be-ee,Fe=U==null?o():U;if($.dlShiftTo(gr,Fe),x.compareTo(Fe)>=0)x.data[x.t++]=1,x.subTo(Fe,x);f.ONE.dlShiftTo(ee,Fe),Fe.subTo($,$);while($.t<ee)$.data[$.t++]=0;while(--gr>=0){var fi=x.data[--Be]==Ee?this.DM:Math.floor(x.data[Be]*Le+(x.data[Be-1]+ge)*Ir);if((x.data[Be]+=$.am(0,fi,x,gr,0,ee))<fi){$.dlShiftTo(gr,Fe),x.subTo(Fe,x);while(x.data[Be]<--fi)x.subTo(Fe,x)}}if(U!=null){if(x.drShiftTo(ee,U),st!=it)f.ZERO.subTo(U,U)}if(x.t=ee,x.clamp(),gt>0)x.rShiftTo(gt,x);if(st<0)f.ZERO.subTo(x,x)}function rt(_){var U=o();if(this.abs().divRemTo(_,null,U),this.s<0&&U.compareTo(f.ZERO)>0)_.subTo(U,U);return U}function ut(_){this.m=_}function ht(_){if(_.s<0||_.compareTo(this.m)>=0)return _.mod(this.m);else return _}function Et(_){return _}function _t(_){_.divRemTo(this.m,null,_)}function J(_,U,x){_.multiplyTo(U,x),this.reduce(x)}function vt(_,U){_.squareTo(U),this.reduce(U)}ut.prototype.convert=ht,ut.prototype.revert=Et,ut.prototype.reduce=_t,ut.prototype.mulTo=J,ut.prototype.sqrTo=vt;function et(){if(this.t<1)return 0;var _=this.data[0];if((_&1)==0)return 0;var U=_&3;return U=U*(2-(_&15)*U)&15,U=U*(2-(_&255)*U)&255,U=U*(2-((_&65535)*U&65535))&65535,U=U*(2-_*U%this.DV)%this.DV,U>0?this.DV-U:-U}function Rt(_){this.m=_,this.mp=_.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<_.DB-15)-1,this.mt2=2*_.t}function yt(_){var U=o();if(_.abs().dlShiftTo(this.m.t,U),U.divRemTo(this.m,null,U),_.s<0&&U.compareTo(f.ZERO)>0)this.m.subTo(U,U);return U}function E(_){var U=o();return _.copyTo(U),this.reduce(U),U}function D(_){while(_.t<=this.mt2)_.data[_.t++]=0;for(var U=0;U<this.m.t;++U){var x=_.data[U]&32767,q=x*this.mpl+((x*this.mph+(_.data[U]>>15)*this.mpl&this.um)<<15)&_.DM;x=U+this.m.t,_.data[x]+=this.m.am(0,q,_,U,0,this.m.t);while(_.data[x]>=_.DV)_.data[x]-=_.DV,_.data[++x]++}if(_.clamp(),_.drShiftTo(this.m.t,_),_.compareTo(this.m)>=0)_.subTo(this.m,_)}function k(_,U){_.squareTo(U),this.reduce(U)}function y(_,U,x){_.multiplyTo(U,x),this.reduce(x)}Rt.prototype.convert=yt,Rt.prototype.revert=E,Rt.prototype.reduce=D,Rt.prototype.mulTo=y,Rt.prototype.sqrTo=k;function b(){return(this.t>0?this.data[0]&1:this.s)==0}function F(_,U){if(_>4294967295||_<1)return f.ONE;var x=o(),q=o(),Y=U.convert(this),$=R(_)-1;Y.copyTo(x);while(--$>=0)if(U.sqrTo(x,q),(_&1<<$)>0)U.mulTo(q,Y,x);else{var st=x;x=q,q=st}return U.revert(x)}function M(_,U){var x;if(_<256||U.isEven())x=new ut(U);else x=new Rt(U);return this.exp(_,x)}f.prototype.copyTo=g,f.prototype.fromInt=l,f.prototype.fromString=I,f.prototype.clamp=N,f.prototype.dlShiftTo=O,f.prototype.drShiftTo=K,f.prototype.lShiftTo=G,f.prototype.rShiftTo=H,f.prototype.subTo=j,f.prototype.multiplyTo=z,f.prototype.squareTo=Z,f.prototype.divRemTo=tt,f.prototype.invDigit=et,f.prototype.isEven=b,f.prototype.exp=F,f.prototype.toString=L,f.prototype.negate=v,f.prototype.abs=h,f.prototype.compareTo=u,f.prototype.bitLength=V,f.prototype.mod=rt,f.prototype.modPowInt=M,f.ZERO=S(0),f.ONE=S(1);function W(){var _=o();return this.copyTo(_),_}function nt(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;else if(this.t==0)return-1}else if(this.t==1)return this.data[0];else if(this.t==0)return 0;return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]}function ct(){return this.t==0?this.s:this.data[0]<<24>>24}function P(){return this.t==0?this.s:this.data[0]<<16>>16}function at(_){return Math.floor(Math.LN2*this.DB/Math.log(_))}function ft(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}function Ct(_){if(_==null)_=10;if(this.signum()==0||_<2||_>36)return"0";var U=this.chunkSize(_),x=Math.pow(_,U),q=S(x),Y=o(),$=o(),st="";this.divRemTo(q,Y,$);while(Y.signum()>0)st=(x+$.intValue()).toString(_).substr(1)+st,Y.divRemTo(q,Y,$);return $.intValue().toString(_)+st}function ot(_,U){if(this.fromInt(0),U==null)U=10;var x=this.chunkSize(U),q=Math.pow(U,x),Y=!1,$=0,st=0;for(var it=0;it<_.length;++it){var gt=A(_,it);if(gt<0){if(_.charAt(it)=="-"&&this.signum()==0)Y=!0;continue}if(st=U*st+gt,++$>=x)this.dMultiply(q),this.dAddOffset(st,0),$=0,st=0}if($>0)this.dMultiply(Math.pow(U,$)),this.dAddOffset(st,0);if(Y)f.ZERO.subTo(this,this)}function bt(_,U,x){if(typeof U=="number")if(_<2)this.fromInt(1);else{if(this.fromNumber(_,x),!this.testBit(_-1))this.bitwiseTo(f.ONE.shiftLeft(_-1),Gt,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(U))if(this.dAddOffset(2,0),this.bitLength()>_)this.subTo(f.ONE.shiftLeft(_-1),this)}else{var q=[],Y=_&7;if(q.length=(_>>3)+1,U.nextBytes(q),Y>0)q[0]&=(1<<Y)-1;else q[0]=0;this.fromString(q,256)}}function Kt(){var _=this.t,U=[];U[0]=this.s;var x=this.DB-_*this.DB%8,q,Y=0;if(_-- >0){if(x<this.DB&&(q=this.data[_]>>x)!=(this.s&this.DM)>>x)U[Y++]=q|this.s<<this.DB-x;while(_>=0){if(x<8)q=(this.data[_]&(1<<x)-1)<<8-x,q|=this.data[--_]>>(x+=this.DB-8);else if(q=this.data[_]>>(x-=8)&255,x<=0)x+=this.DB,--_;if((q&128)!=0)q|=-256;if(Y==0&&(this.s&128)!=(q&128))++Y;if(Y>0||q!=this.s)U[Y++]=q}}return U}function Dt(_){return this.compareTo(_)==0}function Ut(_){return this.compareTo(_)<0?this:_}function wt(_){return this.compareTo(_)>0?this:_}function Nt(_,U,x){var q,Y,$=Math.min(_.t,this.t);for(q=0;q<$;++q)x.data[q]=U(this.data[q],_.data[q]);if(_.t<this.t){Y=_.s&this.DM;for(q=$;q<this.t;++q)x.data[q]=U(this.data[q],Y);x.t=this.t}else{Y=this.s&this.DM;for(q=$;q<_.t;++q)x.data[q]=U(Y,_.data[q]);x.t=_.t}x.s=U(this.s,_.s),x.clamp()}function Ot(_,U){return _&U}function ae(_){var U=o();return this.bitwiseTo(_,Ot,U),U}function Gt(_,U){return _|U}function le(_){var U=o();return this.bitwiseTo(_,Gt,U),U}function he(_,U){return _^U}function ye(_){var U=o();return this.bitwiseTo(_,he,U),U}function de(_,U){return _&~U}function Ae(_){var U=o();return this.bitwiseTo(_,de,U),U}function Re(){var _=o();for(var U=0;U<this.t;++U)_.data[U]=this.DM&~this.data[U];return _.t=this.t,_.s=~this.s,_}function ke(_){var U=o();if(_<0)this.rShiftTo(-_,U);else this.lShiftTo(_,U);return U}function Ge(_){var U=o();if(_<0)this.lShiftTo(-_,U);else this.rShiftTo(_,U);return U}function je(_){if(_==0)return-1;var U=0;if((_&65535)==0)_>>=16,U+=16;if((_&255)==0)_>>=8,U+=8;if((_&15)==0)_>>=4,U+=4;if((_&3)==0)_>>=2,U+=2;if((_&1)==0)++U;return U}function $e(){for(var _=0;_<this.t;++_)if(this.data[_]!=0)return _*this.DB+je(this.data[_]);if(this.s<0)return this.t*this.DB;return-1}function or(_){var U=0;while(_!=0)_&=_-1,++U;return U}function Ar(){var _=0,U=this.s&this.DM;for(var x=0;x<this.t;++x)_+=or(this.data[x]^U);return _}function Ft(_){var U=Math.floor(_/this.DB);if(U>=this.t)return this.s!=0;return(this.data[U]&1<<_%this.DB)!=0}function qt(_,U){var x=f.ONE.shiftLeft(_);return this.bitwiseTo(x,U,x),x}function Ht(_){return this.changeBit(_,Gt)}function jt(_){return this.changeBit(_,de)}function Qt(_){return this.changeBit(_,he)}function zt(_,U){var x=0,q=0,Y=Math.min(_.t,this.t);while(x<Y)q+=this.data[x]+_.data[x],U.data[x++]=q&this.DM,q>>=this.DB;if(_.t<this.t){q+=_.s;while(x<this.t)q+=this.data[x],U.data[x++]=q&this.DM,q>>=this.DB;q+=this.s}else{q+=this.s;while(x<_.t)q+=_.data[x],U.data[x++]=q&this.DM,q>>=this.DB;q+=_.s}if(U.s=q<0?-1:0,q>0)U.data[x++]=q;else if(q<-1)U.data[x++]=this.DV+q;U.t=x,U.clamp()}function Pt(_){var U=o();return this.addTo(_,U),U}function Yt(_){var U=o();return this.subTo(_,U),U}function Xt(_){var U=o();return this.multiplyTo(_,U),U}function Wt(_){var U=o();return this.divRemTo(_,U,null),U}function Zt(_){var U=o();return this.divRemTo(_,null,U),U}function $t(_){var U=o(),x=o();return this.divRemTo(_,U,x),[U,x]}function Jt(_){this.data[this.t]=this.am(0,_-1,this,0,0,this.t),++this.t,this.clamp()}function te(_,U){if(_==0)return;while(this.t<=U)this.data[this.t++]=0;this.data[U]+=_;while(this.data[U]>=this.DV){if(this.data[U]-=this.DV,++U>=this.t)this.data[this.t++]=0;++this.data[U]}}function kt(){}function xt(_){return _}function Ka(_,U,x){_.multiplyTo(U,x)}function Va(_,U){_.squareTo(U)}kt.prototype.convert=xt,kt.prototype.revert=xt,kt.prototype.mulTo=Ka,kt.prototype.sqrTo=Va;function xa(_){return this.exp(_,new kt)}function Ma(_,U,x){var q=Math.min(this.t+_.t,U);x.s=0,x.t=q;while(q>0)x.data[--q]=0;var Y;for(Y=x.t-this.t;q<Y;++q)x.data[q+this.t]=this.am(0,_.data[q],x,q,0,this.t);for(Y=Math.min(_.t,U);q<Y;++q)this.am(0,_.data[q],x,q,0,U-q);x.clamp()}function Oa(_,U,x){--U;var q=x.t=this.t+_.t-U;x.s=0;while(--q>=0)x.data[q]=0;for(q=Math.max(U-this.t,0);q<_.t;++q)x.data[this.t+q-U]=this.am(U-q,_.data[q],x,0,0,this.t+q-U);x.clamp(),x.drShiftTo(1,x)}function Je(_){this.r2=o(),this.q3=o(),f.ONE.dlShiftTo(2*_.t,this.r2),this.mu=this.r2.divide(_),this.m=_}function Ga(_){if(_.s<0||_.t>2*this.m.t)return _.mod(this.m);else if(_.compareTo(this.m)<0)return _;else{var U=o();return _.copyTo(U),this.reduce(U),U}}function Fa(_){return _}function qa(_){if(_.drShiftTo(this.m.t-1,this.r2),_.t>this.m.t+1)_.t=this.m.t+1,_.clamp();this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while(_.compareTo(this.r2)<0)_.dAddOffset(1,this.m.t+1);_.subTo(this.r2,_);while(_.compareTo(this.m)>=0)_.subTo(this.m,_)}function Ha(_,U){_.squareTo(U),this.reduce(U)}function ja(_,U,x){_.multiplyTo(U,x),this.reduce(x)}Je.prototype.convert=Ga,Je.prototype.revert=Fa,Je.prototype.reduce=qa,Je.prototype.mulTo=ja,Je.prototype.sqrTo=Ha;function Qa(_,U){var x=_.bitLength(),q,Y=S(1),$;if(x<=0)return Y;else if(x<18)q=1;else if(x<48)q=3;else if(x<144)q=4;else if(x<768)q=5;else q=6;if(x<8)$=new ut(U);else if(U.isEven())$=new Je(U);else $=new Rt(U);var st=[],it=3,gt=q-1,ee=(1<<q)-1;if(st[1]=$.convert(this),q>1){var Ee=o();$.sqrTo(st[1],Ee);while(it<=ee)st[it]=o(),$.mulTo(Ee,st[it-2],st[it]),it+=2}var Ce=_.t-1,Le,Ir=!0,ge=o(),Be;x=R(_.data[Ce])-1;while(Ce>=0){if(x>=gt)Le=_.data[Ce]>>x-gtⅇelse if(Le=(_.data[Ce]&(1<<x+1)-1)<<gt-x,Ce>0)Le|=_.data[Ce-1]>>this.DB+x-gt;it=q;while((Le&1)==0)Le>>=1,--it;if((x-=it)<0)x+=this.DB,--Ce;if(Ir)st[Le].copyTo(Y),Ir=!1;else{while(it>1)$.sqrTo(Y,ge),$.sqrTo(ge,Y),it-=2;if(it>0)$.sqrTo(Y,ge);else Be=Y,Y=ge,ge=Be;$.mulTo(ge,st[Le],Y)}while(Ce>=0&&(_.data[Ce]&1<<x)==0)if($.sqrTo(Y,ge),Be=Y,Y=ge,ge=Be,--x<0)x=this.DB-1,--Ce}return $.revert(Y)}function za(_){var U=this.s<0?this.negate():this.clone(),x=_.s<0?_.negate():_.clone();if(U.compareTo(x)<0){var q=U;U=x,x=q}var Y=U.getLowestSetBit(),$=x.getLowestSetBit();if($<0)return U;if(Y<$)$=Y;if($>0)U.rShiftTo($,U),x.rShiftTo($,x);while(U.signum()>0){if((Y=U.getLowestSetBit())>0)U.rShiftTo(Y,U);if((Y=x.getLowestSetBit())>0)x.rShiftTo(Y,x);if(U.compareTo(x)>=0)U.subTo(x,U),U.rShiftTo(1,U);else x.subTo(U,x),x.rShiftTo(1,x)}if($>0)x.lShiftTo($,x);return x}function Pa(_){if(_<=0)return 0;var U=this.DV%_,x=this.s<0?_-1:0;if(this.t>0)if(U==0)x=this.data[0]%_;else for(var q=this.t-1;q>=0;--q)x=(U*x+this.data[q])%_;return x}function Ya(_){var U=_.isEven();if(this.isEven()&&U||_.signum()==0)return f.ZERO;var x=_.clone(),q=this.clone(),Y=S(1),$=S(0),st=S(0),it=S(1);while(x.signum()!=0){while(x.isEven()){if(x.rShiftTo(1,x),U){if(!Y.isEven()||!$.isEven())Y.addTo(this,Y),$.subTo(_,$);Y.rShiftTo(1,Y)}else if(!$.isEven())$.subTo(_,$);$.rShiftTo(1,$)}while(q.isEven()){if(q.rShiftTo(1,q),U){if(!st.isEven()||!it.isEven())st.addTo(this,st),it.subTo(_,it);st.rShiftTo(1,st)}else if(!it.isEven())it.subTo(_,it);it.rShiftTo(1,it)}if(x.compareTo(q)>=0){if(x.subTo(q,x),U)Y.subTo(st,Y);$.subTo(it,$)}else{if(q.subTo(x,q),U)st.subTo(Y,st);it.subTo($,it)}}if(q.compareTo(f.ONE)!=0)return f.ZERO;if(it.compareTo(_)>=0)return it.subtract(_);if(it.signum()<0)it.addTo(_,it);else return it;if(it.signum()<0)return it.add(_);else return it}var Ie=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],Xa=67108864/Ie[Ie.length-1];function Wa(_){var U,x=this.abs();if(x.t==1&&x.data[0]<=Ie[Ie.length-1]){for(U=0;U<Ie.length;++U)if(x.data[0]==Ie[U])return!0;return!1}if(x.isEven())return!1;U=1;while(U<Ie.length){var q=Ie[U],Y=U+1;while(Y<Ie.length&&q<Xa)q*=Ie[Y++];q=x.modInt(q);while(U<Y)if(q%Ie[U++]==0)return!1}return x.millerRabin(_)}function Za(_){var U=this.subtract(f.ONE),x=U.getLowestSetBit();if(x<=0)return!1;var q=U.shiftRight(x),Y=$a(),$;for(var st=0;st<_;++st){do $=new f(this.bitLength(),Y);while($.compareTo(f.ONE)<=0||$.compareTo(U)>=0);var it=$.modPow(q,this);if(it.compareTo(f.ONE)!=0&&it.compareTo(U)!=0){var gt=1;while(gt++<x&&it.compareTo(U)!=0)if(it=it.modPowInt(2,this),it.compareTo(f.ONE)==0)return!1;if(it.compareTo(U)!=0)return!1}}return!0}function $a(){return{nextBytes:function(_){for(var U=0;U<_.length;++U)_[U]=Math.floor(Math.random()*256)}}}f.prototype.chunkSize=at,f.prototype.toRadix=Ct,f.prototype.fromRadix=ot,f.prototype.fromNumber=bt,f.prototype.bitwiseTo=Nt,f.prototype.changeBit=qt,f.prototype.addTo=zt,f.prototype.dMultiply=Jt,f.prototype.dAddOffset=te,f.prototype.multiplyLowerTo=Ma,f.prototype.multiplyUpperTo=Oa,f.prototype.modInt=Pa,f.prototype.millerRabin=Za,f.prototype.clone=W,f.prototype.intValue=nt,f.prototype.byteValue=ct,f.prototype.shortValue=P,f.prototype.signum=ft,f.prototype.toByteArray=Kt,f.prototype.equals=Dt,f.prototype.min=Ut,f.prototype.max=wt,f.prototype.and=ae,f.prototype.or=le,f.prototype.xor=ye,f.prototype.andNot=Ae,f.prototype.not=Re,f.prototype.shiftLeft=ke,f.prototype.shiftRight=Ge,f.prototype.getLowestSetBit=$e,f.prototype.bitCount=Ar,f.prototype.testBit=Ft,f.prototype.setBit=Ht,f.prototype.clearBit=jt,f.prototype.flipBit=Qt,f.prototype.add=Pt,f.prototype.subtract=Yt,f.prototype.multiply=Xt,f.prototype.divide=Wt,f.prototype.remainder=Zt,f.prototype.divideAndRemainder=$t,f.prototype.modPow=Qa,f.prototype.modInverse=Ya,f.prototype.pow=xa,f.prototype.gcd=za,f.prototype.isProbablePrime=Wa}),Cr=lt((r,n)=>{var e=pt();Me(),Tt();var t=n.exports=e.sha1=e.sha1||{};e.md.sha1=e.md.algorithms.sha1=t,t.create=function(){if(!c)f();var s=null,a=e.util.createBuffer(),C=Array(80),p={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return p.start=function(){p.messageLength=0,p.fullMessageLength=p.messageLength64=[];var m=p.messageLengthSize/4;for(var w=0;w<m;++w)p.fullMessageLength.push(0);return a=e.util.createBuffer(),s={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},p},p.start(),p.update=function(m,w){if(w==="utf8")m=e.util.encodeUtf8(m);var B=m.length;p.messageLength+=B,B=[B/4294967296>>>0,B>>>0];for(var d=p.fullMessageLength.length-1;d>=0;--d)p.fullMessageLength[d]+=B[1],B[1]=B[0]+(p.fullMessageLength[d]/4294967296>>>0),p.fullMessageLength[d]=p.fullMessageLength[d]>>>0,B[0]=B[1]/4294967296>>>0;if(a.putBytes(m),o(s,C,a),a.read>2048||a.length()===0)a.compact();return p},p.digest=function(){var m=e.util.createBuffer();m.putBytes(a.bytes());var w=p.fullMessageLength[p.fullMessageLength.length-1]+p.messageLengthSize,B=w&p.blockLength-1;m.putBytes(i.substr(0,p.blockLength-B));var d,T,A=p.fullMessageLength[0]*8;for(var g=0;g<p.fullMessageLength.length-1;++g)d=p.fullMessageLength[g+1]*8,T=d/4294967296>>>0,A+=T,m.putInt32(A>>>0),A=d>>>0;m.putInt32(A);var l={h0:s.h0,h1:s.h1,h2:s.h2,h3:s.h3,h4:s.h4};o(l,C,m);var S=e.util.createBuffer();return S.putInt32(l.h0),S.putInt32(l.h1),S.putInt32(l.h2),S.putInt32(l.h3),S.putInt32(l.h4),S},p};var i=null,c=!1;function f(){i=String.fromCharCode(128),i+=e.util.fillString(String.fromCharCode(0),64),c=!0}function o(s,a,C){var p,m,w,B,d,T,A,g,l=C.length();while(l>=64){m=s.h0,w=s.h1,B=s.h2,d=s.h3,T=s.h4;for(g=0;g<16;++g)p=C.getInt32(),a[g]=p,A=d^w&(B^d),p=(m<<5|m>>>27)+A+T+1518500249+p,T=d,d=B,B=(w<<30|w>>>2)>>>0,w=m,m=p;for(;g<20;++g)p=a[g-3]^a[g-8]^a[g-14]^a[g-16],p=p<<1|p>>>31,a[g]=p,A=d^w&(B^d),p=(m<<5|m>>>27)+A+T+1518500249+p,T=d,d=B,B=(w<<30|w>>>2)>>>0,w=m,m=p;for(;g<32;++g)p=a[g-3]^a[g-8]^a[g-14]^a[g-16],p=p<<1|p>>>31,a[g]=p,A=w^B^d,p=(m<<5|m>>>27)+A+T+1859775393+p,T=d,d=B,B=(w<<30|w>>>2)>>>0,w=m,m=p;for(;g<40;++g)p=a[g-6]^a[g-16]^a[g-28]^a[g-32],p=p<<2|p>>>30,a[g]=p,A=w^B^d,p=(m<<5|m>>>27)+A+T+1859775393+p,T=d,d=B,B=(w<<30|w>>>2)>>>0,w=m,m=p;for(;g<60;++g)p=a[g-6]^a[g-16]^a[g-28]^a[g-32],p=p<<2|p>>>30,a[g]=p,A=w&B|d&(w^B),p=(m<<5|m>>>27)+A+T+2400959708+p,T=d,d=B,B=(w<<30|w>>>2)>>>0,w=m,m=p;for(;g<80;++g)p=a[g-6]^a[g-16]^a[g-28]^a[g-32],p=p<<2|p>>>30,a[g]=p,A=w^B^d,p=(m<<5|m>>>27)+A+T+3395469782+p,T=d,d=B,B=(w<<30|w>>>2)>>>0,w=m,m=p;s.h0=s.h0+m|0,s.h1=s.h1+w|0,s.h2=s.h2+B|0,s.h3=s.h3+d|0,s.h4=s.h4+T|0,l-=64}}}),aa=lt((r,n)=>{var e=pt();Tt(),we(),Cr();var t=n.exports=e.pkcs1=e.pkcs1||{};t.encode_rsa_oaep=function(c,f,o){var s,a,C,p;if(typeof o==="string")s=o,a=arguments[3]||void 0,C=arguments[4]||void 0;else if(o){if(s=o.label||void 0,a=o.seed||void 0,C=o.md||void 0,o.mgf1&&o.mgf1.md)p=o.mgf1.md}if(!C)C=e.md.sha1.create();else C.start();if(!p)p=C;var m=Math.ceil(c.n.bitLength()/8),w=m-2*C.digestLength-2;if(f.length>w){var B=Error("RSAES-OAEP input message length is too long.");throw B.length=f.length,B.maxLength=w,B}if(!s)s="";C.update(s,"raw");var d=C.digest(),T="",A=w-f.length;for(var g=0;g<A;g++)T+="\x00";var l=d.getBytes()+T+"\x01"+f;if(!a)a=e.random.getBytes(C.digestLength);else if(a.length!==C.digestLength){var B=Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw B.seedLength=a.length,B.digestLength=C.digestLength,B}var S=i(a,m-C.digestLength-1,p),I=e.util.xorBytes(l,S,l.length),N=i(I,C.digestLength,p),L=e.util.xorBytes(a,N,a.length);return"\x00"+L+I},t.decode_rsa_oaep=function(c,f,o){var s,a,C;if(typeof o==="string")s=o,a=arguments[3]||void 0;else if(o){if(s=o.label||void 0,a=o.md||void 0,o.mgf1&&o.mgf1.md)C=o.mgf1.md}var p=Math.ceil(c.n.bitLength()/8);if(f.length!==p){var I=Error("RSAES-OAEP encoded message length is invalid.");throw I.length=f.length,I.expectedLength=p,I}if(a===void 0)a=e.md.sha1.create();else a.start();if(!C)C=a;if(p<2*a.digestLength+2)throw Error("RSAES-OAEP key is too short for the hash function.");if(!s)s="";a.update(s,"raw");var m=a.digest().getBytes(),w=f.charAt(0),B=f.substring(1,a.digestLength+1),d=f.substring(1+a.digestLength),T=i(d,a.digestLength,C),A=e.util.xorBytes(B,T,B.length),g=i(A,p-a.digestLength-1,C),l=e.util.xorBytes(d,g,d.length),S=l.substring(0,a.digestLength),I=w!=="\x00";for(var N=0;N<a.digestLength;++N)I|=m.charAt(N)!==S.charAt(N);var L=1,v=a.digestLength;for(var h=a.digestLength;h<l.length;h++){var u=l.charCodeAt(h),R=u&1^1,V=L?65534:0;I|=u&V,L=L&R,v+=L}if(I||l.charCodeAt(v)!==1)throw Error("Invalid RSAES-OAEP padding.");return l.substring(v+1)};function i(c,f,o){if(!o)o=e.md.sha1.create();var s="",a=Math.ceil(f/o.digestLength);for(var C=0;C<a;++C){var p=String.fromCharCode(C>>24&255,C>>16&255,C>>8&255,C&255);o.start(),o.update(c+p),s+=o.digest().getBytes()}return s.substring(0,f)}}),sa=lt((r,n)=>{var e=pt();Tt(),$r(),we(),function(){if(e.prime){n.exports=e.prime;return}var t=n.exports=e.prime=e.prime||{},i=e.jsbn.BigInteger,c=[6,4,2,4,2,4,6,2],f=new i(null);f.fromInt(30);var o=function(B,d){return B|d};t.generateProbablePrime=function(B,d,T){if(typeof d==="function")T=d,d={};d=d||{};var A=d.algorithm||"PRIMEINC";if(typeof A==="string")A={name:A};A.options=A.options||{};var g=d.prng||e.random,l={nextBytes:function(S){var I=g.getBytesSync(S.length);for(var N=0;N<S.length;++N)S[N]=I.charCodeAt(N)}};if(A.name==="PRIMEINC")return s(B,l,A.options,T);throw Error("Invalid prime generation algorithm: "+A.name)};function s(B,d,T,A){if("workers"in T)return p(B,d,T,A);return a(B,d,T,A)}function a(B,d,T,A){var g=m(B,d),l=0,S=w(g.bitLength());if("millerRabinTests"in T)S=T.millerRabinTests;var I=10;if("maxBlockTime"in T)I=T.maxBlockTime;C(g,B,d,l,S,I,A)}function C(B,d,T,A,g,l,S){var I=+new Date;do{if(B.bitLength()>d)B=m(d,T);if(B.isProbablePrime(g))return S(null,B);B.dAddOffset(c[A++%8],0)}while(l<0||+new Date-I<l);e.util.setImmediate(function(){C(B,d,T,A,g,l,S)})}function p(B,d,T,A){if(typeof Worker>"u")return a(B,d,T,A);var g=m(B,d),l=T.workers,S=T.workLoad||100,I=S*30/8,N=T.workerScript||"forge/prime.worker.js";if(l===-1)return e.util.estimateCores(function(v,h){if(v)h=2;l=h-1,L()});L();function L(){l=Math.max(1,l);var v=[];for(var h=0;h<l;++h)v[h]=new Worker(N);var u=l;for(var h=0;h<l;++h)v[h].addEventListener("message",V);var R=!1;function V(O){if(R)return;--u;var K=O.data;if(K.found){for(var G=0;G<v.length;++G)v[G].terminate();return R=!0,A(null,new i(K.prime,16))}if(g.bitLength()>B)g=m(B,d);var H=g.toString(16);O.target.postMessage({hex:H,workLoad:S}),g.dAddOffset(I,0)}}}function m(B,d){var T=new i(B,d),A=B-1;if(!T.testBit(A))T.bitwiseTo(i.ONE.shiftLeft(A),o,T);return T.dAddOffset(31-T.mod(f).byteValue(),0),T}function w(B){if(B<=100)return 27;if(B<=150)return 18;if(B<=200)return 15;if(B<=250)return 12;if(B<=300)return 9;if(B<=350)return 8;if(B<=400)return 7;if(B<=500)return 6;if(B<=600)return 5;if(B<=800)return 4;if(B<=1250)return 3;return 2}}()}),Jr=lt((r,n)=>{var e=pt();if(Ue(),$r(),Pe(),aa(),sa(),we(),Tt(),typeof t>"u")t=e.jsbn.BigInteger;var t,i=e.util.isNodejs?Wr("crypto"):null,c=e.asn1,f=e.util;e.pki=e.pki||{},n.exports=e.pki.rsa=e.rsa=e.rsa||{};var o=e.pki,s=[6,4,2,4,2,4,6,2],a={name:"PrivateKeyInfo",tagClass:c.Class.UNIVERSAL,type:c.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:c.Class.UNIVERSAL,type:c.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:c.Class.UNIVERSAL,type:c.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:c.Class.UNIVERSAL,type:c.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:c.Class.UNIVERSAL,type:c.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},C={name:"RSAPrivateKey",tagClass:c.Class.UNIVERSAL,type:c.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:c.Class.UNIVERSAL,type:c.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:c.Class.UNIVERSAL,type:c.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:c.Class.UNIVERSAL,type:c.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:c.Class.UNIVERSAL,type:c.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:c.Class.UNIVERSAL,type:c.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:c.Class.UNIVERSAL,type:c.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:c.Class.UNIVERSAL,type:c.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:c.Class.UNIVERSAL,type:c.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:c.Class.UNIVERSAL,type:c.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},p={name:"RSAPublicKey",tagClass:c.Class.UNIVERSAL,type:c.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:c.Class.UNIVERSAL,type:c.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:c.Class.UNIVERSAL,type:c.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},m=e.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:c.Class.UNIVERSAL,type:c.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:c.Class.UNIVERSAL,type:c.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:c.Class.UNIVERSAL,type:c.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:c.Class.UNIVERSAL,type:c.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:c.Class.UNIVERSAL,type:c.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},w={name:"DigestInfo",tagClass:c.Class.UNIVERSAL,type:c.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:c.Class.UNIVERSAL,type:c.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:c.Class.UNIVERSAL,type:c.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:c.Class.UNIVERSAL,type:c.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:c.Class.UNIVERSAL,type:c.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},B=function(h){var u;if(h.algorithm in o.oids)u=o.oids[h.algorithm];else{var R=Error("Unknown message digest algorithm.");throw R.algorithm=h.algorithm,R}var V=c.oidToDer(u).getBytes(),O=c.create(c.Class.UNIVERSAL,c.Type.SEQUENCE,!0,[]),K=c.create(c.Class.UNIVERSAL,c.Type.SEQUENCE,!0,[]);K.value.push(c.create(c.Class.UNIVERSAL,c.Type.OID,!1,V)),K.value.push(c.create(c.Class.UNIVERSAL,c.Type.NULL,!1,""));var G=c.create(c.Class.UNIVERSAL,c.Type.OCTETSTRING,!1,h.digest().getBytes());return O.value.push(K),O.value.push(G),c.toDer(O).getBytes()},d=function(h,u,R){if(R)return h.modPow(u.e,u.n);if(!u.p||!u.q)return h.modPow(u.d,u.n);if(!u.dP)u.dP=u.d.mod(u.p.subtract(t.ONE));if(!u.dQ)u.dQ=u.d.mod(u.q.subtract(t.ONE));if(!u.qInv)u.qInv=u.q.modInverse(u.p);var V;do V=new t(e.util.bytesToHex(e.random.getBytes(u.n.bitLength()/8)),16);while(V.compareTo(u.n)>=0||!V.gcd(u.n).equals(t.ONE));h=h.multiply(V.modPow(u.e,u.n)).mod(u.n);var O=h.mod(u.p).modPow(u.dP,u.p),K=h.mod(u.q).modPow(u.dQ,u.q);while(O.compareTo(K)<0)O=O.add(u.p);var G=O.subtract(K).multiply(u.qInv).mod(u.p).multiply(u.q).add(K);return G=G.multiply(V.modInverse(u.n)).mod(u.n),G};o.rsa.encrypt=function(h,u,R){var V=R,O,K=Math.ceil(u.n.bitLength()/8);if(R!==!1&&R!==!0)V=R===2,O=T(h,u,R);else O=e.util.createBuffer(),O.putBytes(h);var G=new t(O.toHex(),16),H=d(G,u,V),j=H.toString(16),z=e.util.createBuffer(),Z=K-Math.ceil(j.length/2);while(Z>0)z.putByte(0),--Z;return z.putBytes(e.util.hexToBytes(j)),z.getBytes()},o.rsa.decrypt=function(h,u,R,V){var O=Math.ceil(u.n.bitLength()/8);if(h.length!==O){var K=Error("Encrypted message length is invalid.");throw K.length=h.length,K.expected=O,K}var G=new t(e.util.createBuffer(h).toHex(),16);if(G.compareTo(u.n)>=0)throw Error("Encrypted message is invalid.");var H=d(G,u,R),j=H.toString(16),z=e.util.createBuffer(),Z=O-Math.ceil(j.length/2);while(Z>0)z.putByte(0),--Z;if(z.putBytes(e.util.hexToBytes(j)),V!==!1)return A(z.getBytes(),u,R);return z.getBytes()},o.rsa.createKeyPairGenerationState=function(h,u,R){if(typeof h==="string")h=parseInt(h,10);h=h||2048,R=R||{};var V=R.prng||e.random,O={nextBytes:function(H){var j=V.getBytesSync(H.length);for(var z=0;z<H.length;++z)H[z]=j.charCodeAt(z)}},K=R.algorithm||"PRIMEINC",G;if(K==="PRIMEINC")G={algorithm:K,state:0,bits:h,rng:O,eInt:u||65537,e:new t(null),p:null,q:null,qBits:h>>1,pBits:h-(h>>1),pqState:0,num:null,keys:null},G.e.fromInt(G.eInt);else throw Error("Invalid key generation algorithm: "+K);return G},o.rsa.stepKeyPairGenerationState=function(h,u){if(!("algorithm"in h))h.algorithm="PRIMEINC";var R=new t(null);R.fromInt(30);var V=0,O=function(tt,rt){return tt|rt},K=+new Date,G,H=0;while(h.keys===null&&(u<=0||H<u)){if(h.state===0){var j=h.p===null?h.pBits:h.qBits,z=j-1;if(h.pqState===0){if(h.num=new t(j,h.rng),!h.num.testBit(z))h.num.bitwiseTo(t.ONE.shiftLeft(z),O,h.num);h.num.dAddOffset(31-h.num.mod(R).byteValue(),0),V=0,++h.pqState}else if(h.pqState===1)if(h.num.bitLength()>j)h.pqState=0;else if(h.num.isProbablePrime(S(h.num.bitLength())))++h.pqState;else h.num.dAddOffset(s[V++%8],0);else if(h.pqState===2)h.pqState=h.num.subtract(t.ONE).gcd(h.e).compareTo(t.ONE)===0?3:0;else if(h.pqState===3){if(h.pqState=0,h.p===null)h.p=h.num;else h.q=h.num;if(h.p!==null&&h.q!==null)++h.state;h.num=null}}else if(h.state===1){if(h.p.compareTo(h.q)<0)h.num=h.p,h.p=h.q,h.q=h.num;++h.state}else if(h.state===2)h.p1=h.p.subtract(t.ONE),h.q1=h.q.subtract(t.ONE),h.phi=h.p1.multiply(h.q1),++h.state;else if(h.state===3)if(h.phi.gcd(h.e).compareTo(t.ONE)===0)++h.state;else h.p=null,h.q=null,h.state=0;else if(h.state===4)if(h.n=h.p.multiply(h.q),h.n.bitLength()===h.bits)++h.state;else h.q=null,h.state=0;else if(h.state===5){var Z=h.e.modInverse(h.phi);h.keys={privateKey:o.rsa.setPrivateKey(h.n,h.e,Z,h.p,h.q,Z.mod(h.p1),Z.mod(h.q1),h.q.modInverse(h.p)),publicKey:o.rsa.setPublicKey(h.n,h.e)}}G=+new Date,H+=G-K,K=G}return h.keys!==null},o.rsa.generateKeyPair=function(h,u,R,V){if(arguments.length===1){if(typeof h==="object")R=h,h=void 0;else if(typeof h==="function")V=h,h=void 0}else if(arguments.length===2)if(typeof h==="number"){if(typeof u==="function")V=u,u=void 0;else if(typeof u!=="number")R=u,u=void 0}else R=h,V=u,h=void 0,u=void 0;else if(arguments.length===3)if(typeof u==="number"){if(typeof R==="function")V=R,R=void 0}else V=R,R=u,u=void 0;if(R=R||{},h===void 0)h=R.bits||2048;if(u===void 0)u=R.e||65537;if(!e.options.usePureJavaScript&&!R.prng&&h>=256&&h<=16384&&(u===65537||u===3)){if(V){if(I("generateKeyPair"))return i.generateKeyPair("rsa",{modulusLength:h,publicExponent:u,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(H,j,z){if(H)return V(H);V(null,{privateKey:o.privateKeyFromPem(z),publicKey:o.publicKeyFromPem(j)})});if(N("generateKey")&&N("exportKey"))return f.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:h,publicExponent:v(u),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(H){return f.globalScope.crypto.subtle.exportKey("pkcs8",H.privateKey)}).then(void 0,function(H){V(H)}).then(function(H){if(H){var j=o.privateKeyFromAsn1(c.fromDer(e.util.createBuffer(H)));V(null,{privateKey:j,publicKey:o.setRsaPublicKey(j.n,j.e)})}});if(L("generateKey")&&L("exportKey")){var O=f.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:h,publicExponent:v(u),hash:{name:"SHA-256"}},!0,["sign","verify"]);O.oncomplete=function(H){var j=H.target.result,z=f.globalScope.msCrypto.subtle.exportKey("pkcs8",j.privateKey);z.oncomplete=function(Z){var tt=Z.target.result,rt=o.privateKeyFromAsn1(c.fromDer(e.util.createBuffer(tt)));V(null,{privateKey:rt,publicKey:o.setRsaPublicKey(rt.n,rt.e)})},z.onerror=function(Z){V(Z)}},O.onerror=function(H){V(H)};return}}else if(I("generateKeyPairSync")){var K=i.generateKeyPairSync("rsa",{modulusLength:h,publicExponent:u,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:o.privateKeyFromPem(K.privateKey),publicKey:o.publicKeyFromPem(K.publicKey)}}}var G=o.rsa.createKeyPairGenerationState(h,u,R);if(!V)return o.rsa.stepKeyPairGenerationState(G,0),G.keys;g(G,R,V)},o.setRsaPublicKey=o.rsa.setPublicKey=function(h,u){var R={n:h,e:u};return R.encrypt=function(V,O,K){if(typeof O==="string")O=O.toUpperCase();else if(O===void 0)O="RSAES-PKCS1-V1_5";if(O==="RSAES-PKCS1-V1_5")O={encode:function(H,j,z){return T(H,j,2).getBytes()}};else if(O==="RSA-OAEP"||O==="RSAES-OAEP")O={encode:function(H,j){return e.pkcs1.encode_rsa_oaep(j,H,K)}};else if(["RAW","NONE","NULL",null].indexOf(O)!==-1)O={encode:function(H){return H}};else if(typeof O==="string")throw Error('Unsupported encryption scheme: "'+O+'".');var G=O.encode(V,R,!0);return o.rsa.encrypt(G,R,!0)},R.verify=function(V,O,K,G){if(typeof K==="string")K=K.toUpperCase();else if(K===void 0)K="RSASSA-PKCS1-V1_5";if(G===void 0)G={_parseAllDigestBytes:!0};if(!("_parseAllDigestBytes"in G))G._parseAllDigestBytes=!0;if(K==="RSASSA-PKCS1-V1_5")K={verify:function(j,z){z=A(z,R,!0);var Z=c.fromDer(z,{parseAllBytes:G._parseAllDigestBytes}),tt={},rt=[];if(!c.validate(Z,w,tt,rt)){var ut=Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw ut.errors=rt,ut}var ht=c.derToOid(tt.algorithmIdentifier);if(!(ht===e.oids.md2||ht===e.oids.md5||ht===e.oids.sha1||ht===e.oids.sha224||ht===e.oids.sha256||ht===e.oids.sha384||ht===e.oids.sha512||ht===e.oids["sha512-224"]||ht===e.oids["sha512-256"])){var ut=Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw ut.oid=ht,ut}if(ht===e.oids.md2||ht===e.oids.md5){if(!("parameters"in tt))throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.")}return j===tt.digest}};else if(K==="NONE"||K==="NULL"||K===null)K={verify:function(j,z){return z=A(z,R,!0),j===z}};var H=o.rsa.decrypt(O,R,!0,!1);return K.verify(V,H,R.n.bitLength())},R},o.setRsaPrivateKey=o.rsa.setPrivateKey=function(h,u,R,V,O,K,G,H){var j={n:h,e:u,d:R,p:V,q:O,dP:K,dQ:G,qInv:H};return j.decrypt=function(z,Z,tt){if(typeof Z==="string")Z=Z.toUpperCase();else if(Z===void 0)Z="RSAES-PKCS1-V1_5";var rt=o.rsa.decrypt(z,j,!1,!1);if(Z==="RSAES-PKCS1-V1_5")Z={decode:A};else if(Z==="RSA-OAEP"||Z==="RSAES-OAEP")Z={decode:function(ut,ht){return e.pkcs1.decode_rsa_oaep(ht,ut,tt)}};else if(["RAW","NONE","NULL",null].indexOf(Z)!==-1)Z={decode:function(ut){return ut}};else throw Error('Unsupported encryption scheme: "'+Z+'".');return Z.decode(rt,j,!1)},j.sign=function(z,Z){var tt=!1;if(typeof Z==="string")Z=Z.toUpperCase();if(Z===void 0||Z==="RSASSA-PKCS1-V1_5")Z={encode:B},tt=1;else if(Z==="NONE"||Z==="NULL"||Z===null)Z={encode:function(){return z}},tt=1;var rt=Z.encode(z,j.n.bitLength());return o.rsa.encrypt(rt,j,tt)},j},o.wrapRsaPrivateKey=function(h){return c.create(c.Class.UNIVERSAL,c.Type.SEQUENCE,!0,[c.create(c.Class.UNIVERSAL,c.Type.INTEGER,!1,c.integerToDer(0).getBytes()),c.create(c.Class.UNIVERSAL,c.Type.SEQUENCE,!0,[c.create(c.Class.UNIVERSAL,c.Type.OID,!1,c.oidToDer(o.oids.rsaEncryption).getBytes()),c.create(c.Class.UNIVERSAL,c.Type.NULL,!1,"")]),c.create(c.Class.UNIVERSAL,c.Type.OCTETSTRING,!1,c.toDer(h).getBytes())])},o.privateKeyFromAsn1=function(h){var u={},R=[];if(c.validate(h,a,u,R))h=c.fromDer(e.util.createBuffer(u.privateKey));if(u={},R=[],!c.validate(h,C,u,R)){var V=Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw V.errors=R,V}var O,K,G,H,j,z,Z,tt;return O=e.util.createBuffer(u.privateKeyModulus).toHex(),K=e.util.createBuffer(u.privateKeyPublicExponent).toHex(),G=e.util.createBuffer(u.privateKeyPrivateExponent).toHex(),H=e.util.createBuffer(u.privateKeyPrime1).toHex(),j=e.util.createBuffer(u.privateKeyPrime2).toHex(),z=e.util.createBuffer(u.privateKeyExponent1).toHex(),Z=e.util.createBuffer(u.privateKeyExponent2).toHex(),tt=e.util.createBuffer(u.privateKeyCoefficient).toHex(),o.setRsaPrivateKey(new t(O,16),new t(K,16),new t(G,16),new t(H,16),new t(j,16),new t(z,16),new t(Z,16),new t(tt,16))},o.privateKeyToAsn1=o.privateKeyToRSAPrivateKey=function(h){return c.create(c.Class.UNIVERSAL,c.Type.SEQUENCE,!0,[c.create(c.Class.UNIVERSAL,c.Type.INTEGER,!1,c.integerToDer(0).getBytes()),c.create(c.Class.UNIVERSAL,c.Type.INTEGER,!1,l(h.n)),c.create(c.Class.UNIVERSAL,c.Type.INTEGER,!1,l(h.e)),c.create(c.Class.UNIVERSAL,c.Type.INTEGER,!1,l(h.d)),c.create(c.Class.UNIVERSAL,c.Type.INTEGER,!1,l(h.p)),c.create(c.Class.UNIVERSAL,c.Type.INTEGER,!1,l(h.q)),c.create(c.Class.UNIVERSAL,c.Type.INTEGER,!1,l(h.dP)),c.create(c.Class.UNIVERSAL,c.Type.INTEGER,!1,l(h.dQ)),c.create(c.Class.UNIVERSAL,c.Type.INTEGER,!1,l(h.qInv))])},o.publicKeyFromAsn1=function(h){var u={},R=[];if(c.validate(h,m,u,R)){var V=c.derToOid(u.publicKeyOid);if(V!==o.oids.rsaEncryption){var O=Error("Cannot read public key. Unknown OID.");throw O.oid=V,O}h=u.rsaPublicKey}if(R=[],!c.validate(h,p,u,R)){var O=Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw O.errors=R,O}var K=e.util.createBuffer(u.publicKeyModulus).toHex(),G=e.util.createBuffer(u.publicKeyExponent).toHex();return o.setRsaPublicKey(new t(K,16),new t(G,16))},o.publicKeyToAsn1=o.publicKeyToSubjectPublicKeyInfo=function(h){return c.create(c.Class.UNIVERSAL,c.Type.SEQUENCE,!0,[c.create(c.Class.UNIVERSAL,c.Type.SEQUENCE,!0,[c.create(c.Class.UNIVERSAL,c.Type.OID,!1,c.oidToDer(o.oids.rsaEncryption).getBytes()),c.create(c.Class.UNIVERSAL,c.Type.NULL,!1,"")]),c.create(c.Class.UNIVERSAL,c.Type.BITSTRING,!1,[o.publicKeyToRSAPublicKey(h)])])},o.publicKeyToRSAPublicKey=function(h){return c.create(c.Class.UNIVERSAL,c.Type.SEQUENCE,!0,[c.create(c.Class.UNIVERSAL,c.Type.INTEGER,!1,l(h.n)),c.create(c.Class.UNIVERSAL,c.Type.INTEGER,!1,l(h.e))])};function T(h,u,R){var V=e.util.createBuffer(),O=Math.ceil(u.n.bitLength()/8);if(h.length>O-11){var K=Error("Message is too long for PKCS#1 v1.5 padding.");throw K.length=h.length,K.max=O-11,K}V.putByte(0),V.putByte(R);var G=O-3-h.length,H;if(R===0||R===1){H=R===0?0:255;for(var j=0;j<G;++j)V.putByte(H)}else while(G>0){var z=0,Z=e.random.getBytes(G);for(var j=0;j<G;++j)if(H=Z.charCodeAt(j),H===0)++z;else V.putByte(H);G=z}return V.putByte(0),V.putBytes(h),V}function A(h,u,R,V){var O=Math.ceil(u.n.bitLength()/8),K=e.util.createBuffer(h),G=K.getByte(),H=K.getByte();if(G!==0||R&&H!==0&&H!==1||!R&&H!=2||R&&H===0&&typeof V>"u")throw Error("Encryption block is invalid.");var j=0;if(H===0){j=O-3-V;for(var z=0;z<j;++z)if(K.getByte()!==0)throw Error("Encryption block is invalid.")}else if(H===1){j=0;while(K.length()>1){if(K.getByte()!==255){--K.read;break}++j}}else if(H===2){j=0;while(K.length()>1){if(K.getByte()===0){--K.read;break}++j}}var Z=K.getByte();if(Z!==0||j!==O-3-K.length())throw Error("Encryption block is invalid.");return K.getBytes()}function g(h,u,R){if(typeof u==="function")R=u,u={};u=u||{};var V={algorithm:{name:u.algorithm||"PRIMEINC",options:{workers:u.workers||2,workLoad:u.workLoad||100,workerScript:u.workerScript}}};if("prng"in u)V.prng=u.prng;O();function O(){K(h.pBits,function(H,j){if(H)return R(H);if(h.p=j,h.q!==null)return G(H,h.q);K(h.qBits,G)})}function K(H,j){e.prime.generateProbablePrime(H,V,j)}function G(H,j){if(H)return R(H);if(h.q=j,h.p.compareTo(h.q)<0){var z=h.p;h.p=h.q,h.q=z}if(h.p.subtract(t.ONE).gcd(h.e).compareTo(t.ONE)!==0){h.p=null,O();return}if(h.q.subtract(t.ONE).gcd(h.e).compareTo(t.ONE)!==0){h.q=null,K(h.qBits,G);return}if(h.p1=h.p.subtract(t.ONE),h.q1=h.q.subtract(t.ONE),h.phi=h.p1.multiply(h.q1),h.phi.gcd(h.e).compareTo(t.ONE)!==0){h.p=h.q=null,O();return}if(h.n=h.p.multiply(h.q),h.n.bitLength()!==h.bits){h.q=null,K(h.qBits,G);return}var Z=h.e.modInverse(h.phi);h.keys={privateKey:o.rsa.setPrivateKey(h.n,h.e,Z,h.p,h.q,Z.mod(h.p1),Z.mod(h.q1),h.q.modInverse(h.p)),publicKey:o.rsa.setPublicKey(h.n,h.e)},R(null,h.keys)}}function l(h){var u=h.toString(16);if(u[0]>="8")u="00"+u;var R=e.util.hexToBytes(u);if(R.length>1&&(R.charCodeAt(0)===0&&(R.charCodeAt(1)&128)===0||R.charCodeAt(0)===255&&(R.charCodeAt(1)&128)===128))return R.substr(1);return R}function S(h){if(h<=100)return 27;if(h<=150)return 18;if(h<=200)return 15;if(h<=250)return 12;if(h<=300)return 9;if(h<=350)return 8;if(h<=400)return 7;if(h<=500)return 6;if(h<=600)return 5;if(h<=800)return 4;if(h<=1250)return 3;return 2}function I(h){return e.util.isNodejs&&typeof i[h]==="function"}function N(h){return typeof f.globalScope<"u"&&typeof f.globalScope.crypto==="object"&&typeof f.globalScope.crypto.subtle==="object"&&typeof f.globalScope.crypto.subtle[h]==="function"}function L(h){return typeof f.globalScope<"u"&&typeof f.globalScope.msCrypto==="object"&&typeof f.globalScope.msCrypto.subtle==="object"&&typeof f.globalScope.msCrypto.subtle[h]==="function"}function v(h){var u=e.util.hexToBytes(h.toString(16)),R=new Uint8Array(u.length);for(var V=0;V<u.length;++V)R[V]=u.charCodeAt(V);return R}}),ua=lt((r,n)=>{var e=pt();if(ze(),Ue(),Zr(),Me(),Pe(),Fi(),hr(),we(),na(),Jr(),Tt(),typeof t>"u")t=e.jsbn.BigInteger;var t,i=e.asn1,c=e.pki=e.pki||{};n.exports=c.pbe=e.pbe=e.pbe||{};var f=c.oids,o={name:"EncryptedPrivateKeyInfo",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},s={name:"PBES2Algorithms",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:i.Class.UNIVERSAL,type:i.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},a={name:"pkcs-12PbeParams",tagClass:i.Class.UNIVERSAL,type:i.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:i.Class.UNIVERSAL,type:i.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:i.Class.UNIVERSAL,type:i.Type.INTEGER,constructed:!1,capture:"iterations"}]};c.encryptPrivateKeyInfo=function(B,d,T){T=T||{},T.saltSize=T.saltSize||8,T.count=T.count||2048,T.algorithm=T.algorithm||"aes128",T.prfAlgorithm=T.prfAlgorithm||"sha1";var A=e.random.getBytesSync(T.saltSize),g=T.count,l=i.integerToDer(g),S,I,N;if(T.algorithm.indexOf("aes")===0||T.algorithm==="des"){var L,v,h;switch(T.algorithm){case"aes128":S=16,L=16,v=f["aes128-CBC"],h=e.aes.createEncryptionCipher;break;case"aes192":S=24,L=16,v=f["aes192-CBC"],h=e.aes.createEncryptionCipher;break;case"aes256":S=32,L=16,v=f["aes256-CBC"],h=e.aes.createEncryptionCipher;break;case"des":S=8,L=8,v=f.desCBC,h=e.des.createEncryptionCipher;break;default:var u=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw u.algorithm=T.algorithm,u}var R="hmacWith"+T.prfAlgorithm.toUpperCase(),V=m(R),O=e.pkcs5.pbkdf2(d,A,g,S,V),K=e.random.getBytesSync(L),G=h(O);G.start(K),G.update(i.toDer(B)),G.finish(),N=G.output.getBytes();var H=w(A,l,S,R);I=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(f.pkcs5PBES2).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(f.pkcs5PBKDF2).getBytes()),H]),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(v).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,K)])])])}else if(T.algorithm==="3des"){S=24;var j=new e.util.ByteBuffer(A),O=c.pbe.generatePkcs12Key(d,j,1,g,S),K=c.pbe.generatePkcs12Key(d,j,2,g,S),G=e.des.createEncryptionCipher(O);G.start(K),G.update(i.toDer(B)),G.finish(),N=G.output.getBytes(),I=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(f["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,A),i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,l.getBytes())])])}else{var u=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw u.algorithm=T.algorithm,u}var z=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[I,i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,N)]);return z},c.decryptPrivateKeyInfo=function(B,d){var T=null,A={},g=[];if(!i.validate(B,o,A,g)){var l=Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw l.errors=g,l}var S=i.derToOid(A.encryptionOid),I=c.pbe.getCipher(S,A.encryptionParams,d),N=e.util.createBuffer(A.encryptedData);if(I.update(N),I.finish())T=i.fromDer(I.output);return T},c.encryptedPrivateKeyToPem=function(B,d){var T={type:"ENCRYPTED PRIVATE KEY",body:i.toDer(B).getBytes()};return e.pem.encode(T,{maxline:d})},c.encryptedPrivateKeyFromPem=function(B){var d=e.pem.decode(B)[0];if(d.type!=="ENCRYPTED PRIVATE KEY"){var T=Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw T.headerType=d.type,T}if(d.procType&&d.procType.type==="ENCRYPTED")throw Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return i.fromDer(d.body)},c.encryptRsaPrivateKey=function(B,d,T){if(T=T||{},!T.legacy){var A=c.wrapRsaPrivateKey(c.privateKeyToAsn1(B));return A=c.encryptPrivateKeyInfo(A,d,T),c.encryptedPrivateKeyToPem(A)}var g,l,S,I;switch(T.algorithm){case"aes128":g="AES-128-CBC",S=16,l=e.random.getBytesSync(16),I=e.aes.createEncryptionCipher;break;case"aes192":g="AES-192-CBC",S=24,l=e.random.getBytesSync(16),I=e.aes.createEncryptionCipher;break;case"aes256":g="AES-256-CBC",S=32,l=e.random.getBytesSync(16),I=e.aes.createEncryptionCipher;break;case"3des":g="DES-EDE3-CBC",S=24,l=e.random.getBytesSync(8),I=e.des.createEncryptionCipher;break;case"des":g="DES-CBC",S=8,l=e.random.getBytesSync(8),I=e.des.createEncryptionCipher;break;default:var N=Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+T.algorithm+'".');throw N.algorithm=T.algorithm,N}var L=e.pbe.opensslDeriveBytes(d,l.substr(0,8),S),v=I(L);v.start(l),v.update(i.toDer(c.privateKeyToAsn1(B))),v.finish();var h={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:g,parameters:e.util.bytesToHex(l).toUpperCase()},body:v.output.getBytes()};return e.pem.encode(h)},c.decryptRsaPrivateKey=function(B,d){var T=null,A=e.pem.decode(B)[0];if(A.type!=="ENCRYPTED PRIVATE KEY"&&A.type!=="PRIVATE KEY"&&A.type!=="RSA PRIVATE KEY"){var g=Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw g.headerType=g,g}if(A.procType&&A.procType.type==="ENCRYPTED"){var l,S;switch(A.dekInfo.algorithm){case"DES-CBC":l=8,S=e.des.createDecryptionCipher;break;case"DES-EDE3-CBC":l=24,S=e.des.createDecryptionCipher;break;case"AES-128-CBC":l=16,S=e.aes.createDecryptionCipher;break;case"AES-192-CBC":l=24,S=e.aes.createDecryptionCipher;break;case"AES-256-CBC":l=32,S=e.aes.createDecryptionCipher;break;case"RC2-40-CBC":l=5,S=function(h){return e.rc2.createDecryptionCipher(h,40)};break;case"RC2-64-CBC":l=8,S=function(h){return e.rc2.createDecryptionCipher(h,64)};break;case"RC2-128-CBC":l=16,S=function(h){return e.rc2.createDecryptionCipher(h,128)};break;default:var g=Error('Could not decrypt private key; unsupported encryption algorithm "'+A.dekInfo.algorithm+'".');throw g.algorithm=A.dekInfo.algorithm,g}var I=e.util.hexToBytes(A.dekInfo.parameters),N=e.pbe.opensslDeriveBytes(d,I.substr(0,8),l),L=S(N);if(L.start(I),L.update(e.util.createBuffer(A.body)),L.finish())T=L.output.getBytes();else return T}else T=A.body;if(A.type==="ENCRYPTED PRIVATE KEY")T=c.decryptPrivateKeyInfo(i.fromDer(T),d);else T=i.fromDer(T);if(T!==null)T=c.privateKeyFromAsn1(T);return T},c.pbe.generatePkcs12Key=function(B,d,T,A,g,l){var S,I;if(typeof l>"u"||l===null){if(!("sha1"in e.md))throw Error('"sha1" hash algorithm unavailable.');l=e.md.sha1.create()}var{digestLength:N,blockLength:L}=l,v=new e.util.ByteBuffer,h=new e.util.ByteBuffer;if(B!==null&&B!==void 0){for(I=0;I<B.length;I++)h.putInt16(B.charCodeAt(I));h.putInt16(0)}var u=h.length(),R=d.length(),V=new e.util.ByteBuffer;V.fillWithByte(T,L);var O=L*Math.ceil(R/L),K=new e.util.ByteBuffer;for(I=0;I<O;I++)K.putByte(d.at(I%R));var G=L*Math.ceil(u/L),H=new e.util.ByteBuffer;for(I=0;I<G;I++)H.putByte(h.at(I%u));var j=K;j.putBuffer(H);var z=Math.ceil(g/N);for(var Z=1;Z<=z;Z++){var tt=new e.util.ByteBuffer;tt.putBytes(V.bytes()),tt.putBytes(j.bytes());for(var rt=0;rt<A;rt++)l.start(),l.update(tt.getBytes()),tt=l.digest();var ut=new e.util.ByteBuffer;for(I=0;I<L;I++)ut.putByte(tt.at(I%N));var ht=Math.ceil(R/L)+Math.ceil(u/L),Et=new e.util.ByteBuffer;for(S=0;S<ht;S++){var _t=new e.util.ByteBuffer(j.getBytes(L)),J=511;for(I=ut.length()-1;I>=0;I--)J=J>>8,J+=ut.at(I)+_t.at(I),_t.setAt(I,J&255);Et.putBuffer(_t)}j=Et,v.putBuffer(tt)}return v.truncate(v.length()-g),v},c.pbe.getCipher=function(B,d,T){switch(B){case c.oids.pkcs5PBES2:return c.pbe.getCipherForPBES2(B,d,T);case c.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case c.oids["pbewithSHAAnd40BitRC2-CBC"]:return c.pbe.getCipherForPKCS12PBE(B,d,T);default:var A=Error("Cannot read encrypted PBE data block. Unsupported OID.");throw A.oid=B,A.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],A}},c.pbe.getCipherForPBES2=function(B,d,T){var A={},g=[];if(!i.validate(d,s,A,g)){var l=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw l.errors=g,l}if(B=i.derToOid(A.kdfOid),B!==c.oids.pkcs5PBKDF2){var l=Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw l.oid=B,l.supportedOids=["pkcs5PBKDF2"],l}if(B=i.derToOid(A.encOid),B!==c.oids["aes128-CBC"]&&B!==c.oids["aes192-CBC"]&&B!==c.oids["aes256-CBC"]&&B!==c.oids["des-EDE3-CBC"]&&B!==c.oids.desCBC){var l=Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw l.oid=B,l.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],l}var S=A.kdfSalt,I=e.util.createBuffer(A.kdfIterationCount);I=I.getInt(I.length()<<3);var N,L;switch(c.oids[B]){case"aes128-CBC":N=16,L=e.aes.createDecryptionCipher;break;case"aes192-CBC":N=24,L=e.aes.createDecryptionCipher;break;case"aes256-CBC":N=32,L=e.aes.createDecryptionCipher;break;case"des-EDE3-CBC":N=24,L=e.des.createDecryptionCipher;break;case"desCBC":N=8,L=e.des.createDecryptionCipher;break}var v=p(A.prfOid),h=e.pkcs5.pbkdf2(T,S,I,N,v),u=A.encIv,R=L(h);return R.start(u),R},c.pbe.getCipherForPKCS12PBE=function(B,d,T){var A={},g=[];if(!i.validate(d,a,A,g)){var l=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw l.errors=g,l}var S=e.util.createBuffer(A.salt),I=e.util.createBuffer(A.iterations);I=I.getInt(I.length()<<3);var N,L,v;switch(B){case c.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:N=24,L=8,v=e.des.startDecrypting;break;case c.oids["pbewithSHAAnd40BitRC2-CBC"]:N=5,L=8,v=function(O,K){var G=e.rc2.createDecryptionCipher(O,40);return G.start(K,null),G};break;default:var l=Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw l.oid=B,l}var h=p(A.prfOid),u=c.pbe.generatePkcs12Key(T,S,1,I,N,h);h.start();var R=c.pbe.generatePkcs12Key(T,S,2,I,L,h);return v(u,R)},c.pbe.opensslDeriveBytes=function(B,d,T,A){if(typeof A>"u"||A===null){if(!("md5"in e.md))throw Error('"md5" hash algorithm unavailable.');A=e.md.md5.create()}if(d===null)d="";var g=[C(A,B+d)];for(var l=16,S=1;l<T;++S,l+=16)g.push(C(A,g[S-1]+B+d));return g.join("").substr(0,T)};function C(B,d){return B.start().update(d).digest().getBytes()}function p(B){var d;if(!B)d="hmacWithSHA1";else if(d=c.oids[i.derToOid(B)],!d){var T=Error("Unsupported PRF OID.");throw T.oid=B,T.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],T}return m(d)}function m(B){var d=e.md;switch(B){case"hmacWithSHA224":d=e.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":B=B.substr(8).toLowerCase();break;default:var T=Error("Unsupported PRF algorithm.");throw T.algorithm=B,T.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],T}if(!d||!(B in d))throw Error("Unknown hash algorithm: "+B);return d[B].create()}function w(B,d,T,A){var g=i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OCTETSTRING,!1,B),i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,d.getBytes())]);if(A!=="hmacWithSHA1")g.value.push(i.create(i.Class.UNIVERSAL,i.Type.INTEGER,!1,e.util.hexToBytes(T.toString(16))),i.create(i.Class.UNIVERSAL,i.Type.SEQUENCE,!0,[i.create(i.Class.UNIVERSAL,i.Type.OID,!1,i.oidToDer(c.oids[A]).getBytes()),i.create(i.Class.UNIVERSAL,i.Type.NULL,!1,"")]));return g}}),ca=lt((r,n)=>{var e=pt();Ue(),Tt();var t=e.asn1,i=n.exports=e.pkcs7asn1=e.pkcs7asn1||{};e.pkcs7=e.pkcs7||{},e.pkcs7.asn1=i;var c={name:"ContentInfo",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:t.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};i.contentInfoValidator=c;var f={name:"EncryptedContentInfo",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:t.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:t.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};i.envelopedDataValidator={name:"EnvelopedData",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:t.Class.UNIVERSAL,type:t.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:t.Class.UNIVERSAL,type:t.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(f)},i.encryptedDataValidator={name:"EncryptedData",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:t.Class.UNIVERSAL,type:t.Type.INTEGER,constructed:!1,capture:"version"}].concat(f)};var o={name:"SignerInfo",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:t.Class.UNIVERSAL,type:t.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:t.Class.UNIVERSAL,type:t.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:t.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:t.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:t.Class.UNIVERSAL,type:t.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:t.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};i.signedDataValidator={name:"SignedData",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:t.Class.UNIVERSAL,type:t.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:t.Class.UNIVERSAL,type:t.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},c,{name:"SignedData.Certificates",tagClass:t.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:t.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:t.Class.UNIVERSAL,type:t.Type.SET,capture:"signerInfos",optional:!0,value:[o]}]},i.recipientInfoValidator={name:"RecipientInfo",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:t.Class.UNIVERSAL,type:t.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:t.Class.UNIVERSAL,type:t.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:t.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:t.Class.UNIVERSAL,type:t.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}}),fa=lt((r,n)=>{var e=pt();Tt(),e.mgf=e.mgf||{};var t=n.exports=e.mgf.mgf1=e.mgf1=e.mgf1||{};t.create=function(i){var c={generate:function(f,o){var s=new e.util.ByteBuffer,a=Math.ceil(o/i.digestLength);for(var C=0;C<a;C++){var p=new e.util.ByteBuffer;p.putInt32(C),i.start(),i.update(f+p.getBytes()),s.putBuffer(i.digest())}return s.truncate(s.length()-o),s.getBytes()}};return c}}),nu=lt((r,n)=>{var e=pt();fa(),n.exports=e.mgf=e.mgf||{},e.mgf.mgf1=e.mgf1}),qi=lt((r,n)=>{var e=pt();we(),Tt();var t=n.exports=e.pss=e.pss||{};t.create=function(i){if(arguments.length===3)i={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]};var{md:c,mgf:f}=i,o=c.digestLength,s=i.salt||null;if(typeof s==="string")s=e.util.createBuffer(s);var a;if("saltLength"in i)a=i.saltLength;else if(s!==null)a=s.length();else throw Error("Salt length not specified or specific salt not given.");if(s!==null&&s.length()!==a)throw Error("Given salt length does not match length of given salt.");var C=i.prng||e.random,p={};return p.encode=function(m,w){var B,d=w-1,T=Math.ceil(d/8),A=m.digest().getBytes();if(T<o+a+2)throw Error("Message is too long to encrypt.");var g;if(s===null)g=C.getBytesSync(a);else g=s.bytes();var l=new e.util.ByteBuffer;l.fillWithByte(0,8),l.putBytes(A),l.putBytes(g),c.start(),c.update(l.getBytes());var S=c.digest().getBytes(),I=new e.util.ByteBuffer;I.fillWithByte(0,T-a-o-2),I.putByte(1),I.putBytes(g);var N=I.getBytes(),L=T-o-1,v=f.generate(S,L),h="";for(B=0;B<L;B++)h+=String.fromCharCode(N.charCodeAt(B)^v.charCodeAt(B));var u=65280>>8*T-d&255;return h=String.fromCharCode(h.charCodeAt(0)&~u)+h.substr(1),h+S+String.fromCharCode(188)},p.verify=function(m,w,B){var d,T=B-1,A=Math.ceil(T/8);if(w=w.substr(-A),A<o+a+2)throw Error("Inconsistent parameters to PSS signature verification.");if(w.charCodeAt(A-1)!==188)throw Error("Encoded message does not end in 0xBC.");var g=A-o-1,l=w.substr(0,g),S=w.substr(g,o),I=65280>>8*A-T&255;if((l.charCodeAt(0)&I)!==0)throw Error("Bits beyond keysize not zero as expected.");var N=f.generate(S,g),L="";for(d=0;d<g;d++)L+=String.fromCharCode(l.charCodeAt(d)^N.charCodeAt(d));L=String.fromCharCode(L.charCodeAt(0)&~I)+L.substr(1);var v=A-o-a-2;for(d=0;d<v;d++)if(L.charCodeAt(d)!==0)throw Error("Leftmost octets not zero as expected");if(L.charCodeAt(v)!==1)throw Error("Inconsistent PSS signature, 0x01 marker not found");var h=L.substr(-a),u=new e.util.ByteBuffer;u.fillWithByte(0,8),u.putBytes(m),u.putBytes(h),c.start(),c.update(u.getBytes());var R=c.digest().getBytes();return S===R},p}}),Hi=lt((r,n)=>{var e=pt();ze(),Ue(),Zr(),Me(),nu(),Pe(),hr(),qi(),Jr(),Tt();var t=e.asn1,i=n.exports=e.pki=e.pki||{},c=i.oids,f={};f.CN=c.commonName,f.commonName="CN",f.C=c.countryName,f.countryName="C",f.L=c.localityName,f.localityName="L",f.ST=c.stateOrProvinceName,f.stateOrProvinceName="ST",f.O=c.organizationName,f.organizationName="O",f.OU=c.organizationalUnitName,f.organizationalUnitName="OU",f.E=c.emailAddress,f.emailAddress="E";var o=e.pki.rsa.publicKeyValidator,s={name:"Certificate",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:t.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:t.Class.UNIVERSAL,type:t.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:t.Class.UNIVERSAL,type:t.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:t.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:t.Class.UNIVERSAL,type:t.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:t.Class.UNIVERSAL,type:t.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:t.Class.UNIVERSAL,type:t.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:t.Class.UNIVERSAL,type:t.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},o,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:t.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:t.Class.UNIVERSAL,type:t.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:t.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:t.Class.UNIVERSAL,type:t.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:t.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:t.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:t.Class.UNIVERSAL,type:t.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},a={name:"rsapss",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:t.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:t.Class.UNIVERSAL,type:t.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:t.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:t.Class.UNIVERSAL,type:t.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:t.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:t.Class.UNIVERSAL,type:t.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:t.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:t.Class.UNIVERSAL,type:t.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},C={name:"CertificationRequestInfo",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:t.Class.UNIVERSAL,type:t.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},o,{name:"CertificationRequestInfo.attributes",tagClass:t.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:t.Class.UNIVERSAL,type:t.Type.SET,constructed:!0}]}]}]},p={name:"CertificationRequest",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[C,{name:"CertificationRequest.signatureAlgorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:t.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:t.Class.UNIVERSAL,type:t.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};i.RDNAttributesAsArray=function(v,h){var u=[],R,V,O;for(var K=0;K<v.value.length;++K){R=v.value[K];for(var G=0;G<R.value.length;++G){if(O={},V=R.value[G],O.type=t.derToOid(V.value[0].value),O.value=V.value[1].value,O.valueTagClass=V.value[1].type,O.type in c){if(O.name=c[O.type],O.name in f)O.shortName=f[O.name]}if(h)h.update(O.type),h.update(O.value);u.push(O)}}return u},i.CRIAttributesAsArray=function(v){var h=[];for(var u=0;u<v.length;++u){var R=v[u],V=t.derToOid(R.value[0].value),O=R.value[1].value;for(var K=0;K<O.length;++K){var G={};if(G.type=V,G.value=O[K].value,G.valueTagClass=O[K].type,G.type in c){if(G.name=c[G.type],G.name in f)G.shortName=f[G.name]}if(G.type===c.extensionRequest){G.extensions=[];for(var H=0;H<G.value.length;++H)G.extensions.push(i.certificateExtensionFromAsn1(G.value[H]))}h.push(G)}}return h};function m(v,h){if(typeof h==="string")h={shortName:h};var u=null,R;for(var V=0;u===null&&V<v.attributes.length;++V)if(R=v.attributes[V],h.type&&h.type===R.type)u=R;else if(h.name&&h.name===R.name)u=R;else if(h.shortName&&h.shortName===R.shortName)u=R;return u}var w=function(v,h,u){var R={};if(v!==c["RSASSA-PSS"])return R;if(u)R={hash:{algorithmOid:c.sha1},mgf:{algorithmOid:c.mgf1,hash:{algorithmOid:c.sha1}},saltLength:20};var V={},O=[];if(!t.validate(h,a,V,O)){var K=Error("Cannot read RSASSA-PSS parameter block.");throw K.errors=O,K}if(V.hashOid!==void 0)R.hash=R.hash||{},R.hash.algorithmOid=t.derToOid(V.hashOid);if(V.maskGenOid!==void 0)R.mgf=R.mgf||{},R.mgf.algorithmOid=t.derToOid(V.maskGenOid),R.mgf.hash=R.mgf.hash||{},R.mgf.hash.algorithmOid=t.derToOid(V.maskGenHashOid);if(V.saltLength!==void 0)R.saltLength=V.saltLength.charCodeAt(0);return R},B=function(v){switch(c[v.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return e.md.sha1.create();case"md5WithRSAEncryption":return e.md.md5.create();case"sha256WithRSAEncryption":return e.md.sha256.create();case"sha384WithRSAEncryption":return e.md.sha384.create();case"sha512WithRSAEncryption":return e.md.sha512.create();case"RSASSA-PSS":return e.md.sha256.create();default:var h=Error("Could not compute "+v.type+" digest. Unknown signature OID.");throw h.signatureOid=v.signatureOid,h}},d=function(v){var h=v.certificate,u;switch(h.signatureOid){case c.sha1WithRSAEncryption:case c.sha1WithRSASignature:break;case c["RSASSA-PSS"]:var R,V;if(R=c[h.signatureParameters.mgf.hash.algorithmOid],R===void 0||e.md[R]===void 0){var O=Error("Unsupported MGF hash function.");throw O.oid=h.signatureParameters.mgf.hash.algorithmOid,O.name=R,O}if(V=c[h.signatureParameters.mgf.algorithmOid],V===void 0||e.mgf[V]===void 0){var O=Error("Unsupported MGF function.");throw O.oid=h.signatureParameters.mgf.algorithmOid,O.name=V,O}if(V=e.mgf[V].create(e.md[R].create()),R=c[h.signatureParameters.hash.algorithmOid],R===void 0||e.md[R]===void 0){var O=Error("Unsupported RSASSA-PSS hash function.");throw O.oid=h.signatureParameters.hash.algorithmOid,O.name=R,O}u=e.pss.create(e.md[R].create(),V,h.signatureParameters.saltLength);break}return h.publicKey.verify(v.md.digest().getBytes(),v.signature,u)};i.certificateFromPem=function(v,h,u){var R=e.pem.decode(v)[0];if(R.type!=="CERTIFICATE"&&R.type!=="X509 CERTIFICATE"&&R.type!=="TRUSTED CERTIFICATE"){var V=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw V.headerType=R.type,V}if(R.procType&&R.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var O=t.fromDer(R.body,u);return i.certificateFromAsn1(O,h)},i.certificateToPem=function(v,h){var u={type:"CERTIFICATE",body:t.toDer(i.certificateToAsn1(v)).getBytes()};return e.pem.encode(u,{maxline:h})},i.publicKeyFromPem=function(v){var h=e.pem.decode(v)[0];if(h.type!=="PUBLIC KEY"&&h.type!=="RSA PUBLIC KEY"){var u=Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');throw u.headerType=h.type,u}if(h.procType&&h.procType.type==="ENCRYPTED")throw Error("Could not convert public key from PEM; PEM is encrypted.");var R=t.fromDer(h.body);return i.publicKeyFromAsn1(R)},i.publicKeyToPem=function(v,h){var u={type:"PUBLIC KEY",body:t.toDer(i.publicKeyToAsn1(v)).getBytes()};return e.pem.encode(u,{maxline:h})},i.publicKeyToRSAPublicKeyPem=function(v,h){var u={type:"RSA PUBLIC KEY",body:t.toDer(i.publicKeyToRSAPublicKey(v)).getBytes()};return e.pem.encode(u,{maxline:h})},i.getPublicKeyFingerprint=function(v,h){h=h||{};var u=h.md||e.md.sha1.create(),R=h.type||"RSAPublicKey",V;switch(R){case"RSAPublicKey":V=t.toDer(i.publicKeyToRSAPublicKey(v)).getBytes();break;case"SubjectPublicKeyInfo":V=t.toDer(i.publicKeyToAsn1(v)).getBytes();break;default:throw Error('Unknown fingerprint type "'+h.type+'".')}u.start(),u.update(V);var O=u.digest();if(h.encoding==="hex"){var K=O.toHex();if(h.delimiter)return K.match(/.{2}/g).join(h.delimiter);return K}else if(h.encoding==="binary")return O.getBytes();else if(h.encoding)throw Error('Unknown encoding "'+h.encoding+'".');return O},i.certificationRequestFromPem=function(v,h,u){var R=e.pem.decode(v)[0];if(R.type!=="CERTIFICATE REQUEST"){var V=Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');throw V.headerType=R.type,V}if(R.procType&&R.procType.type==="ENCRYPTED")throw Error("Could not convert certification request from PEM; PEM is encrypted.");var O=t.fromDer(R.body,u);return i.certificationRequestFromAsn1(O,h)},i.certificationRequestToPem=function(v,h){var u={type:"CERTIFICATE REQUEST",body:t.toDer(i.certificationRequestToAsn1(v)).getBytes()};return e.pem.encode(u,{maxline:h})},i.createCertificate=function(){var v={};return v.version=2,v.serialNumber="00",v.signatureOid=null,v.signature=null,v.siginfo={},v.siginfo.algorithmOid=null,v.validity={},v.validity.notBefore=new Date,v.validity.notAfter=new Date,v.issuer={},v.issuer.getField=function(h){return m(v.issuer,h)},v.issuer.addField=function(h){A([h]),v.issuer.attributes.push(h)},v.issuer.attributes=[],v.issuer.hash=null,v.subject={},v.subject.getField=function(h){return m(v.subject,h)},v.subject.addField=function(h){A([h]),v.subject.attributes.push(h)},v.subject.attributes=[],v.subject.hash=null,v.extensions=[],v.publicKey=null,v.md=null,v.setSubject=function(h,u){if(A(h),v.subject.attributes=h,delete v.subject.uniqueId,u)v.subject.uniqueId=u;v.subject.hash=null},v.setIssuer=function(h,u){if(A(h),v.issuer.attributes=h,delete v.issuer.uniqueId,u)v.issuer.uniqueId=u;v.issuer.hash=null},v.setExtensions=function(h){for(var u=0;u<h.length;++u)g(h[u],{cert:v});v.extensions=h},v.getExtension=function(h){if(typeof h==="string")h={name:h};var u=null,R;for(var V=0;u===null&&V<v.extensions.length;++V)if(R=v.extensions[V],h.id&&R.id===h.id)u=R;else if(h.name&&R.name===h.name)u=R;return u},v.sign=function(h,u){v.md=u||e.md.sha1.create();var R=c[v.md.algorithm+"WithRSAEncryption"];if(!R){var V=Error("Could not compute certificate digest. Unknown message digest algorithm OID.");throw V.algorithm=v.md.algorithm,V}v.signatureOid=v.siginfo.algorithmOid=R,v.tbsCertificate=i.getTBSCertificate(v);var O=t.toDer(v.tbsCertificate);v.md.update(O.getBytes()),v.signature=h.sign(v.md)},v.verify=function(h){var u=!1;if(!v.issued(h)){var R=h.issuer,V=v.subject,O=Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw O.expectedIssuer=V.attributes,O.actualIssuer=R.attributes,O}var K=h.md;if(K===null){K=B({signatureOid:h.signatureOid,type:"certificate"});var G=h.tbsCertificate||i.getTBSCertificate(h),H=t.toDer(G);K.update(H.getBytes())}if(K!==null)u=d({certificate:v,md:K,signature:h.signature});return u},v.isIssuer=function(h){var u=!1,R=v.issuer,V=h.subject;if(R.hash&&V.hash)u=R.hash===V.hash;else if(R.attributes.length===V.attributes.length){u=!0;var O,K;for(var G=0;u&&G<R.attributes.length;++G)if(O=R.attributes[G],K=V.attributes[G],O.type!==K.type||O.value!==K.value)u=!1}return u},v.issued=function(h){return h.isIssuer(v)},v.generateSubjectKeyIdentifier=function(){return i.getPublicKeyFingerprint(v.publicKey,{type:"RSAPublicKey"})},v.verifySubjectKeyIdentifier=function(){var h=c.subjectKeyIdentifier;for(var u=0;u<v.extensions.length;++u){var R=v.extensions[u];if(R.id===h){var V=v.generateSubjectKeyIdentifier().getBytes();return e.util.hexToBytes(R.subjectKeyIdentifier)===V}}return!1},v},i.certificateFromAsn1=function(v,h){var u={},R=[];if(!t.validate(v,s,u,R)){var V=Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw V.errors=R,V}var O=t.derToOid(u.publicKeyOid);if(O!==i.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var K=i.createCertificate();K.version=u.certVersion?u.certVersion.charCodeAt(0):0;var G=e.util.createBuffer(u.certSerialNumber);K.serialNumber=G.toHex(),K.signatureOid=e.asn1.derToOid(u.certSignatureOid),K.signatureParameters=w(K.signatureOid,u.certSignatureParams,!0),K.siginfo.algorithmOid=e.asn1.derToOid(u.certinfoSignatureOid),K.siginfo.parameters=w(K.siginfo.algorithmOid,u.certinfoSignatureParams,!1),K.signature=u.certSignature;var H=[];if(u.certValidity1UTCTime!==void 0)H.push(t.utcTimeToDate(u.certValidity1UTCTime));if(u.certValidity2GeneralizedTime!==void 0)H.push(t.generalizedTimeToDate(u.certValidity2GeneralizedTime));if(u.certValidity3UTCTime!==void 0)H.push(t.utcTimeToDate(u.certValidity3UTCTime));if(u.certValidity4GeneralizedTime!==void 0)H.push(t.generalizedTimeToDate(u.certValidity4GeneralizedTime));if(H.length>2)throw Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(H.length<2)throw Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(K.validity.notBefore=H[0],K.validity.notAfter=H[1],K.tbsCertificate=u.tbsCertificate,h){K.md=B({signatureOid:K.signatureOid,type:"certificate"});var j=t.toDer(K.tbsCertificate);K.md.update(j.getBytes())}var z=e.md.sha1.create(),Z=t.toDer(u.certIssuer);if(z.update(Z.getBytes()),K.issuer.getField=function(ut){return m(K.issuer,ut)},K.issuer.addField=function(ut){A([ut]),K.issuer.attributes.push(ut)},K.issuer.attributes=i.RDNAttributesAsArray(u.certIssuer),u.certIssuerUniqueId)K.issuer.uniqueId=u.certIssuerUniqueId;K.issuer.hash=z.digest().toHex();var tt=e.md.sha1.create(),rt=t.toDer(u.certSubject);if(tt.update(rt.getBytes()),K.subject.getField=function(ut){return m(K.subject,ut)},K.subject.addField=function(ut){A([ut]),K.subject.attributes.push(ut)},K.subject.attributes=i.RDNAttributesAsArray(u.certSubject),u.certSubjectUniqueId)K.subject.uniqueId=u.certSubjectUniqueId;if(K.subject.hash=tt.digest().toHex(),u.certExtensions)K.extensions=i.certificateExtensionsFromAsn1(u.certExtensions);else K.extensions=[];return K.publicKey=i.publicKeyFromAsn1(u.subjectPublicKeyInfo),K},i.certificateExtensionsFromAsn1=function(v){var h=[];for(var u=0;u<v.value.length;++u){var R=v.value[u];for(var V=0;V<R.value.length;++V)h.push(i.certificateExtensionFromAsn1(R.value[V]))}return h},i.certificateExtensionFromAsn1=function(v){var h={};if(h.id=t.derToOid(v.value[0].value),h.critical=!1,v.value[1].type===t.Type.BOOLEAN)h.critical=v.value[1].value.charCodeAt(0)!==0,h.value=v.value[2].value;else h.value=v.value[1].value;if(h.id in c){if(h.name=c[h.id],h.name==="keyUsage"){var u=t.fromDer(h.value),R=0,V=0;if(u.value.length>1)R=u.value.charCodeAt(1),V=u.value.length>2?u.value.charCodeAt(2):0;h.digitalSignature=(R&128)===128,h.nonRepudiation=(R&64)===64,h.keyEncipherment=(R&32)===32,h.dataEncipherment=(R&16)===16,h.keyAgreement=(R&8)===8,h.keyCertSign=(R&4)===4,h.cRLSign=(R&2)===2,h.encipherOnly=(R&1)===1,h.decipherOnly=(V&128)===128}else if(h.name==="basicConstraints"){var u=t.fromDer(h.value);if(u.value.length>0&&u.value[0].type===t.Type.BOOLEAN)h.cA=u.value[0].value.charCodeAt(0)!==0;else h.cA=!1;var O=null;if(u.value.length>0&&u.value[0].type===t.Type.INTEGER)O=u.value[0].value;else if(u.value.length>1)O=u.value[1].value;if(O!==null)h.pathLenConstraint=t.derToInteger(O)}else if(h.name==="extKeyUsage"){var u=t.fromDer(h.value);for(var K=0;K<u.value.length;++K){var G=t.derToOid(u.value[K].value);if(G in c)h[c[G]]=!0;else h[G]=!0}}else if(h.name==="nsCertType"){var u=t.fromDer(h.value),R=0;if(u.value.length>1)R=u.value.charCodeAt(1);h.client=(R&128)===128,h.server=(R&64)===64,h.email=(R&32)===32,h.objsign=(R&16)===16,h.reserved=(R&8)===8,h.sslCA=(R&4)===4,h.emailCA=(R&2)===2,h.objCA=(R&1)===1}else if(h.name==="subjectAltName"||h.name==="issuerAltName"){h.altNames=[];var H,u=t.fromDer(h.value);for(var j=0;j<u.value.length;++j){H=u.value[j];var z={type:H.type,value:H.value};switch(h.altNames.push(z),H.type){case 1:case 2:case 6:break;case 7:z.ip=e.util.bytesToIP(H.value);break;case 8:z.oid=t.derToOid(H.value);break;default:}}}else if(h.name==="subjectKeyIdentifier"){var u=t.fromDer(h.value);h.subjectKeyIdentifier=e.util.bytesToHex(u.value)}}return h},i.certificationRequestFromAsn1=function(v,h){var u={},R=[];if(!t.validate(v,p,u,R)){var V=Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");throw V.errors=R,V}var O=t.derToOid(u.publicKeyOid);if(O!==i.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var K=i.createCertificationRequest();if(K.version=u.csrVersion?u.csrVersion.charCodeAt(0):0,K.signatureOid=e.asn1.derToOid(u.csrSignatureOid),K.signatureParameters=w(K.signatureOid,u.csrSignatureParams,!0),K.siginfo.algorithmOid=e.asn1.derToOid(u.csrSignatureOid),K.siginfo.parameters=w(K.siginfo.algorithmOid,u.csrSignatureParams,!1),K.signature=u.csrSignature,K.certificationRequestInfo=u.certificationRequestInfo,h){K.md=B({signatureOid:K.signatureOid,type:"certification request"});var G=t.toDer(K.certificationRequestInfo);K.md.update(G.getBytes())}var H=e.md.sha1.create();return K.subject.getField=function(j){return m(K.subject,j)},K.subject.addField=function(j){A([j]),K.subject.attributes.push(j)},K.subject.attributes=i.RDNAttributesAsArray(u.certificationRequestInfoSubject,H),K.subject.hash=H.digest().toHex(),K.publicKey=i.publicKeyFromAsn1(u.subjectPublicKeyInfo),K.getAttribute=function(j){return m(K,j)},K.addAttribute=function(j){A([j]),K.attributes.push(j)},K.attributes=i.CRIAttributesAsArray(u.certificationRequestInfoAttributes||[]),K},i.createCertificationRequest=function(){var v={};return v.version=0,v.signatureOid=null,v.signature=null,v.siginfo={},v.siginfo.algorithmOid=null,v.subject={},v.subject.getField=function(h){return m(v.subject,h)},v.subject.addField=function(h){A([h]),v.subject.attributes.push(h)},v.subject.attributes=[],v.subject.hash=null,v.publicKey=null,v.attributes=[],v.getAttribute=function(h){return m(v,h)},v.addAttribute=function(h){A([h]),v.attributes.push(h)},v.md=null,v.setSubject=function(h){A(h),v.subject.attributes=h,v.subject.hash=null},v.setAttributes=function(h){A(h),v.attributes=h},v.sign=function(h,u){v.md=u||e.md.sha1.create();var R=c[v.md.algorithm+"WithRSAEncryption"];if(!R){var V=Error("Could not compute certification request digest. Unknown message digest algorithm OID.");throw V.algorithm=v.md.algorithm,V}v.signatureOid=v.siginfo.algorithmOid=R,v.certificationRequestInfo=i.getCertificationRequestInfo(v);var O=t.toDer(v.certificationRequestInfo);v.md.update(O.getBytes()),v.signature=h.sign(v.md)},v.verify=function(){var h=!1,u=v.md;if(u===null){u=B({signatureOid:v.signatureOid,type:"certification request"});var R=v.certificationRequestInfo||i.getCertificationRequestInfo(v),V=t.toDer(R);u.update(V.getBytes())}if(u!==null)h=d({certificate:v,md:u,signature:v.signature});return h},v};function T(v){var h=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[]),u,R,V=v.attributes;for(var O=0;O<V.length;++O){u=V[O];var K=u.value,G=t.Type.PRINTABLESTRING;if("valueTagClass"in u){if(G=u.valueTagClass,G===t.Type.UTF8)K=e.util.encodeUtf8(K)}R=t.create(t.Class.UNIVERSAL,t.Type.SET,!0,[t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(u.type).getBytes()),t.create(t.Class.UNIVERSAL,G,!1,K)])]),h.value.push(R)}return h}function A(v){var h;for(var u=0;u<v.length;++u){if(h=v[u],typeof h.name>"u"){if(h.type&&h.type in i.oids)h.name=i.oids[h.type];else if(h.shortName&&h.shortName in f)h.name=i.oids[f[h.shortName]]}if(typeof h.type>"u")if(h.name&&h.name in i.oids)h.type=i.oids[h.name];else{var R=Error("Attribute type not specified.");throw R.attribute=h,R}if(typeof h.shortName>"u"){if(h.name&&h.name in f)h.shortName=f[h.name]}if(h.type===c.extensionRequest){if(h.valueConstructed=!0,h.valueTagClass=t.Type.SEQUENCE,!h.value&&h.extensions){h.value=[];for(var V=0;V<h.extensions.length;++V)h.value.push(i.certificateExtensionToAsn1(g(h.extensions[V])))}}if(typeof h.value>"u"){var R=Error("Attribute value not specified.");throw R.attribute=h,R}}}function g(v,h){if(h=h||{},typeof v.name>"u"){if(v.id&&v.id in i.oids)v.name=i.oids[v.id]}if(typeof v.id>"u")if(v.name&&v.name in i.oids)v.id=i.oids[v.name];else{var u=Error("Extension ID not specified.");throw u.extension=v,u}if(typeof v.value<"u")return v;if(v.name==="keyUsage"){var R=0,V=0,O=0;if(v.digitalSignature)V|=128,R=7;if(v.nonRepudiation)V|=64,R=6;if(v.keyEncipherment)V|=32,R=5;if(v.dataEncipherment)V|=16,R=4;if(v.keyAgreement)V|=8,R=3;if(v.keyCertSign)V|=4,R=2;if(v.cRLSign)V|=2,R=1;if(v.encipherOnly)V|=1,R=0;if(v.decipherOnly)O|=128,R=7;var K=String.fromCharCode(R);if(O!==0)K+=String.fromCharCode(V)+String.fromCharCode(O);else if(V!==0)K+=String.fromCharCode(V);v.value=t.create(t.Class.UNIVERSAL,t.Type.BITSTRING,!1,K)}else if(v.name==="basicConstraints"){if(v.value=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[]),v.cA)v.value.value.push(t.create(t.Class.UNIVERSAL,t.Type.BOOLEAN,!1,String.fromCharCode(255)));if("pathLenConstraint"in v)v.value.value.push(t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,t.integerToDer(v.pathLenConstraint).getBytes()))}else if(v.name==="extKeyUsage"){v.value=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[]);var G=v.value.value;for(var H in v){if(v[H]!==!0)continue;if(H in c)G.push(t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(c[H]).getBytes()));else if(H.indexOf(".")!==-1)G.push(t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(H).getBytes()))}}else if(v.name==="nsCertType"){var R=0,V=0;if(v.client)V|=128,R=7;if(v.server)V|=64,R=6;if(v.email)V|=32,R=5;if(v.objsign)V|=16,R=4;if(v.reserved)V|=8,R=3;if(v.sslCA)V|=4,R=2;if(v.emailCA)V|=2,R=1;if(v.objCA)V|=1,R=0;var K=String.fromCharCode(R);if(V!==0)K+=String.fromCharCode(V);v.value=t.create(t.Class.UNIVERSAL,t.Type.BITSTRING,!1,K)}else if(v.name==="subjectAltName"||v.name==="issuerAltName"){v.value=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[]);var j;for(var z=0;z<v.altNames.length;++z){j=v.altNames[z];var K=j.value;if(j.type===7&&j.ip){if(K=e.util.bytesFromIP(j.ip),K===null){var u=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw u.extension=v,u}}else if(j.type===8)if(j.oid)K=t.oidToDer(t.oidToDer(j.oid));else K=t.oidToDer(K);v.value.value.push(t.create(t.Class.CONTEXT_SPECIFIC,j.type,!1,K))}}else if(v.name==="nsComment"&&h.cert){if(!/^[\x00-\x7F]*$/.test(v.comment)||v.comment.length<1||v.comment.length>128)throw Error('Invalid "nsComment" content.');v.value=t.create(t.Class.UNIVERSAL,t.Type.IA5STRING,!1,v.comment)}else if(v.name==="subjectKeyIdentifier"&&h.cert){var Z=h.cert.generateSubjectKeyIdentifier();v.subjectKeyIdentifier=Z.toHex(),v.value=t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,Z.getBytes())}else if(v.name==="authorityKeyIdentifier"&&h.cert){v.value=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[]);var G=v.value.value;if(v.keyIdentifier){var tt=v.keyIdentifier===!0?h.cert.generateSubjectKeyIdentifier().getBytes():v.keyIdentifier;G.push(t.create(t.Class.CONTEXT_SPECIFIC,0,!1,tt))}if(v.authorityCertIssuer){var rt=[t.create(t.Class.CONTEXT_SPECIFIC,4,!0,[T(v.authorityCertIssuer===!0?h.cert.issuer:v.authorityCertIssuer)])];G.push(t.create(t.Class.CONTEXT_SPECIFIC,1,!0,rt))}if(v.serialNumber){var ut=e.util.hexToBytes(v.serialNumber===!0?h.cert.serialNumber:v.serialNumber);G.push(t.create(t.Class.CONTEXT_SPECIFIC,2,!1,ut))}}else if(v.name==="cRLDistributionPoints"){v.value=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[]);var G=v.value.value,ht=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[]),Et=t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[]),j;for(var z=0;z<v.altNames.length;++z){j=v.altNames[z];var K=j.value;if(j.type===7&&j.ip){if(K=e.util.bytesFromIP(j.ip),K===null){var u=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw u.extension=v,u}}else if(j.type===8)if(j.oid)K=t.oidToDer(t.oidToDer(j.oid));else K=t.oidToDer(K);Et.value.push(t.create(t.Class.CONTEXT_SPECIFIC,j.type,!1,K))}ht.value.push(t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[Et])),G.push(ht)}if(typeof v.value>"u"){var u=Error("Extension value not specified.");throw u.extension=v,u}return v}function l(v,h){switch(v){case c["RSASSA-PSS"]:var u=[];if(h.hash.algorithmOid!==void 0)u.push(t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(h.hash.algorithmOid).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.NULL,!1,"")])]));if(h.mgf.algorithmOid!==void 0)u.push(t.create(t.Class.CONTEXT_SPECIFIC,1,!0,[t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(h.mgf.algorithmOid).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(h.mgf.hash.algorithmOid).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.NULL,!1,"")])])]));if(h.saltLength!==void 0)u.push(t.create(t.Class.CONTEXT_SPECIFIC,2,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,t.integerToDer(h.saltLength).getBytes())]));return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,u);default:return t.create(t.Class.UNIVERSAL,t.Type.NULL,!1,"")}}function S(v){var h=t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[]);if(v.attributes.length===0)return h;var u=v.attributes;for(var R=0;R<u.length;++R){var V=u[R],O=V.value,K=t.Type.UTF8;if("valueTagClass"in V)K=V.valueTagClass;if(K===t.Type.UTF8)O=e.util.encodeUtf8(O);var G=!1;if("valueConstructed"in V)G=V.valueConstructed;var H=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(V.type).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SET,!0,[t.create(t.Class.UNIVERSAL,K,G,O)])]);h.value.push(H)}return h}var I=new Date("1950-01-01T00:00:00Z"),N=new Date("2050-01-01T00:00:00Z");function L(v){if(v>=I&&v<N)return t.create(t.Class.UNIVERSAL,t.Type.UTCTIME,!1,t.dateToUtcTime(v));else return t.create(t.Class.UNIVERSAL,t.Type.GENERALIZEDTIME,!1,t.dateToGeneralizedTime(v))}i.getTBSCertificate=function(v){var h=L(v.validity.notBefore),u=L(v.validity.notAfter),R=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,t.integerToDer(v.version).getBytes())]),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,e.util.hexToBytes(v.serialNumber)),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(v.siginfo.algorithmOid).getBytes()),l(v.siginfo.algorithmOid,v.siginfo.parameters)]),T(v.issuer),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[h,u]),T(v.subject),i.publicKeyToAsn1(v.publicKey)]);if(v.issuer.uniqueId)R.value.push(t.create(t.Class.CONTEXT_SPECIFIC,1,!0,[t.create(t.Class.UNIVERSAL,t.Type.BITSTRING,!1,String.fromCharCode(0)+v.issuer.uniqueId)]));if(v.subject.uniqueId)R.value.push(t.create(t.Class.CONTEXT_SPECIFIC,2,!0,[t.create(t.Class.UNIVERSAL,t.Type.BITSTRING,!1,String.fromCharCode(0)+v.subject.uniqueId)]));if(v.extensions.length>0)R.value.push(i.certificateExtensionsToAsn1(v.extensions));return R},i.getCertificationRequestInfo=function(v){var h=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,t.integerToDer(v.version).getBytes()),T(v.subject),i.publicKeyToAsn1(v.publicKey),S(v)]);return h},i.distinguishedNameToAsn1=function(v){return T(v)},i.certificateToAsn1=function(v){var h=v.tbsCertificate||i.getTBSCertificate(v);return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[h,t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(v.signatureOid).getBytes()),l(v.signatureOid,v.signatureParameters)]),t.create(t.Class.UNIVERSAL,t.Type.BITSTRING,!1,String.fromCharCode(0)+v.signature)])},i.certificateExtensionsToAsn1=function(v){var h=t.create(t.Class.CONTEXT_SPECIFIC,3,!0,[]),u=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[]);h.value.push(u);for(var R=0;R<v.length;++R)u.value.push(i.certificateExtensionToAsn1(v[R]));return h},i.certificateExtensionToAsn1=function(v){var h=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[]);if(h.value.push(t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(v.id).getBytes())),v.critical)h.value.push(t.create(t.Class.UNIVERSAL,t.Type.BOOLEAN,!1,String.fromCharCode(255)));var u=v.value;if(typeof v.value!=="string")u=t.toDer(u).getBytes();return h.value.push(t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,u)),h},i.certificationRequestToAsn1=function(v){var h=v.certificationRequestInfo||i.getCertificationRequestInfo(v);return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[h,t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(v.signatureOid).getBytes()),l(v.signatureOid,v.signatureParameters)]),t.create(t.Class.UNIVERSAL,t.Type.BITSTRING,!1,String.fromCharCode(0)+v.signature)])},i.createCaStore=function(v){var h={certs:{}};h.getIssuer=function(K){var G=u(K.issuer);return G},h.addCertificate=function(K){if(typeof K==="string")K=e.pki.certificateFromPem(K);if(R(K.subject),!h.hasCertificate(K))if(K.subject.hash in h.certs){var G=h.certs[K.subject.hash];if(!e.util.isArray(G))G=[G];G.push(K),h.certs[K.subject.hash]=G}else h.certs[K.subject.hash]=K},h.hasCertificate=function(K){if(typeof K==="string")K=e.pki.certificateFromPem(K);var G=u(K.subject);if(!G)return!1;if(!e.util.isArray(G))G=[G];var H=t.toDer(i.certificateToAsn1(K)).getBytes();for(var j=0;j<G.length;++j){var z=t.toDer(i.certificateToAsn1(G[j])).getBytes();if(H===z)return!0}return!1},h.listAllCertificates=function(){var K=[];for(var G in h.certs)if(h.certs.hasOwnProperty(G)){var H=h.certs[G];if(!e.util.isArray(H))K.push(H);else for(var j=0;j<H.length;++j)K.push(H[j])}return K},h.removeCertificate=function(K){var G;if(typeof K==="string")K=e.pki.certificateFromPem(K);if(R(K.subject),!h.hasCertificate(K))return null;var H=u(K.subject);if(!e.util.isArray(H))return G=h.certs[K.subject.hash],delete h.certs[K.subject.hash],G;var j=t.toDer(i.certificateToAsn1(K)).getBytes();for(var z=0;z<H.length;++z){var Z=t.toDer(i.certificateToAsn1(H[z])).getBytes();if(j===Z)G=H[z],H.splice(z,1)}if(H.length===0)delete h.certs[K.subject.hash];return G};function u(K){return R(K),h.certs[K.hash]||null}function R(K){if(!K.hash){var G=e.md.sha1.create();K.attributes=i.RDNAttributesAsArray(T(K),G),K.hash=G.digest().toHex()}}if(v)for(var V=0;V<v.length;++V){var O=v[V];h.addCertificate(O)}return h},i.certificateError={bad_certificate:"forge.pki.BadCertificate",unsupported_certificate:"forge.pki.UnsupportedCertificate",certificate_revoked:"forge.pki.CertificateRevoked",certificate_expired:"forge.pki.CertificateExpired",certificate_unknown:"forge.pki.CertificateUnknown",unknown_ca:"forge.pki.UnknownCertificateAuthority"},i.verifyCertificateChain=function(v,h,u){if(typeof u==="function")u={verify:u};u=u||{},h=h.slice(0);var R=h.slice(0),V=u.validityCheckDate;if(typeof V>"u")V=new Date;var O=!0,K=null,G=0;do{var H=h.shift(),j=null,z=!1;if(V){if(V<H.validity.notBefore||V>H.validity.notAfter)K={message:"Certificate is not valid yet or has expired.",error:i.certificateError.certificate_expired,notBefore:H.validity.notBefore,notAfter:H.validity.notAfter,now:V}}if(K===null){if(j=h[0]||v.getIssuer(H),j===null){if(H.isIssuer(H))z=!0,j=H}if(j){var Z=j;if(!e.util.isArray(Z))Z=[Z];var tt=!1;while(!tt&&Z.length>0){j=Z.shift();try{tt=j.verify(H)}catch(Rt){}}if(!tt)K={message:"Certificate signature is invalid.",error:i.certificateError.bad_certificate}}if(K===null&&(!j||z)&&!v.hasCertificate(H))K={message:"Certificate is not trusted.",error:i.certificateError.unknown_ca}}if(K===null&&j&&!H.isIssuer(j))K={message:"Certificate issuer is invalid.",error:i.certificateError.bad_certificate};if(K===null){var rt={keyUsage:!0,basicConstraints:!0};for(var ut=0;K===null&&ut<H.extensions.length;++ut){var ht=H.extensions[ut];if(ht.critical&&!(ht.name in rt))K={message:"Certificate has an unsupported critical extension.",error:i.certificateError.unsupported_certificate}}}if(K===null&&(!O||h.length===0&&(!j||z))){var Et=H.getExtension("basicConstraints"),_t=H.getExtension("keyUsage");if(_t!==null){if(!_t.keyCertSign||Et===null)K={message:"Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.",error:i.certificateError.bad_certificate}}if(K===null&&Et!==null&&!Et.cA)K={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:i.certificateError.bad_certificate};if(K===null&&_t!==null&&"pathLenConstraint"in Et){var J=G-1;if(J>Et.pathLenConstraint)K={message:"Certificate basicConstraints pathLenConstraint violated.",error:i.certificateError.bad_certificate}}}var vt=K===null?!0:K.error,et=u.verify?u.verify(vt,G,R):vt;if(et===!0)K=null;else{if(vt===!0)K={message:"The application rejected the certificate.",error:i.certificateError.bad_certificate};if(et||et===0){if(typeof et==="object"&&!e.util.isArray(et)){if(et.message)K.message=et.message;if(et.error)K.error=et.error}else if(typeof et==="string")K.error=et}throw K}O=!1,++G}while(h.length>0);return!0}}),la=lt((r,n)=>{var e=pt();Ue(),dr(),Pe(),ca(),ua(),we(),Jr(),Cr(),Tt(),Hi();var{asn1:t,pki:i}=e,c=n.exports=e.pkcs12=e.pkcs12||{},f={name:"ContentInfo",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:t.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},o={name:"PFX",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:t.Class.UNIVERSAL,type:t.Type.INTEGER,constructed:!1,capture:"version"},f,{name:"PFX.macData",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",tagClass:t.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:t.Class.UNIVERSAL,type:t.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:t.Class.UNIVERSAL,type:t.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:t.Class.UNIVERSAL,type:t.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},s={name:"SafeBag",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:t.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:t.Class.UNIVERSAL,type:t.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},a={name:"Attribute",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:t.Class.UNIVERSAL,type:t.Type.SET,constructed:!0,capture:"values"}]},C={name:"CertBag",tagClass:t.Class.UNIVERSAL,type:t.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:t.Class.UNIVERSAL,type:t.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:t.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:t.Class.UNIVERSAL,type:t.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function p(A,g,l,S){var I=[];for(var N=0;N<A.length;N++)for(var L=0;L<A[N].safeBags.length;L++){var v=A[N].safeBags[L];if(S!==void 0&&v.type!==S)continue;if(g===null){I.push(v);continue}if(v.attributes[g]!==void 0&&v.attributes[g].indexOf(l)>=0)I.push(v)}return I}c.pkcs12FromAsn1=function(A,g,l){if(typeof g==="string")l=g,g=!0;else if(g===void 0)g=!0;var S={},I=[];if(!t.validate(A,o,S,I)){var N=Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw N.errors=N,N}var L={version:S.version.charCodeAt(0),safeContents:[],getBags:function(j){var z={},Z;if("localKeyId"in j)Z=j.localKeyId;else if("localKeyIdHex"in j)Z=e.util.hexToBytes(j.localKeyIdHex);if(Z===void 0&&!("friendlyName"in j)&&"bagType"in j)z[j.bagType]=p(L.safeContents,null,null,j.bagType);if(Z!==void 0)z.localKeyId=p(L.safeContents,"localKeyId",Z,j.bagType);if("friendlyName"in j)z.friendlyName=p(L.safeContents,"friendlyName",j.friendlyName,j.bagType);return z},getBagsByFriendlyName:function(j,z){return p(L.safeContents,"friendlyName",j,z)},getBagsByLocalKeyId:function(j,z){return p(L.safeContents,"localKeyId",j,z)}};if(S.version.charCodeAt(0)!==3){var N=Error("PKCS#12 PFX of version other than 3 not supported.");throw N.version=S.version.charCodeAt(0),N}if(t.derToOid(S.contentType)!==i.oids.data){var N=Error("Only PKCS#12 PFX in password integrity mode supported.");throw N.oid=t.derToOid(S.contentType),N}var v=S.content.value[0];if(v.tagClass!==t.Class.UNIVERSAL||v.type!==t.Type.OCTETSTRING)throw Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(v=m(v),S.mac){var h=null,u=0,R=t.derToOid(S.macAlgorithm);switch(R){case i.oids.sha1:h=e.md.sha1.create(),u=20;break;case i.oids.sha256:h=e.md.sha256.create(),u=32;break;case i.oids.sha384:h=e.md.sha384.create(),u=48;break;case i.oids.sha512:h=e.md.sha512.create(),u=64;break;case i.oids.md5:h=e.md.md5.create(),u=16;break}if(h===null)throw Error("PKCS#12 uses unsupported MAC algorithm: "+R);var V=new e.util.ByteBuffer(S.macSalt),O="macIterations"in S?parseInt(e.util.bytesToHex(S.macIterations),16):1,K=c.generateKey(l,V,3,O,u,h),G=e.hmac.create();G.start(h,K),G.update(v.value);var H=G.getMac();if(H.getBytes()!==S.macDigest)throw Error("PKCS#12 MAC could not be verified. Invalid password?")}return w(L,v.value,g,l),L};function m(A){if(A.composed||A.constructed){var g=e.util.createBuffer();for(var l=0;l<A.value.length;++l)g.putBytes(A.value[l].value);A.composed=A.constructed=!1,A.value=g.getBytes()}return A}function w(A,g,l,S){if(g=t.fromDer(g,l),g.tagClass!==t.Class.UNIVERSAL||g.type!==t.Type.SEQUENCE||g.constructed!==!0)throw Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var I=0;I<g.value.length;I++){var N=g.value[I],L={},v=[];if(!t.validate(N,f,L,v)){var h=Error("Cannot read ContentInfo.");throw h.errors=v,h}var u={encrypted:!1},R=null,V=L.content.value[0];switch(t.derToOid(L.contentType)){case i.oids.data:if(V.tagClass!==t.Class.UNIVERSAL||V.type!==t.Type.OCTETSTRING)throw Error("PKCS#12 SafeContents Data is not an OCTET STRING.");R=m(V).value;break;case i.oids.encryptedData:R=B(V,S),u.encrypted=!0;break;default:var h=Error("Unsupported PKCS#12 contentType.");throw h.contentType=t.derToOid(L.contentType),h}u.safeBags=d(R,l,S),A.safeContents.push(u)}}function B(A,g){var l={},S=[];if(!t.validate(A,e.pkcs7.asn1.encryptedDataValidator,l,S)){var I=Error("Cannot read EncryptedContentInfo.");throw I.errors=S,I}var N=t.derToOid(l.contentType);if(N!==i.oids.data){var I=Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw I.oid=N,I}N=t.derToOid(l.encAlgorithm);var L=i.pbe.getCipher(N,l.encParameter,g),v=m(l.encryptedContentAsn1),h=e.util.createBuffer(v.value);if(L.update(h),!L.finish())throw Error("Failed to decrypt PKCS#12 SafeContents.");return L.output.getBytes()}function d(A,g,l){if(!g&&A.length===0)return[];if(A=t.fromDer(A,g),A.tagClass!==t.Class.UNIVERSAL||A.type!==t.Type.SEQUENCE||A.constructed!==!0)throw Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.");var S=[];for(var I=0;I<A.value.length;I++){var N=A.value[I],L={},v=[];if(!t.validate(N,s,L,v)){var h=Error("Cannot read SafeBag.");throw h.errors=v,h}var u={type:t.derToOid(L.bagId),attributes:T(L.bagAttributes)};S.push(u);var R,V,O=L.bagValue.value[0];switch(u.type){case i.oids.pkcs8ShroudedKeyBag:if(O=i.decryptPrivateKeyInfo(O,l),O===null)throw Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case i.oids.keyBag:try{u.key=i.privateKeyFromAsn1(O)}catch(G){u.key=null,u.asn1=O}continue;case i.oids.certBag:R=C,V=function(){if(t.derToOid(L.certId)!==i.oids.x509Certificate){var G=Error("Unsupported certificate type, only X.509 supported.");throw G.oid=t.derToOid(L.certId),G}var H=t.fromDer(L.cert,g);try{u.cert=i.certificateFromAsn1(H,!0)}catch(j){u.cert=null,u.asn1=H}};break;default:var h=Error("Unsupported PKCS#12 SafeBag type.");throw h.oid=u.type,h}if(R!==void 0&&!t.validate(O,R,L,v)){var h=Error("Cannot read PKCS#12 "+R.name);throw h.errors=v,h}V()}return S}function T(A){var g={};if(A!==void 0)for(var l=0;l<A.length;++l){var S={},I=[];if(!t.validate(A[l],a,S,I)){var N=Error("Cannot read PKCS#12 BagAttribute.");throw N.errors=I,N}var L=t.derToOid(S.oid);if(i.oids[L]===void 0)continue;g[i.oids[L]]=[];for(var v=0;v<S.values.length;++v)g[i.oids[L]].push(S.values[v].value)}return g}c.toPkcs12Asn1=function(A,g,l,S){if(S=S||{},S.saltSize=S.saltSize||8,S.count=S.count||2048,S.algorithm=S.algorithm||S.encAlgorithm||"aes128",!("useMac"in S))S.useMac=!0;if(!("localKeyId"in S))S.localKeyId=null;if(!("generateLocalKeyId"in S))S.generateLocalKeyId=!0;var I=S.localKeyId,N;if(I!==null)I=e.util.hexToBytes(I);else if(S.generateLocalKeyId)if(g){var L=e.util.isArray(g)?g[0]:g;if(typeof L==="string")L=i.certificateFromPem(L);var v=e.md.sha1.create();v.update(t.toDer(i.certificateToAsn1(L)).getBytes()),I=v.digest().getBytes()}else I=e.random.getBytes(20);var h=[];if(I!==null)h.push(t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(i.oids.localKeyId).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SET,!0,[t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,I)])]));if("friendlyName"in S)h.push(t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(i.oids.friendlyName).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SET,!0,[t.create(t.Class.UNIVERSAL,t.Type.BMPSTRING,!1,S.friendlyName)])]));if(h.length>0)N=t.create(t.Class.UNIVERSAL,t.Type.SET,!0,h);var u=[],R=[];if(g!==null)if(e.util.isArray(g))R=g;else R=[g];var V=[];for(var O=0;O<R.length;++O){if(g=R[O],typeof g==="string")g=i.certificateFromPem(g);var K=O===0?N:void 0,G=i.certificateToAsn1(g),H=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(i.oids.certBag).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(i.oids.x509Certificate).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,t.toDer(G).getBytes())])])]),K]);V.push(H)}if(V.length>0){var j=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,V),z=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(i.oids.data).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,t.toDer(j).getBytes())])]);u.push(z)}var Z=null;if(A!==null){var tt=i.wrapRsaPrivateKey(i.privateKeyToAsn1(A));if(l===null)Z=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(i.oids.keyBag).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[tt]),N]);else Z=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(i.oids.pkcs8ShroudedKeyBag).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[i.encryptPrivateKeyInfo(tt,l,S)]),N]);var rt=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[Z]),ut=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(i.oids.data).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,t.toDer(rt).getBytes())])]);u.push(ut)}var ht=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,u),Et;if(S.useMac){var v=e.md.sha1.create(),_t=new e.util.ByteBuffer(e.random.getBytes(S.saltSize)),J=S.count,A=c.generateKey(l,_t,3,J,20),vt=e.hmac.create();vt.start(v,A),vt.update(t.toDer(ht).getBytes());var et=vt.getMac();Et=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(i.oids.sha1).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.NULL,!1,"")]),t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,et.getBytes())]),t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,_t.getBytes()),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,t.integerToDer(J).getBytes())])}return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,t.integerToDer(3).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(i.oids.data).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,t.toDer(ht).getBytes())])]),Et])},c.generateKey=e.pbe.generatePkcs12Key}),ha=lt((r,n)=>{var e=pt();Ue(),Pe(),ua(),hr(),Fi(),la(),qi(),Jr(),Tt(),Hi();var t=e.asn1,i=n.exports=e.pki=e.pki||{};i.pemToDer=function(c){var f=e.pem.decode(c)[0];if(f.procType&&f.procType.type==="ENCRYPTED")throw Error("Could not convert PEM to DER; PEM is encrypted.");return e.util.createBuffer(f.body)},i.privateKeyFromPem=function(c){var f=e.pem.decode(c)[0];if(f.type!=="PRIVATE KEY"&&f.type!=="RSA PRIVATE KEY"){var o=Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw o.headerType=f.type,o}if(f.procType&&f.procType.type==="ENCRYPTED")throw Error("Could not convert private key from PEM; PEM is encrypted.");var s=t.fromDer(f.body);return i.privateKeyFromAsn1(s)},i.privateKeyToPem=function(c,f){var o={type:"RSA PRIVATE KEY",body:t.toDer(i.privateKeyToAsn1(c)).getBytes()};return e.pem.encode(o,{maxline:f})},i.privateKeyInfoToPem=function(c,f){var o={type:"PRIVATE KEY",body:t.toDer(c).getBytes()};return e.pem.encode(o,{maxline:f})}}),oa=lt((r,n)=>{var e=pt();Ue(),dr(),Gi(),hr(),ha(),we(),Cr(),Tt();var t=function(E,D,k,y){var b=e.util.createBuffer(),F=E.length>>1,M=F+(E.length&1),W=E.substr(0,M),nt=E.substr(F,M),ct=e.util.createBuffer(),P=e.hmac.create();k=D+k;var at=Math.ceil(y/16),ft=Math.ceil(y/20);P.start("MD5",W);var Ct=e.util.createBuffer();ct.putBytes(k);for(var ot=0;ot<at;++ot)P.start(null,null),P.update(ct.getBytes()),ct.putBuffer(P.digest()),P.start(null,null),P.update(ct.bytes()+k),Ct.putBuffer(P.digest());P.start("SHA1",nt);var bt=e.util.createBuffer();ct.clear(),ct.putBytes(k);for(var ot=0;ot<ft;++ot)P.start(null,null),P.update(ct.getBytes()),ct.putBuffer(P.digest()),P.start(null,null),P.update(ct.bytes()+k),bt.putBuffer(P.digest());return b.putBytes(e.util.xorBytes(Ct.getBytes(),bt.getBytes(),y)),b},i=function(E,D,k){var y=e.hmac.create();y.start("SHA1",E);var b=e.util.createBuffer();return b.putInt32(D[0]),b.putInt32(D[1]),b.putByte(k.type),b.putByte(k.version.major),b.putByte(k.version.minor),b.putInt16(k.length),b.putBytes(k.fragment.bytes()),y.update(b.getBytes()),y.digest().getBytes()},c=function(E,D,k){var y=!1;try{var b=E.deflate(D.fragment.getBytes());D.fragment=e.util.createBuffer(b),D.length=b.length,y=!0}catch(F){}return y},f=function(E,D,k){var y=!1;try{var b=E.inflate(D.fragment.getBytes());D.fragment=e.util.createBuffer(b),D.length=b.length,y=!0}catch(F){}return y},o=function(E,D){var k=0;switch(D){case 1:k=E.getByte();break;case 2:k=E.getInt16();break;case 3:k=E.getInt24();break;case 4:k=E.getInt32();break}return e.util.createBuffer(E.getBytes(k))},s=function(E,D,k){E.putInt(k.length(),D<<3),E.putBuffer(k)},a={};a.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}},a.SupportedVersions=[a.Versions.TLS_1_1,a.Versions.TLS_1_0],a.Version=a.SupportedVersions[0],a.MaxFragment=15360,a.ConnectionEnd={server:0,client:1},a.PRFAlgorithm={tls_prf_sha256:0},a.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2},a.CipherType={stream:0,block:1,aead:2},a.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4},a.CompressionMethod={none:0,deflate:1},a.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24},a.HandshakeType={hello_request:0,client_hello:1,server_hello:2,certificate:11,server_key_exchange:12,certificate_request:13,server_hello_done:14,certificate_verify:15,client_key_exchange:16,finished:20},a.Alert={},a.Alert.Level={warning:1,fatal:2},a.Alert.Description={close_notify:0,unexpected_message:10,bad_record_mac:20,decryption_failed:21,record_overflow:22,decompression_failure:30,handshake_failure:40,bad_certificate:42,unsupported_certificate:43,certificate_revoked:44,certificate_expired:45,certificate_unknown:46,illegal_parameter:47,unknown_ca:48,access_denied:49,decode_error:50,decrypt_error:51,export_restriction:60,protocol_version:70,insufficient_security:71,internal_error:80,user_canceled:90,no_renegotiation:100},a.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2},a.CipherSuites={},a.getCipherSuite=function(E){var D=null;for(var k in a.CipherSuites){var y=a.CipherSuites[k];if(y.id[0]===E.charCodeAt(0)&&y.id[1]===E.charCodeAt(1)){D=y;break}}return D},a.handleUnexpected=function(E,D){var k=!E.open&&E.entity===a.ConnectionEnd.client;if(!k)E.error(E,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.unexpected_message}})},a.handleHelloRequest=function(E,D,k){if(!E.handshaking&&E.handshakes>0)a.queue(E,a.createAlert(E,{level:a.Alert.Level.warning,description:a.Alert.Description.no_renegotiation})),a.flush(E);E.process()},a.parseHelloMessage=function(E,D,k){var y=null,b=E.entity===a.ConnectionEnd.client;if(k<38)E.error(E,{message:b?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.illegal_parameter}});else{var F=D.fragment,M=F.length();if(y={version:{major:F.getByte(),minor:F.getByte()},random:e.util.createBuffer(F.getBytes(32)),session_id:o(F,1),extensions:[]},b)y.cipher_suite=F.getBytes(2),y.compression_method=F.getByte();else y.cipher_suites=o(F,2),y.compression_methods=o(F,1);if(M=k-(M-F.length()),M>0){var W=o(F,2);while(W.length()>0)y.extensions.push({type:[W.getByte(),W.getByte()],data:o(W,2)});if(!b)for(var nt=0;nt<y.extensions.length;++nt){var ct=y.extensions[nt];if(ct.type[0]===0&&ct.type[1]===0){var P=o(ct.data,2);while(P.length()>0){var at=P.getByte();if(at!==0)break;E.session.extensions.server_name.serverNameList.push(o(P,2).getBytes())}}}}if(E.session.version){if(y.version.major!==E.session.version.major||y.version.minor!==E.session.version.minor)return E.error(E,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.protocol_version}})}if(b)E.session.cipherSuite=a.getCipherSuite(y.cipher_suite);else{var ft=e.util.createBuffer(y.cipher_suites.bytes());while(ft.length()>0)if(E.session.cipherSuite=a.getCipherSuite(ft.getBytes(2)),E.session.cipherSuite!==null)break}if(E.session.cipherSuite===null)return E.error(E,{message:"No cipher suites in common.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.handshake_failure},cipherSuite:e.util.bytesToHex(y.cipher_suite)});if(b)E.session.compressionMethod=y.compression_method;else E.session.compressionMethod=a.CompressionMethod.none}return y},a.createSecurityParameters=function(E,D){var k=E.entity===a.ConnectionEnd.client,y=D.random.bytes(),b=k?E.session.sp.client_random:y,F=k?y:a.createRandom().getBytes();E.session.sp={entity:E.entity,prf_algorithm:a.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:E.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:b,server_random:F}},a.handleServerHello=function(E,D,k){var y=a.parseHelloMessage(E,D,k);if(E.fail)return;if(y.version.minor<=E.version.minor)E.version.minor=y.version.minor;else return E.error(E,{message:"Incompatible TLS version.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.protocol_version}});E.session.version=E.version;var b=y.session_id.bytes();if(b.length>0&&b===E.session.id)E.expect=d,E.session.resuming=!0,E.session.sp.server_random=y.random.bytes();else E.expect=p,E.session.resuming=!1,a.createSecurityParameters(E,y);E.session.id=b,E.process()},a.handleClientHello=function(E,D,k){var y=a.parseHelloMessage(E,D,k);if(E.fail)return;var b=y.session_id.bytes(),F=null;if(E.sessionCache){if(F=E.sessionCache.getSession(b),F===null)b="";else if(F.version.major!==y.version.major||F.version.minor>y.version.minor)F=null,b=""}if(b.length===0)b=e.random.getBytes(32);if(E.session.id=b,E.session.clientHelloVersion=y.version,E.session.sp={},F)E.version=E.session.version=F.version,E.session.sp=F.sp;else{var M;for(var W=1;W<a.SupportedVersions.length;++W)if(M=a.SupportedVersions[W],M.minor<=y.version.minor)break;E.version={major:M.major,minor:M.minor},E.session.version=E.version}if(F!==null)E.expect=L,E.session.resuming=!0,E.session.sp.client_random=y.random.bytes();else E.expect=E.verifyClient!==!1?S:I,E.session.resuming=!1,a.createSecurityParameters(E,y);if(E.open=!0,a.queue(E,a.createRecord(E,{type:a.ContentType.handshake,data:a.createServerHello(E)})),E.session.resuming)a.queue(E,a.createRecord(E,{type:a.ContentType.change_cipher_spec,data:a.createChangeCipherSpec()})),E.state.pending=a.createConnectionState(E),E.state.current.write=E.state.pending.write,a.queue(E,a.createRecord(E,{type:a.ContentType.handshake,data:a.createFinished(E)}));else if(a.queue(E,a.createRecord(E,{type:a.ContentType.handshake,data:a.createCertificate(E)})),!E.fail){if(a.queue(E,a.createRecord(E,{type:a.ContentType.handshake,data:a.createServerKeyExchange(E)})),E.verifyClient!==!1)a.queue(E,a.createRecord(E,{type:a.ContentType.handshake,data:a.createCertificateRequest(E)}));a.queue(E,a.createRecord(E,{type:a.ContentType.handshake,data:a.createServerHelloDone(E)}))}a.flush(E),E.process()},a.handleCertificate=function(E,D,k){if(k<3)return E.error(E,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.illegal_parameter}});var y=D.fragment,b={certificate_list:o(y,3)},F,M,W=[];try{while(b.certificate_list.length()>0)F=o(b.certificate_list,3),M=e.asn1.fromDer(F),F=e.pki.certificateFromAsn1(M,!0),W.push(F)}catch(ct){return E.error(E,{message:"Could not parse certificate list.",cause:ct,send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.bad_certificate}})}var nt=E.entity===a.ConnectionEnd.client;if((nt||E.verifyClient===!0)&&W.length===0)E.error(E,{message:nt?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.illegal_parameter}});else if(W.length===0)E.expect=nt?m:I;else{if(nt)E.session.serverCertificate=W[0];else E.session.clientCertificate=W[0];if(a.verifyCertificateChain(E,W))E.expect=nt?m:I}E.process()},a.handleServerKeyExchange=function(E,D,k){if(k>0)return E.error(E,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.unsupported_certificate}});E.expect=w,E.process()},a.handleClientKeyExchange=function(E,D,k){if(k<48)return E.error(E,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.unsupported_certificate}});var y=D.fragment,b={enc_pre_master_secret:o(y,2).getBytes()},F=null;if(E.getPrivateKey)try{F=E.getPrivateKey(E,E.session.serverCertificate),F=e.pki.privateKeyFromPem(F)}catch(nt){E.error(E,{message:"Could not get private key.",cause:nt,send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.internal_error}})}if(F===null)return E.error(E,{message:"No private key set.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.internal_error}});try{var M=E.session.sp;M.pre_master_secret=F.decrypt(b.enc_pre_master_secret);var W=E.session.clientHelloVersion;if(W.major!==M.pre_master_secret.charCodeAt(0)||W.minor!==M.pre_master_secret.charCodeAt(1))throw Error("TLS version rollback attack detected.")}catch(nt){M.pre_master_secret=e.random.getBytes(48)}if(E.expect=L,E.session.clientCertificate!==null)E.expect=N;E.process()},a.handleCertificateRequest=function(E,D,k){if(k<3)return E.error(E,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.illegal_parameter}});var y=D.fragment,b={certificate_types:o(y,1),certificate_authorities:o(y,2)};E.session.certificateRequest=b,E.expect=B,E.process()},a.handleCertificateVerify=function(E,D,k){if(k<2)return E.error(E,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.illegal_parameter}});var y=D.fragment;y.read-=4;var b=y.bytes();y.read+=4;var F={signature:o(y,2).getBytes()},M=e.util.createBuffer();M.putBuffer(E.session.md5.digest()),M.putBuffer(E.session.sha1.digest()),M=M.getBytes();try{var W=E.session.clientCertificate;if(!W.publicKey.verify(M,F.signature,"NONE"))throw Error("CertificateVerify signature does not match.");E.session.md5.update(b),E.session.sha1.update(b)}catch(nt){return E.error(E,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.handshake_failure}})}E.expect=L,E.process()},a.handleServerHelloDone=function(E,D,k){if(k>0)return E.error(E,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.record_overflow}});if(E.serverCertificate===null){var y={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.insufficient_security}},b=0,F=E.verify(E,y.alert.description,b,[]);if(F!==!0){if(F||F===0){if(typeof F==="object"&&!e.util.isArray(F)){if(F.message)y.message=F.message;if(F.alert)y.alert.description=F.alert}else if(typeof F==="number")y.alert.description=F}return E.error(E,y)}}if(E.session.certificateRequest!==null)D=a.createRecord(E,{type:a.ContentType.handshake,data:a.createCertificate(E)}),a.queue(E,D);D=a.createRecord(E,{type:a.ContentType.handshake,data:a.createClientKeyExchange(E)}),a.queue(E,D),E.expect=g;var M=function(W,nt){if(W.session.certificateRequest!==null&&W.session.clientCertificate!==null)a.queue(W,a.createRecord(W,{type:a.ContentType.handshake,data:a.createCertificateVerify(W,nt)}));a.queue(W,a.createRecord(W,{type:a.ContentType.change_cipher_spec,data:a.createChangeCipherSpec()})),W.state.pending=a.createConnectionState(W),W.state.current.write=W.state.pending.write,a.queue(W,a.createRecord(W,{type:a.ContentType.handshake,data:a.createFinished(W)})),W.expect=d,a.flush(W),W.process()};if(E.session.certificateRequest===null||E.session.clientCertificate===null)return M(E,null);a.getClientSignature(E,M)},a.handleChangeCipherSpec=function(E,D){if(D.fragment.getByte()!==1)return E.error(E,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.illegal_parameter}});var k=E.entity===a.ConnectionEnd.client;if(E.session.resuming&&k||!E.session.resuming&&!k)E.state.pending=a.createConnectionState(E);if(E.state.current.read=E.state.pending.read,!E.session.resuming&&k||E.session.resuming&&!k)E.state.pending=null;E.expect=k?T:v,E.process()},a.handleFinished=function(E,D,k){var y=D.fragment;y.read-=4;var b=y.bytes();y.read+=4;var F=D.fragment.getBytes();y=e.util.createBuffer(),y.putBuffer(E.session.md5.digest()),y.putBuffer(E.session.sha1.digest());var M=E.entity===a.ConnectionEnd.client,W=M?"server finished":"client finished",nt=E.session.sp,ct=12,P=t;if(y=P(nt.master_secret,W,y.getBytes(),ct),y.getBytes()!==F)return E.error(E,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.decrypt_error}});if(E.session.md5.update(b),E.session.sha1.update(b),E.session.resuming&&M||!E.session.resuming&&!M)a.queue(E,a.createRecord(E,{type:a.ContentType.change_cipher_spec,data:a.createChangeCipherSpec()})),E.state.current.write=E.state.pending.write,E.state.pending=null,a.queue(E,a.createRecord(E,{type:a.ContentType.handshake,data:a.createFinished(E)}));E.expect=M?A:h,E.handshaking=!1,++E.handshakes,E.peerCertificate=M?E.session.serverCertificate:E.session.clientCertificate,a.flush(E),E.isConnected=!0,E.connected(E),E.process()},a.handleAlert=function(E,D){var k=D.fragment,y={level:k.getByte(),description:k.getByte()},b;switch(y.description){case a.Alert.Description.close_notify:b="Connection closed.";break;case a.Alert.Description.unexpected_message:b="Unexpected message.";break;case a.Alert.Description.bad_record_mac:b="Bad record MAC.";break;case a.Alert.Description.decryption_failed:b="Decryption failed.";break;case a.Alert.Description.record_overflow:b="Record overflow.";break;case a.Alert.Description.decompression_failure:b="Decompression failed.";break;case a.Alert.Description.handshake_failure:b="Handshake failure.";break;case a.Alert.Description.bad_certificate:b="Bad certificate.";break;case a.Alert.Description.unsupported_certificate:b="Unsupported certificate.";break;case a.Alert.Description.certificate_revoked:b="Certificate revoked.";break;case a.Alert.Description.certificate_expired:b="Certificate expired.";break;case a.Alert.Description.certificate_unknown:b="Certificate unknown.";break;case a.Alert.Description.illegal_parameter:b="Illegal parameter.";break;case a.Alert.Description.unknown_ca:b="Unknown certificate authority.";break;case a.Alert.Description.access_denied:b="Access denied.";break;case a.Alert.Description.decode_error:b="Decode error.";break;case a.Alert.Description.decrypt_error:b="Decrypt error.";break;case a.Alert.Description.export_restriction:b="Export restriction.";break;case a.Alert.Description.protocol_version:b="Unsupported protocol version.";break;case a.Alert.Description.insufficient_security:b="Insufficient security.";break;case a.Alert.Description.internal_error:b="Internal error.";break;case a.Alert.Description.user_canceled:b="User canceled.";break;case a.Alert.Description.no_renegotiation:b="Renegotiation not supported.";break;default:b="Unknown error.";break}if(y.description===a.Alert.Description.close_notify)return E.close();E.error(E,{message:b,send:!1,origin:E.entity===a.ConnectionEnd.client?"server":"client",alert:y}),E.process()},a.handleHandshake=function(E,D){var k=D.fragment,y=k.getByte(),b=k.getInt24();if(b>k.length())return E.fragmented=D,D.fragment=e.util.createBuffer(),k.read-=4,E.process();E.fragmented=null,k.read-=4;var F=k.bytes(b+4);if(k.read+=4,y in Et[E.entity][E.expect]){if(E.entity===a.ConnectionEnd.server&&!E.open&&!E.fail)E.handshaking=!0,E.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:e.md.md5.create(),sha1:e.md.sha1.create()};if(y!==a.HandshakeType.hello_request&&y!==a.HandshakeType.certificate_verify&&y!==a.HandshakeType.finished)E.session.md5.update(F),E.session.sha1.update(F);Et[E.entity][E.expect][y](E,D,b)}else a.handleUnexpected(E,D)},a.handleApplicationData=function(E,D){E.data.putBuffer(D.fragment),E.dataReady(E),E.process()},a.handleHeartbeat=function(E,D){var k=D.fragment,y=k.getByte(),b=k.getInt16(),F=k.getBytes(b);if(y===a.HeartbeatMessageType.heartbeat_request){if(E.handshaking||b>F.length)return E.process();a.queue(E,a.createRecord(E,{type:a.ContentType.heartbeat,data:a.createHeartbeat(a.HeartbeatMessageType.heartbeat_response,F)})),a.flush(E)}else if(y===a.HeartbeatMessageType.heartbeat_response){if(F!==E.expectedHeartbeatPayload)return E.process();if(E.heartbeatReceived)E.heartbeatReceived(E,e.util.createBuffer(F))}E.process()};var C=0,p=1,m=2,w=3,B=4,d=5,T=6,A=7,g=8,l=0,S=1,I=2,N=3,L=4,v=5,h=6,u=a.handleUnexpected,R=a.handleChangeCipherSpec,V=a.handleAlert,O=a.handleHandshake,K=a.handleApplicationData,G=a.handleHeartbeat,H=[];H[a.ConnectionEnd.client]=[[u,V,O,u,G],[u,V,O,u,G],[u,V,O,u,G],[u,V,O,u,G],[u,V,O,u,G],[R,V,u,u,G],[u,V,O,u,G],[u,V,O,K,G],[u,V,O,u,G]],H[a.ConnectionEnd.server]=[[u,V,O,u,G],[u,V,O,u,G],[u,V,O,u,G],[u,V,O,u,G],[R,V,u,u,G],[u,V,O,u,G],[u,V,O,K,G],[u,V,O,u,G]];var{handleHelloRequest:j,handleServerHello:z,handleCertificate:Z,handleServerKeyExchange:tt,handleCertificateRequest:rt,handleServerHelloDone:ut,handleFinished:ht}=a,Et=[];Et[a.ConnectionEnd.client]=[[u,u,z,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u],[j,u,u,u,u,u,u,u,u,u,u,Z,tt,rt,ut,u,u,u,u,u,u],[j,u,u,u,u,u,u,u,u,u,u,u,tt,rt,ut,u,u,u,u,u,u],[j,u,u,u,u,u,u,u,u,u,u,u,u,rt,ut,u,u,u,u,u,u],[j,u,u,u,u,u,u,u,u,u,u,u,u,u,ut,u,u,u,u,u,u],[j,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u],[j,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,ht],[j,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u],[j,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u]];var{handleClientHello:_t,handleClientKeyExchange:J,handleCertificateVerify:vt}=a;Et[a.ConnectionEnd.server]=[[u,_t,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u],[u,u,u,u,u,u,u,u,u,u,u,Z,u,u,u,u,u,u,u,u,u],[u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,J,u,u,u,u],[u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,vt,u,u,u,u,u],[u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u],[u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,ht],[u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u],[u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u]],a.generateKeys=function(E,D){var k=t,y=D.client_random+D.server_random;if(!E.session.resuming)D.master_secret=k(D.pre_master_secret,"master secret",y,48).bytes(),D.pre_master_secret=null;y=D.server_random+D.client_random;var b=2*D.mac_key_length+2*D.enc_key_length,F=E.version.major===a.Versions.TLS_1_0.major&&E.version.minor===a.Versions.TLS_1_0.minor;if(F)b+=2*D.fixed_iv_length;var M=k(D.master_secret,"key expansion",y,b),W={client_write_MAC_key:M.getBytes(D.mac_key_length),server_write_MAC_key:M.getBytes(D.mac_key_length),client_write_key:M.getBytes(D.enc_key_length),server_write_key:M.getBytes(D.enc_key_length)};if(F)W.client_write_IV=M.getBytes(D.fixed_iv_length),W.server_write_IV=M.getBytes(D.fixed_iv_length);return W},a.createConnectionState=function(E){var D=E.entity===a.ConnectionEnd.client,k=function(){var F={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(M){return!0},compressionState:null,compressFunction:function(M){return!0},updateSequenceNumber:function(){if(F.sequenceNumber[1]===4294967295)F.sequenceNumber[1]=0,++F.sequenceNumber[0];else++F.sequenceNumber[1]}};return F},y={read:k(),write:k()};if(y.read.update=function(F,M){if(!y.read.cipherFunction(M,y.read))F.error(F,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.bad_record_mac}});else if(!y.read.compressFunction(F,M,y.read))F.error(F,{message:"Could not decompress record.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.decompression_failure}});return!F.fail},y.write.update=function(F,M){if(!y.write.compressFunction(F,M,y.write))F.error(F,{message:"Could not compress record.",send:!1,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.internal_error}});else if(!y.write.cipherFunction(M,y.write))F.error(F,{message:"Could not encrypt record.",send:!1,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.internal_error}});return!F.fail},E.session){var b=E.session.sp;switch(E.session.cipherSuite.initSecurityParameters(b),b.keys=a.generateKeys(E,b),y.read.macKey=D?b.keys.server_write_MAC_key:b.keys.client_write_MAC_key,y.write.macKey=D?b.keys.client_write_MAC_key:b.keys.server_write_MAC_key,E.session.cipherSuite.initConnectionState(y,E,b),b.compression_algorithm){case a.CompressionMethod.none:break;case a.CompressionMethod.deflate:y.read.compressFunction=f,y.write.compressFunction=c;break;default:throw Error("Unsupported compression algorithm.")}}return y},a.createRandom=function(){var E=new Date,D=+E+E.getTimezoneOffset()*60000,k=e.util.createBuffer();return k.putInt32(D),k.putBytes(e.random.getBytes(28)),k},a.createRecord=function(E,D){if(!D.data)return null;var k={type:D.type,version:{major:E.version.major,minor:E.version.minor},length:D.data.length(),fragment:D.data};return k},a.createAlert=function(E,D){var k=e.util.createBuffer();return k.putByte(D.level),k.putByte(D.description),a.createRecord(E,{type:a.ContentType.alert,data:k})},a.createClientHello=function(E){E.session.clientHelloVersion={major:E.version.major,minor:E.version.minor};var D=e.util.createBuffer();for(var k=0;k<E.cipherSuites.length;++k){var y=E.cipherSuites[k];D.putByte(y.id[0]),D.putByte(y.id[1])}var b=D.length(),F=e.util.createBuffer();F.putByte(a.CompressionMethod.none);var M=F.length(),W=e.util.createBuffer();if(E.virtualHost){var nt=e.util.createBuffer();nt.putByte(0),nt.putByte(0);var ct=e.util.createBuffer();ct.putByte(0),s(ct,2,e.util.createBuffer(E.virtualHost));var P=e.util.createBuffer();s(P,2,ct),s(nt,2,P),W.putBuffer(nt)}var at=W.length();if(at>0)at+=2;var ft=E.session.id,Ct=ft.length+1+2+4+28+2+b+1+M+at,ot=e.util.createBuffer();if(ot.putByte(a.HandshakeType.client_hello),ot.putInt24(Ct),ot.putByte(E.version.major),ot.putByte(E.version.minor),ot.putBytes(E.session.sp.client_random),s(ot,1,e.util.createBuffer(ft)),s(ot,2,D),s(ot,1,F),at>0)s(ot,2,W);return ot},a.createServerHello=function(E){var D=E.session.id,k=D.length+1+2+4+28+2+1,y=e.util.createBuffer();return y.putByte(a.HandshakeType.server_hello),y.putInt24(k),y.putByte(E.version.major),y.putByte(E.version.minor),y.putBytes(E.session.sp.server_random),s(y,1,e.util.createBuffer(D)),y.putByte(E.session.cipherSuite.id[0]),y.putByte(E.session.cipherSuite.id[1]),y.putByte(E.session.compressionMethod),y},a.createCertificate=function(E){var D=E.entity===a.ConnectionEnd.client,k=null;if(E.getCertificate){var y;if(D)y=E.session.certificateRequest;else y=E.session.extensions.server_name.serverNameList;k=E.getCertificate(E,y)}var b=e.util.createBuffer();if(k!==null)try{if(!e.util.isArray(k))k=[k];var F=null;for(var M=0;M<k.length;++M){var W=e.pem.decode(k[M])[0];if(W.type!=="CERTIFICATE"&&W.type!=="X509 CERTIFICATE"&&W.type!=="TRUSTED CERTIFICATE"){var nt=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw nt.headerType=W.type,nt}if(W.procType&&W.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var ct=e.util.createBuffer(W.body);if(F===null)F=e.asn1.fromDer(ct.bytes(),!1);var P=e.util.createBuffer();s(P,3,ct),b.putBuffer(P)}if(k=e.pki.certificateFromAsn1(F),D)E.session.clientCertificate=k;else E.session.serverCertificate=k}catch(Ct){return E.error(E,{message:"Could not send certificate list.",cause:Ct,send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.bad_certificate}})}var at=3+b.length(),ft=e.util.createBuffer();return ft.putByte(a.HandshakeType.certificate),ft.putInt24(at),s(ft,3,b),ft},a.createClientKeyExchange=function(E){var D=e.util.createBuffer();D.putByte(E.session.clientHelloVersion.major),D.putByte(E.session.clientHelloVersion.minor),D.putBytes(e.random.getBytes(46));var k=E.session.sp;k.pre_master_secret=D.getBytes();var y=E.session.serverCertificate.publicKey;D=y.encrypt(k.pre_master_secret);var b=D.length+2,F=e.util.createBuffer();return F.putByte(a.HandshakeType.client_key_exchange),F.putInt24(b),F.putInt16(D.length),F.putBytes(D),F},a.createServerKeyExchange=function(E){var D=0,k=e.util.createBuffer();if(D>0)k.putByte(a.HandshakeType.server_key_exchange),k.putInt24(D);return k},a.getClientSignature=function(E,D){var k=e.util.createBuffer();k.putBuffer(E.session.md5.digest()),k.putBuffer(E.session.sha1.digest()),k=k.getBytes(),E.getSignature=E.getSignature||function(y,b,F){var M=null;if(y.getPrivateKey)try{M=y.getPrivateKey(y,y.session.clientCertificate),M=e.pki.privateKeyFromPem(M)}catch(W){y.error(y,{message:"Could not get private key.",cause:W,send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.internal_error}})}if(M===null)y.error(y,{message:"No private key set.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.internal_error}});else b=M.sign(b,null);F(y,b)},E.getSignature(E,k,D)},a.createCertificateVerify=function(E,D){var k=D.length+2,y=e.util.createBuffer();return y.putByte(a.HandshakeType.certificate_verify),y.putInt24(k),y.putInt16(D.length),y.putBytes(D),y},a.createCertificateRequest=function(E){var D=e.util.createBuffer();D.putByte(1);var k=e.util.createBuffer();for(var y in E.caStore.certs){var b=E.caStore.certs[y],F=e.pki.distinguishedNameToAsn1(b.subject),M=e.asn1.toDer(F);k.putInt16(M.length()),k.putBuffer(M)}var W=1+D.length()+2+k.length(),nt=e.util.createBuffer();return nt.putByte(a.HandshakeType.certificate_request),nt.putInt24(W),s(nt,1,D),s(nt,2,k),nt},a.createServerHelloDone=function(E){var D=e.util.createBuffer();return D.putByte(a.HandshakeType.server_hello_done),D.putInt24(0),D},a.createChangeCipherSpec=function(){var E=e.util.createBuffer();return E.putByte(1),E},a.createFinished=function(E){var D=e.util.createBuffer();D.putBuffer(E.session.md5.digest()),D.putBuffer(E.session.sha1.digest());var k=E.entity===a.ConnectionEnd.client,y=E.session.sp,b=12,F=t,M=k?"client finished":"server finished";D=F(y.master_secret,M,D.getBytes(),b);var W=e.util.createBuffer();return W.putByte(a.HandshakeType.finished),W.putInt24(D.length()),W.putBuffer(D),W},a.createHeartbeat=function(E,D,k){if(typeof k>"u")k=D.length;var y=e.util.createBuffer();y.putByte(E),y.putInt16(k),y.putBytes(D);var b=y.length(),F=Math.max(16,b-k-3);return y.putBytes(e.random.getBytes(F)),y},a.queue=function(E,D){if(!D)return;if(D.fragment.length()===0){if(D.type===a.ContentType.handshake||D.type===a.ContentType.alert||D.type===a.ContentType.change_cipher_spec)return}if(D.type===a.ContentType.handshake){var k=D.fragment.bytes();E.session.md5.update(k),E.session.sha1.update(k),k=null}var y;if(D.fragment.length()<=a.MaxFragment)y=[D];else{y=[];var b=D.fragment.bytes();while(b.length>a.MaxFragment)y.push(a.createRecord(E,{type:D.type,data:e.util.createBuffer(b.slice(0,a.MaxFragment))})),b=b.slice(a.MaxFragment);if(b.length>0)y.push(a.createRecord(E,{type:D.type,data:e.util.createBuffer(b)}))}for(var F=0;F<y.length&&!E.fail;++F){var M=y[F],W=E.state.current.write;if(W.update(E,M))E.records.push(M)}},a.flush=function(E){for(var D=0;D<E.records.length;++D){var k=E.records[D];E.tlsData.putByte(k.type),E.tlsData.putByte(k.version.major),E.tlsData.putByte(k.version.minor),E.tlsData.putInt16(k.fragment.length()),E.tlsData.putBuffer(E.records[D].fragment)}return E.records=[],E.tlsDataReady(E)};var et=function(E){switch(E){case!0:return!0;case e.pki.certificateError.bad_certificate:return a.Alert.Description.bad_certificate;case e.pki.certificateError.unsupported_certificate:return a.Alert.Description.unsupported_certificate;case e.pki.certificateError.certificate_revoked:return a.Alert.Description.certificate_revoked;case e.pki.certificateError.certificate_expired:return a.Alert.Description.certificate_expired;case e.pki.certificateError.certificate_unknown:return a.Alert.Description.certificate_unknown;case e.pki.certificateError.unknown_ca:return a.Alert.Description.unknown_ca;default:return a.Alert.Description.bad_certificate}},Rt=function(E){switch(E){case!0:return!0;case a.Alert.Description.bad_certificate:return e.pki.certificateError.bad_certificate;case a.Alert.Description.unsupported_certificate:return e.pki.certificateError.unsupported_certificate;case a.Alert.Description.certificate_revoked:return e.pki.certificateError.certificate_revoked;case a.Alert.Description.certificate_expired:return e.pki.certificateError.certificate_expired;case a.Alert.Description.certificate_unknown:return e.pki.certificateError.certificate_unknown;case a.Alert.Description.unknown_ca:return e.pki.certificateError.unknown_ca;default:return e.pki.certificateError.bad_certificate}};a.verifyCertificateChain=function(E,D){try{var k={};for(var y in E.verifyOptions)k[y]=E.verifyOptions[y];k.verify=function(F,M,W){var nt=et(F),ct=E.verify(E,F,M,W);if(ct!==!0){if(typeof ct==="object"&&!e.util.isArray(ct)){var P=Error("The application rejected the certificate.");if(P.send=!0,P.alert={level:a.Alert.Level.fatal,description:a.Alert.Description.bad_certificate},ct.message)P.message=ct.message;if(ct.alert)P.alert.description=ct.alert;throw P}if(ct!==F)ct=Rt(ct)}return ct},e.pki.verifyCertificateChain(E.caStore,D,k)}catch(F){var b=F;if(typeof b!=="object"||e.util.isArray(b))b={send:!0,alert:{level:a.Alert.Level.fatal,description:et(F)}};if(!("send"in b))b.send=!0;if(!("alert"in b))b.alert={level:a.Alert.Level.fatal,description:et(b.error)};E.error(E,b)}return!E.fail},a.createSessionCache=function(E,D){var k=null;if(E&&E.getSession&&E.setSession&&E.order)k=E;else{k={},k.cache=E||{},k.capacity=Math.max(D||100,1),k.order=[];for(var y in E)if(k.order.length<=D)k.order.push(y);else delete E[y];k.getSession=function(b){var F=null,M=null;if(b)M=e.util.bytesToHex(b);else if(k.order.length>0)M=k.order[0];if(M!==null&&M in k.cache){F=k.cache[M],delete k.cache[M];for(var W in k.order)if(k.order[W]===M){k.order.splice(W,1);break}}return F},k.setSession=function(b,F){if(k.order.length===k.capacity){var M=k.order.shift();delete k.cache[M]}var M=e.util.bytesToHex(b);k.order.push(M),k.cache[M]=F}}return k},a.createConnection=function(E){var D=null;if(E.caStore)if(e.util.isArray(E.caStore))D=e.pki.createCaStore(E.caStore);else D=E.caStore;else D=e.pki.createCaStore();var k=E.cipherSuites||null;if(k===null){k=[];for(var y in a.CipherSuites)k.push(a.CipherSuites[y])}var b=E.server?a.ConnectionEnd.server:a.ConnectionEnd.client,F=E.sessionCache?a.createSessionCache(E.sessionCache):null,M={version:{major:a.Version.major,minor:a.Version.minor},entity:b,sessionId:E.sessionId,caStore:D,sessionCache:F,cipherSuites:k,connected:E.connected,virtualHost:E.virtualHost||null,verifyClient:E.verifyClient||!1,verify:E.verify||function(P,at,ft,Ct){return at},verifyOptions:E.verifyOptions||{},getCertificate:E.getCertificate||null,getPrivateKey:E.getPrivateKey||null,getSignature:E.getSignature||null,input:e.util.createBuffer(),tlsData:e.util.createBuffer(),data:e.util.createBuffer(),tlsDataReady:E.tlsDataReady,dataReady:E.dataReady,heartbeatReceived:E.heartbeatReceived,closed:E.closed,error:function(P,at){if(at.origin=at.origin||(P.entity===a.ConnectionEnd.client?"client":"server"),at.send)a.queue(P,a.createAlert(P,at.alert)),a.flush(P);var ft=at.fatal!==!1;if(ft)P.fail=!0;if(E.error(P,at),ft)P.close(!1)},deflate:E.deflate||null,inflate:E.inflate||null};M.reset=function(P){M.version={major:a.Version.major,minor:a.Version.minor},M.record=null,M.session=null,M.peerCertificate=null,M.state={pending:null,current:null},M.expect=M.entity===a.ConnectionEnd.client?C:l,M.fragmented=null,M.records=[],M.open=!1,M.handshakes=0,M.handshaking=!1,M.isConnected=!1,M.fail=!(P||typeof P>"u"),M.input.clear(),M.tlsData.clear(),M.data.clear(),M.state.current=a.createConnectionState(M)},M.reset();var W=function(P,at){var ft=at.type-a.ContentType.change_cipher_spec,Ct=H[P.entity][P.expect];if(ft in Ct)Ct[ft](P,at);else a.handleUnexpected(P,at)},nt=function(P){var at=0,ft=P.input,Ct=ft.length();if(Ct<5)at=5-Ct;else{P.record={type:ft.getByte(),version:{major:ft.getByte(),minor:ft.getByte()},length:ft.getInt16(),fragment:e.util.createBuffer(),ready:!1};var ot=P.record.version.major===P.version.major;if(ot&&P.session&&P.session.version)ot=P.record.version.minor===P.version.minor;if(!ot)P.error(P,{message:"Incompatible TLS version.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.protocol_version}})}return at},ct=function(P){var at=0,ft=P.input,Ct=ft.length();if(Ct<P.record.length)at=P.record.length-Ct;else{P.record.fragment.putBytes(ft.getBytes(P.record.length)),ft.compact();var ot=P.state.current.read;if(ot.update(P,P.record)){if(P.fragmented!==null)if(P.fragmented.type===P.record.type)P.fragmented.fragment.putBuffer(P.record.fragment),P.record=P.fragmented;else P.error(P,{message:"Invalid fragmented record.",send:!0,alert:{level:a.Alert.Level.fatal,description:a.Alert.Description.unexpected_message}});P.record.ready=!0}}return at};return M.handshake=function(P){if(M.entity!==a.ConnectionEnd.client)M.error(M,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(M.handshaking)M.error(M,{message:"Handshake already in progress.",fatal:!1});else{if(M.fail&&!M.open&&M.handshakes===0)M.fail=!1;M.handshaking=!0,P=P||"";var at=null;if(P.length>0){if(M.sessionCache)at=M.sessionCache.getSession(P);if(at===null)P=""}if(P.length===0&&M.sessionCache){if(at=M.sessionCache.getSession(),at!==null)P=at.id}if(M.session={id:P,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:e.md.md5.create(),sha1:e.md.sha1.create()},at)M.version=at.version,M.session.sp=at.sp;M.session.sp.client_random=a.createRandom().getBytes(),M.open=!0,a.queue(M,a.createRecord(M,{type:a.ContentType.handshake,data:a.createClientHello(M)})),a.flush(M)}},M.process=function(P){var at=0;if(P)M.input.putBytes(P);if(!M.fail){if(M.record!==null&&M.record.ready&&M.record.fragment.isEmpty())M.record=null;if(M.record===null)at=nt(M);if(!M.fail&&M.record!==null&&!M.record.ready)at=ct(M);if(!M.fail&&M.record!==null&&M.record.ready)W(M,M.record)}return at},M.prepare=function(P){return a.queue(M,a.createRecord(M,{type:a.ContentType.application_data,data:e.util.createBuffer(P)})),a.flush(M)},M.prepareHeartbeatRequest=function(P,at){if(P instanceof e.util.ByteBuffer)P=P.bytes();if(typeof at>"u")at=P.length;return M.expectedHeartbeatPayload=P,a.queue(M,a.createRecord(M,{type:a.ContentType.heartbeat,data:a.createHeartbeat(a.HeartbeatMessageType.heartbeat_request,P,at)})),a.flush(M)},M.close=function(P){if(!M.fail&&M.sessionCache&&M.session){var at={id:M.session.id,version:M.session.version,sp:M.session.sp};at.sp.keys=null,M.sessionCache.setSession(at.id,at)}if(M.open){if(M.open=!1,M.input.clear(),M.isConnected||M.handshaking)M.isConnected=M.handshaking=!1,a.queue(M,a.createAlert(M,{level:a.Alert.Level.warning,description:a.Alert.Description.close_notify})),a.flush(M);M.closed(M)}M.reset(P)},M},n.exports=e.tls=e.tls||{};for(yt in a)if(typeof a[yt]!=="function")e.tls[yt]=a[yt];var yt;e.tls.prf_tls1=t,e.tls.hmac_sha1=i,e.tls.createSessionCache=a.createSessionCache,e.tls.createConnection=a.createConnection}),au=lt((r,n)=>{var e=pt();ze(),oa();var t=n.exports=e.tls;t.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(C){C.bulk_cipher_algorithm=t.BulkCipherAlgorithm.aes,C.cipher_type=t.CipherType.block,C.enc_key_length=16,C.block_length=16,C.fixed_iv_length=16,C.record_iv_length=16,C.mac_algorithm=t.MACAlgorithm.hmac_sha1,C.mac_length=20,C.mac_key_length=20},initConnectionState:i},t.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(C){C.bulk_cipher_algorithm=t.BulkCipherAlgorithm.aes,C.cipher_type=t.CipherType.block,C.enc_key_length=32,C.block_length=16,C.fixed_iv_length=16,C.record_iv_length=16,C.mac_algorithm=t.MACAlgorithm.hmac_sha1,C.mac_length=20,C.mac_key_length=20},initConnectionState:i};function i(C,p,m){var w=p.entity===e.tls.ConnectionEnd.client;C.read.cipherState={init:!1,cipher:e.cipher.createDecipher("AES-CBC",w?m.keys.server_write_key:m.keys.client_write_key),iv:w?m.keys.server_write_IV:m.keys.client_write_IV},C.write.cipherState={init:!1,cipher:e.cipher.createCipher("AES-CBC",w?m.keys.client_write_key:m.keys.server_write_key),iv:w?m.keys.client_write_IV:m.keys.server_write_IV},C.read.cipherFunction=s,C.write.cipherFunction=c,C.read.macLength=C.write.macLength=m.mac_length,C.read.macFunction=C.write.macFunction=t.hmac_sha1}function c(C,p){var m=!1,w=p.macFunction(p.macKey,p.sequenceNumber,C);C.fragment.putBytes(w),p.updateSequenceNumber();var B;if(C.version.minor===t.Versions.TLS_1_0.minor)B=p.cipherState.init?null:p.cipherState.iv;else B=e.random.getBytesSync(16);p.cipherState.init=!0;var d=p.cipherState.cipher;if(d.start({iv:B}),C.version.minor>=t.Versions.TLS_1_1.minor)d.output.putBytes(B);if(d.update(C.fragment),d.finish(f))C.fragment=d.output,C.length=C.fragment.length(),m=!0;return m}function f(C,p,m){if(!m){var w=C-p.length()%C;p.fillWithByte(w-1,w)}return!0}function o(C,p,m){var w=!0;if(m){var B=p.length(),d=p.last();for(var T=B-1-d;T<B-1;++T)w=w&&p.at(T)==d;if(w)p.truncate(d+1)}return w}function s(C,p){var m=!1,w;if(C.version.minor===t.Versions.TLS_1_0.minor)w=p.cipherState.init?null:p.cipherState.iv;else w=C.fragment.getBytes(16);p.cipherState.init=!0;var B=p.cipherState.cipher;B.start({iv:w}),B.update(C.fragment),m=B.finish(o);var d=p.macLength,T=e.random.getBytesSync(d),A=B.output.length();if(A>=d)C.fragment=B.output.getBytes(A-d),T=B.output.getBytes(d);else C.fragment=B.output.getBytes();C.fragment=e.util.createBuffer(C.fragment),C.length=C.fragment.length();var g=p.macFunction(p.macKey,p.sequenceNumber,C);return p.updateSequenceNumber(),m=a(p.macKey,T,g)&&m,m}function a(C,p,m){var w=e.hmac.create();return w.start("SHA1",C),w.update(p),p=w.digest().getBytes(),w.start(null,null),w.update(m),m=w.digest().getBytes(),p===m}}),pa=lt((r,n)=>{var e=pt();Me(),Tt();var t=n.exports=e.sha512=e.sha512||{};e.md.sha512=e.md.algorithms.sha512=t;var i=e.sha384=e.sha512.sha384=e.sha512.sha384||{};i.create=function(){return t.create("SHA-384")},e.md.sha384=e.md.algorithms.sha384=i,e.sha512.sha256=e.sha512.sha256||{create:function(){return t.create("SHA-512/256")}},e.md["sha512/256"]=e.md.algorithms["sha512/256"]=e.sha512.sha256,e.sha512.sha224=e.sha512.sha224||{create:function(){return t.create("SHA-512/224")}},e.md["sha512/224"]=e.md.algorithms["sha512/224"]=e.sha512.sha224,t.create=function(p){if(!f)a();if(typeof p>"u")p="SHA-512";if(!(p in s))throw Error("Invalid SHA-512 algorithm: "+p);var m=s[p],w=null,B=e.util.createBuffer(),d=Array(80);for(var T=0;T<80;++T)d[T]=[,,];var A=64;switch(p){case"SHA-384":A=48;break;case"SHA-512/256":A=32;break;case"SHA-512/224":A=28;break}var g={algorithm:p.replace("-","").toLowerCase(),blockLength:128,digestLength:A,messageLength:0,fullMessageLength:null,messageLengthSize:16};return g.start=function(){g.messageLength=0,g.fullMessageLength=g.messageLength128=[];var l=g.messageLengthSize/4;for(var S=0;S<l;++S)g.fullMessageLength.push(0);B=e.util.createBuffer(),w=Array(m.length);for(var S=0;S<m.length;++S)w[S]=m[S].slice(0);return g},g.start(),g.update=function(l,S){if(S==="utf8")l=e.util.encodeUtf8(l);var I=l.length;g.messageLength+=I,I=[I/4294967296>>>0,I>>>0];for(var N=g.fullMessageLength.length-1;N>=0;--N)g.fullMessageLength[N]+=I[1],I[1]=I[0]+(g.fullMessageLength[N]/4294967296>>>0),g.fullMessageLength[N]=g.fullMessageLength[N]>>>0,I[0]=I[1]/4294967296>>>0;if(B.putBytes(l),C(w,d,B),B.read>2048||B.length()===0)B.compact();return g},g.digest=function(){var l=e.util.createBuffer();l.putBytes(B.bytes());var S=g.fullMessageLength[g.fullMessageLength.length-1]+g.messageLengthSize,I=S&g.blockLength-1;l.putBytes(c.substr(0,g.blockLength-I));var N,L,v=g.fullMessageLength[0]*8;for(var h=0;h<g.fullMessageLength.length-1;++h)N=g.fullMessageLength[h+1]*8,L=N/4294967296>>>0,v+=L,l.putInt32(v>>>0),v=N>>>0;l.putInt32(v);var u=Array(w.length);for(var h=0;h<w.length;++h)u[h]=w[h].slice(0);C(u,d,l);var R=e.util.createBuffer(),V;if(p==="SHA-512")V=u.length;else if(p==="SHA-384")V=u.length-2;else V=u.length-4;for(var h=0;h<V;++h)if(R.putInt32(u[h][0]),h!==V-1||p!=="SHA-512/224")R.putInt32(u[h][1]);return R},g};var c=null,f=!1,o=null,s=null;function a(){c=String.fromCharCode(128),c+=e.util.fillString(String.fromCharCode(0),128),o=[[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]],s={},s["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],s["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],s["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],s["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],f=!0}function C(p,m,w){var B,d,T,A,g,l,S,I,N,L,v,h,u,R,V,O,K,G,H,j,z,Z,tt,rt,ut,ht,Et,_t,J,vt,et,Rt,yt,E,D,k=w.length();while(k>=128){for(J=0;J<16;++J)m[J][0]=w.getInt32()>>>0,m[J][1]=w.getInt32()>>>0;for(;J<80;++J)Rt=m[J-2],vt=Rt[0],et=Rt[1],B=((vt>>>19|et<<13)^(et>>>29|vt<<3)^vt>>>6)>>>0,d=((vt<<13|et>>>19)^(et<<3|vt>>>29)^(vt<<26|et>>>6))>>>0,E=m[J-15],vt=E[0],et=E[1],T=((vt>>>1|et<<31)^(vt>>>8|et<<24)^vt>>>7)>>>0,A=((vt<<31|et>>>1)^(vt<<24|et>>>8)^(vt<<25|et>>>7))>>>0,yt=m[J-7],D=m[J-16],et=d+yt[1]+A+D[1],m[J][0]=B+yt[0]+T+D[0]+(et/4294967296>>>0)>>>0,m[J][1]=et>>>0;u=p[0][0],R=p[0][1],V=p[1][0],O=p[1][1],K=p[2][0],G=p[2][1],H=p[3][0],j=p[3][1],z=p[4][0],Z=p[4][1],tt=p[5][0],rt=p[5][1],ut=p[6][0],ht=p[6][1],Et=p[7][0],_t=p[7][1];for(J=0;J<80;++J)S=((z>>>14|Z<<18)^(z>>>18|Z<<14)^(Z>>>9|z<<23))>>>0,I=((z<<18|Z>>>14)^(z<<14|Z>>>18)^(Z<<23|z>>>9))>>>0,N=(ut^z&(tt^ut))>>>0,L=(ht^Z&(rt^ht))>>>0,g=((u>>>28|R<<4)^(R>>>2|u<<30)^(R>>>7|u<<25))>>>0,l=((u<<4|R>>>28)^(R<<30|u>>>2)^(R<<25|u>>>7))>>>0,v=(u&V|K&(u^V))>>>0,h=(R&O|G&(R^O))>>>0,et=_t+I+L+o[J][1]+m[J][1],B=Et+S+N+o[J][0]+m[J][0]+(et/4294967296>>>0)>>>0,d=et>>>0,et=l+h,T=g+v+(et/4294967296>>>0)>>>0,A=et>>>0,Et=ut,_t=ht,ut=tt,ht=rt,tt=z,rt=Z,et=j+d,z=H+B+(et/4294967296>>>0)>>>0,Z=et>>>0,H=K,j=G,K=V,G=O,V=u,O=R,et=d+A,u=B+T+(et/4294967296>>>0)>>>0,R=et>>>0;et=p[0][1]+R,p[0][0]=p[0][0]+u+(et/4294967296>>>0)>>>0,p[0][1]=et>>>0,et=p[1][1]+O,p[1][0]=p[1][0]+V+(et/4294967296>>>0)>>>0,p[1][1]=et>>>0,et=p[2][1]+G,p[2][0]=p[2][0]+K+(et/4294967296>>>0)>>>0,p[2][1]=et>>>0,et=p[3][1]+j,p[3][0]=p[3][0]+H+(et/4294967296>>>0)>>>0,p[3][1]=et>>>0,et=p[4][1]+Z,p[4][0]=p[4][0]+z+(et/4294967296>>>0)>>>0,p[4][1]=et>>>0,et=p[5][1]+rt,p[5][0]=p[5][0]+tt+(et/4294967296>>>0)>>>0,p[5][1]=et>>>0,et=p[6][1]+ht,p[6][0]=p[6][0]+ut+(et/4294967296>>>0)>>>0,p[6][1]=et>>>0,et=p[7][1]+_t,p[7][0]=p[7][0]+Et+(et/4294967296>>>0)>>>0,p[7][1]=et>>>0,k-=128}}}),su=lt((r)=>{var n=pt();Ue();var e=n.asn1;r.privateKeyValidator={name:"PrivateKeyInfo",tagClass:e.Class.UNIVERSAL,type:e.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:e.Class.UNIVERSAL,type:e.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:e.Class.UNIVERSAL,type:e.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:e.Class.UNIVERSAL,type:e.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:e.Class.UNIVERSAL,type:e.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},r.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:e.Class.UNIVERSAL,type:e.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:e.Class.UNIVERSAL,type:e.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:e.Class.UNIVERSAL,type:e.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:e.Class.UNIVERSAL,type:e.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}}),uu=lt((r,n)=>{var e=pt();$r(),we(),pa(),Tt();var t=su(),i=t.publicKeyValidator,c=t.privateKeyValidator;if(typeof f>"u")f=e.jsbn.BigInteger;var f,o=e.util.ByteBuffer,s=typeof Buffer>"u"?Uint8Array:Buffer;e.pki=e.pki||{},n.exports=e.pki.ed25519=e.ed25519=e.ed25519||{};var a=e.ed25519;a.constants={},a.constants.PUBLIC_KEY_BYTE_LENGTH=32,a.constants.PRIVATE_KEY_BYTE_LENGTH=64,a.constants.SEED_BYTE_LENGTH=32,a.constants.SIGN_BYTE_LENGTH=64,a.constants.HASH_BYTE_LENGTH=64,a.generateKeyPair=function(E){E=E||{};var D=E.seed;if(D===void 0)D=e.random.getBytesSync(a.constants.SEED_BYTE_LENGTH);else if(typeof D==="string"){if(D.length!==a.constants.SEED_BYTE_LENGTH)throw TypeError('"seed" must be '+a.constants.SEED_BYTE_LENGTH+" bytes in length.")}else if(!(D instanceof Uint8Array))throw TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.');D=C({message:D,encoding:"binary"});var k=new s(a.constants.PUBLIC_KEY_BYTE_LENGTH),y=new s(a.constants.PRIVATE_KEY_BYTE_LENGTH);for(var b=0;b<32;++b)y[b]=D[b];return S(k,y),{publicKey:k,privateKey:y}},a.privateKeyFromAsn1=function(E){var D={},k=[],y=e.asn1.validate(E,c,D,k);if(!y){var b=Error("Invalid Key.");throw b.errors=k,b}var F=e.asn1.derToOid(D.privateKeyOid),M=e.oids.EdDSA25519;if(F!==M)throw Error('Invalid OID "'+F+'"; OID must be "'+M+'".');var W=D.privateKey,nt=C({message:e.asn1.fromDer(W).value,encoding:"binary"});return{privateKeyBytes:nt}},a.publicKeyFromAsn1=function(E){var D={},k=[],y=e.asn1.validate(E,i,D,k);if(!y){var b=Error("Invalid Key.");throw b.errors=k,b}var F=e.asn1.derToOid(D.publicKeyOid),M=e.oids.EdDSA25519;if(F!==M)throw Error('Invalid OID "'+F+'"; OID must be "'+M+'".');var W=D.ed25519PublicKey;if(W.length!==a.constants.PUBLIC_KEY_BYTE_LENGTH)throw Error("Key length is invalid.");return C({message:W,encoding:"binary"})},a.publicKeyFromPrivateKey=function(E){E=E||{};var D=C({message:E.privateKey,encoding:"binary"});if(D.length!==a.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+a.constants.PRIVATE_KEY_BYTE_LENGTH);var k=new s(a.constants.PUBLIC_KEY_BYTE_LENGTH);for(var y=0;y<k.length;++y)k[y]=D[32+y];return k},a.sign=function(E){E=E||{};var D=C(E),k=C({message:E.privateKey,encoding:"binary"});if(k.length===a.constants.SEED_BYTE_LENGTH){var y=a.generateKeyPair({seed:k});k=y.privateKey}else if(k.length!==a.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+a.constants.SEED_BYTE_LENGTH+" or "+a.constants.PRIVATE_KEY_BYTE_LENGTH);var b=new s(a.constants.SIGN_BYTE_LENGTH+D.length);I(b,D,D.length,k);var F=new s(a.constants.SIGN_BYTE_LENGTH);for(var M=0;M<F.length;++M)F[M]=b[M];return F},a.verify=function(E){E=E||{};var D=C(E);if(E.signature===void 0)throw TypeError('"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.');var k=C({message:E.signature,encoding:"binary"});if(k.length!==a.constants.SIGN_BYTE_LENGTH)throw TypeError('"options.signature" must have a byte length of '+a.constants.SIGN_BYTE_LENGTH);var y=C({message:E.publicKey,encoding:"binary"});if(y.length!==a.constants.PUBLIC_KEY_BYTE_LENGTH)throw TypeError('"options.publicKey" must have a byte length of '+a.constants.PUBLIC_KEY_BYTE_LENGTH);var b=new s(a.constants.SIGN_BYTE_LENGTH+D.length),F=new s(a.constants.SIGN_BYTE_LENGTH+D.length),M;for(M=0;M<a.constants.SIGN_BYTE_LENGTH;++M)b[M]=k[M];for(M=0;M<D.length;++M)b[M+a.constants.SIGN_BYTE_LENGTH]=D[M];return N(F,b,b.length,y)>=0};function C(E){var D=E.message;if(D instanceof Uint8Array||D instanceof s)return D;var k=E.encoding;if(D===void 0)if(E.md)D=E.md.digest().getBytes(),k="binary";else throw TypeError('"options.message" or "options.md" not specified.');if(typeof D==="string"&&!k)throw TypeError('"options.encoding" must be "binary" or "utf8".');if(typeof D==="string"){if(typeof Buffer<"u")return Buffer.from(D,k);D=new o(D,k)}else if(!(D instanceof o))throw TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');var y=new s(D.length());for(var b=0;b<y.length;++b)y[b]=D.at(b);return y}var p=J(),m=J([1]),w=J([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),B=J([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),d=J([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),T=J([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),A=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]),g=J([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function l(E,D){var k=e.md.sha512.create(),y=new o(E);k.update(y.getBytes(D),"binary");var b=k.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(b,"binary");var F=new s(a.constants.HASH_BYTE_LENGTH);for(var M=0;M<64;++M)F[M]=b.charCodeAt(M);return F}function S(E,D){var k=[J(),J(),J(),J()],y,b=l(D,32);b[0]&=248,b[31]&=127,b[31]|=64,rt(k,b),R(E,k);for(y=0;y<32;++y)D[y+32]=E[y];return 0}function I(E,D,k,y){var b,F,M=new Float64Array(64),W=[J(),J(),J(),J()],nt=l(y,32);nt[0]&=248,nt[31]&=127,nt[31]|=64;var ct=k+64;for(b=0;b<k;++b)E[64+b]=D[b];for(b=0;b<32;++b)E[32+b]=nt[32+b];var P=l(E.subarray(32),k+32);v(P),rt(W,P),R(E,W);for(b=32;b<64;++b)E[b]=y[b];var at=l(E,k+64);v(at);for(b=32;b<64;++b)M[b]=0;for(b=0;b<32;++b)M[b]=P[b];for(b=0;b<32;++b)for(F=0;F<32;F++)M[b+F]+=at[b]*nt[F];return L(E.subarray(32),M),ct}function N(E,D,k,y){var b,F,M=new s(32),W=[J(),J(),J(),J()],nt=[J(),J(),J(),J()];if(F=-1,k<64)return-1;if(O(nt,y))return-1;for(b=0;b<k;++b)E[b]=D[b];for(b=0;b<32;++b)E[b+32]=y[b];var ct=l(E,k);if(v(ct),tt(W,nt,ct),rt(nt,D.subarray(32)),h(W,nt),R(M,W),k-=64,j(D,0,M,0)){for(b=0;b<k;++b)E[b]=0;return-1}for(b=0;b<k;++b)E[b]=D[b+64];return F=k,F}function L(E,D){var k,y,b,F;for(y=63;y>=32;--y){k=0;for(b=y-32,F=y-12;b<F;++b)D[b]+=k-16*D[y]*A[b-(y-32)],k=D[b]+128>>8,D[b]-=k*256;D[b]+=k,D[y]=0}k=0;for(b=0;b<32;++b)D[b]+=k-(D[31]>>4)*A[b],k=D[b]>>8,D[b]&=255;for(b=0;b<32;++b)D[b]-=k*A[b];for(y=0;y<32;++y)D[y+1]+=D[y]>>8,E[y]=D[y]&255}function v(E){var D=new Float64Array(64);for(var k=0;k<64;++k)D[k]=E[k],E[k]=0;L(E,D)}function h(E,D){var k=J(),y=J(),b=J(),F=J(),M=J(),W=J(),nt=J(),ct=J(),P=J();et(k,E[1],E[0]),et(P,D[1],D[0]),yt(k,k,P),vt(y,E[0],E[1]),vt(P,D[0],D[1]),yt(y,y,P),yt(b,E[3],D[3]),yt(b,b,B),yt(F,E[2],D[2]),vt(F,F,F),et(M,y,k),et(W,F,b),vt(nt,F,b),vt(ct,y,k),yt(E[0],M,W),yt(E[1],ct,nt),yt(E[2],nt,W),yt(E[3],M,ct)}function u(E,D,k){for(var y=0;y<4;++y)_t(E[y],D[y],k)}function R(E,D){var k=J(),y=J(),b=J();ht(b,D[2]),yt(k,D[0],b),yt(y,D[1],b),V(E,y),E[31]^=Z(k)<<7}function V(E,D){var k,y,b,F=J(),M=J();for(k=0;k<16;++k)M[k]=D[k];Et(M),Et(M),Et(M);for(y=0;y<2;++y){F[0]=M[0]-65517;for(k=1;k<15;++k)F[k]=M[k]-65535-(F[k-1]>>16&1),F[k-1]&=65535;F[15]=M[15]-32767-(F[14]>>16&1),b=F[15]>>16&1,F[14]&=65535,_t(M,F,1-b)}for(k=0;k<16;k++)E[2*k]=M[k]&255,E[2*k+1]=M[k]>>8}function O(E,D){var k=J(),y=J(),b=J(),F=J(),M=J(),W=J(),nt=J();if(ut(E[2],m),K(E[1],D),Rt(b,E[1]),yt(F,b,w),et(b,b,E[2]),vt(F,E[2],F),Rt(M,F),Rt(W,M),yt(nt,W,M),yt(k,nt,b),yt(k,k,F),G(k,k),yt(k,k,b),yt(k,k,F),yt(k,k,F),yt(E[0],k,F),Rt(y,E[0]),yt(y,y,F),H(y,b))yt(E[0],E[0],g);if(Rt(y,E[0]),yt(y,y,F),H(y,b))return-1;if(Z(E[0])===D[31]>>7)et(E[0],p,E[0]);return yt(E[3],E[0],E[1]),0}function K(E,D){var k;for(k=0;k<16;++k)E[k]=D[2*k]+(D[2*k+1]<<8);E[15]&=32767}function G(E,D){var k=J(),y;for(y=0;y<16;++y)k[y]=D[y];for(y=250;y>=0;--y)if(Rt(k,k),y!==1)yt(k,k,D);for(y=0;y<16;++y)E[y]=k[y]}function H(E,D){var k=new s(32),y=new s(32);return V(k,E),V(y,D),j(k,0,y,0)}function j(E,D,k,y){return z(E,D,k,y,32)}function z(E,D,k,y,b){var F,M=0;for(F=0;F<b;++F)M|=E[D+F]^k[y+F];return(1&M-1>>>8)-1}function Z(E){var D=new s(32);return V(D,E),D[0]&1}function tt(E,D,k){var y,b;ut(E[0],p),ut(E[1],m),ut(E[2],m),ut(E[3],p);for(b=255;b>=0;--b)y=k[b/8|0]>>(b&7)&1,u(E,D,y),h(D,E),h(E,E),u(E,D,y)}function rt(E,D){var k=[J(),J(),J(),J()];ut(k[0],d),ut(k[1],T),ut(k[2],m),yt(k[3],d,T),tt(E,k,D)}function ut(E,D){var k;for(k=0;k<16;k++)E[k]=D[k]|0}function ht(E,D){var k=J(),y;for(y=0;y<16;++y)k[y]=D[y];for(y=253;y>=0;--y)if(Rt(k,k),y!==2&&y!==4)yt(k,k,D);for(y=0;y<16;++y)E[y]=k[y]}function Et(E){var D,k,y=1;for(D=0;D<16;++D)k=E[D]+y+65535,y=Math.floor(k/65536),E[D]=k-y*65536;E[0]+=y-1+37*(y-1)}function _t(E,D,k){var y,b=~(k-1);for(var F=0;F<16;++F)y=b&(E[F]^D[F]),E[F]^=y,D[F]^=y}function J(E){var D,k=new Float64Array(16);if(E)for(D=0;D<E.length;++D)k[D]=E[D];return k}function vt(E,D,k){for(var y=0;y<16;++y)E[y]=D[y]+k[y]}function et(E,D,k){for(var y=0;y<16;++y)E[y]=D[y]-k[y]}function Rt(E,D){yt(E,D,D)}function yt(E,D,k){var y,b,F=0,M=0,W=0,nt=0,ct=0,P=0,at=0,ft=0,Ct=0,ot=0,bt=0,Kt=0,Dt=0,Ut=0,wt=0,Nt=0,Ot=0,ae=0,Gt=0,le=0,he=0,ye=0,de=0,Ae=0,Re=0,ke=0,Ge=0,je=0,$e=0,or=0,Ar=0,Ft=k[0],qt=k[1],Ht=k[2],jt=k[3],Qt=k[4],zt=k[5],Pt=k[6],Yt=k[7],Xt=k[8],Wt=k[9],Zt=k[10],$t=k[11],Jt=k[12],te=k[13],kt=k[14],xt=k[15];y=D[0],F+=y*Ft,M+=y*qt,W+=y*Ht,nt+=y*jt,ct+=y*Qt,P+=y*zt,at+=y*Pt,ft+=y*Yt,Ct+=y*Xt,ot+=y*Wt,bt+=y*Zt,Kt+=y*$t,Dt+=y*Jt,Ut+=y*te,wt+=y*kt,Nt+=y*xt,y=D[1],M+=y*Ft,W+=y*qt,nt+=y*Ht,ct+=y*jt,P+=y*Qt,at+=y*zt,ft+=y*Pt,Ct+=y*Yt,ot+=y*Xt,bt+=y*Wt,Kt+=y*Zt,Dt+=y*$t,Ut+=y*Jt,wt+=y*te,Nt+=y*kt,Ot+=y*xt,y=D[2],W+=y*Ft,nt+=y*qt,ct+=y*Ht,P+=y*jt,at+=y*Qt,ft+=y*zt,Ct+=y*Pt,ot+=y*Yt,bt+=y*Xt,Kt+=y*Wt,Dt+=y*Zt,Ut+=y*$t,wt+=y*Jt,Nt+=y*te,Ot+=y*kt,ae+=y*xt,y=D[3],nt+=y*Ft,ct+=y*qt,P+=y*Ht,at+=y*jt,ft+=y*Qt,Ct+=y*zt,ot+=y*Pt,bt+=y*Yt,Kt+=y*Xt,Dt+=y*Wt,Ut+=y*Zt,wt+=y*$t,Nt+=y*Jt,Ot+=y*te,ae+=y*kt,Gt+=y*xt,y=D[4],ct+=y*Ft,P+=y*qt,at+=y*Ht,ft+=y*jt,Ct+=y*Qt,ot+=y*zt,bt+=y*Pt,Kt+=y*Yt,Dt+=y*Xt,Ut+=y*Wt,wt+=y*Zt,Nt+=y*$t,Ot+=y*Jt,ae+=y*te,Gt+=y*kt,le+=y*xt,y=D[5],P+=y*Ft,at+=y*qt,ft+=y*Ht,Ct+=y*jt,ot+=y*Qt,bt+=y*zt,Kt+=y*Pt,Dt+=y*Yt,Ut+=y*Xt,wt+=y*Wt,Nt+=y*Zt,Ot+=y*$t,ae+=y*Jt,Gt+=y*te,le+=y*kt,he+=y*xt,y=D[6],at+=y*Ft,ft+=y*qt,Ct+=y*Ht,ot+=y*jt,bt+=y*Qt,Kt+=y*zt,Dt+=y*Pt,Ut+=y*Yt,wt+=y*Xt,Nt+=y*Wt,Ot+=y*Zt,ae+=y*$t,Gt+=y*Jt,le+=y*te,he+=y*kt,ye+=y*xt,y=D[7],ft+=y*Ft,Ct+=y*qt,ot+=y*Ht,bt+=y*jt,Kt+=y*Qt,Dt+=y*zt,Ut+=y*Pt,wt+=y*Yt,Nt+=y*Xt,Ot+=y*Wt,ae+=y*Zt,Gt+=y*$t,le+=y*Jt,he+=y*te,ye+=y*kt,de+=y*xt,y=D[8],Ct+=y*Ft,ot+=y*qt,bt+=y*Ht,Kt+=y*jt,Dt+=y*Qt,Ut+=y*zt,wt+=y*Pt,Nt+=y*Yt,Ot+=y*Xt,ae+=y*Wt,Gt+=y*Zt,le+=y*$t,he+=y*Jt,ye+=y*te,de+=y*kt,Ae+=y*xt,y=D[9],ot+=y*Ft,bt+=y*qt,Kt+=y*Ht,Dt+=y*jt,Ut+=y*Qt,wt+=y*zt,Nt+=y*Pt,Ot+=y*Yt,ae+=y*Xt,Gt+=y*Wt,le+=y*Zt,he+=y*$t,ye+=y*Jt,de+=y*te,Ae+=y*kt,Re+=y*xt,y=D[10],bt+=y*Ft,Kt+=y*qt,Dt+=y*Ht,Ut+=y*jt,wt+=y*Qt,Nt+=y*zt,Ot+=y*Pt,ae+=y*Yt,Gt+=y*Xt,le+=y*Wt,he+=y*Zt,ye+=y*$t,de+=y*Jt,Ae+=y*te,Re+=y*kt,ke+=y*xt,y=D[11],Kt+=y*Ft,Dt+=y*qt,Ut+=y*Ht,wt+=y*jt,Nt+=y*Qt,Ot+=y*zt,ae+=y*Pt,Gt+=y*Yt,le+=y*Xt,he+=y*Wt,ye+=y*Zt,de+=y*$t,Ae+=y*Jt,Re+=y*te,ke+=y*kt,Ge+=y*xt,y=D[12],Dt+=y*Ft,Ut+=y*qt,wt+=y*Ht,Nt+=y*jt,Ot+=y*Qt,ae+=y*zt,Gt+=y*Pt,le+=y*Yt,he+=y*Xt,ye+=y*Wt,de+=y*Zt,Ae+=y*$t,Re+=y*Jt,ke+=y*te,Ge+=y*kt,je+=y*xt,y=D[13],Ut+=y*Ft,wt+=y*qt,Nt+=y*Ht,Ot+=y*jt,ae+=y*Qt,Gt+=y*zt,le+=y*Pt,he+=y*Yt,ye+=y*Xt,de+=y*Wt,Ae+=y*Zt,Re+=y*$t,ke+=y*Jt,Ge+=y*te,je+=y*kt,$e+=y*xt,y=D[14],wt+=y*Ft,Nt+=y*qt,Ot+=y*Ht,ae+=y*jt,Gt+=y*Qt,le+=y*zt,he+=y*Pt,ye+=y*Yt,de+=y*Xt,Ae+=y*Wt,Re+=y*Zt,ke+=y*$t,Ge+=y*Jt,je+=y*te,$e+=y*kt,or+=y*xt,y=D[15],Nt+=y*Ft,Ot+=y*qt,ae+=y*Ht,Gt+=y*jt,le+=y*Qt,he+=y*zt,ye+=y*Pt,de+=y*Yt,Ae+=y*Xt,Re+=y*Wt,ke+=y*Zt,Ge+=y*$t,je+=y*Jt,$e+=y*te,or+=y*kt,Ar+=y*xt,F+=38*Ot,M+=38*ae,W+=38*Gt,nt+=38*le,ct+=38*he,P+=38*ye,at+=38*de,ft+=38*Ae,Ct+=38*Re,ot+=38*ke,bt+=38*Ge,Kt+=38*je,Dt+=38*$e,Ut+=38*or,wt+=38*Ar,b=1,y=F+b+65535,b=Math.floor(y/65536),F=y-b*65536,y=M+b+65535,b=Math.floor(y/65536),M=y-b*65536,y=W+b+65535,b=Math.floor(y/65536),W=y-b*65536,y=nt+b+65535,b=Math.floor(y/65536),nt=y-b*65536,y=ct+b+65535,b=Math.floor(y/65536),ct=y-b*65536,y=P+b+65535,b=Math.floor(y/65536),P=y-b*65536,y=at+b+65535,b=Math.floor(y/65536),at=y-b*65536,y=ft+b+65535,b=Math.floor(y/65536),ft=y-b*65536,y=Ct+b+65535,b=Math.floor(y/65536),Ct=y-b*65536,y=ot+b+65535,b=Math.floor(y/65536),ot=y-b*65536,y=bt+b+65535,b=Math.floor(y/65536),bt=y-b*65536,y=Kt+b+65535,b=Math.floor(y/65536),Kt=y-b*65536,y=Dt+b+65535,b=Math.floor(y/65536),Dt=y-b*65536,y=Ut+b+65535,b=Math.floor(y/65536),Ut=y-b*65536,y=wt+b+65535,b=Math.floor(y/65536),wt=y-b*65536,y=Nt+b+65535,b=Math.floor(y/65536),Nt=y-b*65536,F+=b-1+37*(b-1),b=1,y=F+b+65535,b=Math.floor(y/65536),F=y-b*65536,y=M+b+65535,b=Math.floor(y/65536),M=y-b*65536,y=W+b+65535,b=Math.floor(y/65536),W=y-b*65536,y=nt+b+65535,b=Math.floor(y/65536),nt=y-b*65536,y=ct+b+65535,b=Math.floor(y/65536),ct=y-b*65536,y=P+b+65535,b=Math.floor(y/65536),P=y-b*65536,y=at+b+65535,b=Math.floor(y/65536),at=y-b*65536,y=ft+b+65535,b=Math.floor(y/65536),ft=y-b*65536,y=Ct+b+65535,b=Math.floor(y/65536),Ct=y-b*65536,y=ot+b+65535,b=Math.floor(y/65536),ot=y-b*65536,y=bt+b+65535,b=Math.floor(y/65536),bt=y-b*65536,y=Kt+b+65535,b=Math.floor(y/65536),Kt=y-b*65536,y=Dt+b+65535,b=Math.floor(y/65536),Dt=y-b*65536,y=Ut+b+65535,b=Math.floor(y/65536),Ut=y-b*65536,y=wt+b+65535,b=Math.floor(y/65536),wt=y-b*65536,y=Nt+b+65535,b=Math.floor(y/65536),Nt=y-b*65536,F+=b-1+37*(b-1),E[0]=F,E[1]=M,E[2]=W,E[3]=nt,E[4]=ct,E[5]=P,E[6]=at,E[7]=ft,E[8]=Ct,E[9]=ot,E[10]=bt,E[11]=Kt,E[12]=Dt,E[13]=Ut,E[14]=wt,E[15]=Nt}}),cu=lt((r,n)=>{var e=pt();Tt(),we(),$r(),n.exports=e.kem=e.kem||{};var t=e.jsbn.BigInteger;e.kem.rsa={},e.kem.rsa.create=function(c,f){f=f||{};var o=f.prng||e.random,s={};return s.encrypt=function(a,C){var p=Math.ceil(a.n.bitLength()/8),m;do m=new t(e.util.bytesToHex(o.getBytesSync(p)),16).mod(a.n);while(m.compareTo(t.ONE)<=0);m=e.util.hexToBytes(m.toString(16));var w=p-m.length;if(w>0)m=e.util.fillString(String.fromCharCode(0),w)+m;var B=a.encrypt(m,"NONE"),d=c.generate(m,C);return{encapsulation:B,key:d}},s.decrypt=function(a,C,p){var m=a.decrypt(C,"NONE");return c.generate(m,p)},s},e.kem.kdf1=function(c,f){i(this,c,0,f||c.digestLength)},e.kem.kdf2=function(c,f){i(this,c,1,f||c.digestLength)};function i(c,f,o,s){c.generate=function(a,C){var p=new e.util.ByteBuffer,m=Math.ceil(C/s)+o,w=new e.util.ByteBuffer;for(var B=o;B<m;++B){w.putInt32(B),f.start(),f.update(a+w.getBytes());var d=f.digest();p.putBytes(d.getBytes(s))}return p.truncate(p.length()-C),p.getBytes()}}}),fu=lt((r,n)=>{var e=pt();Tt(),n.exports=e.log=e.log||{},e.log.levels=["none","error","warning","info","debug","verbose","max"];var t={},i=[],c=null;e.log.LEVEL_LOCKED=2,e.log.NO_LEVEL_CHECK=4,e.log.INTERPOLATE=8;for(s=0;s<e.log.levels.length;++s)f=e.log.levels[s],t[f]={index:s,name:f.toUpperCase()};var f,s;e.log.logMessage=function(B){var d=t[B.level].index;for(var T=0;T<i.length;++T){var A=i[T];if(A.flags&e.log.NO_LEVEL_CHECK)A.f(B);else{var g=t[A.level].index;if(d<=g)A.f(A,B)}}},e.log.prepareStandard=function(B){if(!("standard"in B))B.standard=t[B.level].name+" ["+B.category+"] "+B.message},e.log.prepareFull=function(B){if(!("full"in B)){var d=[B.message];d=d.concat([]),B.full=e.util.format.apply(this,d)}},e.log.prepareStandardFull=function(B){if(!("standardFull"in B))e.log.prepareStandard(B),B.standardFull=B.standard},o=["error","warning","info","debug","verbose"];for(s=0;s<o.length;++s)(function(B){e.log[B]=function(d,T){var A=Array.prototype.slice.call(arguments).slice(2),g={timestamp:new Date,level:B,category:d,message:T,arguments:A};e.log.logMessage(g)}})(o[s]);var o,s;if(e.log.makeLogger=function(B){var d={flags:0,f:B};return e.log.setLevel(d,"none"),d},e.log.setLevel=function(B,d){var T=!1;if(B&&!(B.flags&e.log.LEVEL_LOCKED))for(var A=0;A<e.log.levels.length;++A){var g=e.log.levels[A];if(d==g){B.level=d,T=!0;break}}return T},e.log.lock=function(B,d){if(typeof d>"u"||d)B.flags|=e.log.LEVEL_LOCKED;else B.flags&=~e.log.LEVEL_LOCKED},e.log.addLogger=function(B){i.push(B)},typeof console<"u"&&"log"in console){if(console.error&&console.warn&&console.info&&console.debug)C={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},p=function(B,d){e.log.prepareStandard(d);var T=C[d.level],A=[d.standard];A=A.concat(d.arguments.slice()),T.apply(console,A)},a=e.log.makeLogger(p);else p=function(B,d){e.log.prepareStandardFull(d),console.log(d.standardFull)},a=e.log.makeLogger(p);e.log.setLevel(a,"debug"),e.log.addLogger(a),c=a}else console={log:function(){}};var a,C,p;if(c!==null&&typeof window<"u"&&window.location){if(m=new URL(window.location.href).searchParams,m.has("console.level"))e.log.setLevel(c,m.get("console.level").slice(-1)[0]);if(m.has("console.lock")){if(w=m.get("console.lock").slice(-1)[0],w=="true")e.log.lock(c)}}var m,w;e.log.consoleLogger=c}),lu=lt((r,n)=>{n.exports=Me(),Gi(),Cr(),ra(),pa()}),hu=lt((r,n)=>{var e=pt();ze(),Ue(),Zr(),Pe(),hr(),ca(),we(),Tt(),Hi();var t=e.asn1,i=n.exports=e.pkcs7=e.pkcs7||{};i.messageFromPem=function(d){var T=e.pem.decode(d)[0];if(T.type!=="PKCS7"){var A=Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw A.headerType=T.type,A}if(T.procType&&T.procType.type==="ENCRYPTED")throw Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var g=t.fromDer(T.body);return i.messageFromAsn1(g)},i.messageToPem=function(d,T){var A={type:"PKCS7",body:t.toDer(d.toAsn1()).getBytes()};return e.pem.encode(A,{maxline:T})},i.messageFromAsn1=function(d){var T={},A=[];if(!t.validate(d,i.asn1.contentInfoValidator,T,A)){var g=Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw g.errors=A,g}var l=t.derToOid(T.contentType),S;switch(l){case e.pki.oids.envelopedData:S=i.createEnvelopedData();break;case e.pki.oids.encryptedData:S=i.createEncryptedData();break;case e.pki.oids.signedData:S=i.createSignedData();break;default:throw Error("Cannot read PKCS#7 message. ContentType with OID "+l+" is not (yet) supported.")}return S.fromAsn1(T.content.value[0]),S},i.createSignedData=function(){var d=null;return d={type:e.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(g){if(w(d,g,i.asn1.signedDataValidator),d.certificates=[],d.crls=[],d.digestAlgorithmIdentifiers=[],d.contentInfo=null,d.signerInfos=[],d.rawCapture.certificates){var l=d.rawCapture.certificates.value;for(var S=0;S<l.length;++S)d.certificates.push(e.pki.certificateFromAsn1(l[S]))}},toAsn1:function(){if(!d.contentInfo)d.sign();var g=[];for(var l=0;l<d.certificates.length;++l)g.push(e.pki.certificateToAsn1(d.certificates[l]));var S=[],I=t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,t.integerToDer(d.version).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SET,!0,d.digestAlgorithmIdentifiers),d.contentInfo])]);if(g.length>0)I.value[0].value.push(t.create(t.Class.CONTEXT_SPECIFIC,0,!0,g));if(S.length>0)I.value[0].value.push(t.create(t.Class.CONTEXT_SPECIFIC,1,!0,S));return I.value[0].value.push(t.create(t.Class.UNIVERSAL,t.Type.SET,!0,d.signerInfos)),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(d.type).getBytes()),I])},addSigner:function(g){var{issuer:l,serialNumber:S}=g;if(g.certificate){var I=g.certificate;if(typeof I==="string")I=e.pki.certificateFromPem(I);l=I.issuer.attributes,S=I.serialNumber}var N=g.key;if(!N)throw Error("Could not add PKCS#7 signer; no private key specified.");if(typeof N==="string")N=e.pki.privateKeyFromPem(N);var L=g.digestAlgorithm||e.pki.oids.sha1;switch(L){case e.pki.oids.sha1:case e.pki.oids.sha256:case e.pki.oids.sha384:case e.pki.oids.sha512:case e.pki.oids.md5:break;default:throw Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+L)}var v=g.authenticatedAttributes||[];if(v.length>0){var h=!1,u=!1;for(var R=0;R<v.length;++R){var V=v[R];if(!h&&V.type===e.pki.oids.contentType){if(h=!0,u)break;continue}if(!u&&V.type===e.pki.oids.messageDigest){if(u=!0,h)break;continue}}if(!h||!u)throw Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}d.signers.push({key:N,version:1,issuer:l,serialNumber:S,digestAlgorithm:L,signatureAlgorithm:e.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:v,unauthenticatedAttributes:[]})},sign:function(g){if(g=g||{},typeof d.content!=="object"||d.contentInfo===null){if(d.contentInfo=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(e.pki.oids.data).getBytes())]),"content"in d){var l;if(d.content instanceof e.util.ByteBuffer)l=d.content.bytes();else if(typeof d.content==="string")l=e.util.encodeUtf8(d.content);if(g.detached)d.detachedContent=t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,l);else d.contentInfo.value.push(t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,l)]))}}if(d.signers.length===0)return;var S=T();A(S)},verify:function(){throw Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(g){if(typeof g==="string")g=e.pki.certificateFromPem(g);d.certificates.push(g)},addCertificateRevokationList:function(g){throw Error("PKCS#7 CRL support not yet implemented.")}},d;function T(){var g={};for(var l=0;l<d.signers.length;++l){var S=d.signers[l],I=S.digestAlgorithm;if(!(I in g))g[I]=e.md[e.pki.oids[I]].create();if(S.authenticatedAttributes.length===0)S.md=g[I];else S.md=e.md[e.pki.oids[I]].create()}d.digestAlgorithmIdentifiers=[];for(var I in g)d.digestAlgorithmIdentifiers.push(t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(I).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.NULL,!1,"")]));return g}function A(g){var l;if(d.detachedContent)l=d.detachedContent;else l=d.contentInfo.value[1],l=l.value[0];if(!l)throw Error("Could not sign PKCS#7 message; there is no content to sign.");var S=t.derToOid(d.contentInfo.value[0].value),I=t.toDer(l);I.getByte(),t.getBerValueLength(I),I=I.getBytes();for(var N in g)g[N].start().update(I);var L=new Date;for(var v=0;v<d.signers.length;++v){var h=d.signers[v];if(h.authenticatedAttributes.length===0){if(S!==e.pki.oids.data)throw Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{h.authenticatedAttributesAsn1=t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[]);var u=t.create(t.Class.UNIVERSAL,t.Type.SET,!0,[]);for(var R=0;R<h.authenticatedAttributes.length;++R){var V=h.authenticatedAttributes[R];if(V.type===e.pki.oids.messageDigest)V.value=g[h.digestAlgorithm].digest();else if(V.type===e.pki.oids.signingTime){if(!V.value)V.value=L}u.value.push(p(V)),h.authenticatedAttributesAsn1.value.push(p(V))}I=t.toDer(u).getBytes(),h.md.start().update(I)}h.signature=h.key.sign(h.md,"RSASSA-PKCS1-V1_5")}d.signerInfos=C(d.signers)}},i.createEncryptedData=function(){var d=null;return d={type:e.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:e.pki.oids["aes256-CBC"]},fromAsn1:function(T){w(d,T,i.asn1.encryptedDataValidator)},decrypt:function(T){if(T!==void 0)d.encryptedContent.key=T;B(d)}},d},i.createEnvelopedData=function(){var d=null;return d={type:e.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:e.pki.oids["aes256-CBC"]},fromAsn1:function(T){var A=w(d,T,i.asn1.envelopedDataValidator);d.recipients=o(A.recipientInfos.value)},toAsn1:function(){return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(d.type).getBytes()),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,t.integerToDer(d.version).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SET,!0,s(d.recipients)),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,m(d.encryptedContent))])])])},findRecipient:function(T){var A=T.issuer.attributes;for(var g=0;g<d.recipients.length;++g){var l=d.recipients[g],S=l.issuer;if(l.serialNumber!==T.serialNumber)continue;if(S.length!==A.length)continue;var I=!0;for(var N=0;N<A.length;++N)if(S[N].type!==A[N].type||S[N].value!==A[N].value){I=!1;break}if(I)return l}return null},decrypt:function(T,A){if(d.encryptedContent.key===void 0&&T!==void 0&&A!==void 0)switch(T.encryptedContent.algorithm){case e.pki.oids.rsaEncryption:case e.pki.oids.desCBC:var g=A.decrypt(T.encryptedContent.content);d.encryptedContent.key=e.util.createBuffer(g);break;default:throw Error("Unsupported asymmetric cipher, OID "+T.encryptedContent.algorithm)}B(d)},addRecipient:function(T){d.recipients.push({version:0,issuer:T.issuer.attributes,serialNumber:T.serialNumber,encryptedContent:{algorithm:e.pki.oids.rsaEncryption,key:T.publicKey}})},encrypt:function(T,A){if(d.encryptedContent.content===void 0){A=A||d.encryptedContent.algorithm,T=T||d.encryptedContent.key;var g,l,S;switch(A){case e.pki.oids["aes128-CBC"]:g=16,l=16,S=e.aes.createEncryptionCipher;break;case e.pki.oids["aes192-CBC"]:g=24,l=16,S=e.aes.createEncryptionCipher;break;case e.pki.oids["aes256-CBC"]:g=32,l=16,S=e.aes.createEncryptionCipher;break;case e.pki.oids["des-EDE3-CBC"]:g=24,l=8,S=e.des.createEncryptionCipher;break;default:throw Error("Unsupported symmetric cipher, OID "+A)}if(T===void 0)T=e.util.createBuffer(e.random.getBytes(g));else if(T.length()!=g)throw Error("Symmetric key has wrong length; got "+T.length()+" bytes, expected "+g+".");d.encryptedContent.algorithm=A,d.encryptedContent.key=T,d.encryptedContent.parameter=e.util.createBuffer(e.random.getBytes(l));var I=S(T);if(I.start(d.encryptedContent.parameter.copy()),I.update(d.content),!I.finish())throw Error("Symmetric encryption failed.");d.encryptedContent.content=I.output}for(var N=0;N<d.recipients.length;++N){var L=d.recipients[N];if(L.encryptedContent.content!==void 0)continue;switch(L.encryptedContent.algorithm){case e.pki.oids.rsaEncryption:L.encryptedContent.content=L.encryptedContent.key.encrypt(d.encryptedContent.key.data);break;default:throw Error("Unsupported asymmetric cipher, OID "+L.encryptedContent.algorithm)}}}},d};function c(d){var T={},A=[];if(!t.validate(d,i.asn1.recipientInfoValidator,T,A)){var g=Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw g.errors=A,g}return{version:T.version.charCodeAt(0),issuer:e.pki.RDNAttributesAsArray(T.issuer),serialNumber:e.util.createBuffer(T.serial).toHex(),encryptedContent:{algorithm:t.derToOid(T.encAlgorithm),parameter:T.encParameter?T.encParameter.value:void 0,content:T.encKey}}}function f(d){return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,t.integerToDer(d.version).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[e.pki.distinguishedNameToAsn1({attributes:d.issuer}),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,e.util.hexToBytes(d.serialNumber))]),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(d.encryptedContent.algorithm).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.NULL,!1,"")]),t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,d.encryptedContent.content)])}function o(d){var T=[];for(var A=0;A<d.length;++A)T.push(c(d[A]));return T}function s(d){var T=[];for(var A=0;A<d.length;++A)T.push(f(d[A]));return T}function a(d){var T=t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,t.integerToDer(d.version).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[e.pki.distinguishedNameToAsn1({attributes:d.issuer}),t.create(t.Class.UNIVERSAL,t.Type.INTEGER,!1,e.util.hexToBytes(d.serialNumber))]),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(d.digestAlgorithm).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.NULL,!1,"")])]);if(d.authenticatedAttributesAsn1)T.value.push(d.authenticatedAttributesAsn1);if(T.value.push(t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(d.signatureAlgorithm).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.NULL,!1,"")])),T.value.push(t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,d.signature)),d.unauthenticatedAttributes.length>0){var A=t.create(t.Class.CONTEXT_SPECIFIC,1,!0,[]);for(var g=0;g<d.unauthenticatedAttributes.length;++g){var l=d.unauthenticatedAttributes[g];A.values.push(p(l))}T.value.push(A)}return T}function C(d){var T=[];for(var A=0;A<d.length;++A)T.push(a(d[A]));return T}function p(d){var T;if(d.type===e.pki.oids.contentType)T=t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(d.value).getBytes());else if(d.type===e.pki.oids.messageDigest)T=t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,d.value.bytes());else if(d.type===e.pki.oids.signingTime){var A=new Date("1950-01-01T00:00:00Z"),g=new Date("2050-01-01T00:00:00Z"),l=d.value;if(typeof l==="string"){var S=Date.parse(l);if(!isNaN(S))l=new Date(S);else if(l.length===13)l=t.utcTimeToDate(l);else l=t.generalizedTimeToDate(l)}if(l>=A&&l<g)T=t.create(t.Class.UNIVERSAL,t.Type.UTCTIME,!1,t.dateToUtcTime(l));else T=t.create(t.Class.UNIVERSAL,t.Type.GENERALIZEDTIME,!1,t.dateToGeneralizedTime(l))}return t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(d.type).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SET,!0,[T])])}function m(d){return[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(e.pki.oids.data).getBytes()),t.create(t.Class.UNIVERSAL,t.Type.SEQUENCE,!0,[t.create(t.Class.UNIVERSAL,t.Type.OID,!1,t.oidToDer(d.algorithm).getBytes()),!d.parameter?void 0:t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,d.parameter.getBytes())]),t.create(t.Class.CONTEXT_SPECIFIC,0,!0,[t.create(t.Class.UNIVERSAL,t.Type.OCTETSTRING,!1,d.content.getBytes())])]}function w(d,T,A){var g={},l=[];if(!t.validate(T,A,g,l)){var S=Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw S.errors=S,S}var I=t.derToOid(g.contentType);if(I!==e.pki.oids.data)throw Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(g.encryptedContent){var N="";if(e.util.isArray(g.encryptedContent))for(var L=0;L<g.encryptedContent.length;++L){if(g.encryptedContent[L].type!==t.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");N+=g.encryptedContent[L].value}else N=g.encryptedContent;d.encryptedContent={algorithm:t.derToOid(g.encAlgorithm),parameter:e.util.createBuffer(g.encParameter.value),content:e.util.createBuffer(N)}}if(g.content){var N="";if(e.util.isArray(g.content))for(var L=0;L<g.content.length;++L){if(g.content[L].type!==t.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");N+=g.content[L].value}else N=g.content;d.content=e.util.createBuffer(N)}return d.version=g.version.charCodeAt(0),d.rawCapture=g,g}function B(d){if(d.encryptedContent.key===void 0)throw Error("Symmetric key not available.");if(d.content===void 0){var T;switch(d.encryptedContent.algorithm){case e.pki.oids["aes128-CBC"]:case e.pki.oids["aes192-CBC"]:case e.pki.oids["aes256-CBC"]:T=e.aes.createDecryptionCipher(d.encryptedContent.key);break;case e.pki.oids.desCBC:case e.pki.oids["des-EDE3-CBC"]:T=e.des.createDecryptionCipher(d.encryptedContent.key);break;default:throw Error("Unsupported symmetric cipher, OID "+d.encryptedContent.algorithm)}if(T.start(d.encryptedContent.parameter),T.update(d.encryptedContent.content),!T.finish())throw Error("Symmetric decryption failed.");d.content=T.output}}}),ou=lt((r,n)=>{var e=pt();ze(),dr(),Gi(),Cr(),Tt();var t=n.exports=e.ssh=e.ssh||{};t.privateKeyToPutty=function(o,s,a){a=a||"",s=s||"";var C="ssh-rsa",p=s===""?"none":"aes256-cbc",m="PuTTY-User-Key-File-2: "+C+`\r
|
|
54
|
+
`;m+="Encryption: "+p+`\r
|
|
55
|
+
`,m+="Comment: "+a+`\r
|
|
56
|
+
`;var w=e.util.createBuffer();c(w,C),i(w,o.e),i(w,o.n);var B=e.util.encode64(w.bytes(),64),d=Math.floor(B.length/66)+1;m+="Public-Lines: "+d+`\r
|
|
57
|
+
`,m+=B;var T=e.util.createBuffer();i(T,o.d),i(T,o.p),i(T,o.q),i(T,o.qInv);var A;if(!s)A=e.util.encode64(T.bytes(),64);else{var g=T.length()+16-1;g-=g%16;var l=f(T.bytes());l.truncate(l.length()-g+T.length()),T.putBuffer(l);var S=e.util.createBuffer();S.putBuffer(f("\x00\x00\x00\x00",s)),S.putBuffer(f("\x00\x00\x00\x01",s));var I=e.aes.createEncryptionCipher(S.truncate(8),"CBC");I.start(e.util.createBuffer().fillWithByte(0,16)),I.update(T.copy()),I.finish();var N=I.output;N.truncate(16),A=e.util.encode64(N.bytes(),64)}d=Math.floor(A.length/66)+1,m+=`\r
|
|
58
|
+
Private-Lines: `+d+`\r
|
|
59
|
+
`,m+=A;var L=f("putty-private-key-file-mac-key",s),v=e.util.createBuffer();c(v,C),c(v,p),c(v,a),v.putInt32(w.length()),v.putBuffer(w),v.putInt32(T.length()),v.putBuffer(T);var h=e.hmac.create();return h.start("sha1",L),h.update(v.bytes()),m+=`\r
|
|
60
|
+
Private-MAC: `+h.digest().toHex()+`\r
|
|
61
|
+
`,m},t.publicKeyToOpenSSH=function(o,s){var a="ssh-rsa";s=s||"";var C=e.util.createBuffer();return c(C,a),i(C,o.e),i(C,o.n),a+" "+e.util.encode64(C.bytes())+" "+s},t.privateKeyToOpenSSH=function(o,s){if(!s)return e.pki.privateKeyToPem(o);return e.pki.encryptRsaPrivateKey(o,s,{legacy:!0,algorithm:"aes128"})},t.getPublicKeyFingerprint=function(o,s){s=s||{};var a=s.md||e.md.md5.create(),C="ssh-rsa",p=e.util.createBuffer();c(p,C),i(p,o.e),i(p,o.n),a.start(),a.update(p.getBytes());var m=a.digest();if(s.encoding==="hex"){var w=m.toHex();if(s.delimiter)return w.match(/.{2}/g).join(s.delimiter);return w}else if(s.encoding==="binary")return m.getBytes();else if(s.encoding)throw Error('Unknown encoding "'+s.encoding+'".');return m};function i(o,s){var a=s.toString(16);if(a[0]>="8")a="00"+a;var C=e.util.hexToBytes(a);o.putInt32(C.length),o.putBytes(C)}function c(o,s){o.putInt32(s.length),o.putString(s)}function f(){var o=e.md.sha1.create(),s=arguments.length;for(var a=0;a<s;++a)o.update(arguments[a]);return o.digest()}}),ya=lt((r,n)=>{n.exports=pt(),ze(),au(),Ue(),Oi(),Zr(),uu(),dr(),cu(),fu(),lu(),fa(),Fi(),hr(),aa(),la(),hu(),ha(),sa(),ia(),qi(),we(),na(),ou(),oa(),Tt()});function xi(r,n){if(Array.isArray(n)&&!Array.isArray(r))return n;if(Array.isArray(n)&&Array.isArray(r))return n.map((t,i)=>{let c=r[i];if(fr(t)&&fr(c))return xi(c,t);return t});if(!fr(n)||!fr(r))return n;let e={...r};for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){let i=n[t],c=e[t];if(i===null||i===void 0)e[t]=i;else if(fr(i)&&fr(c))e[t]=xi(c,i);else e[t]=i}return e}function fr(r){return Boolean(r&&typeof r==="object"&&!Array.isArray(r))}async function du({name:r,cwd:n,defaultConfig:e}){let t=pu(n||yu.cwd(),`${r}.config`);try{let i=await import(t),c=i.default||i;return xi(e,c)}catch(i){return e}}var da={altNameIPs:["127.0.0.1"],altNameURIs:["localhost"],organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",commonName:"stacks.localhost",validityDays:825,hostCertCN:"stacks.localhost",domain:"stacks.localhost",rootCA:{certificate:"",privateKey:""},basePath:"",caCertPath:Vi.join(Ki.homedir(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Vi.join(Ki.homedir(),".stacks","ssl","stacks.localhost.crt"),keyPath:Vi.join(Ki.homedir(),".stacks","ssl","stacks.localhost.crt.key"),verbose:!1},ne=await du({name:"tls",defaultConfig:da}),Lf=Mi(ya(),1);function Ca(r){let n=Number.parseInt(r[0],16);if(n<8)return r;return n-=8,n.toString()+r.substring(1)}function Ea(r,n){let e=[];function t(i){try{let c=$n.readdirSync(i);for(let f of c){let o=Eu.join(i,f);if($n.lstatSync(o).isDirectory())t(o);else if(f===n)e.push(i)}}catch(c){console.warn(`Error reading directory ${i}: ${c}`)}}return t(r),e}function dt(r,n,e){if(e||ne.verbose)console.debug(`[tlsx:${r}] ${n}`)}var Tu=Su(Cu);async function yr(r,n={}){try{let{stdout:e,stderr:t}=await Tu(r,{cwd:n.cwd||vu.cwd(),timeout:n.timeout||30000});return{stdout:e.trim(),stderr:t.trim()}}catch(e){let t=Error(`Failed to execute command: ${r}
|
|
62
|
+
Error: ${e.message}`);throw t.stack=e.stack,t}}function va(r){if(r.domain)return r.domain;if(r.domains?.length)return r.domains[0];throw Error("Either domain or domains must be specified")}var ie=Mi(ya(),1);function Au(r){let n=[],e=new Set;if(r.domain)e.add(r.domain);if(r.domains?.length)r.domains.forEach((t)=>e.add(t));for(let t of e)n.push({type:2,value:t});if(r.altNameIPs?.length)for(let t of r.altNameIPs)n.push({type:7,value:t});if(r.altNameURIs?.length)for(let t of r.altNameURIs)n.push({type:6,value:t});if(r.subjectAltNames?.length)n.push(...r.subjectAltNames);return dt("cert",`Generated ${n.length} Subject Alternative Names`,r.verbose),n}function ji(r){dt("cert","Generating random serial number",r);let n=Ca(ie.default.util.bytesToHex(ie.default.random.getBytesSync(20)));return dt("cert",`Generated serial number: ${n}`,r),n}function Qi(r){let n=r.notBeforeDays??2,e=r.validityDays??(r.validityYears?r.validityYears*365:180);dt("cert","Calculating certificate validity dates",r.verbose);let t=new Date(Date.now()-86400*n*1000),i=new Date(t.getTime()+e*24*60*60*1000);return t.setUTCHours(0,0,0,0),i.setUTCHours(23,59,59,999),dt("cert",`Validity period: ${t.toISOString()} to ${i.toISOString()}`,r.verbose),{notBefore:t,notAfter:i}}function Iu(r){let n=[];n.push({name:"basicConstraints",cA:r.isCA??!1,critical:!0,...r.basicConstraints||{}});let e=Au(r);if(e.length>0)n.push({name:"subjectAltName",altNames:e});if(r.keyUsage)n.push({name:"keyUsage",critical:!0,...r.keyUsage});if(r.extKeyUsage)n.push({name:"extKeyUsage",...r.extKeyUsage});return n}async function zi(r={}){dt("ca","Creating new Root CA Certificate",r.verbose);let n=r.keySize||2048;dt("ca",`Generating ${n}-bit RSA key pair`,r.verbose);let{privateKey:e,publicKey:t}=ie.pki.rsa.generateKeyPair(n),i=[{shortName:"C",value:r.countryName||ne.countryName},{shortName:"ST",value:r.stateName||ne.stateName},{shortName:"L",value:r.localityName||ne.localityName},{shortName:"O",value:r.organization||"Local Development CA"},{shortName:"OU",value:r.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:r.commonName||"Local Development Root CA"},...r.extraAttributes||[]],{notBefore:c,notAfter:f}=Qi({validityYears:r.validityYears||100,verbose:r.verbose}),o=ie.pki.createCertificate();return o.publicKey=t,o.serialNumber=ji(r.verbose),o.validity.notBefore=c,o.validity.notAfter=f,o.setSubject(i),o.setIssuer(i),o.setExtensions([{name:"basicConstraints",cA:!0,critical:!0},{name:"keyUsage",keyCertSign:!0,cRLSign:!0,critical:!0},{name:"subjectKeyIdentifier"}]),o.sign(e,ie.default.md.sha256.create()),{certificate:ie.pki.certificateToPem(o),privateKey:ie.pki.privateKeyToPem(e),notBefore:c,notAfter:f}}async function Pi(r){if(dt("cert","Generating new certificate",r.verbose),dt("cert",`Options: ${JSON.stringify(r)}`,r.verbose),!r.domain&&!r.domains?.length)throw Error("Either domain or domains must be specified");if(!r.rootCA?.certificate||!r.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let n=ie.pki.certificateFromPem(r.rootCA.certificate),e=ie.pki.privateKeyFromPem(r.rootCA.privateKey);dt("cert","Generating 2048-bit RSA key pair for host certificate",r.verbose);let t=2048,{privateKey:i,publicKey:c}=ie.pki.rsa.generateKeyPair(t),f=r.commonName||va(r),o=r.certificateAttributes||[{shortName:"C",value:r.countryName||ne.countryName},{shortName:"ST",value:r.stateName||ne.stateName},{shortName:"L",value:r.localityName||ne.localityName},{shortName:"O",value:r.organizationName||ne.organizationName},{shortName:"CN",value:f}],{notBefore:s,notAfter:a}=Qi({validityDays:r.validityDays,verbose:r.verbose}),C=ie.pki.createCertificate();return C.publicKey=c,C.serialNumber=ji(r.verbose),C.validity.notBefore=s,C.validity.notAfter=a,C.setSubject(o),C.setIssuer(n.subject.attributes),C.setExtensions(Iu(r)),C.sign(e,ie.default.md.sha256.create()),{certificate:ie.pki.certificateToPem(C),privateKey:ie.pki.privateKeyToPem(i),notBefore:s,notAfter:a}}async function Yi(r,n,e){dt("trust",`Adding certificate to system trust store with options: ${JSON.stringify(e)}`,e?.verbose),dt("trust","Storing certificate and private key",e?.verbose);let t=Sa(r,e);dt("trust","Storing CA certificate",e?.verbose);let i=Ta(n,e),c=Jn.platform();dt("trust",`Detected platform: ${c}`,e?.verbose);let f="TC, C, C";if(c==="darwin")dt("trust","Adding certificate to macOS keychain",e?.verbose),await yr(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`);else if(c==="win32")dt("trust","Adding certificate to Windows certificate store",e?.verbose),await yr(`certutil -f -v -addstore -enterprise Root ${i}`);else if(c==="linux"){dt("trust","Adding certificate to Linux certificate store",e?.verbose);let o=Jn.homedir(),s="cert9.db";dt("trust",`Searching for certificate databases in ${o}`,e?.verbose);let a=Ea(o,s);for(let C of a){dt("trust",`Processing certificate database in ${C}`,e?.verbose);try{dt("trust",`Attempting to delete existing cert for ${ne.commonName}`,e?.verbose),await yr(`certutil -d sql:${C} -D -n ${ne.commonName}`)}catch(p){dt("trust",`Warning: Error deleting existing cert: ${p}`,e?.verbose),console.warn(`Error deleting existing cert: ${p}`)}dt("trust",`Adding new certificate to ${C}`,e?.verbose),await yr(`certutil -d sql:${C} -A -t ${f} -n ${ne.commonName} -i ${i}`),ta.info(`Cert added to ${C}`)}}else throw dt("trust",`Error: Unsupported platform ${c}`,e?.verbose),Error(`Unsupported platform: ${c}`);return dt("trust","Certificate successfully added to system trust store",e?.verbose),t}function Sa(r,n){dt("storage",`Storing certificate and private key with options: ${JSON.stringify(n)}`,n?.verbose);let e=lr.join(n?.basePath||ne.basePath,n?.certPath||ne.certPath),t=lr.join(n?.basePath||ne.basePath,n?.keyPath||ne.keyPath);dt("storage",`Certificate path: ${e}`,n?.verbose),dt("storage",`Private key path: ${t}`,n?.verbose);let i=lr.dirname(e);if(!xe.existsSync(i))dt("storage",`Creating certificate directory: ${i}`,n?.verbose),xe.mkdirSync(i,{recursive:!0});dt("storage","Writing certificate file",n?.verbose),xe.writeFileSync(e,r.certificate);let c=lr.dirname(t);if(!xe.existsSync(c))dt("storage",`Creating private key directory: ${c}`,n?.verbose),xe.mkdirSync(c,{recursive:!0});return dt("storage","Writing private key file",n?.verbose),xe.writeFileSync(t,r.privateKey),dt("storage","Certificate and private key stored successfully",n?.verbose),e}function Ta(r,n){dt("storage","Storing CA certificate",n?.verbose);let e=lr.join(n?.basePath||ne.basePath,n?.caCertPath||ne.caCertPath);dt("storage",`CA certificate path: ${e}`,n?.verbose);let t=lr.dirname(e);if(!xe.existsSync(t))dt("storage",`Creating CA certificate directory: ${t}`,n?.verbose),xe.mkdirSync(t,{recursive:!0});return dt("storage","Writing CA certificate file",n?.verbose),xe.writeFileSync(e,r),dt("storage","CA certificate stored successfully",n?.verbose),e}var Zf=ie.tls,$f=ie.pki,Jf=ie.default;var Ye=null;function Aa(r){let n=new Set;n.add(r);let e=r.split(".");if(e.length>=2)n.add(`*.${e.slice(1).join(".")}`);return Array.from(n)}function ma(r){let e=$i(r).replace(/\*/g,"wildcard"),t=pe(Er(),".stacks","ssl"),i=t;if(typeof r?.https==="object")return i=r.https.basePath&&r.https.basePath.trim()!==""?r.https.basePath:t,{caCertPath:r.https.caCertPath||pe(i,`${e}.ca.crt`),certPath:r.https.certPath||pe(i,`${e}.crt`),keyPath:r.https.keyPath||pe(i,`${e}.key`)};return{caCertPath:pe(i,`${e}.ca.crt`),certPath:pe(i,`${e}.crt`),keyPath:pe(i,`${e}.key`)}}function Ia(r){let n=new Set;if(Ji(r))r.proxies.forEach((e)=>{let t=e.to||"rpx.localhost";Aa(t).forEach((i)=>n.add(i))});else if(ga(r)){let e=r.to||"rpx.localhost";Aa(e).forEach((t)=>n.add(t))}else n.add("rpx.localhost");return n.add("localhost"),n.add("*.localhost"),n}async function ll(r){Q("ssl","Loading SSL configuration",r.verbose);let n={...Qr,...r};if(r.https=Xe(n),!r.https?.keyPath&&!r.https?.certPath)return Q("ssl","No SSL configuration provided",r.verbose),null;if(r.https?.keyPath&&!r.https?.certPath||!r.https?.keyPath&&r.https?.certPath){let e=!r.https?.keyPath?"keyPath":"certPath";throw Q("ssl",`Invalid SSL configuration - missing ${e}`,r.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${e}`)}try{if(!r.https?.keyPath||!r.https?.certPath)return null;try{Q("ssl","Reading SSL certificate files",r.verbose);let e=await ue.readFile(r.https?.keyPath,"utf8"),t=await ue.readFile(r.https?.certPath,"utf8");return Q("ssl","SSL configuration loaded successfully",r.verbose),{key:e,cert:t}}catch(e){return Q("ssl",`Failed to read certificates: ${e}`,r.verbose),null}}catch(e){throw Q("ssl",`SSL configuration error: ${e}`,r.verbose),e}}async function hl(r){if(Ne.platform==="darwin")return gu(r);if(Ne.platform==="linux")try{let{exec:n}=await import("node:child_process");return await new Promise((e)=>{n(`sudo cp "${r}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(t)=>{if(!t)e(!0);else n(`sudo cp "${r}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(i)=>{e(!i)})})})}catch{return!1}return!1}async function gu(r){if(Ne.platform!=="darwin")return!1;try{if(await en(r,{verbose:!1,regenerateUntrustedCerts:!0}))return Q("ssl","Certificate is already trusted, skipping trust operation",!1),!0;X.info("Attempting to trust certificate using macOS security command");try{return Wi(`security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${r}"`),X.success("Successfully added certificate to system trust store"),!0}catch(e){X.warn(`Could not add to system keychain: ${e}`);try{return Oe(`security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db "${r}"`),X.success("Successfully added certificate to user login keychain"),!0}catch(t){return X.warn(`Could not add to user keychain: ${t}`),!1}}}catch(n){return X.error(`Failed to trust certificate: ${n}`),!1}}async function tn(r){if(Ye){Q("ssl","Using cached SSL configuration",r.verbose);return}let n=Ji(r)?r.proxies.map((s)=>s.to):[r.to];Q("ssl",`Generating certificate for domains: ${n.join(", ")}`,r.verbose);let e=Xe(r,r.verbose);X.info("Generating Root CA certificate...");let t=await zi(e),i=Xe(r,r.verbose);X.info(`Generating host certificate for: ${n.join(", ")}`);let c=await Pi({...i,rootCA:{certificate:t.certificate,privateKey:t.privateKey}});try{let s=i.basePath||pe(Er(),".stacks","ssl");await ue.mkdir(s,{recursive:!0}),await Promise.all([ue.writeFile(i.certPath,c.certificate),ue.writeFile(i.keyPath,c.privateKey),ue.writeFile(i.caCertPath,t.certificate)]),Q("ssl","Certificate files saved successfully",r.verbose)}catch(s){throw Q("ssl",`Error saving certificate files: ${s}`,r.verbose),Error(`Failed to save certificate files: ${s}`)}if(await en(i.certPath,{verbose:r.verbose,regenerateUntrustedCerts:!0})){Q("ssl","Certificate is already trusted, skipping trust store update",r.verbose),X.success("Certificate is already trusted in system trust store"),Ye={key:c.privateKey,cert:c.certificate,ca:t.certificate},X.success(`Certificate generated successfully for ${n.length} domain${n.length>1?"s":""}`);return}X.info("Adding certificate to system trust store (may require sudo permission)...");let o=!1;if(Ne.platform==="darwin")try{let s=`security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${i.caCertPath}" && security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${i.certPath}"`;Wi(s),X.success("Successfully added CA and host certificates to system trust store");try{Oe(`security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db "${i.certPath}"`,{stdio:"pipe"})}catch{}o=!0;let a=i.basePath||pe(Er(),".stacks","ssl"),C=pe(a,"trust-rpx-cert.sh"),p=`#!/bin/bash
|
|
63
|
+
echo "Trusting RPX certificate for domains: ${n.join(", ")}"
|
|
64
|
+
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${i.caCertPath}"
|
|
65
|
+
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${i.certPath}"
|
|
66
|
+
echo "Certificates trusted! Please restart your browser."
|
|
67
|
+
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
68
|
+
`;await ue.writeFile(C,p,{mode:493})}catch(s){X.warn(`Could not add certificate to trust store automatically: ${s}`);let a=i.basePath||pe(Er(),".stacks","ssl"),C=pe(a,"trust-rpx-cert.sh"),p=`#!/bin/bash
|
|
69
|
+
echo "Trusting RPX certificate for domains: ${n.join(", ")}"
|
|
70
|
+
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${i.caCertPath}"
|
|
71
|
+
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${i.certPath}"
|
|
72
|
+
echo "Certificates trusted! Please restart your browser."
|
|
73
|
+
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
74
|
+
`;await ue.writeFile(C,p,{mode:493}),X.info(`Created a trust helper script at: ${C}`),X.info(`If you're still having certificate issues, run: sh ${C}`)}else if(Ne.platform==="linux")try{let{exec:s}=await import("node:child_process"),a="/usr/local/share/ca-certificates/rpx",C=`
|
|
75
|
+
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
76
|
+
cp "${i.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
77
|
+
cp "${i.certPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
78
|
+
update-ca-certificates
|
|
79
|
+
echo "RPX certificates installed. Please restart your browser."
|
|
80
|
+
`,p=pe(Xi.tmpdir(),`rpx-trust-${Date.now()}.sh`);await ue.writeFile(p,C,{mode:493}),await new Promise((m)=>{s(`sudo bash "${p}"`,(w)=>{if(w)X.warn(`Could not trust certificates: ${w}`),m(!1);else X.success("Successfully added certificates to system trust store"),m(!0)})}),await ue.unlink(p).catch(()=>{}),o=!0}catch(s){X.warn(`Failed to trust certificates: ${s}`)}else if(Ne.platform==="win32")try{let s=`
|
|
81
|
+
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${i.caCertPath.replace(/\//g,"\\")}")
|
|
82
|
+
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
83
|
+
$store.Open("ReadWrite")
|
|
84
|
+
$store.Add($cert)
|
|
85
|
+
$store.Close()
|
|
86
|
+
Write-Host "Certificate trusted successfully!"
|
|
87
|
+
`,a=pe(Xi.tmpdir(),"rpx-trust.ps1");await ue.writeFile(a,s),Oe(`powershell -ExecutionPolicy Bypass -File "${a}"`),X.success("Successfully added certificate to Windows trust store"),o=!0}catch(s){X.warn(`Could not trust certificate: ${s}`)}else try{await Yi(c,t.certificate,i),o=!0}catch(s){X.warn(`Could not add certificate to trust store: ${s}`)}if(Ye={key:c.privateKey,cert:c.certificate,ca:t.certificate},X.success(`Certificate generated successfully for ${n.length} domain${n.length>1?"s":""}`),!o)X.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),X.warn("This will bypass the warning and you should only need to do it once")}async function vr(r){if(!r)return null;if(Ye)return Ye;let n=Xe(r);try{let[e,t,i]=await Promise.all([ue.access(n.keyPath).then(()=>!0).catch(()=>!1),ue.access(n.certPath).then(()=>!0).catch(()=>!1),n.caCertPath?ue.access(n.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!e||!t)return Q("ssl",`Certificate files don't exist: key=${e}, cert=${t}`,r.verbose),null;if(!(("regenerateUntrustedCerts"in r?r.regenerateUntrustedCerts!==!1:!0)?await en(n.certPath,r):!0))return Q("ssl","Certificate exists but is not trusted, will regenerate",r.verbose),null;let[o,s,a]=await Promise.all([ue.readFile(n.keyPath,"utf8"),ue.readFile(n.certPath,"utf8"),i&&n.caCertPath?ue.readFile(n.caCertPath,"utf8"):Promise.resolve(void 0)]);if(a&&!Zi(a))return Q("ssl","Invalid root CA certificate, will regenerate",r.verbose),null;return Q("ssl","Successfully loaded existing certificates",r.verbose),Ye={key:o,cert:s,ca:a},Ye}catch(e){return Q("ssl",`Error checking existing certificates: ${e}`,r.verbose),null}}function Xe(r,n){let e=$i(r);Q("ssl",`Primary domain: ${e}`,n);let t=ma(r),i=pe(Er(),".stacks","ssl");if(typeof r.https==="object"){let c=r.https.basePath&&r.https.basePath.trim()!==""?r.https.basePath:i,f={domain:e,hostCertCN:e,basePath:c,caCertPath:r.https.caCertPath||t.caCertPath,certPath:r.https.certPath||t.certPath,keyPath:r.https.keyPath||t.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r.https.commonName||e,organizationName:r.https.organizationName||"Local Development",countryName:r.https.countryName||"US",stateName:r.https.stateName||"California",localityName:r.https.localityName||"Playa Vista",validityDays:r.https.validityDays||825,verbose:n||!1,subjectAltNames:Array.from(Ia(r)).map((o)=>({type:2,value:o}))};if(Zi(r.https.rootCA))f.rootCA=r.https.rootCA;return f}return{domain:e,hostCertCN:e,basePath:i,...t,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:e,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:n||!1,subjectAltNames:Array.from(Ia(r)).map((c)=>({type:2,value:c}))}}async function wa(r,n){let e=ma({to:r,verbose:n}),t=[e.caCertPath,e.certPath,e.keyPath];Q("certificates","Attempting to clean up relating certificates",n),await Promise.all(t.map((i)=>Ba(i,n)))}async function en(r,n){try{if(Q("ssl",`Checking if certificate is trusted: ${r}`,n?.verbose),Ne.platform==="darwin")try{let t=Oe(`openssl x509 -noout -fingerprint -sha256 -in "${r}"`).toString().trim().split("=")[1]?.trim()||"";if(!t)return Q("ssl","Could not extract certificate fingerprint",n?.verbose),!1;if(Oe("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256").toString().includes(t))return Q("ssl","Certificate fingerprint found in system keychain",n?.verbose),!0;return Q("ssl","Certificate fingerprint not found in system keychain",n?.verbose),!1}catch(e){return Q("ssl",`Error checking certificate trust: ${e}`,n?.verbose),!1}else if(Ne.platform==="win32")try{let t=Oe(`openssl x509 -noout -subject -in "${r}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!t)return Q("ssl","Could not extract certificate subject",n?.verbose),!1;let i=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${t}*' } | Select-Object Subject"`;if(Oe(i).toString().includes(t))return Q("ssl","Certificate found in trusted root store",n?.verbose),!0;return Q("ssl","Certificate not found in trusted root store",n?.verbose),!1}catch(e){return Q("ssl",`Error checking certificate trust on Windows: ${e}`,n?.verbose),!1}else if(Ne.platform==="linux")try{let t=Oe(`openssl x509 -noout -fingerprint -sha256 -in "${r}"`).toString().trim().split("=")[1]?.trim()||"",i=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let c of i)try{if(Oe(`find ${c} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${t}"`).toString().includes(t))return Q("ssl",`Certificate fingerprint found in ${c}`,n?.verbose),!0}catch{}return Q("ssl","Certificate not found in system trust stores",n?.verbose),!1}catch(e){return Q("ssl",`Error checking certificate trust on Linux: ${e}`,n?.verbose),!1}return Q("ssl",`Platform ${Ne.platform} not supported for certificate trust check`,n?.verbose),!1}catch(e){return Q("ssl",`Error checking if certificate is trusted: ${e}`,n?.verbose),!1}}import*as ti from"node:net";function Sr(r,n,e){return Q("port",`Checking if port ${r} is in use on ${n}`,e),new Promise((t)=>{let i=ti.createServer(),c=setTimeout(()=>{Q("port",`Checking port ${r} timed out, assuming it's in use`,e),i.close(),t(!0)},3000);i.once("error",(f)=>{if(clearTimeout(c),f.code==="EADDRINUSE")Q("port",`Port ${r} is in use`,e),t(!0);else Q("port",`Error checking port ${r}: ${f.message}`,e),t(!0)}),i.once("listening",()=>{clearTimeout(c),Q("port",`Port ${r} is available`,e),i.close(),t(!1)});try{i.listen(r,n)}catch(f){clearTimeout(c),Q("port",`Exception checking port ${r}: ${f}`,e),t(!0)}})}async function Bu(r,n,e,t=50){Q("port",`Finding available port starting from ${r} (max attempts: ${t})`,e);let i=r,c=0;while(c<t){if(c++,!await Sr(i,n,e))return Q("port",`Found available port: ${i} after ${c} attempts`,e),i;Q("port",`Port ${i} is in use, trying ${i+1} (attempt ${c}/${t})`,e),i++}throw Error(`Unable to find available port after ${t} attempts starting from ${r}`)}function Na(r,n,e=5000,t){return Q("port",`Testing connection to ${n}:${r}`,t),new Promise((i)=>{let c=ti.connect({host:n,port:r,timeout:e});c.once("connect",()=>{Q("port",`Successfully connected to ${n}:${r}`,t),c.end(),i(!0)}),c.once("timeout",()=>{Q("port",`Connection to ${n}:${r} timed out`,t),c.destroy(),i(!1)}),c.once("error",(f)=>{Q("port",`Failed to connect to ${n}:${r}: ${f.message}`,t),c.destroy(),i(!1)})})}class ei{usedPorts=new Set;hostname;verbose;maxRetries;constructor(r="0.0.0.0",n,e=50){this.hostname=r,this.verbose=n,this.maxRetries=e}async getNextAvailablePort(r,n=!1){if(this.usedPorts.has(r))return this.findNextAvailablePort(r+1,n);if(await Sr(r,this.hostname,this.verbose))return this.findNextAvailablePort(r+1,n);if(n){if(!await Na(r,this.hostname,3000,this.verbose))return Q("port",`Port ${r} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(r+1,n)}return this.usedPorts.add(r),r}async findNextAvailablePort(r,n=!1){let e=await Bu(r,this.hostname,this.verbose,this.maxRetries);if(n){if(!await Na(e,this.hostname,3000,this.verbose))if(e<r+this.maxRetries)return this.findNextAvailablePort(e+1,n);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(e),e}releasePort(r){Q("port",`Releasing port ${r}`,this.verbose),this.usedPorts.delete(r)}}var yl=new ei;import{spawn as mu}from"node:child_process";import*as We from"node:process";class ri{processes=new Map;isShuttingDown=!1;async startProcess(r,n,e){if(this.processes.has(r)){Q("start",`Process ${r} is already running`,e);return}let[t,...i]=n.command.split(" "),c=n.cwd||We.cwd();Q("start",`Starting process ${r}:`,e),Q("start",` Command: ${t} ${i.join(" ")}`,e),Q("start",` Working directory: ${c}`,e),Q("start",` Environment variables: ${JSON.stringify(n.env)}`,e);let f=mu(t,i,{cwd:c,env:{...We.env,...n.env},shell:!0,stdio:"inherit"});return this.processes.set(r,{command:n.command,cwd:c,process:f,env:n.env}),new Promise((o,s)=>{if(f.on("error",(a)=>{if(!this.isShuttingDown)Q("start",`Process ${r} failed to start: ${a}`,e),this.processes.delete(r),s(a),We.emit("SIGINT")}),f.on("exit",(a)=>{if(!this.isShuttingDown&&a!==null&&a!==0)Q("start",`Process ${r} exited with code ${a}`,e),this.processes.delete(r),s(Error(`Process ${r} exited with code ${a}`)),We.emit("SIGINT")}),e)f.stdout?.on("data",(a)=>{Q("process",`[${r}] ${a.toString().trim()}`,!0)}),f.stderr?.on("data",(a)=>{Q("process",`[${r}] ERR: ${a.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&f.killed)this.processes.delete(r),s(Error(`Process ${r} was killed during startup`));else Q("start",`Process ${r} started successfully`,e),o()},1000)})}async stopProcess(r,n){let e=this.processes.get(r);if(!e?.process){Q("start",`No process found for ${r}`,n);return}return Q("start",`Stopping process ${r}`,n),new Promise((t)=>{if(!e.process){t();return}e.process.once("exit",()=>{this.processes.delete(r),Q("start",`Process ${r} stopped`,n),t()});try{e.process.kill("SIGTERM"),setTimeout(()=>{if(e.process){Q("start",`Force killing process ${r}`,n);try{e.process.kill("SIGKILL")}catch(i){}}},3000)}catch(i){Q("start",`Error stopping process ${r}: ${i}`,n),this.processes.delete(r),t()}})}async stopAll(r){if(this.isShuttingDown){Q("start","Already shutting down, skipping duplicate stopAll call",r);return}this.isShuttingDown=!0,Q("start","Stopping all processes",r);let n=Array.from(this.processes.keys()).map((e)=>this.stopProcess(e,r).catch((t)=>{X.error(`Failed to stop process ${e}:`,t)}));await Promise.allSettled(n),this.processes.clear(),this.isShuttingDown=!1}isRunning(r){let n=this.processes.get(r);return!!n?.process&&!n.process.killed}}var Sl=new ri;import*as Ze from"node:http";import*as ka from"node:http2";import*as La from"node:net";import*as Vt from"node:process";var _e=bu(ba(),1);var si=new ri,Uu=new ei("0.0.0.0"),ui=new Set,nn=!1,ai=null,an=null;async function ci(r){if(nn)return Q("cleanup","Cleanup already in progress, skipping",r?.verbose),an||Promise.resolve();nn=!0,Q("cleanup","Starting cleanup process",r?.verbose),an=new Promise((n)=>{ai=n});try{await si.stopAll(r?.verbose),X.info("Shutting down proxy servers...");let n=[],e=Array.from(ui).map((t)=>new Promise((i)=>{t.close(()=>{Q("cleanup","Server closed successfully",r?.verbose),i()})}));if(n.push(...e),r?.hosts&&r.domains?.length){Q("cleanup","Cleaning up hosts file entries",r?.verbose),Q("cleanup",`Original domains for cleanup: ${JSON.stringify(r.domains)}`,r?.verbose);let t=r.domains.filter((i)=>{if(i==="test.local")return!0;return i!=="localhost"&&!i.startsWith("localhost.")&&i!=="127.0.0.1"});if(Q("cleanup",`Filtered domains for cleanup: ${JSON.stringify(t)}`,r?.verbose),t.length>0)X.info("Cleaning up hosts file entries..."),n.push(Zn(t,r?.verbose).then(()=>{Q("cleanup",`Removed hosts entries for ${t.join(", ")}`,r?.verbose)}).catch((i)=>{Q("cleanup",`Failed to remove hosts entries: ${i}`,r?.verbose),X.warn(`Failed to clean up hosts file entries for ${t.join(", ")}:`,i)}))}if(r?.certs&&r.domains?.length){Q("cleanup","Cleaning up SSL certificates",r?.verbose),X.info("Cleaning up SSL certificates...");let t=r.domains.map(async(i)=>{try{await wa(i,r?.verbose),Q("cleanup",`Removed certificates for ${i}`,r?.verbose)}catch(c){Q("cleanup",`Failed to remove certificates for ${i}: ${c}`,r?.verbose),X.warn(`Failed to clean up certificates for ${i}:`,c)}});n.push(...t)}await Promise.allSettled(n),Q("cleanup","All cleanup tasks completed successfully",r?.verbose),X.success("All cleanup tasks completed successfully")}catch(n){Q("cleanup",`Error during cleanup: ${n}`,r?.verbose),X.error("Error during cleanup:",n)}finally{if(ai)ai();ai=null,nn=!1;let n=r&&"vitePluginUsage"in r&&r.vitePluginUsage===!0;if(Vt.env.NODE_ENV!=="test"&&Vt.env.BUN_ENV!=="test"&&!n)Vt.exit(0)}return an}var sn=!1;function un(r){if(sn){Q("signal",`Received second ${r} signal, forcing exit`,!0),Vt.exit(1);return}sn=!0,Q("signal",`Received ${r} signal, initiating cleanup`,!0),ci().catch((n)=>{Q("signal",`Cleanup failed after ${r}: ${n}`,!0),Vt.exit(1)}).finally(()=>{sn=!1})}Vt.once("SIGINT",()=>un("SIGINT"));Vt.once("SIGTERM",()=>un("SIGTERM"));Vt.on("uncaughtException",(r)=>{Q("process",`Uncaught exception: ${r}`,!0),X.error("Uncaught exception:",r),un("uncaughtException")});async function Tr(r,n,e,t=5){Q("connection",`Testing connection to ${r}:${n} (retries left: ${t})`,e);let i=15000,c=Date.now();if(Vt.env.RPX_BYPASS_CONNECTION_TEST==="true"){Q("connection",`Bypassing connection test for ${r}:${n} due to RPX_BYPASS_CONNECTION_TEST flag`,e);return}let f=()=>new Promise((o,s)=>{let a=La.connect({host:r,port:n,timeout:3000});a.once("connect",()=>{Q("connection",`Successfully connected to ${r}:${n}`,e),a.end(),o()}),a.once("timeout",()=>{Q("connection",`Connection to ${r}:${n} timed out`,e),a.destroy(),s(Error("Connection timed out"))}),a.once("error",(C)=>{Q("connection",`Failed to connect to ${r}:${n}: ${C}`,e),a.destroy(),s(C)})});try{await f()}catch(o){if(Date.now()-c>i){Q("connection",`Connection test timed out after ${i}ms, but continuing anyway`,e),X.warn(`Connection test to ${r}:${n} timed out, but RPX will try to proceed anyway.`);return}if(o.code==="ECONNREFUSED"&&t>0)return Q("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${t} retries left)`,e),await new Promise((a)=>setTimeout(a,2000)),Tr(r,n,e,t-1);if(t>0)try{Q("connection",`Trying HTTP request to ${r}:${n}`,e),await new Promise((a,C)=>{let p=Ze.request({hostname:r,port:n,path:"/",method:"HEAD",timeout:5000},(m)=>{Q("connection",`Received HTTP response with status: ${m.statusCode}`,e),a()});p.on("error",(m)=>C(m)),p.on("timeout",()=>{p.destroy(),C(Error("HTTP request timed out"))}),p.end()}),Q("connection",`HTTP request to ${r}:${n} succeeded`,e);return}catch(a){return Q("connection",`HTTP request to ${r}:${n} failed: ${a}`,e),Q("connection",`Retrying socket connection in 2 seconds... (${t} retries left)`,e),await new Promise((C)=>setTimeout(C,2000)),Tr(r,n,e,t-1)}let s=`Failed to connect to ${r}:${n} after ${5-t} attempts: ${o.message}`;Q("connection",`${s}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,e),X.warn(s),X.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function Da(r){Q("server",`Starting server with options: ${JSON.stringify(r)}`,r.verbose);let n=new URL((r.from?.startsWith("http")?r.from:`http://${r.from}`)||"localhost:5173"),e=new URL((r.to?.startsWith("http")?r.to:`http://${r.to}`)||"rpx.localhost"),t=Number.parseInt(n.port)||(n.protocol.includes("https:")?443:80),i=[e.hostname];if(!e.hostname.includes("localhost")&&!e.hostname.includes("127.0.0.1")){Q("hosts",`Checking if hosts file entry exists for: ${e.hostname}`,r?.verbose);try{if(!(await Xr(i,r.verbose))[0]){X.info(`Adding ${e.hostname} to hosts file...`),X.info("This may require sudo/administrator privileges");try{await Yr(i,r.verbose)}catch(o){if(X.error("Failed to add hosts entry:",o.message),X.warn("You can manually add this entry to your hosts file:"),X.warn(`127.0.0.1 ${e.hostname}`),X.warn(`::1 ${e.hostname}`),Vt.platform==="win32")X.warn("On Windows:"),X.warn("1. Run notepad as administrator"),X.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else X.warn("On Unix systems:"),X.warn("sudo nano /etc/hosts")}}else Q("hosts",`Host entry already exists for ${e.hostname}`,r.verbose)}catch(f){X.error("Failed to check hosts file:",f.message)}}try{await Tr(n.hostname,t,r.verbose)}catch(f){Q("server",`Connection test failed: ${f}`,r.verbose),X.error(f.message),X.warn("Continuing with proxy setup despite connection test failure..."),X.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let c=r._cachedSSLConfig||null;if(r.https)try{if(r.https===!0)r.https=Xe({...r,to:e.hostname});if(c=await vr({...r,to:e.hostname,https:r.https}),!c){if(Q("ssl",`Generating new certificates for ${e.hostname}`,r.verbose),await tn({...r,from:n.toString(),to:e.hostname,https:r.https}),c=await vr({...r,to:e.hostname,https:r.https}),!c)throw Error(`Failed to load SSL configuration after generating certificates for ${e.hostname}`)}}catch(f){throw Q("server",`SSL setup failed: ${f}`,r.verbose),f}Q("server",`Setting up reverse proxy with SSL config for ${e.hostname}`,r.verbose),await Lu({...r,from:r.from||"localhost:5173",to:e.hostname,fromPort:t,sourceUrl:{hostname:n.hostname,host:n.host},ssl:c})}async function ku(r,n,e,t,i,c,f,o,s,a,C){Q("proxy",`Creating proxy server ${r} -> ${n} with cleanUrls: ${a}`,s);function p(d){let T={};for(let[A,g]of Object.entries(d))if(!A.startsWith(":"))T[A]=g;return T}let m=(d,T)=>{Q("request",`Incoming request: ${d.method} ${d.url}`,s);let A=d.url||"/",g=d.method||"GET";if(d instanceof ka.Http2ServerRequest){let N=d.headers;g=N[":method"]||g,A=N[":path"]||A}if(a){if(!A.match(/\.[a-z0-9]+$/i))if(A.endsWith("/"))A=`${A}index.html`;else A=`${A}.html`}let l=p(d.headers);if(C)l.host=`${c.hostname}:${e}`,Q("request",`Changed origin: setting host header to ${l.host}`,s);let S={hostname:c.hostname,port:e,path:A,method:g,headers:l};Q("request",`Proxy request options: ${JSON.stringify(S)}`,s);let I=Ze.request(S,(N)=>{if(Q("response",`Proxy response received with status ${N.statusCode}`,s),a&&N.statusCode===404){let v=[];if(A.endsWith(".html"))v.push(A.slice(0,-5));else if(!A.match(/\.[a-z0-9]+$/i))v.push(`${A}.html`);if(!A.endsWith("/"))v.push(`${A}/index.html`);if(v.length>0){Q("cleanUrls",`Trying alternative paths: ${v.join(", ")}`,s);let h=(u)=>{if(u.length===0){T.writeHead(N.statusCode||404,N.headers),N.pipe(T);return}let R=u[0],V={...S,path:R},O=Ze.request(V,(K)=>{if(K.statusCode===200)Q("cleanUrls",`Found matching path: ${R}`,s),T.writeHead(K.statusCode,K.headers),K.pipe(T);else h(u.slice(1))});O.on("error",()=>h(u.slice(1))),O.end()};h(v);return}}let L={...N.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};T.writeHead(N.statusCode||500,L),N.pipe(T)});I.on("error",(N)=>{Q("request",`Proxy request failed: ${N}`,s),X.error("Proxy request failed:",N),T.writeHead(502),T.end(`Proxy Error: ${N.message}`)}),d.pipe(I)};if(Q("server",`Creating server with SSL config: ${!!f}`,s),f)return new Promise((d,T)=>{try{let A=Bun.serve({port:t,hostname:i,tls:{key:f.key,cert:f.cert,ca:f.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(g){let l=new URL(g.url);Q("request",`Bun.serve received: ${g.method} ${l.pathname}`,s);let S=`http://${c.host}`,I=new URL(l.pathname+l.search,S);try{let N=new Headers(g.headers);if(N.set("host",c.host),C)N.set("origin",S);N.set("x-forwarded-for","127.0.0.1"),N.set("x-forwarded-proto","https"),N.set("x-forwarded-host",n);let L=await fetch(I.toString(),{method:g.method,headers:N,body:g.body,redirect:"manual"}),v=new Headers(L.headers);if(a&&l.pathname.endsWith(".html")){let h=l.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:h}})}return new Response(L.body,{status:L.status,statusText:L.statusText,headers:v})}catch(N){return Q("request",`Proxy error: ${N}`,s),new Response(`Proxy Error: ${N}`,{status:502})}},error(g){return Q("server",`Bun.serve error: ${g}`,s),new Response(`Server Error: ${g.message}`,{status:500})}});ui.add(A),Ua({from:r,to:n,vitePluginUsage:o,listenPort:t,ssl:!0,cleanUrls:a}),d()}catch(A){T(A)}});let w=Ze.createServer(m);function B(d){return ui.add(d),new Promise((T,A)=>{d.listen(t,i,()=>{Q("server",`Server listening on port ${t}`,s),Ua({from:r,to:n,vitePluginUsage:o,listenPort:t,ssl:!!f,cleanUrls:a}),T()}),d.on("error",(g)=>{Q("server",`Server error: ${g}`,s),A(g)})})}return B(w)}async function Lu(r){Q("setup",`Setting up reverse proxy: ${JSON.stringify(r)}`,r.verbose);let{from:n,to:e,fromPort:t,sourceUrl:i,ssl:c,verbose:f,cleanup:o,vitePluginUsage:s,changeOrigin:a,cleanUrls:C}=r,p=80,m=443,w="0.0.0.0",B=r.portManager||Uu;try{if(e&&!e.includes("localhost")&&!e.includes("127.0.0.1")){if(!(await Xr([e],f))[0]){X.warn(`The hostname ${e} isn't in your hosts file. Adding it now...`);try{await Yr([e],f),X.success(`Added ${e} to your hosts file.`)}catch(l){X.error(`Failed to add ${e} to your hosts file: ${l}`),X.info(`You may need to manually add '127.0.0.1 ${e}' to your /etc/hosts file.`)}}}else if(e&&e.includes("localhost")&&!e.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await Xr([e],f))[0]){X.warn(`The hostname ${e} isn't in your hosts file. Adding it now...`);try{await Yr([e],f),X.success(`Added ${e} to your hosts file.`)}catch(l){X.error(`Failed to add ${e} to your hosts file: ${l}`),X.info(`You may need to manually add '127.0.0.1 ${e}' to your /etc/hosts file.`)}}}if(c&&!B.usedPorts.has(p))if(!await Sr(p,w,f))Q("setup","Starting HTTP redirect server",f),Du(f),B.usedPorts.add(p);else Q("setup","Port 80 is in use, skipping HTTP redirect",f),X.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available");let d=c?m:p,T=await Sr(d,w,f),A;if(T)if(X.warn(`Port ${d} is already in use. This may be another instance of rpx or another service.`),d===443)X.info("HTTPS requires port 443 for standard operation. Using an alternative port instead."),A=await B.getNextAvailablePort(3443,!0),X.info(`Using port ${A} instead. Access your site at https://${e}:${A}`);else A=await B.getNextAvailablePort(d+1000,!0),X.info(`Using port ${A} instead. Access your site at http://${e}:${A}`);else if(A=d,B.usedPorts.add(A),d===443)X.info(`Using standard HTTPS port 443. Access your site at https://${e}`);else X.info(`Using standard HTTP port 80. Access your site at http://${e}`);await ku(n,e,t,A,w,i,c,s,f,C,a)}catch(d){Q("setup",`Setup failed: ${d}`,f),X.error(`Failed to setup reverse proxy: ${d.message}`),ci({domains:[e],hosts:typeof o==="boolean"?o:o?.hosts,certs:typeof o==="boolean"?o:o?.certs,verbose:f,vitePluginUsage:s})}}function Du(r){Q("redirect","Starting HTTP redirect server",r);let n=Ze.createServer((e,t)=>{let i=e.headers.host||"";Q("redirect",`Redirecting request from ${i}${e.url} to HTTPS`,r),t.writeHead(301,{Location:`https://${i}${e.url}`}),t.end()}).listen(80);ui.add(n),Q("redirect","HTTP redirect server started",r)}function kl(r){let n={...Qr,...r};Q("proxy",`Starting proxy with options: ${JSON.stringify(n)}`,n?.verbose);let e=n.to||"",t=e.split(".").pop()?.toLowerCase()||"",i=Vt.platform==="darwin"&&e&&!e.includes("localhost")&&!e.includes("127.0.0.1"),c=["dev","app","page","new","day","foo"],f=["test","localhost","local","example","invalid"];if(i&&c.includes(t))X.warn(`The .${t} TLD may not work reliably for local development`),X.info(` Google owns .${t} with HSTS preloading, which can bypass local DNS`),X.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(i)import("./chunk-s4etpr6b.js").then(({startDnsServer:s,setupResolver:a})=>{s([e],n.verbose).then((C)=>{if(C)a(n.verbose,[e]).then(()=>{if(f.includes(t))X.success(`DNS server started for .${t} domains`);else X.success(`DNS server started for .${t} domains (hosts file entry also added)`)});else X.warn(`Could not start DNS server - ${e} may not resolve in browser`)})}).catch((s)=>{Q("dns",`Failed to start DNS server: ${s}`,n.verbose)});let o={from:n.from,to:n.to,cleanUrls:n.cleanUrls,https:Xe(n),cleanup:n.cleanup,vitePluginUsage:n.vitePluginUsage,changeOrigin:n.changeOrigin,verbose:n.verbose};Q("proxy",`Server options: ${JSON.stringify(o)}`,n.verbose),Da(o).catch((s)=>{Q("proxy",`Failed to start proxy: ${s}`,n.verbose),X.error(`Failed to start proxy: ${s.message}`),ci({domains:[n.to],hosts:typeof n.cleanup==="boolean"?n.cleanup:n.cleanup?.hosts,certs:typeof n.cleanup==="boolean"?n.cleanup:n.cleanup?.certs,verbose:n.verbose})})}function Ku(r){return r?.verbose||!1}async function Ll(r){let n={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!1};if(r)n={...n,...r};let e=Ku(n);if(Q("config",`Starting with config: ${JSON.stringify(n,null,2)}`,e),Q("config",`Is multi-proxy? ${"proxies"in n}`,e),"proxies"in n&&Array.isArray(n.proxies)){Q("servers",`Found ${n.proxies.length} proxies in config`,e);for(let w of n.proxies)if(w.start){let B=`${w.from}-${w.to}`;try{Q("watch",`Starting command for ${B} with command: ${w.start.command}`,e),X.info(`Starting command for ${B}...`),await si.startProcess(B,w.start,e);let d=new URL(w.from.startsWith("http")?w.from:`http://${w.from}`),T=d.hostname||"localhost",A=Number(d.port)||80;try{await Tr(T,A,e),Q("watch",`Dev server is ready at ${T}:${A}`,e)}catch(g){Q("watch",`Connection check failed, but continuing with proxy setup: ${g}`,e),X.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(d){throw Q("watch",`Failed to start command for ${B}: ${d}`,e),Error(`Failed to start command for ${B}: ${d}`)}}else Q("watch",`No start command for proxy ${w.from} -> ${w.to}`,e)}else if("start"in n&&n.start){Q("watch","Found start command in single proxy config",e);let w=`${n.from}-${n.to}`;try{if(n.start)Q("watch",`Starting command: ${n.start.command}`,e),await si.startProcess(w,n.start,e);let B=new URL(n.from?.startsWith("http")?n.from:`http://${n.from}`),d=B.hostname||"localhost",T=Number(B.port)||80;try{await Tr(d,T,e),Q("watch",`Dev server is ready at ${d}:${T}`,e)}catch(A){Q("watch",`Connection check failed, but continuing with proxy setup: ${A}`,e),X.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(B){throw Q("watch",`Failed to run start command: ${B}`,e),Error(`Failed to run start command: ${B}`)}}else Q("watch","No start command found in config",e);let t="proxies"in n&&Array.isArray(n.proxies)?n.proxies[0]?.to:("to"in n)?n.to:"rpx.localhost";if(n.https){let w=await vr(n);if(!w){if(Q("ssl",`No valid or trusted certificates found for ${t}, generating new ones`,n.verbose),await tn(n),w=await vr(n),!w)throw Error(`Failed to load SSL certificates after generation for ${t}`)}else Q("ssl",`Using existing and trusted certificates for ${t}`,n.verbose);n._cachedSSLConfig=w}let i="proxies"in n&&Array.isArray(n.proxies)?n.proxies.map((w)=>({...w,https:n.https,cleanup:n.cleanup,cleanUrls:w.cleanUrls??("cleanUrls"in n?n.cleanUrls:!1),vitePluginUsage:n.vitePluginUsage,changeOrigin:w.changeOrigin??n.changeOrigin,verbose:e,_cachedSSLConfig:n._cachedSSLConfig})):[{from:"from"in n?n.from:"localhost:5173",to:"to"in n?n.to:"rpx.localhost",cleanUrls:"cleanUrls"in n?n.cleanUrls:!1,https:n.https,cleanup:n.cleanup,vitePluginUsage:n.vitePluginUsage,start:"start"in n?n.start:void 0,changeOrigin:n.changeOrigin,verbose:e,_cachedSSLConfig:n._cachedSSLConfig}],c=i.map((w)=>w.to||"rpx.localhost"),f=n._cachedSSLConfig,o=c.filter((w)=>w&&!w.includes("localhost")&&!w.includes("127.0.0.1")),s=["dev","app","page","new","day","foo"],a=["test","localhost","local","example","invalid"],C=[...new Set(o.map((w)=>w.split(".").pop()?.toLowerCase()))],p=C.filter((w)=>typeof w==="string"&&s.includes(w));if(p.length>0)X.warn(`The following TLDs may not work reliably for local development: ${p.map((w)=>`.${w}`).join(", ")}`),X.info(" These TLDs have HSTS preloading which can bypass local DNS"),X.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(Vt.platform==="darwin"&&o.length>0){let{startDnsServer:w,setupResolver:B}=await import("./chunk-s4etpr6b.js");if(await w(o,e))if(await B(e,o),C.every((A)=>typeof A==="string"&&a.includes(A)))X.success(`DNS server started for ${C.map((A)=>`.${A}`).join(", ")} domains`);else X.success(`DNS server started for ${C.map((A)=>`.${A}`).join(", ")} domains (hosts file entries also added)`);else X.warn("Could not start DNS server - custom domains may not resolve")}let m=async()=>{Q("cleanup","Starting cleanup handler",n.verbose);try{let{stopDnsServer:w,removeResolver:B}=await import("./chunk-s4etpr6b.js");w(n.verbose),await B(n.verbose)}catch(w){Q("cleanup",`Error stopping DNS server: ${w}`,n.verbose)}try{await si.stopAll(n.verbose)}catch(w){Q("cleanup",`Error stopping processes: ${w}`,n.verbose)}await ci({domains:c,hosts:typeof n.cleanup==="boolean"?n.cleanup:n.cleanup?.hosts,certs:typeof n.cleanup==="boolean"?n.cleanup:n.cleanup?.certs,verbose:n.verbose||!1})};Vt.on("SIGINT",m),Vt.on("SIGTERM",m),Vt.on("uncaughtException",(w)=>{Q("process",`Uncaught exception: ${w}`,!0),console.error("Uncaught exception:",w),m()});for(let w of i)try{let B=w.to||"rpx.localhost";Q("proxy",`Starting proxy for ${B} with SSL config: ${!!f}`,w.verbose),await Da({from:w.from||"localhost:5173",to:B,cleanUrls:w.cleanUrls||!1,https:w.https||!1,cleanup:w.cleanup||!1,vitePluginUsage:w.vitePluginUsage||!1,verbose:w.verbose||!1,_cachedSSLConfig:f,changeOrigin:w.changeOrigin||!1})}catch(B){Q("proxies",`Failed to start proxy for ${w.to}: ${B}`,w.verbose),console.error(`Failed to start proxy for ${w.to}:`,B),m()}}function Ua(r){if(!r?.vitePluginUsage){if(console.log(""),console.log(` ${_e.default.green(_e.default.bold("rpx"))} ${_e.default.green(`v${cn}`)}`),console.log(""),console.log(` ${_e.default.green("➜")} ${_e.default.dim(r?.from??"")} ${_e.default.dim("➜")} ${_e.default.cyan(r?.ssl?` https://${r?.to}`:` http://${r?.to}`)}`),r?.listenPort!==(r?.ssl?443:80))console.log(` ${_e.default.green("➜")} Listening on port ${r?.listenPort}`);if(r?.ssl)console.log(` ${_e.default.green("➜")} SSL enabled with:`),console.log(" - TLS 1.2/1.3"),console.log(" - Modern cipher suite"),console.log(" - HTTP/2 enabled"),console.log(" - HSTS enabled");if(r?.cleanUrls)console.log(` ${_e.default.green("➜")} Clean URLs enabled`)}}
|
|
88
|
+
export{cn as a,Qr as b,Yr as c,Zn as d,Xr as e,ll as f,hl as g,tn as h,vr as i,Xe as j,wa as k,en as l,Sr as m,Bu as n,ei as o,yl as p,Sl as q,ci as r,Da as s,kl as t,Ll as u};
|